platypush/platypush/message/response/__init__.py

88 lines
2.5 KiB
Python
Raw Normal View History

import json
import time
from platypush.message import Message
2019-12-11 18:05:17 +01:00
class Response(Message):
""" Response message class """
2019-12-11 18:05:17 +01:00
def __init__(self, target=None, origin=None, id=None, output=None, errors=None,
timestamp=None, disable_logging=False):
"""
Params:
target -- Target [String]
origin -- Origin [String]
output -- Output [String]
errors -- Errors [List of strings or exceptions]
id -- Message ID this response refers to
timestamp -- Message timestamp [Float]
"""
2018-10-08 15:30:00 +02:00
super().__init__(timestamp=timestamp)
self.target = target
self.output = self._parse_msg(output)
2019-12-11 18:05:17 +01:00
self.errors = self._parse_msg(errors or [])
self.origin = origin
self.id = id
self.disable_logging = disable_logging
def is_error(self):
2019-12-11 18:05:17 +01:00
""" Returns True if the response has errors """
return len(self.errors) != 0
@classmethod
def _parse_msg(cls, msg):
if isinstance(msg, bytes) or isinstance(msg, bytearray):
msg = msg.decode('utf-8')
if isinstance(msg, str):
2019-12-11 18:05:17 +01:00
try:
msg = json.loads(msg.strip())
except ValueError:
pass
return msg
@classmethod
def build(cls, msg):
msg = super().parse(msg)
args = {
2019-12-11 18:05:17 +01:00
'target': msg['target'],
'output': msg['response']['output'],
'errors': msg['response']['errors'],
'timestamp': msg['_timestamp'] if '_timestamp' in msg else time.time(),
'disable_logging': msg.get('_disable_logging', False),
}
2019-12-11 18:05:17 +01:00
if 'id' in msg:
args['id'] = msg['id']
if 'origin' in msg:
args['origin'] = msg['origin']
2019-12-11 18:05:17 +01:00
return cls(**args)
def __str__(self):
"""
Overrides the str() operator and converts
the message into a UTF-8 JSON string
"""
response_dict = {
2019-12-11 18:05:17 +01:00
'id': self.id,
'type': 'response',
'target': self.target if hasattr(self, 'target') else None,
'origin': self.origin if hasattr(self, 'origin') else None,
'_timestamp': self.timestamp,
'response': {
'output': self.output,
'errors': self.errors,
},
}
if self.disable_logging:
response_dict['_disable_logging'] = self.disable_logging
return json.dumps(response_dict)
# vim:sw=4:ts=4:et: