2018-01-04 23:10:53 +01:00
|
|
|
import copy
|
2017-12-24 01:03:26 +01:00
|
|
|
import json
|
|
|
|
import logging
|
2018-11-28 01:01:16 +01:00
|
|
|
import threading
|
2020-04-08 23:22:54 +02:00
|
|
|
from functools import wraps
|
2017-12-24 01:03:26 +01:00
|
|
|
|
2021-02-27 20:27:36 +01:00
|
|
|
from platypush.common import exec_wrapper
|
2017-12-24 01:03:26 +01:00
|
|
|
from platypush.config import Config
|
2020-04-08 23:22:54 +02:00
|
|
|
from platypush.message.event import Event
|
2017-12-24 01:03:26 +01:00
|
|
|
from platypush.message.request import Request
|
2018-09-27 01:52:35 +02:00
|
|
|
from platypush.procedure import Procedure
|
2020-04-08 23:22:54 +02:00
|
|
|
from platypush.utils import get_event_class_by_type, set_thread_name, is_functional_hook
|
2017-12-24 01:03:26 +01:00
|
|
|
|
2020-09-27 01:33:38 +02:00
|
|
|
logger = logging.getLogger('platypush')
|
2018-06-06 20:09:18 +02:00
|
|
|
|
2017-12-24 01:03:26 +01:00
|
|
|
|
|
|
|
def parse(msg):
|
|
|
|
""" Builds a dict given another dictionary or
|
|
|
|
a JSON UTF-8 encoded string/bytearray """
|
|
|
|
|
|
|
|
if isinstance(msg, bytes) or isinstance(msg, bytearray):
|
|
|
|
msg = msg.decode('utf-8')
|
|
|
|
if isinstance(msg, str):
|
|
|
|
try:
|
|
|
|
msg = json.loads(msg.strip())
|
2020-04-08 23:22:54 +02:00
|
|
|
except json.JSONDecodeError:
|
2018-06-06 20:09:18 +02:00
|
|
|
logger.warning('Invalid JSON message: {}'.format(msg))
|
2017-12-24 01:03:26 +01:00
|
|
|
return None
|
|
|
|
|
|
|
|
return msg
|
|
|
|
|
|
|
|
|
|
|
|
class EventCondition(object):
|
|
|
|
""" Event hook condition class """
|
|
|
|
|
2018-01-05 10:09:02 +01:00
|
|
|
def __init__(self, type=Event.__class__, priority=None, **kwargs):
|
2017-12-24 01:03:26 +01:00
|
|
|
"""
|
|
|
|
Rule constructor.
|
|
|
|
Params:
|
|
|
|
type -- Class of the event to be built
|
|
|
|
kwargs -- Fields rules as a key-value (e.g. source_button=btn_id
|
|
|
|
or recognized_phrase='Your phrase')
|
|
|
|
"""
|
|
|
|
|
|
|
|
self.type = type
|
|
|
|
self.args = {}
|
|
|
|
self.parsed_args = {}
|
2018-01-05 10:09:02 +01:00
|
|
|
self.priority = priority
|
2017-12-24 01:03:26 +01:00
|
|
|
|
|
|
|
for (key, value) in kwargs.items():
|
|
|
|
# TODO So far we only allow simple value match. If value is a dict
|
|
|
|
# instead, we should allow more a sophisticated attribute matching,
|
|
|
|
# e.g. or conditions, in, and other operators.
|
|
|
|
self.args[key] = value
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def build(cls, rule):
|
|
|
|
""" Builds a rule given either another EventRule, a dictionary or
|
|
|
|
a JSON UTF-8 encoded string/bytearray """
|
|
|
|
|
2020-04-08 23:22:54 +02:00
|
|
|
if isinstance(rule, cls):
|
|
|
|
return rule
|
|
|
|
else:
|
|
|
|
rule = parse(rule)
|
2017-12-24 01:03:26 +01:00
|
|
|
|
2020-04-08 23:22:54 +02:00
|
|
|
assert isinstance(rule, dict)
|
2017-12-24 01:03:26 +01:00
|
|
|
type = get_event_class_by_type(
|
|
|
|
rule.pop('type') if 'type' in rule else 'Event')
|
|
|
|
|
|
|
|
args = {}
|
|
|
|
for (key, value) in rule.items():
|
|
|
|
args[key] = value
|
|
|
|
|
|
|
|
return cls(type=type, **args)
|
|
|
|
|
|
|
|
|
|
|
|
class EventAction(Request):
|
|
|
|
""" Event hook action class. It is a special type of runnable request
|
|
|
|
whose fields can be configured later depending on the event context """
|
|
|
|
|
2018-01-02 19:44:58 +01:00
|
|
|
def __init__(self, target=None, action=None, **args):
|
2020-04-08 23:22:54 +02:00
|
|
|
if target is None:
|
|
|
|
target = Config.get('device_id')
|
2021-09-16 17:53:40 +02:00
|
|
|
args_copy = dict(copy.deepcopy(args))
|
2018-01-04 23:10:53 +01:00
|
|
|
super().__init__(target=target, action=action, **args_copy)
|
2017-12-24 01:03:26 +01:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def build(cls, action):
|
|
|
|
action = super().parse(action)
|
|
|
|
action['origin'] = Config.get('device_id')
|
|
|
|
|
|
|
|
if 'target' not in action:
|
|
|
|
action['target'] = action['origin']
|
2018-07-06 02:08:38 +02:00
|
|
|
|
|
|
|
token = Config.get('token')
|
|
|
|
if token:
|
|
|
|
action['token'] = token
|
|
|
|
|
2017-12-24 01:03:26 +01:00
|
|
|
return super().build(action)
|
|
|
|
|
2018-01-03 00:16:01 +01:00
|
|
|
|
2017-12-24 01:03:26 +01:00
|
|
|
class EventHook(object):
|
2020-04-08 23:22:54 +02:00
|
|
|
""" Event hook class. It consists of one conditions and
|
2017-12-24 01:03:26 +01:00
|
|
|
one or multiple actions to be executed """
|
|
|
|
|
2020-04-08 23:22:54 +02:00
|
|
|
def __init__(self, name, priority=None, condition=None, actions=None):
|
|
|
|
""" Constructor. Takes a name, a EventCondition object and an event action
|
2018-09-27 01:52:35 +02:00
|
|
|
procedure as input. It may also have a priority attached
|
2018-01-04 19:19:56 +01:00
|
|
|
as a positive number. If multiple hooks match against an event,
|
|
|
|
only the ones that have either the maximum match score or the
|
|
|
|
maximum pre-configured priority will be run. """
|
2017-12-24 01:03:26 +01:00
|
|
|
|
|
|
|
self.name = name
|
|
|
|
self.condition = EventCondition.build(condition or {})
|
2020-04-08 23:22:54 +02:00
|
|
|
self.actions = actions or []
|
2018-01-04 19:19:56 +01:00
|
|
|
self.priority = priority or 0
|
2018-01-05 10:09:02 +01:00
|
|
|
self.condition.priority = self.priority
|
2017-12-24 01:03:26 +01:00
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def build(cls, name, hook):
|
|
|
|
""" Builds a rule given either another EventRule, a dictionary or
|
|
|
|
a JSON UTF-8 encoded string/bytearray """
|
|
|
|
|
2020-04-08 23:22:54 +02:00
|
|
|
if isinstance(hook, cls):
|
|
|
|
return hook
|
|
|
|
else:
|
|
|
|
hook = parse(hook)
|
2017-12-24 01:03:26 +01:00
|
|
|
|
2020-04-08 23:22:54 +02:00
|
|
|
if is_functional_hook(hook):
|
|
|
|
actions = Procedure(name=name, requests=[hook], _async=False)
|
|
|
|
return cls(name=name, condition=hook.condition, actions=actions)
|
|
|
|
|
|
|
|
assert isinstance(hook, dict)
|
2017-12-24 01:03:26 +01:00
|
|
|
condition = EventCondition.build(hook['if']) if 'if' in hook else None
|
|
|
|
actions = []
|
2018-01-04 19:19:56 +01:00
|
|
|
priority = hook['priority'] if 'priority' in hook else None
|
2018-01-05 10:09:02 +01:00
|
|
|
condition.priority = priority
|
2018-01-04 19:19:56 +01:00
|
|
|
|
2017-12-24 01:03:26 +01:00
|
|
|
if 'then' in hook:
|
|
|
|
if isinstance(hook['then'], list):
|
2018-01-04 23:10:53 +01:00
|
|
|
actions = hook['then']
|
2017-12-24 01:03:26 +01:00
|
|
|
else:
|
2018-01-04 23:10:53 +01:00
|
|
|
actions = [hook['then']]
|
2017-12-24 01:03:26 +01:00
|
|
|
|
2020-04-08 23:22:54 +02:00
|
|
|
actions = Procedure.build(name=name + '__Hook', requests=actions, _async=False)
|
2018-01-04 19:19:56 +01:00
|
|
|
return cls(name=name, condition=condition, actions=actions, priority=priority)
|
2017-12-24 01:03:26 +01:00
|
|
|
|
2017-12-24 13:15:37 +01:00
|
|
|
def matches_event(self, event):
|
|
|
|
""" Returns an EventMatchResult object containing the information
|
|
|
|
about the match between the event and this hook """
|
|
|
|
|
|
|
|
return event.matches_condition(self.condition)
|
|
|
|
|
2017-12-24 01:03:26 +01:00
|
|
|
def run(self, event):
|
|
|
|
""" Checks the condition of the hook against a particular event and
|
|
|
|
runs the hook actions if the condition is met """
|
|
|
|
|
2018-11-28 01:01:16 +01:00
|
|
|
def _thread_func(result):
|
2019-01-13 20:41:15 +01:00
|
|
|
set_thread_name('Event-' + self.name)
|
2018-11-28 01:01:16 +01:00
|
|
|
self.actions.execute(event=event, **result.parsed_args)
|
|
|
|
|
2017-12-24 13:15:37 +01:00
|
|
|
result = self.matches_event(event)
|
|
|
|
|
|
|
|
if result.is_match:
|
2018-06-06 20:09:18 +02:00
|
|
|
logger.info('Running hook {} triggered by an event'.format(self.name))
|
2020-04-08 23:22:54 +02:00
|
|
|
threading.Thread(target=_thread_func, name='Event-' + self.name, args=(result,)).start()
|
2017-12-24 01:03:26 +01:00
|
|
|
|
|
|
|
|
2020-04-09 00:09:36 +02:00
|
|
|
def hook(event_type=Event, **condition):
|
|
|
|
def wrapper(f):
|
|
|
|
f.hook = True
|
|
|
|
f.condition = EventCondition(type=event_type, **condition)
|
2020-04-08 23:22:54 +02:00
|
|
|
|
2020-04-09 00:09:36 +02:00
|
|
|
@wraps(f)
|
|
|
|
def wrapped(*args, **kwargs):
|
2021-02-27 20:27:36 +01:00
|
|
|
return exec_wrapper(f, *args, **kwargs)
|
2017-12-24 01:03:26 +01:00
|
|
|
|
2020-04-09 00:09:36 +02:00
|
|
|
return wrapped
|
2020-04-08 23:22:54 +02:00
|
|
|
|
2020-04-09 00:09:36 +02:00
|
|
|
return wrapper
|
2020-04-08 23:22:54 +02:00
|
|
|
|
|
|
|
|
|
|
|
# vim:sw=4:ts=4:et:
|