67 lines
2.6 KiB
Python
67 lines
2.6 KiB
Python
import logging
|
|
import random
|
|
import ipaddress
|
|
|
|
from libs.fspn.protocol.server import Server
|
|
from libs.fspn.protocol.connection import Connection, EVENTS as CONNECTION_EVENTS
|
|
from libs.noSys.peers import Peer, ConnectionState
|
|
from libs.noSys.noSysModule import NoSysModule
|
|
from libs.noSys.noSysModuleServer import NoSysModuleServer
|
|
from libs.noSys.events import Events as nosys_events, DynamicEvents as nosys_dynamic_events
|
|
from .rendezvousServerApiBlueprint import Blueprint
|
|
from libs.app.common.logging import get_logger
|
|
|
|
|
|
logger = get_logger("server")
|
|
RENDEZVOUS_CLIENT_MODULE = ("rendezvous", "rendezvousClient")
|
|
|
|
class RendezvousServer(NoSysModuleServer):
|
|
def __init__(self, nosys_core):
|
|
super().__init__(nosys_core)
|
|
|
|
def setup(self):
|
|
super().setup()
|
|
self.host = self.config.get("server").get("host")
|
|
self.port = self.config.get("server").get("port")
|
|
|
|
self.nosys_core.modules.api.register_blueprint(Blueprint(self).blueprint)
|
|
|
|
def on_nosys_ready(self, event):
|
|
# TODO Subscribe to event new_user in NoSys. If user in auto_start
|
|
pass
|
|
|
|
def on_connection(self, peer):
|
|
print(f"RENDEZVOUS SERVER PEER CONNECTED {peer.connection.address}")
|
|
|
|
def on_disconnection(self, peer):
|
|
print(f"RENDEZVOUS SERVER PEER DISCONNECTED {peer.connection.address}")
|
|
|
|
def on_module_message(self, event):
|
|
logger.debug(f'RENDEZVOUS SERVER {event.__dict__}')
|
|
handler_action = getattr(self, 'on_'+event.data['action'])
|
|
handler_action(event)
|
|
|
|
def on_get_random_peer(self, event):
|
|
self.send_random_peer(event.peer)
|
|
|
|
def send_random_peer(self, peer: Peer):
|
|
excepts = [peer.id]
|
|
available_peers = [x for x in self.clients.keys() if x not in excepts and self.clients[x].state == ConnectionState.CONNECTED]
|
|
|
|
chosen_peer = False
|
|
if available_peers:
|
|
rand = random.choice(available_peers)
|
|
chosen_peer = self.clients[rand]
|
|
|
|
if chosen_peer:
|
|
body = {"action":"random_peer"}
|
|
body["address"] = f'{chosen_peer.connection.address[0]}:{chosen_peer.connection.address[1]}'
|
|
self.nosys_core.dispatcher.send_message(body, peer.id, RENDEZVOUS_CLIENT_MODULE)
|
|
|
|
body["address"] = f"{peer.connection.address[0]}:{peer.connection.address[1]}"
|
|
self.nosys_core.dispatcher.send_message(body, chosen_peer.id, RENDEZVOUS_CLIENT_MODULE)
|
|
else:
|
|
body = {"action":"random_peer"}
|
|
body["address"] = None
|
|
self.nosys_core.dispatcher.send_message(body, peer.id, RENDEZVOUS_CLIENT_MODULE)
|