From 46be979d34c7910514938e6c3568d69e3be72ff2 Mon Sep 17 00:00:00 2001
From: Nico Alt <nicoalt@posteo.org>
Date: Thu, 16 Jul 2020 13:52:27 -0400
Subject: [PATCH] Add method to watch connection state of contacts

Related to:
* https://code.briarproject.org/briar/briar-gtk/-/issues/19
* https://code.briarproject.org/briar/briar/-/merge_requests/1260
---
 briar_wrapper/models/contacts.py | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)

diff --git a/briar_wrapper/models/contacts.py b/briar_wrapper/models/contacts.py
index 9619c28..bbef463 100644
--- a/briar_wrapper/models/contacts.py
+++ b/briar_wrapper/models/contacts.py
@@ -15,6 +15,9 @@ from briar_wrapper.model import Model
 class Contacts(Model):
 
     API_ENDPOINT = "contacts/"
+    CONNECTION_EVENTS = ("ContactConnectedEvent", "ContactDisconnectedEvent")
+
+    _connections_callback = None
 
     def add_pending(self, link, alias):
         url = urljoin(BASE_HTTP_URL, self.API_ENDPOINT + "add/pending/")
@@ -32,6 +35,24 @@ class Contacts(Model):
         request = _get(url, headers=self._headers).json()
         return request['link']
 
+    def watch_connections(self, callback):
+        self._connections_callback = callback
+        signal_ids = list()
+        event_callback = self._handle_connections_callback
+        for event in self.CONNECTION_EVENTS:
+            signal_id = self._api.socket_listener.connect(event, event_callback)
+            signal_ids.append(signal_id)
+        return signal_ids
+
+    def _handle_connections_callback(self, message):
+        contact_id = message["data"]["contactId"]
+        if message["name"] == "ContactConnectedEvent":
+            self._connections_callback(contact_id, True)
+        elif message["name"] == "ContactDisconnectedEvent":
+            self._connections_callback(contact_id, False)
+        else:
+            raise Exception(f"Wrong event in callback: {message['name']}")
+
     def _sort_contact_list(contacts):
         contacts.sort(key=itemgetter("lastChatActivity"),
                       reverse=True)
-- 
GitLab