mirror of
https://github.com/avatao-content/baseimage-tutorial-framework
synced 2024-11-05 16:31:21 +00:00
89 lines
2.5 KiB
Python
89 lines
2.5 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, key):
|
|
self.server_connector = ServerConnector()
|
|
self.key = key
|
|
self.subscriptions = set()
|
|
self.subscribe(self.key)
|
|
self.subscribe('reset')
|
|
self.server_connector.register_callback(self.event_handler_callback)
|
|
self.cenerator = cycle(cenator())
|
|
|
|
def event_handler_callback(self, msg_parts):
|
|
key, message = deserialize_all(*msg_parts)
|
|
from .message_sender import MessageSender
|
|
ms = MessageSender()
|
|
ms.send('JOHN CENA', next(self.cenerator))
|
|
response = self.dispatch_handling(key, message)
|
|
if response is None: return
|
|
self.server_connector.send(key, response)
|
|
|
|
def dispatch_handling(self, key, message):
|
|
raise NotImplementedError
|
|
|
|
def _dispatch_handling(self, key, message):
|
|
if key != 'reset': return self.handle_event(key, message)
|
|
else: return self.handle_reset(message)
|
|
|
|
def handle_event(self, key, data_json):
|
|
raise NotImplementedError
|
|
|
|
def handle_reset(self, data_json):
|
|
return None
|
|
|
|
def cleanup(self):
|
|
pass
|
|
|
|
def message_other(self, key, data):
|
|
message = {
|
|
'key': key,
|
|
'data': data
|
|
}
|
|
self.server_connector.send(key, message)
|
|
|
|
def subscribe(self, key):
|
|
if key not in self.subscriptions:
|
|
self.subscriptions.add(key)
|
|
self.server_connector.subscribe(key)
|
|
|
|
def unsubscribe(self, key):
|
|
try:
|
|
self.subscriptions.remove(key)
|
|
self.server_connector.unsubscribe(key)
|
|
except KeyError:
|
|
pass
|
|
|
|
def unsubscribe_all(self):
|
|
for sub in self.subscriptions:
|
|
self.server_connector.unsubscribe(key=sub)
|
|
self.subscriptions.clear()
|
|
|
|
|
|
class TriggerlessEventHandler(EventHandlerBase):
|
|
def dispatch_handling(self, key, message):
|
|
return self._dispatch_handling(key, message)
|
|
|
|
|
|
class TriggeredEventHandler(EventHandlerBase):
|
|
def __init__(self, key, trigger):
|
|
super().__init__(key)
|
|
self.trigger = trigger
|
|
|
|
def dispatch_handling(self, key, message):
|
|
if message.get('trigger') == self.trigger:
|
|
return self._dispatch_handling(key, message)
|