From 984eab1dd3e5df317e3629f34127ead6617251a8 Mon Sep 17 00:00:00 2001 From: Niklas Halle Date: Mon, 24 Aug 2020 15:56:31 +0200 Subject: add mark_read and mark every message handled as read --- signald/main.py | 44 +++++++++++++++++++++++++++----------------- 1 file changed, 27 insertions(+), 17 deletions(-) diff --git a/signald/main.py b/signald/main.py index cfaa79c..4a54707 100644 --- a/signald/main.py +++ b/signald/main.py @@ -10,8 +10,8 @@ from .types import Attachment, Message RE_TYPE = type(re.compile("")) -def readlines(s: socket.socket) -> Iterator[bytes]: - "Read a socket, line by line." +def read_lines(s: socket.socket) -> Iterator[bytes]: + """Read a socket, line by line.""" buf = [] # type: List[bytes] while True: char = s.recv(1) @@ -31,12 +31,8 @@ class Signal: self.socket_path = socket_path self._chat_handlers = [] - def _get_id(self): - "Generate a random ID." - return "".join(random.choice("abcdefghijklmnopqrstuvwxyz0123456789") for _ in range(10)) - def _get_socket(self) -> socket.socket: - "Create a socket, connect to the server and return it." + """Create a socket, connect to the server and return it.""" # Support TCP sockets on the sly. if isinstance(self.socket_path, tuple): @@ -48,7 +44,7 @@ class Signal: def _send_command(self, payload: dict, block: bool = False): s = self._get_socket() - msg_id = self._get_id() + msg_id = _get_id() payload["id"] = msg_id s.recv(1024) # Flush the buffer. s.send(json.dumps(payload).encode("utf8") + b"\n") @@ -87,21 +83,29 @@ class Signal: payload = {"type": "verify", "username": self.username, "code": code} self._send_command(payload) + def mark_read(self, message: Message): + """ + Mark the given message as read + """ + payload = {"type": "mark_read", "username": self.username, "recipientAddress": message.source, + "timestamps": [message.timestamp]} + self._send_command(payload) + def receive_messages(self) -> Iterator[Message]: - "Keep returning received messages." + """Keep returning received messages.""" s = self._get_socket() s.send(json.dumps({"type": "subscribe", "username": self.username}).encode("utf8") + b"\n") - for line in readlines(s): + for line in read_lines(s): + message = json.loads("{}") try: message = json.loads(line.decode()) except json.JSONDecodeError: print("Invalid JSON") - #print("type: " + message.get("type")) - if message.get("type") != "message": #or ( - #not message["data"]["isReceipt"] and message["data"].get("dataMessage") is None - #): + if message.get("type") != "message" or ( + not message["data"]["is_receipt"] and message["data"].get("dataMessage") is None + ): # If the message type isn't "message", or if it's a weird message whose # purpose I don't know, return. I think the weird message is a typing # notification. @@ -118,7 +122,7 @@ class Signal: timestamp=data_message.get("timestamp"), timestamp_iso=message["timestampISO"], expiration_secs=data_message.get("expiresInSeconds"), -# is_receipt=message["isReceipt"], + is_receipt=message["is_receipt"], group_info=data_message.get("group", {}), attachments=[ Attachment( @@ -141,7 +145,6 @@ class Signal: are any errors. """ payload = {"type": "send", "username": self.username, "recipientAddress": recipient, "messageBody": text} -# print(f"payload: {payload}") self._send_command(payload, block) def send_group_message(self, recipient_group_id: str, text: str, block: bool = False) -> None: @@ -183,12 +186,14 @@ class Signal: for message in self.receive_messages(): if not message.text: continue - #print("text: " + message.text) for _, regex, func in self._chat_handlers: match = re.search(regex, message.text) if not match: continue + # mark every message that we read and forward as read + self.mark_read(message) + try: reply = func(message, match) except: # noqa - We don't care why this failed. @@ -210,3 +215,8 @@ class Signal: if stop: # We don't want to continue matching things. break + + +def _get_id(): + """Generate a random ID.""" + return "".join(random.choice("abcdefghijklmnopqrstuvwxyz0123456789") for _ in range(10)) -- cgit v1.2.3-54-g00ecf