Move the json decoding into the MatrixMessage class.

This commit is contained in:
poljar (Damir Jelić) 2018-02-13 10:13:40 +01:00
parent 390d08b229
commit f78bd95d3f
2 changed files with 22 additions and 16 deletions

View file

@ -234,6 +234,19 @@ class MatrixMessage():
self.request = request_func(**func_args) self.request = request_func(**func_args)
def decode_body(self):
try:
self.decoded_response = json.loads(
self.response.body,
encoding='utf-8'
)
return (True, None)
except Exception as error:
return (False, error)
def to_event():
pass
class MatrixLoginMessage(MatrixMessage): class MatrixLoginMessage(MatrixMessage):
def __init__(self, client, user, password, device_name, device_id=None): def __init__(self, client, user, password, device_name, device_id=None):

View file

@ -760,29 +760,22 @@ def handle_http_response(server, message):
assert message.response assert message.response
status_code = message.response.status if ('content-type' in message.response.headers and
message.response.headers['content-type'] == 'application/json'):
ret, error = message.decode_body()
def decode_json(server, json_string): if not ret:
try: # TODO try to resend the message if decoding has failed?
return json.loads(json_string, encoding='utf-8')
except Exception as error:
message = ("{prefix}matrix: Error decoding json response from " message = ("{prefix}matrix: Error decoding json response from "
"server: {error}").format( "server: {error}").format(
prefix=W.prefix("error"), prefix=W.prefix("error"),
error=error) error=error)
W.prnt(server.server_buffer, message) W.prnt(server.server_buffer, message)
return None return
status_code = message.response.status
if status_code == 200: if status_code == 200:
message.decoded_response = decode_json(server, message.response.body)
# if not response:
# # Resend the message
# message.response = None
# send_or_queue(server, message)
# return
matrix_handle_message( matrix_handle_message(
server, server,
message, message,
@ -795,7 +788,7 @@ def handle_http_response(server, message):
elif status_code == 403: elif status_code == 403:
if message.type == MessageType.LOGIN: if message.type == MessageType.LOGIN:
response = decode_json(server, message.response.body) response = message.response.decoded_response
reason = ("." if not response or not response["error"] else reason = ("." if not response or not response["error"] else
": {r}.".format(r=response["error"])) ": {r}.".format(r=response["error"]))
@ -809,7 +802,7 @@ def handle_http_response(server, message):
server.disconnect() server.disconnect()
elif message.type == MessageType.TOPIC: elif message.type == MessageType.TOPIC:
response = decode_json(server, message.response.body) response = message.decoded_response
reason = ("." if not response or not response["error"] else reason = ("." if not response or not response["error"] else
": {r}.".format(r=response["error"])) ": {r}.".format(r=response["error"]))