|
| 1 | +import asyncio |
| 2 | +import logging |
| 3 | + |
| 4 | +import aiohttp.web |
| 5 | +from aiohttp.web import Response |
| 6 | + |
| 7 | +from pybot._vendor.slack.events import Event |
| 8 | +from pybot._vendor.slack.sansio import validate_request_signature |
| 9 | +from pybot._vendor.slack.actions import Action |
| 10 | +from pybot._vendor.slack.commands import Command |
| 11 | +from pybot._vendor.slack.exceptions import InvalidTimestamp, FailedVerification, InvalidSlackSignature |
| 12 | + |
| 13 | +LOG = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +async def incoming_event(request): |
| 17 | + slack = request.app.plugins["slack"] |
| 18 | + payload = await request.json() |
| 19 | + LOG.log(5, "Incoming event payload: %s", payload) |
| 20 | + |
| 21 | + if payload.get("type") == "url_verification": |
| 22 | + if slack.signing_secret: |
| 23 | + try: |
| 24 | + raw_payload = await request.read() |
| 25 | + validate_request_signature( |
| 26 | + raw_payload.decode("utf-8"), request.headers, slack.signing_secret |
| 27 | + ) |
| 28 | + return Response(body=payload["challenge"]) |
| 29 | + except (InvalidSlackSignature, InvalidTimestamp): |
| 30 | + return Response(status=500) |
| 31 | + elif payload["token"] == slack.verify: |
| 32 | + return Response(body=payload["challenge"]) |
| 33 | + else: |
| 34 | + return Response(status=500) |
| 35 | + |
| 36 | + try: |
| 37 | + verification_token = await _validate_request(request, slack) |
| 38 | + event = Event.from_http(payload, verification_token=verification_token) |
| 39 | + except (FailedVerification, InvalidSlackSignature, InvalidTimestamp): |
| 40 | + return Response(status=401) |
| 41 | + |
| 42 | + if event["type"] == "message": |
| 43 | + return await _incoming_message(event, request) |
| 44 | + else: |
| 45 | + futures = list(_dispatch(slack.routers["event"], event, request.app)) |
| 46 | + if futures: |
| 47 | + return await _wait_and_check_result(futures) |
| 48 | + |
| 49 | + return Response(status=200) |
| 50 | + |
| 51 | + |
| 52 | +async def _incoming_message(event, request): |
| 53 | + slack = request.app.plugins["slack"] |
| 54 | + |
| 55 | + if slack.bot_id and ( |
| 56 | + event.get("bot_id") == slack.bot_id |
| 57 | + or event.get("message", {}).get("bot_id") == slack.bot_id |
| 58 | + ): |
| 59 | + return Response(status=200) |
| 60 | + |
| 61 | + LOG.debug("Incoming message: %s", event) |
| 62 | + text = event.get("text") |
| 63 | + if slack.bot_user_id and text: |
| 64 | + mention = slack.bot_user_id in event["text"] or event["channel"].startswith("D") |
| 65 | + else: |
| 66 | + mention = False |
| 67 | + |
| 68 | + if mention and text and text.startswith(f"<@{slack.bot_user_id}>"): |
| 69 | + event["text"] = event["text"][len(f"<@{slack.bot_user_id}>") :] |
| 70 | + event["text"] = event["text"].strip() |
| 71 | + |
| 72 | + futures = [] |
| 73 | + for handler, configuration in slack.routers["message"].dispatch(event): |
| 74 | + if configuration["mention"] and not mention: |
| 75 | + continue |
| 76 | + elif configuration["admin"] and event["user"] not in slack.admins: |
| 77 | + continue |
| 78 | + |
| 79 | + f = asyncio.ensure_future(handler(event, request.app)) |
| 80 | + if configuration["wait"]: |
| 81 | + futures.append(f) |
| 82 | + else: |
| 83 | + f.add_done_callback(_callback) |
| 84 | + |
| 85 | + if futures: |
| 86 | + return await _wait_and_check_result(futures) |
| 87 | + |
| 88 | + return Response(status=200) |
| 89 | + |
| 90 | + |
| 91 | +async def incoming_command(request): |
| 92 | + slack = request.app.plugins["slack"] |
| 93 | + payload = await request.post() |
| 94 | + |
| 95 | + try: |
| 96 | + verification_token = await _validate_request(request, slack) |
| 97 | + command = Command(payload, verification_token=verification_token) |
| 98 | + except (FailedVerification, InvalidSlackSignature, InvalidTimestamp): |
| 99 | + return Response(status=401) |
| 100 | + |
| 101 | + LOG.debug("Incoming command: %s", command) |
| 102 | + futures = list(_dispatch(slack.routers["command"], command, request.app)) |
| 103 | + if futures: |
| 104 | + return await _wait_and_check_result(futures) |
| 105 | + |
| 106 | + return Response(status=200) |
| 107 | + |
| 108 | + |
| 109 | +async def incoming_action(request): |
| 110 | + slack = request.app.plugins["slack"] |
| 111 | + payload = await request.post() |
| 112 | + LOG.log(5, "Incoming action payload: %s", payload) |
| 113 | + |
| 114 | + try: |
| 115 | + verification_token = await _validate_request(request, slack) |
| 116 | + action = Action.from_http(payload, verification_token=verification_token) |
| 117 | + except (FailedVerification, InvalidSlackSignature, InvalidTimestamp): |
| 118 | + return Response(status=401) |
| 119 | + |
| 120 | + LOG.debug("Incoming action: %s", action) |
| 121 | + |
| 122 | + futures = list(_dispatch(slack.routers["action"], action, request.app)) |
| 123 | + if futures: |
| 124 | + return await _wait_and_check_result(futures) |
| 125 | + |
| 126 | + return Response(status=200) |
| 127 | + |
| 128 | + |
| 129 | +def _callback(f): |
| 130 | + try: |
| 131 | + f.result() |
| 132 | + except Exception as e: |
| 133 | + LOG.exception(e) |
| 134 | + |
| 135 | + |
| 136 | +def _dispatch(router, event, app): |
| 137 | + for handler, configuration in router.dispatch(event): |
| 138 | + f = asyncio.ensure_future(handler(event, app)) |
| 139 | + if configuration["wait"]: |
| 140 | + yield f |
| 141 | + else: |
| 142 | + f.add_done_callback(_callback) |
| 143 | + |
| 144 | + |
| 145 | +async def _wait_and_check_result(futures): |
| 146 | + dones, _ = await asyncio.wait(futures, return_when=asyncio.ALL_COMPLETED) |
| 147 | + try: |
| 148 | + results = [done.result() for done in dones] |
| 149 | + except Exception as e: |
| 150 | + LOG.exception(e) |
| 151 | + return Response(status=500) |
| 152 | + |
| 153 | + results = [result for result in results if isinstance(result, aiohttp.web.Response)] |
| 154 | + if len(results) > 1: |
| 155 | + LOG.warning("Multiple web.Response for handler, returning none") |
| 156 | + elif results: |
| 157 | + return results[0] |
| 158 | + |
| 159 | + return Response(status=200) |
| 160 | + |
| 161 | + |
| 162 | +async def _validate_request(request, slack): |
| 163 | + if slack.signing_secret: |
| 164 | + raw_payload = await request.read() |
| 165 | + validate_request_signature( |
| 166 | + raw_payload.decode("utf-8"), request.headers, slack.signing_secret |
| 167 | + ) |
| 168 | + return None |
| 169 | + else: |
| 170 | + return slack.verify |
0 commit comments