]> git.cworth.org Git - turbot/blobdiff - turbot/interaction.py
Fix error with missing search terems
[turbot] / turbot / interaction.py
index 0d2743e20fe3ddc8a5703d71435cf99f75d02b33..e6f7503e20bf2ffd5a1e53ae924230ab370a4931 100644 (file)
@@ -1,6 +1,9 @@
 from slack.errors import SlackApiError
-from turbot.blocks import input_block, section_block, text_block
-from turbot.hunt import find_hunt_for_hunt_id
+from turbot.blocks import (
+    input_block, section_block, text_block, multi_select_block
+)
+from turbot.hunt import find_hunt_for_hunt_id, hunt_blocks
+from turbot.puzzle import find_puzzle_for_url
 import turbot.rot
 import turbot.sheets
 import turbot.slack
@@ -10,6 +13,7 @@ import requests
 from botocore.exceptions import ClientError
 from boto3.dynamodb.conditions import Key
 from turbot.slack import slack_send_message
+import shlex
 
 actions = {}
 commands = {}
@@ -52,6 +56,13 @@ def submission_error(field, error):
         })
     }
 
+def multi_static_select(turb, payload):
+    """Handler for the action of user entering a multi-select value"""
+
+    return lambda_ok
+
+actions['multi_static_select'] = {"*": multi_static_select}
+
 def new_hunt(turb, payload):
     """Handler for the action of user pressing the new_hunt button"""
 
@@ -110,13 +121,14 @@ def new_hunt_submission(turb, payload, metadata):
             TableName='turbot',
             KeySchema=[
                 {'AttributeName': 'hunt_id', 'KeyType': 'HASH'},
-                {'AttributeName': 'SK', 'KeyType': 'RANGE'},
+                {'AttributeName': 'SK', 'KeyType': 'RANGE'}
             ],
             AttributeDefinitions=[
                 {'AttributeName': 'hunt_id', 'AttributeType': 'S'},
                 {'AttributeName': 'SK', 'AttributeType': 'S'},
                 {'AttributeName': 'channel_id', 'AttributeType': 'S'},
                 {'AttributeName': 'is_hunt', 'AttributeType': 'S'},
+                {'AttributeName': 'url', 'AttributeType': 'S'}
             ],
             ProvisionedThroughput={
                 'ReadCapacityUnits': 5,
@@ -149,6 +161,18 @@ def new_hunt_submission(turb, payload, metadata):
                         'WriteCapacityUnits': 5
                     }
                 }
+            ],
+            LocalSecondaryIndexes = [
+                {
+                    'IndexName': 'url_index',
+                    'KeySchema': [
+                        {'AttributeName': 'hunt_id', 'KeyType': 'HASH'},
+                        {'AttributeName': 'url', 'KeyType': 'RANGE'},
+                    ],
+                    'Projection': {
+                        'ProjectionType': 'ALL'
+                    }
+                }
             ]
         )
         return submission_error(
@@ -316,6 +340,28 @@ def hunt_for_channel(turb, channel_id):
     # we expect this to be a puzzle channel instead
     return find_hunt_for_hunt_id(turb, entry['hunt_id'])
 
+# python3.9 has a built-in removeprefix but AWS only has python3.8
+def remove_prefix(text, prefix):
+    if text.startswith(prefix):
+        return text[len(prefix):]
+    return text
+
+def hunt_rounds(turb, hunt_id):
+    """Returns array of strings giving rounds that exist in the given hunt"""
+
+    response = turb.table.query(
+        KeyConditionExpression=(
+            Key('hunt_id').eq(hunt_id) &
+            Key('SK').begins_with('round-')
+        )
+    )
+
+    if response['Count'] == 0:
+        return []
+
+    return [remove_prefix(option['SK'], 'round-')
+            for option in response['Items']]
+
 def puzzle(turb, body, args):
     """Implementation of the /puzzle command
 
@@ -331,6 +377,17 @@ def puzzle(turb, body, args):
         return bot_reply("Sorry, this channel doesn't appear to "
                          + "be a hunt or puzzle channel")
 
+    round_options = hunt_rounds(turb, hunt['hunt_id'])
+
+    if len(round_options):
+        round_options_block = [
+            multi_select_block("Round(s)", "rounds",
+                               "Existing round(s) this puzzle belongs to",
+                               round_options)
+        ]
+    else:
+        round_options_block = []
+
     view = {
         "type": "modal",
         "private_metadata": json.dumps({
@@ -342,6 +399,11 @@ def puzzle(turb, body, args):
             section_block(text_block("*For {}*".format(hunt['name']))),
             input_block("Puzzle name", "name", "Name of the puzzle"),
             input_block("Puzzle URL", "url", "External URL of puzzle",
+                        optional=True),
+            * round_options_block,
+            input_block("New round(s)", "new_rounds",
+                        "New round(s) this puzzle belongs to " +
+                        "(comma separated)",
                         optional=True)
         ]
     }
@@ -362,12 +424,28 @@ def puzzle_submission(turb, payload, metadata):
     This is the modal view presented to the user by the puzzle function
     above."""
 
+    # First, read all the various data from the request
     meta = json.loads(metadata)
     hunt_id = meta['hunt_id']
 
     state = payload['view']['state']['values']
     name = state['name']['name']['value']
     url = state['url']['url']['value']
+    if 'rounds' in state:
+        rounds = [option['value'] for option in
+                  state['rounds']['rounds']['selected_options']]
+    else:
+        rounds = []
+    new_rounds = state['new_rounds']['new_rounds']['value']
+
+    # Before doing anything, reject this puzzle if a puzzle already
+    # exists with the same URL.
+    if url:
+        existing = find_puzzle_for_url(turb, hunt_id, url)
+        if existing:
+            return submission_error(
+                "url",
+                "Error: A puzzle with this URL already exists.")
 
     # Create a Slack-channel-safe puzzle_id
     puzzle_id = re.sub(r'[^a-zA-Z0-9_]', '', name).lower()
@@ -386,6 +464,22 @@ def puzzle_submission(turb, payload, metadata):
 
     channel_id = response['channel']['id']
 
+    # Add any new rounds to the database
+    if new_rounds:
+        for round in new_rounds.split(','):
+            # Drop any leading/trailing spaces from the round name
+            round = round.strip()
+            # Ignore any empty string
+            if not len(round):
+                continue
+            rounds.append(round)
+            turb.table.put_item(
+                Item={
+                    'hunt_id': hunt_id,
+                    'SK': 'round-' + round
+                }
+            )
+
     # Insert the newly-created puzzle into the database
     item={
         "hunt_id": hunt_id,
@@ -398,6 +492,8 @@ def puzzle_submission(turb, payload, metadata):
     }
     if url:
         item['url'] = url
+    if rounds:
+        item['rounds'] = rounds
     turb.table.put_item(Item=item)
 
     return lambda_ok
@@ -430,6 +526,10 @@ def set_channel_topic(turb, puzzle):
     if state:
         description += " {}".format(state)
 
+    # Slack only allows 250 characters for a topic
+    if len(description) > 250:
+        description = description[:247] + "..."
+
     turb.slack_client.conversations_setTopic(channel=channel_id,
                                              topic=description)
 
@@ -444,7 +544,8 @@ def state(turb, body, args):
     puzzle = puzzle_for_channel(turb, channel_id)
 
     if not puzzle:
-        return bot_reply("Sorry, this is not a puzzle channel.")
+        return bot_reply(
+            "Sorry, the /state command only works in a puzzle channel")
 
     # Set the state field in the database
     puzzle['state'] = args
@@ -469,9 +570,15 @@ def solved(turb, body, args):
     if not puzzle:
         return bot_reply("Sorry, this is not a puzzle channel.")
 
+    if not args:
+        return bot_reply(
+            "Error, no solution provided. Usage: `/solved SOLUTION HERE`")
+
     # Set the status and solution fields in the database
     puzzle['status'] = 'solved'
     puzzle['solution'].append(args)
+    if 'state' in puzzle:
+        del puzzle['state']
     turb.table.put_item(Item=puzzle)
 
     # Report the solution to the puzzle's channel
@@ -506,3 +613,62 @@ def solved(turb, body, args):
     return lambda_ok
 
 commands["/solved"] = solved
+
+
+def hunt(turb, body, args):
+    """Implementation of the /hunt command
+
+    The (optional) args string can be used to filter which puzzles to
+    display. The first word can be one of 'all', 'unsolved', or
+    'solved' and can be used to display only puzzles with the given
+    status. Any remaining text in the args string will be interpreted
+    as search terms. These will be split into separate terms on space
+    characters, (though quotation marks can be used to include a space
+    character in a term). All terms must match on a puzzle in order
+    for that puzzle to be included. But a puzzle will be considered to
+    match if any of the puzzle title, round title, puzzle URL, puzzle
+    state, or puzzle solution match. Matching will be performed
+    without regard to case sensitivity and the search terms can
+    include regular expression syntax.
+    """
+
+    channel_id = body['channel_id'][0]
+    response_url = body['response_url'][0]
+
+    terms = None
+    if args:
+        # The first word can be a puzzle status and all remaining word
+        # (if any) are search terms. _But_, if the first word is not a
+        # valid puzzle status ('all', 'unsolved', 'solved'), then all
+        # words are search terms and we default status to 'unsolved'.
+        split_args = args.split(' ', 1)
+        status = split_args[0]
+        if (len(split_args) > 1):
+            terms = split_args[1]
+        if status not in ('unsolved', 'solved', 'all'):
+            terms = args
+            status = 'unsolved'
+    else:
+        status = 'unsolved'
+
+    # Separate search terms on spaces (but allow for quotation marks
+    # to capture spaces in a search term)
+    if terms:
+        terms = shlex.split(terms)
+
+    hunt = hunt_for_channel(turb, channel_id)
+
+    if not hunt:
+        return bot_reply("Sorry, this channel doesn't appear to "
+                         + "be a hunt or puzzle channel")
+
+    blocks = hunt_blocks(turb, hunt, puzzle_status=status, search_terms=terms)
+
+    requests.post(response_url,
+                  json = { 'blocks': blocks },
+                  headers = {'Content-type': 'application/json'}
+                  )
+
+    return lambda_ok
+
+commands["/hunt"] = hunt