feat: extract nostr_client class

This commit is contained in:
Vlad Stan 2023-03-16 16:01:14 +02:00
parent 45c7744282
commit f6b5034e74
5 changed files with 90 additions and 97 deletions

View file

@ -1,11 +1,5 @@
import asyncio
import json
from asyncio import Queue
import websocket
from loguru import logger
from websocket import WebSocketApp
from lnbits.core.models import Payment
from lnbits.tasks import register_invoice_listener
@ -14,7 +8,7 @@ from .crud import (
get_last_order_time,
get_public_keys_for_merchants,
)
from .nostr.nostr_client import connect_to_nostrclient_ws, subscribe_to_direct_messages
from .nostr.nostr_client import NostrClient
from .services import handle_order_paid, process_nostr_message
@ -39,41 +33,15 @@ async def on_invoice_paid(payment: Payment) -> None:
await handle_order_paid(order_id, merchant_pubkey)
async def subscribe_to_nostr_client(recieve_event_queue: Queue, send_req_queue: Queue):
def on_open(_):
logger.info("Connected to 'nostrclient' websocket")
def on_message(_, message):
# print("### on_message", message)
recieve_event_queue.put_nowait(message)
ws: WebSocketApp = None
while True:
try:
req = None
if not ws:
ws = await connect_to_nostrclient_ws(on_open, on_message)
# be sure the connection is open
await asyncio.sleep(3)
req = await send_req_queue.get()
ws.send(json.dumps(req))
except Exception as ex:
logger.warning(ex)
if req:
await send_req_queue.put(req)
ws = None # todo close
await asyncio.sleep(5)
async def wait_for_nostr_events(recieve_event_queue: Queue):
async def wait_for_nostr_events(nostr_client: NostrClient):
public_keys = await get_public_keys_for_merchants()
for p in public_keys:
last_order_time = await get_last_order_time(p)
last_dm_time = await get_last_direct_messages_time(p)
since = max(last_order_time, last_dm_time)
await subscribe_to_direct_messages(p, since)
await nostr_client.subscribe_to_direct_messages(p, since)
while True:
message = await recieve_event_queue.get()
message = await nostr_client.get_event()
await process_nostr_message(message)