2019-02-28 01:21:25 +01:00
|
|
|
import inspect
|
2020-02-24 17:17:36 +01:00
|
|
|
import logging
|
2019-02-28 01:21:25 +01:00
|
|
|
import threading
|
|
|
|
|
|
|
|
|
|
|
|
class EventGenerator(object):
|
2019-02-28 01:28:51 +01:00
|
|
|
"""
|
|
|
|
Abstract class for event generators. It allows to fire events to the bus and
|
|
|
|
trigger/register/unregister custom callback handlers associated to event
|
|
|
|
types. Both plugins and backends extend this class.
|
|
|
|
"""
|
|
|
|
|
2020-09-27 01:33:38 +02:00
|
|
|
logger = logging.getLogger('platypush')
|
2020-02-24 17:17:36 +01:00
|
|
|
|
2019-02-28 01:21:25 +01:00
|
|
|
def __init__(self, *args, **kwargs):
|
2021-04-05 00:58:44 +02:00
|
|
|
self._event_handlers = {} # Event type => callback map
|
2019-02-28 01:21:25 +01:00
|
|
|
|
|
|
|
def fire_event(self, event):
|
2021-11-17 23:59:17 +01:00
|
|
|
# Fires an event (instance of :class:`platypush.message.event.Event` or a
|
|
|
|
# subclass) to the internal bus and triggers any handler callback
|
|
|
|
# associated to the event type or any of its super-classes.
|
2019-02-28 01:21:25 +01:00
|
|
|
|
2021-04-05 00:58:44 +02:00
|
|
|
def hndl_thread(handler):
|
|
|
|
handler(event)
|
2019-02-28 01:21:25 +01:00
|
|
|
|
|
|
|
from platypush.backend import Backend
|
|
|
|
from platypush.context import get_bus
|
|
|
|
|
|
|
|
bus = self.bus if isinstance(self, Backend) else get_bus()
|
2020-02-24 17:17:36 +01:00
|
|
|
if not bus:
|
|
|
|
self.logger.warning('No bus available to post the event: {}'.format(event))
|
|
|
|
else:
|
|
|
|
bus.post(event)
|
|
|
|
|
2019-02-28 01:21:25 +01:00
|
|
|
handlers = set()
|
|
|
|
|
|
|
|
for cls in inspect.getmro(event.__class__):
|
|
|
|
if cls in self._event_handlers:
|
|
|
|
handlers.update(self._event_handlers[cls])
|
|
|
|
|
|
|
|
for hndl in handlers:
|
2021-04-05 00:58:44 +02:00
|
|
|
threading.Thread(target=hndl_thread, args=(hndl,)).start()
|
2019-02-28 01:21:25 +01:00
|
|
|
|
|
|
|
def register_handler(self, event_type, callback):
|
|
|
|
if event_type not in self._event_handlers:
|
|
|
|
self._event_handlers[event_type] = set()
|
|
|
|
self._event_handlers[event_type].add(callback)
|
|
|
|
|
|
|
|
def unregister_handler(self, event_type, callback):
|
|
|
|
if event_type not in self._event_handlers:
|
|
|
|
return
|
|
|
|
if callback not in self._event_handlers[event_type]:
|
|
|
|
return
|
|
|
|
|
|
|
|
self._event_handlers[event_type].remove(callback)
|
|
|
|
|
|
|
|
if not self._event_handlers[event_type]:
|
|
|
|
del self._event_handlers[event_type]
|
|
|
|
|
|
|
|
|
|
|
|
# vim:sw=4:ts=4:et:
|