From 7ab59ec636187c8aa15c9611a348e8b28d85085b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?poljar=20=28Damir=20Jeli=C4=87=29?= Date: Mon, 12 Feb 2018 10:55:27 +0100 Subject: [PATCH] Start separating messages into their own subclasses. --- main.py | 14 +++++++++++--- matrix/api.py | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index 4b68777..a51f7a2 100644 --- a/main.py +++ b/main.py @@ -31,7 +31,12 @@ from typing import (List, Set, Dict, Tuple, Text, Optional, AnyStr, Deque, Any) from matrix.colors import Formatted from matrix.utf import utf8_decode from matrix.http import HttpResponse -from matrix.api import MatrixMessage, MessageType, matrix_login +from matrix.api import ( + MatrixMessage, + MessageType, + matrix_login, + MatrixSendMessage +) from matrix.messages import handle_http_response # Weechat searches for the registered callbacks in the scope of the main script @@ -409,8 +414,11 @@ def room_input_cb(server_name, buffer, input_data): formatted_data = Formatted.from_input_line(input_data) - message = MatrixMessage(server, OPTIONS, MessageType.SEND, room_id=room_id, - formatted_message=formatted_data) + message = MatrixSendMessage( + server.client, + room_id=room_id, + formatted_message=formatted_data + ) server.send_or_queue(message) return W.WEECHAT_RC_OK diff --git a/matrix/api.py b/matrix/api.py index f160eef..ac5db4f 100644 --- a/matrix/api.py +++ b/matrix/api.py @@ -307,6 +307,51 @@ class MatrixMessage: self.request = server.client.room_invite(self.room_id, self.user_id) +class MatrixGenericMessage(): + def __init__( + self, + message_type, # type: MessageType + request_func, # type: Callable[[...], HttpRequest] + func_args, + ): + # type: (...) -> None + self.type = message_type # type: MessageType + + self.request = None # type: HttpRequest + self.response = None # type: HttpResponse + self.decoded_response = None # type: Dict[Any, Any] + + self.creation_time = time.time() # type: float + self.send_time = None # type: float + self.receive_time = None # type: float + + self.request = request_func(**func_args) + + +class MatrixSendMessage(MatrixGenericMessage): + def __init__(self, client, room_id, formatted_message): + self.room_id = room_id + self.formatted_message = formatted_message + + assert self.room_id + assert self.formatted_message + + data = { + "room_id": self.room_id, + "content": self.formatted_message.to_plain() + } + + if self.formatted_message.is_formatted: + data["formatted_content"] = self.formatted_message.to_html() + + MatrixGenericMessage.__init__( + self, + MessageType.SEND, + client.room_send_message, + data + ) + + class MatrixUser: def __init__(self, name, display_name): self.name = name # type: str