+def edit(turb, body, args):
+
+ """Implementation of the `/edit` command
+
+ This can be used as `/edit` (with no arguments) in either a hunt
+ or a puzzle channel to edit that hunt or puzzle. It can also be
+ called explicitly as `/edit hunt` to edit a hunt even from a
+ puzzle channel.
+
+ In any case, the operation is identical to `/hunt edit` or
+ `/puzzle edit`.
+ """
+
+ # If we have an explicit argument, do what it says to do
+ if args == "hunt":
+ return edit_hunt_command(turb, body)
+
+ if args == "puzzle":
+ return edit_puzzle_command(turb, body)
+
+ # Any other argument string is an error
+ if args:
+ return bot_reply("Error: Unexpected argument: {}\n".format(args) +
+ "Usage: `/edit puzzle`, `/edit hunt`, or " +
+ "`/edit` (to choose based on channel)"
+ )
+
+ # No explicit argument, so select what to edit based on the current channel
+ channel_id = body['channel_id'][0]
+ trigger_id = body['trigger_id'][0]
+
+ puzzle = puzzle_for_channel(turb, channel_id)
+ if puzzle:
+ return edit_puzzle(turb, puzzle, trigger_id)
+
+ hunt = hunt_for_channel(turb, channel_id)
+ if hunt:
+ return edit_hunt(turb, hunt, trigger_id)
+
+ return bot_reply("Sorry, `/edit` only works in a hunt or puzzle channel.")
+
+commands["/edit"] = edit
+
+
+def edit_puzzle_command(turb, body):
+ """Implementation of the `/puzzle edit` command
+
+ As dispatched from the puzzle() function.
+ """
+
+ channel_id = body['channel_id'][0]
+ trigger_id = body['trigger_id'][0]
+
+ puzzle = puzzle_for_channel(turb, channel_id)
+
+ if not puzzle:
+ return bot_reply("Sorry, this does not appear to be a puzzle channel.")
+
+ return edit_puzzle(turb, puzzle, trigger_id)
+
+def edit_puzzle_button(turb, payload):
+ """Handler for the action of user pressing an edit_puzzle button"""
+
+ action_id = payload['actions'][0]['action_id']
+ trigger_id = payload['trigger_id']
+
+ (hunt_id, sort_key) = action_id.split('-', 1)
+
+ puzzle = find_puzzle_for_sort_key(turb, hunt_id, sort_key)
+
+ if not puzzle:
+ return bot_reply("Error: Puzzle not found.")
+
+ return edit_puzzle(turb, puzzle, trigger_id)
+
+actions['button']['edit_puzzle'] = edit_puzzle_button
+
+def edit_puzzle(turb, puzzle, trigger_id):
+ """Common code for implementing an edit puzzle dialog
+
+ This implementation is common whether the edit operation was invoked
+ by a button (edit_puzzle_button) or a command (edit_puzzle_command).
+ """
+
+ round_options = hunt_rounds(turb, puzzle['hunt_id'])
+
+ if len(round_options):
+ round_options_block = [
+ multi_select_block("Round(s)", "rounds",
+ "Existing round(s) this puzzle belongs to",
+ round_options,
+ initial_options=puzzle.get("rounds", None)),
+ ]
+ else:
+ round_options_block = []
+
+ solved = False
+ if puzzle.get("status", "unsolved") == solved:
+ solved = True
+
+ solution_str = None
+ solution_list = puzzle.get("solution", [])
+ if solution_list:
+ solution_str = ", ".join(solution_list)
+
+ view = {
+ "type": "modal",
+ "private_metadata": json.dumps({
+ "hunt_id": puzzle['hunt_id'],
+ "SK": puzzle["SK"],
+ "puzzle_id": puzzle['puzzle_id'],
+ "channel_id": puzzle["channel_id"],
+ "channel_url": puzzle["channel_url"],
+ "sheet_url": puzzle["sheet_url"],
+ }),
+ "title": {"type": "plain_text", "text": "Edit Puzzle"},
+ "submit": { "type": "plain_text", "text": "Save" },
+ "blocks": [
+ input_block("Puzzle name", "name", "Name of the puzzle",
+ initial_value=puzzle["name"]),
+ input_block("Puzzle URL", "url", "External URL of puzzle",
+ initial_value=puzzle.get("url", None),
+ optional=True),
+ checkbox_block("Is this a meta puzzle?", "Meta", "meta",
+ checked=(puzzle.get('type', 'plain') == 'meta')),
+ * round_options_block,
+ input_block("New round(s)", "new_rounds",
+ "New round(s) this puzzle belongs to " +
+ "(comma separated)",
+ optional=True),
+ input_block("State", "state",
+ "State of this puzzle (partial progress, next steps)",
+ initial_value=puzzle.get("state", None),
+ optional=True),
+ checkbox_block(
+ "Puzzle status", "Solved", "solved",
+ checked=(puzzle.get('status', 'unsolved') == 'solved')),
+ input_block("Solution", "solution",
+ "Solution(s) (comma-separated if multiple)",
+ initial_value=solution_str,
+ optional=True),
+ ]
+ }
+
+ result = turb.slack_client.views_open(trigger_id=trigger_id,
+ view=view)
+
+ if (result['ok']):
+ submission_handlers[result['view']['id']] = edit_puzzle_submission
+
+ return lambda_ok
+
+def edit_puzzle_submission(turb, payload, metadata):
+ """Handler for the user submitting the edit puzzle modal
+
+ This is the modal view presented to the user by the edit_puzzle
+ function above.
+ """
+
+ puzzle={}
+
+ # First, read all the various data from the request
+ meta = json.loads(metadata)
+ puzzle['hunt_id'] = meta['hunt_id']
+ puzzle['SK'] = meta['SK']
+ puzzle['puzzle_id'] = meta['puzzle_id']
+ puzzle['channel_id'] = meta['channel_id']
+ puzzle['channel_url'] = meta['channel_url']
+ puzzle['sheet_url'] = meta['sheet_url']
+
+ state = payload['view']['state']['values']
+ user_id = payload['user']['id']
+
+ puzzle['name'] = state['name']['name']['value']
+ url = state['url']['url']['value']
+ if url:
+ puzzle['url'] = url
+ if state['meta']['meta']['selected_options']:
+ puzzle['type'] = 'meta'
+ else:
+ puzzle['type'] = 'plain'
+ rounds = [option['value'] for option in
+ state['rounds']['rounds']['selected_options']]
+ if rounds:
+ puzzle['rounds'] = rounds
+ new_rounds = state['new_rounds']['new_rounds']['value']
+ puzzle_state = state['state']['state']['value']
+ if puzzle_state:
+ puzzle['state'] = puzzle_state
+ if state['solved']['solved']['selected_options']:
+ puzzle['status'] = 'solved'
+ else:
+ puzzle['status'] = 'unsolved'
+ puzzle['solution'] = []
+ solution = state['solution']['solution']['value']
+ if solution:
+ puzzle['solution'] = [
+ sol.strip() for sol in solution.split(',')
+ ]
+
+ # Verify that there's a solution if the puzzle is mark solved
+ if puzzle['status'] == 'solved' and not puzzle['solution']:
+ return submission_error("solution",
+ "A solved puzzle requires a solution.")
+
+ if puzzle['status'] == 'unsolved' and puzzle['solution']:
+ return submission_error("solution",
+ "An unsolved puzzle should have no solution.")
+
+ # Add any new rounds to the database
+ if new_rounds:
+ if 'rounds' not in puzzle:
+ puzzle['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
+ puzzle['rounds'].append(round)
+ turb.table.put_item(
+ Item={
+ 'hunt_id': puzzle['hunt_id'],
+ 'SK': 'round-' + round
+ }
+ )
+
+ # Get old puzzle from the database (to determine what's changed)
+ old_puzzle = find_puzzle_for_sort_key(turb,
+ puzzle['hunt_id'],
+ puzzle['SK'])
+
+ # If we are changing puzzle type (meta -> plain or plain -> meta)
+ # the the sort key has to change, so compute the new one and delete
+ # the old item from the database.
+ #
+ # XXX: We should really be using a transaction here to combine the
+ # delete_item and the put_item into a single transaction, but
+ # the boto interface is annoying in that transactions are only on
+ # the "Client" object which has a totally different interface than
+ # the "Table" object I've been using so I haven't figured out how
+ # to do that yet.
+
+ if puzzle['type'] != old_puzzle.get('type', 'plain'):
+ puzzle['SK'] = puzzle_sort_key(puzzle)
+ turb.table.delete_item(Key={
+ 'hunt_id': old_puzzle['hunt_id'],
+ 'SK': old_puzzle['SK']
+ })
+
+ # Update the puzzle in the database
+ turb.table.put_item(Item=puzzle)
+
+ # Inform the puzzle channel about the edit
+ edit_message = "Puzzle edited by <@{}>".format(user_id)
+ blocks = ([section_block(text_block(edit_message+":\n"))] +
+ puzzle_blocks(puzzle, include_rounds=True))
+ slack_send_message(
+ turb.slack_client, puzzle['channel_id'],
+ edit_message, blocks=blocks)
+
+ # Also inform the hunt if the puzzle's solved status changed
+ if puzzle['status'] != old_puzzle['status']:
+ hunt = find_hunt_for_hunt_id(turb, puzzle['hunt_id'])
+ if puzzle['status'] == 'solved':
+ message = "Puzzle <{}|{}> has been solved!".format(
+ puzzle['channel_url'],
+ puzzle['name'])
+ else:
+ message = "Oops. Puzzle <{}|{}> has been marked unsolved!".format(
+ puzzle['channel_url'],
+ puzzle['name'])
+ slack_send_message(turb.slack_client, hunt['channel_id'], message)
+
+ # We need to set the channel topic if any of puzzle name, url,
+ # state, status, or solution, has changed. Let's just do that
+ # unconditionally here.
+ puzzle_update_channel_and_sheet(turb, puzzle, old_puzzle=old_puzzle)
+
+ return lambda_ok
+
+def edit_hunt_command(turb, body):
+ """Implementation of the `/hunt edit` command
+
+ As dispatched from the hunt() function.
+ """
+
+ channel_id = body['channel_id'][0]
+ trigger_id = body['trigger_id'][0]
+
+ hunt = hunt_for_channel(turb, channel_id)
+
+ if not hunt:
+ return bot_reply("Sorry, this does not appear to be a hunt channel.")
+
+ return edit_hunt(turb, hunt, trigger_id)
+
+def edit_hunt_button(turb, payload):
+ """Handler for the action of user pressing an edit_hunt button"""
+
+ hunt_id = payload['actions'][0]['action_id']
+ trigger_id = payload['trigger_id']
+
+ hunt = find_hunt_for_hunt_id(turb, hunt_id)
+
+ if not hunt:
+ return bot_reply("Error: Hunt not found.")
+
+ return edit_hunt(turb, hunt, trigger_id)
+
+actions['button']['edit_hunt'] = edit_hunt_button
+
+def edit_hunt(turb, hunt, trigger_id):
+ """Common code for implementing an edit hunt dialog
+
+ This implementation is common whether the edit operation was invoked
+ by a button (edit_hunt_button) or a command (edit_hunt_command).
+ """
+
+ view = {
+ "type": "modal",
+ "private_metadata": json.dumps({
+ "hunt_id": hunt["hunt_id"],
+ "SK": hunt["SK"],
+ "is_hunt": hunt["is_hunt"],
+ "channel_id": hunt["channel_id"],
+ "sheet_url": hunt["sheet_url"],
+ "folder_id": hunt["folder_id"],
+ }),
+ "title": { "type": "plain_text", "text": "Edit Hunt" },
+ "submit": { "type": "plain_text", "text": "Save" },
+ "blocks": [
+ input_block("Hunt name", "name", "Name of the hunt",
+ initial_value=hunt["name"]),
+ input_block("Hunt URL", "url", "External URL of hunt",
+ initial_value=hunt.get("url", None),
+ optional=True),
+ checkbox_block("Is this hunt active?", "Active", "active",
+ checked=(hunt.get('active', False)))
+ ]
+ }
+
+ result = turb.slack_client.views_open(trigger_id=trigger_id,
+ view=view)
+
+ if result['ok']:
+ submission_handlers[result['view']['id']] = edit_hunt_submission
+
+ return lambda_ok
+
+def edit_hunt_submission(turb, payload, metadata):
+ """Handler for the user submitting the edit hunt modal
+
+ This is the modal view presented by the edit_hunt function above.
+ """
+
+ hunt={}
+
+ # First, read all the various data from the request
+ meta = json.loads(metadata)
+ hunt['hunt_id'] = meta['hunt_id']
+ hunt['SK'] = meta['SK']
+ hunt['is_hunt'] = meta['is_hunt']
+ hunt['channel_id'] = meta['channel_id']
+ hunt['sheet_url'] = meta['sheet_url']
+ hunt['folder_id'] = meta['folder_id']
+
+ state = payload['view']['state']['values']
+ user_id = payload['user']['id']
+
+ hunt['name'] = state['name']['name']['value']
+ url = state['url']['url']['value']
+ if url:
+ hunt['url'] = url
+
+ if state['active']['active']['selected_options']:
+ hunt['active'] = True
+ else:
+ hunt['active'] = False
+
+ # Update the hunt in the database
+ turb.table.put_item(Item=hunt)
+
+ # Inform the hunt channel about the edit
+ edit_message = "Hunt edited by <@{}>".format(user_id)
+ blocks = [
+ section_block(text_block(edit_message)),
+ section_block(text_block("Hunt name: {}".format(hunt['name']))),
+ ]
+
+ url = hunt.get('url', None)
+ if url:
+ blocks.append(
+ section_block(text_block("Hunt URL: {}".format(hunt['url'])))
+ )
+
+ slack_send_message(
+ turb.slack_client, hunt['channel_id'],
+ edit_message, blocks=blocks)
+
+ return lambda_ok
+
+def new_hunt_command(turb, body):
+ """Implementation of the '/hunt new' command
+
+ As dispatched from the hunt() function.
+ """
+
+ trigger_id = body['trigger_id'][0]
+
+ return new_hunt(turb, trigger_id)
+
+def new_hunt_button(turb, payload):