mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-09-08 23:54:09 +00:00
67 lines
1.9 KiB
Python
67 lines
1.9 KiB
Python
from itertools import cycle
|
|
|
|
from tfw.networking.serialization import deserialize_all
|
|
from tfw.networking.event_handlers.server_connector import ServerConnector
|
|
|
|
|
|
def cenator():
|
|
yield from [
|
|
'**Your time is up**',
|
|
'`My time is now`',
|
|
'_You can\'t see me_',
|
|
'My time is now'
|
|
]
|
|
|
|
|
|
class EventHandlerBase:
|
|
def __init__(self, anchor):
|
|
self.server_connector = ServerConnector()
|
|
self.anchor = anchor
|
|
self.subscriptions = set()
|
|
self.subscribe(self.anchor)
|
|
self.subscribe('reset')
|
|
self.server_connector.register_callback(self.event_handler_callback)
|
|
self.cenerator = cycle(cenator())
|
|
|
|
def event_handler_callback(self, msg_parts):
|
|
anchor, message = deserialize_all(*msg_parts)
|
|
from .message_sender import MessageSender
|
|
ms = MessageSender()
|
|
ms.send('JOHN CENA', next(self.cenerator))
|
|
response = self.handle_event(anchor, message) if anchor != 'reset' else self.handle_reset(message)
|
|
if response is None: return
|
|
self.server_connector.send(anchor, response)
|
|
|
|
def handle_event(self, anchor, data_json):
|
|
raise NotImplementedError
|
|
|
|
def handle_reset(self, data_json):
|
|
return None
|
|
|
|
def cleanup(self):
|
|
pass
|
|
|
|
def message_other(self, anchor, data):
|
|
message = {
|
|
'anchor': anchor,
|
|
'data': data
|
|
}
|
|
self.server_connector.send(anchor, message)
|
|
|
|
def subscribe(self, anchor):
|
|
if anchor not in self.subscriptions:
|
|
self.subscriptions.add(anchor)
|
|
self.server_connector.subscribe(anchor)
|
|
|
|
def unsubscribe(self, anchor):
|
|
try:
|
|
self.subscriptions.remove(anchor)
|
|
self.server_connector.unsubscribe(anchor)
|
|
except KeyError:
|
|
pass
|
|
|
|
def unsubscribe_all(self):
|
|
for sub in self.subscriptions:
|
|
self.server_connector.unsubscribe(anchor=sub)
|
|
self.subscriptions.clear()
|