2020-08-31 15:32:30 +02:00
|
|
|
from abc import ABC, abstractmethod
|
2023-04-24 00:43:06 +02:00
|
|
|
from dataclasses import asdict, is_dataclass
|
2022-10-29 13:35:52 +02:00
|
|
|
import decimal
|
2019-12-27 15:55:56 +01:00
|
|
|
import datetime
|
2023-03-26 03:43:04 +02:00
|
|
|
from enum import Enum
|
2023-01-25 00:52:37 +01:00
|
|
|
import io
|
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
|
2023-03-02 21:58:26 +01:00
|
|
|
from uuid import UUID
|
2017-12-17 16:15:44 +01:00
|
|
|
|
2023-07-15 01:37:49 +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()
|
|
|
|
|
|
|
|
|
2022-10-29 13:35:52 +02:00
|
|
|
class Message:
|
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()
|
2022-10-29 13:35:52 +02:00
|
|
|
if isinstance(obj, decimal.Decimal):
|
|
|
|
return float(obj)
|
2023-04-02 02:43:06 +02:00
|
|
|
if isinstance(obj, (bytes, bytearray)):
|
|
|
|
return '0x' + ''.join([f'{x:02x}' for x in obj])
|
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):
|
2022-10-29 13:35:52 +02:00
|
|
|
if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):
|
2019-12-27 23:26:39 +01:00
|
|
|
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)
|
|
|
|
|
2023-03-02 21:58:26 +01:00
|
|
|
if isinstance(obj, UUID):
|
|
|
|
return str(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()
|
|
|
|
|
2023-03-26 03:43:04 +02:00
|
|
|
if isinstance(obj, Enum):
|
|
|
|
return obj.value
|
|
|
|
|
2023-07-22 15:14:05 +02:00
|
|
|
if isinstance(obj, Exception):
|
|
|
|
return f'<{obj.__class__.__name__}>' + (f' {obj}' if obj else '')
|
|
|
|
|
2023-04-24 00:43:06 +02:00
|
|
|
if is_dataclass(obj):
|
2023-04-24 01:18:17 +02:00
|
|
|
return asdict(obj)
|
2023-04-24 00:43:06 +02:00
|
|
|
|
2023-01-25 00:52:37 +01:00
|
|
|
# Don't serialize I/O wrappers/objects
|
|
|
|
if isinstance(obj, io.IOBase):
|
|
|
|
return None
|
|
|
|
|
2020-08-31 18:26:08 +02:00
|
|
|
try:
|
|
|
|
return super().default(obj)
|
|
|
|
except Exception as e:
|
2023-07-15 01:37:49 +02:00
|
|
|
_logger.warning(
|
2023-04-24 00:43:06 +02:00
|
|
|
'Could not serialize object type %s: %s: %s', type(obj), e, obj
|
2022-10-29 13:35:52 +02:00
|
|
|
)
|
2019-12-27 23:26:39 +01:00
|
|
|
|
2022-12-11 11:39:38 +01:00
|
|
|
def __init__(self, *_, timestamp=None, logging_level=logging.INFO, **__):
|
2018-10-08 15:30:00 +02:00
|
|
|
self.timestamp = timestamp or time.time()
|
2022-12-11 11:39:38 +01:00
|
|
|
self.logging_level = logging_level
|
2023-07-15 01:37:49 +02:00
|
|
|
self._logger = _logger
|
|
|
|
self._default_log_prefix = ''
|
2022-12-11 11:39:38 +01:00
|
|
|
|
|
|
|
def log(self, prefix=''):
|
|
|
|
if self.logging_level is None:
|
|
|
|
return # Skip logging
|
|
|
|
|
2023-07-15 01:37:49 +02:00
|
|
|
log_func = self._logger.info
|
2022-12-11 11:39:38 +01:00
|
|
|
if self.logging_level == logging.DEBUG:
|
2023-07-15 01:37:49 +02:00
|
|
|
log_func = self._logger.debug
|
2022-12-11 11:39:38 +01:00
|
|
|
elif self.logging_level == logging.WARNING:
|
2023-07-15 01:37:49 +02:00
|
|
|
log_func = self._logger.warning
|
2022-12-11 11:39:38 +01:00
|
|
|
elif self.logging_level == logging.ERROR:
|
2023-07-15 01:37:49 +02:00
|
|
|
log_func = self._logger.error
|
2022-12-11 11:39:38 +01:00
|
|
|
elif self.logging_level == logging.FATAL:
|
2023-07-15 01:37:49 +02:00
|
|
|
log_func = self._logger.fatal
|
2022-12-11 11:39:38 +01:00
|
|
|
|
|
|
|
if not prefix:
|
2023-07-15 01:37:49 +02:00
|
|
|
prefix = self._default_log_prefix
|
|
|
|
log_func('%s%s', prefix, self)
|
2018-10-08 15:30:00 +02:00
|
|
|
|
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
|
|
|
|
"""
|
|
|
|
|
2022-10-29 13:35:52 +02:00
|
|
|
return json.dumps(
|
|
|
|
{
|
|
|
|
attr: getattr(self, attr)
|
|
|
|
for attr in self.__dir__()
|
|
|
|
if (attr != '_timestamp' or not attr.startswith('_'))
|
|
|
|
and not inspect.ismethod(getattr(self, attr))
|
|
|
|
},
|
|
|
|
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
|
2022-03-03 15:15:55 +01:00
|
|
|
|
|
|
|
:param msg: Original message. It can be a dictionary, a Message,
|
|
|
|
or a string/bytearray, as long as it's valid UTF-8 JSON
|
2017-12-17 16:15:44 +01:00
|
|
|
"""
|
|
|
|
|
|
|
|
if isinstance(msg, cls):
|
|
|
|
msg = str(msg)
|
2022-10-29 13:35:52 +02:00
|
|
|
if isinstance(msg, (bytes, bytearray)):
|
2017-12-17 16:15:44 +01:00
|
|
|
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):
|
2023-07-15 01:37:49 +02:00
|
|
|
_logger.warning('Invalid JSON message: %s', 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.
|
2022-03-03 15:15:55 +01:00
|
|
|
|
|
|
|
:param 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:
|