2020-08-31 15:32:30 +02:00
|
|
|
from abc import ABC, abstractmethod
|
2019-12-27 15:55:56 +01:00
|
|
|
import datetime
|
2017-12-22 00:49:03 +01:00
|
|
|
import logging
|
2017-12-17 16:15:44 +01:00
|
|
|
import inspect
|
|
|
|
import json
|
2018-10-08 12:35:56 +02:00
|
|
|
import time
|
2020-08-31 15:32:30 +02:00
|
|
|
from typing import Union
|
2017-12-17 16:15:44 +01:00
|
|
|
|
2020-09-27 01:33:38 +02:00
|
|
|
logger = logging.getLogger('platypush')
|
2018-06-06 20:09:18 +02:00
|
|
|
|
2017-12-22 00:49:03 +01:00
|
|
|
|
2020-08-31 15:32:30 +02:00
|
|
|
class JSONAble(ABC):
|
|
|
|
"""
|
|
|
|
Generic interface for JSON-able objects.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@abstractmethod
|
|
|
|
def to_json(self) -> Union[str, list, dict]:
|
|
|
|
raise NotImplementedError()
|
|
|
|
|
|
|
|
|
2017-12-17 16:15:44 +01:00
|
|
|
class Message(object):
|
2021-11-15 01:05:53 +01:00
|
|
|
"""
|
|
|
|
Message generic class
|
|
|
|
"""
|
2017-12-17 16:15:44 +01:00
|
|
|
|
2019-12-27 23:26:39 +01:00
|
|
|
class Encoder(json.JSONEncoder):
|
2020-03-14 18:35:45 +01:00
|
|
|
@staticmethod
|
|
|
|
def parse_numpy(obj):
|
|
|
|
try:
|
|
|
|
import numpy as np
|
|
|
|
except ImportError:
|
|
|
|
return
|
|
|
|
|
|
|
|
if isinstance(obj, np.floating):
|
|
|
|
return float(obj)
|
|
|
|
if isinstance(obj, np.integer):
|
|
|
|
return int(obj)
|
|
|
|
if isinstance(obj, np.ndarray):
|
|
|
|
return obj.tolist()
|
2020-04-12 22:56:12 +02:00
|
|
|
if callable(obj):
|
|
|
|
return '<function at {}.{}>'.format(obj.__module__, obj.__name__)
|
2020-03-14 18:35:45 +01:00
|
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def parse_datetime(obj):
|
2019-12-27 23:26:39 +01:00
|
|
|
if isinstance(obj, datetime.datetime) or \
|
|
|
|
isinstance(obj, datetime.date) or \
|
|
|
|
isinstance(obj, datetime.time):
|
|
|
|
return obj.isoformat()
|
|
|
|
|
2020-03-14 18:35:45 +01:00
|
|
|
def default(self, obj):
|
|
|
|
value = self.parse_datetime(obj)
|
|
|
|
if value is not None:
|
|
|
|
return value
|
|
|
|
|
2020-02-20 02:34:28 +01:00
|
|
|
if isinstance(obj, set):
|
|
|
|
return list(obj)
|
|
|
|
|
2020-03-14 18:35:45 +01:00
|
|
|
value = self.parse_numpy(obj)
|
|
|
|
if value is not None:
|
|
|
|
return value
|
|
|
|
|
2020-08-31 15:32:30 +02:00
|
|
|
if isinstance(obj, JSONAble):
|
|
|
|
return obj.to_json()
|
|
|
|
|
2020-08-31 18:26:08 +02:00
|
|
|
try:
|
|
|
|
return super().default(obj)
|
|
|
|
except Exception as e:
|
|
|
|
logger.warning('Could not serialize object type {}: {}: {}'.format(
|
|
|
|
type(obj), str(e), obj))
|
2019-12-27 23:26:39 +01:00
|
|
|
|
2018-10-08 15:30:00 +02:00
|
|
|
def __init__(self, timestamp=None, *args, **kwargs):
|
|
|
|
self.timestamp = timestamp or time.time()
|
|
|
|
|
2017-12-17 16:15:44 +01:00
|
|
|
def __str__(self):
|
|
|
|
"""
|
|
|
|
Overrides the str() operator and converts
|
|
|
|
the message into a UTF-8 JSON string
|
|
|
|
"""
|
|
|
|
|
|
|
|
return json.dumps({
|
|
|
|
attr: getattr(self, attr)
|
|
|
|
for attr in self.__dir__()
|
2018-10-08 12:35:56 +02:00
|
|
|
if (attr != '_timestamp' or not attr.startswith('_'))
|
2017-12-17 16:15:44 +01:00
|
|
|
and not inspect.ismethod(getattr(self, attr))
|
2019-12-27 23:26:39 +01:00
|
|
|
}, cls=self.Encoder).replace('\n', ' ')
|
2017-12-17 16:15:44 +01:00
|
|
|
|
|
|
|
def __bytes__(self):
|
|
|
|
"""
|
|
|
|
Overrides the bytes() operator, converts the message into
|
|
|
|
its JSON-serialized UTF-8-encoded representation
|
|
|
|
"""
|
|
|
|
return str(self).encode('utf-8')
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def parse(cls, msg):
|
|
|
|
"""
|
|
|
|
Parse a generic message into a key-value dictionary
|
|
|
|
Params:
|
|
|
|
msg -- Original message - can be a dictionary, a Message,
|
|
|
|
or a string/bytearray, as long as it's valid UTF-8 JSON
|
|
|
|
"""
|
|
|
|
|
|
|
|
if isinstance(msg, cls):
|
|
|
|
msg = str(msg)
|
|
|
|
if isinstance(msg, bytes) or isinstance(msg, bytearray):
|
|
|
|
msg = msg.decode('utf-8')
|
|
|
|
if isinstance(msg, str):
|
2017-12-22 00:49:03 +01:00
|
|
|
try:
|
|
|
|
msg = json.loads(msg.strip())
|
2021-04-05 00:58:44 +02:00
|
|
|
except (ValueError, TypeError):
|
2018-06-06 20:09:18 +02:00
|
|
|
logger.warning('Invalid JSON message: {}'.format(msg))
|
2017-12-17 16:15:44 +01:00
|
|
|
|
|
|
|
assert isinstance(msg, dict)
|
2018-10-08 12:35:56 +02:00
|
|
|
|
2019-12-25 20:32:54 +01:00
|
|
|
if '_timestamp' not in msg:
|
2018-10-08 12:35:56 +02:00
|
|
|
msg['_timestamp'] = time.time()
|
|
|
|
|
2017-12-17 16:15:44 +01:00
|
|
|
return msg
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def build(cls, msg):
|
|
|
|
"""
|
|
|
|
Builds a Message object from a dictionary.
|
|
|
|
Params:
|
2017-12-22 00:49:03 +01:00
|
|
|
msg -- The message as a key-value dictionary, Message object or JSON string
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
2017-12-22 00:49:03 +01:00
|
|
|
from platypush.utils import get_message_class_by_type
|
|
|
|
|
|
|
|
msg = cls.parse(msg)
|
|
|
|
msgtype = get_message_class_by_type(msg['type'])
|
2019-12-25 20:32:54 +01:00
|
|
|
if msgtype != cls:
|
|
|
|
return msgtype.build(msg)
|
2017-12-17 16:15:44 +01:00
|
|
|
|
|
|
|
|
2019-12-25 20:32:54 +01:00
|
|
|
class Mapping(dict):
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super().__init__(*args, **kwargs)
|
2019-12-27 15:55:56 +01:00
|
|
|
for k, v in kwargs.items():
|
|
|
|
self.__setattr__(k, v)
|
2019-12-25 20:32:54 +01:00
|
|
|
|
|
|
|
def __setitem__(self, key, item):
|
|
|
|
self.__dict__[key] = item
|
|
|
|
|
|
|
|
def __getitem__(self, key):
|
|
|
|
return self.__dict__[key]
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return repr(self.__dict__)
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return len(self.__dict__)
|
|
|
|
|
|
|
|
def __delitem__(self, key):
|
|
|
|
del self.__dict__[key]
|
|
|
|
|
|
|
|
def clear(self):
|
|
|
|
return self.__dict__.clear()
|
|
|
|
|
|
|
|
def copy(self):
|
|
|
|
return self.__dict__.copy()
|
|
|
|
|
|
|
|
def has_key(self, k):
|
|
|
|
return k in self.__dict__
|
|
|
|
|
|
|
|
def update(self, *args, **kwargs):
|
|
|
|
return self.__dict__.update(*args, **kwargs)
|
|
|
|
|
|
|
|
def keys(self):
|
|
|
|
return self.__dict__.keys()
|
|
|
|
|
|
|
|
def values(self):
|
|
|
|
return self.__dict__.values()
|
|
|
|
|
|
|
|
def items(self):
|
|
|
|
return self.__dict__.items()
|
|
|
|
|
|
|
|
def pop(self, *args):
|
|
|
|
return self.__dict__.pop(*args)
|
|
|
|
|
|
|
|
def __cmp__(self, dict_):
|
|
|
|
return self.__cmp__(dict_)
|
|
|
|
|
|
|
|
def __contains__(self, item):
|
|
|
|
return item in self.__dict__
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
return iter(self.__dict__)
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return str(self.__dict__)
|
|
|
|
|
|
|
|
|
|
|
|
# vim:sw=4:ts=4:et:
|