]> git.cworth.org Git - turbot/blobdiff - turbot/interaction.py
Fix storage of rounds for new puzzle creation
[turbot] / turbot / interaction.py
index df2f96f634da97af16b79973fad1ae207aa6aa5b..d8a252b316d13363d45950adf8b8ad2169f1ba17 100644 (file)
@@ -1,6 +1,9 @@
 from slack.errors import SlackApiError
-from turbot.blocks import input_block, section_block, text_block
+from turbot.blocks import (
+    input_block, section_block, text_block, multi_select_block
+)
 from turbot.hunt import find_hunt_for_hunt_id
+from turbot.puzzle import find_puzzle_for_url
 import turbot.rot
 import turbot.sheets
 import turbot.slack
@@ -52,6 +55,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 +120,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 +160,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 +339,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 +376,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 +398,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 +423,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 +463,17 @@ 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(','):
+            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 +486,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 +520,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)
 
@@ -470,9 +564,14 @@ 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)
+    del puzzle['state']
     turb.table.put_item(Item=puzzle)
 
     # Report the solution to the puzzle's channel