From e0938cb7601bf54eb94ab5328fa966031d4c7f0d Mon Sep 17 00:00:00 2001 From: callebtc <93376500+callebtc@users.noreply.github.com> Date: Tue, 11 Apr 2023 15:47:21 +0200 Subject: [PATCH] resubscribe when a new relay is added --- README.md | 2 -- services.py | 4 ++-- tasks.py | 18 ++++++++++++++++++ 3 files changed, 20 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e609b6c..5f9bfbc 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,4 @@ `nostrclient` is an always-on extension that can open multiple connections to nostr relays and act as a multiplexer for other clients: You open a single websocket to `nostrclient` which then sends the data to multiple relays. The responses from these relays are then sent back to the client. - - ![2023-03-08 18 11 07](https://user-images.githubusercontent.com/93376500/225265727-369f0f8a-196e-41df-a0d1-98b50a0228be.jpg) diff --git a/services.py b/services.py index 09e9235..b1f5ad5 100644 --- a/services.py +++ b/services.py @@ -45,7 +45,6 @@ class NostrRouter: except WebSocketDisconnect: self.connected = False break - # print(json_str) # registers a subscription if the input was a REQ request subscription_id, json_str_rewritten = await self._add_nostr_subscription( @@ -81,7 +80,7 @@ class NostrRouter: } # this reconstructs the original response from the relay - # reconstruct oriiginal subscription id + # reconstruct original subscription id s_original = s[len(f"{self.subscription_id_rewrite}_") :] event_to_forward = ["EVENT", s_original, event_json] # print(json.dumps(event_to_forward)) @@ -104,6 +103,7 @@ class NostrRouter: async def stop(self): for t in self.tasks: t.cancel() + self.connected = False def _marshall_nostr_filters(self, data: Union[dict, list]): filters = data if isinstance(data, list) else [data] diff --git a/tasks.py b/tasks.py index 7894e40..7cee5bb 100644 --- a/tasks.py +++ b/tasks.py @@ -1,5 +1,6 @@ import asyncio import ssl +import json import threading from .nostr.event import Event @@ -17,6 +18,13 @@ from .crud import get_relays async def init_relays(): + # we save any subscriptions teporarily to re-add them after reinitializing the client + subscriptions = {} + for relay in nostr.client.relay_manager.relays.values(): + # relay.add_subscription(id, filters) + for subscription_id, filters in relay.subscriptions.items(): + subscriptions[subscription_id] = filters + # reinitialize the entire client nostr.__init__() # get relays from db @@ -24,6 +32,16 @@ async def init_relays(): # set relays and connect to them nostr.client.relays = list(set([r.url for r in relays.__root__ if r.url])) nostr.client.connect() + + await asyncio.sleep(2) + # re-add subscriptions + for subscription_id, subscription in subscriptions.items(): + nostr.client.relay_manager.add_subscription( + subscription_id, subscription.filters + ) + s = subscription.to_json_object() + json_str = json.dumps(["REQ", s["id"], s["filters"][0]]) + nostr.client.relay_manager.publish_message(json_str) return