From cf054631e85f405fe8a25a58caaedaa95aadeed5 Mon Sep 17 00:00:00 2001 From: Jochen Kupperschmidt Date: Sun, 27 Dec 2020 14:07:04 +0100 Subject: [PATCH 1/5] Extract room ID into variable --- matrix_webhook.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/matrix_webhook.py b/matrix_webhook.py index 5ffb69f..9e5fb44 100755 --- a/matrix_webhook.py +++ b/matrix_webhook.py @@ -43,6 +43,7 @@ async def handler(request): status, ret = HTTPStatus.UNAUTHORIZED, 'I need the good "key"' if data['key'] == API_KEY: status, ret = HTTPStatus.OK, 'OK' + room_id = str(request.rel_url)[1:] content = { "msgtype": "m.text", "body": data['text'], @@ -50,12 +51,12 @@ async def handler(request): "formatted_body": markdown(data['text'], extensions=['extra']), } try: - await CLIENT.room_send(room_id=str(request.rel_url)[1:], + await CLIENT.room_send(room_id=room_id, message_type="m.room.message", content=content) except LocalProtocolError: # Connection lost, try another login await CLIENT.login(MATRIX_PW) - await CLIENT.room_send(room_id=str(request.rel_url)[1:], + await CLIENT.room_send(room_id=room_id, message_type="m.room.message", content=content) From 54baf29d513aca87f79e969efc51064d0669f2ad Mon Sep 17 00:00:00 2001 From: Jochen Kupperschmidt Date: Sun, 27 Dec 2020 14:11:51 +0100 Subject: [PATCH 2/5] Extract function to send message Merges duplicated code. --- matrix_webhook.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/matrix_webhook.py b/matrix_webhook.py index 9e5fb44..903c4bb 100755 --- a/matrix_webhook.py +++ b/matrix_webhook.py @@ -51,20 +51,23 @@ async def handler(request): "formatted_body": markdown(data['text'], extensions=['extra']), } try: - await CLIENT.room_send(room_id=room_id, - message_type="m.room.message", - content=content) + await send_room_message(room_id, content) except LocalProtocolError: # Connection lost, try another login await CLIENT.login(MATRIX_PW) - await CLIENT.room_send(room_id=room_id, - message_type="m.room.message", - content=content) + await send_room_message(room_id, content) return web.Response(text='{"status": %i, "ret": "%s"}' % (status, ret), content_type='application/json', status=status) +async def send_room_message(room_id, content): + """Send a message to a room.""" + return await CLIENT.room_send(room_id=room_id, + message_type='m.room.message', + content=content) + + async def main(event): """ Launch main coroutine. From 139ec1670cbeb6515665ab97035bdf9e0f2c5861 Mon Sep 17 00:00:00 2001 From: Jochen Kupperschmidt Date: Sun, 27 Dec 2020 14:37:54 +0100 Subject: [PATCH 3/5] Use `aiohttp.web.json_response()` Avoids explicit setting of JSON content type, handles serialization to JSON. --- matrix_webhook.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/matrix_webhook.py b/matrix_webhook.py index 903c4bb..12f47d2 100755 --- a/matrix_webhook.py +++ b/matrix_webhook.py @@ -56,9 +56,13 @@ async def handler(request): await CLIENT.login(MATRIX_PW) await send_room_message(room_id, content) - return web.Response(text='{"status": %i, "ret": "%s"}' % (status, ret), - content_type='application/json', - status=status) + return create_json_response(status, ret) + + +def create_json_response(status, ret): + """Create a JSON response.""" + response_data = {'status': status, 'ret': ret} + return web.json_response(response_data, status=status) async def send_room_message(room_id, content): From 78b9533e2bd0c567cea0f4e150dd4ac884a19e0e Mon Sep 17 00:00:00 2001 From: Jochen Kupperschmidt Date: Sun, 27 Dec 2020 14:50:52 +0100 Subject: [PATCH 4/5] Exit early after each request check Keeps the "happy path" on the function's base indentation level. Avoids carrying status and return value variables, pre-filled in anticipation of an error, along. --- matrix_webhook.py | 43 +++++++++++++++++++++++-------------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/matrix_webhook.py b/matrix_webhook.py index 12f47d2..6a88346 100755 --- a/matrix_webhook.py +++ b/matrix_webhook.py @@ -33,30 +33,33 @@ async def handler(request): This one handles a POST, checks its content, and forwards it to the matrix room. """ data = await request.read() + try: data = json.loads(data.decode()) - status, ret = HTTPStatus.BAD_REQUEST, 'I need a json dict with text & key' except json.decoder.JSONDecodeError: - data = {} - status, ret = HTTPStatus.BAD_REQUEST, 'This was not valid JSON' - if all(key in data for key in ['text', 'key']): - status, ret = HTTPStatus.UNAUTHORIZED, 'I need the good "key"' - if data['key'] == API_KEY: - status, ret = HTTPStatus.OK, 'OK' - room_id = str(request.rel_url)[1:] - content = { - "msgtype": "m.text", - "body": data['text'], - "format": "org.matrix.custom.html", - "formatted_body": markdown(data['text'], extensions=['extra']), - } - try: - await send_room_message(room_id, content) - except LocalProtocolError: # Connection lost, try another login - await CLIENT.login(MATRIX_PW) - await send_room_message(room_id, content) + return create_json_response(HTTPStatus.BAD_REQUEST, 'Invalid JSON') - return create_json_response(status, ret) + if not all(key in data for key in ['text', 'key']): + return create_json_response(HTTPStatus.BAD_REQUEST, + 'Missing text and/or API key property') + + if data['key'] != API_KEY: + return create_json_response(HTTPStatus.UNAUTHORIZED, 'Invalid API key') + + room_id = str(request.rel_url)[1:] + content = { + "msgtype": "m.text", + "body": data['text'], + "format": "org.matrix.custom.html", + "formatted_body": markdown(data['text'], extensions=['extra']), + } + try: + await send_room_message(room_id, content) + except LocalProtocolError: # Connection lost, try another login + await CLIENT.login(MATRIX_PW) + await send_room_message(room_id, content) + + return create_json_response(HTTPStatus.OK, 'OK') def create_json_response(status, ret): From 00f47f99a923ceb845d2e1606c4ddb45dfdce08f Mon Sep 17 00:00:00 2001 From: Jochen Kupperschmidt Date: Sun, 27 Dec 2020 14:57:14 +0100 Subject: [PATCH 5/5] Unify use of single quotes for non-docstring string literals --- matrix_webhook.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/matrix_webhook.py b/matrix_webhook.py index 6a88346..2f8482e 100755 --- a/matrix_webhook.py +++ b/matrix_webhook.py @@ -48,10 +48,10 @@ async def handler(request): room_id = str(request.rel_url)[1:] content = { - "msgtype": "m.text", - "body": data['text'], - "format": "org.matrix.custom.html", - "formatted_body": markdown(data['text'], extensions=['extra']), + 'msgtype': 'm.text', + 'body': data['text'], + 'format': 'org.matrix.custom.html', + 'formatted_body': markdown(data['text'], extensions=['extra']), } try: await send_room_message(room_id, content)