aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLorenz Diener <[email protected]>2017-11-24 13:59:13 +0100
committerLorenz Diener <[email protected]>2017-11-24 13:59:50 +0100
commitde2114b92b1d9dd67935fb3be96bce73576ceaea (patch)
tree38b9ce4951bd8b70e3fb298e83b68a35c6411ebe /mastodon
parent8987590545861c3963bdfe7f979e6dc2e9c89fdb (diff)
downloadmastodon.py-de2114b92b1d9dd67935fb3be96bce73576ceaea.tar.gz
BREAKING: Make streaming use json hooks
Diffstat (limited to 'mastodon')
-rw-r--r--mastodon/Mastodon.py16
-rw-r--r--mastodon/streaming.py36
2 files changed, 27 insertions, 25 deletions
diff --git a/mastodon/Mastodon.py b/mastodon/Mastodon.py
index b4d4aa3..ab0071b 100644
--- a/mastodon/Mastodon.py
+++ b/mastodon/Mastodon.py
@@ -1083,8 +1083,8 @@ class Mastodon:
1083 1083
1084 return (date_time_utc - epoch_utc).total_seconds() 1084 return (date_time_utc - epoch_utc).total_seconds()
1085 1085
1086 1086 @staticmethod
1087 def __json_date_parse(self, json_object): 1087 def __json_date_parse(json_object):
1088 """ 1088 """
1089 Parse dates in certain known json fields, if possible. 1089 Parse dates in certain known json fields, if possible.
1090 """ 1090 """
@@ -1100,7 +1100,8 @@ class Mastodon:
1100 raise MastodonAPIError('Encountered invalid date.') 1100 raise MastodonAPIError('Encountered invalid date.')
1101 return json_object 1101 return json_object
1102 1102
1103 def __json_id_to_bignum(self, json_object): 1103 @staticmethod
1104 def __json_id_to_bignum(json_object):
1104 """ 1105 """
1105 Converts json string IDs to native python bignums. 1106 Converts json string IDs to native python bignums.
1106 """ 1107 """
@@ -1117,10 +1118,11 @@ class Mastodon:
1117 pass 1118 pass
1118 1119
1119 return json_object 1120 return json_object
1120 1121
1121 def __json_hooks(self, json_object): 1122 @staticmethod
1122 json_object = self.__json_date_parse(json_object) 1123 def __json_hooks(json_object):
1123 json_object = self.__json_id_to_bignum(json_object) 1124 json_object = Mastodon.__json_date_parse(json_object)
1125 json_object = Mastodon.__json_id_to_bignum(json_object)
1124 return json_object 1126 return json_object
1125 1127
1126 def __api_request(self, method, endpoint, params={}, files={}, do_ratelimiting=True): 1128 def __api_request(self, method, endpoint, params={}, files={}, do_ratelimiting=True):
diff --git a/mastodon/streaming.py b/mastodon/streaming.py
index 290ed44..c202ff6 100644
--- a/mastodon/streaming.py
+++ b/mastodon/streaming.py
@@ -6,11 +6,10 @@ https://github.com/tootsuite/mastodon/blob/master/docs/Using-the-API/Streaming-A
6import json 6import json
7import logging 7import logging
8import six 8import six
9 9from mastodon import Mastodon
10 10
11log = logging.getLogger(__name__) 11log = logging.getLogger(__name__)
12 12
13
14class MalformedEventError(Exception): 13class MalformedEventError(Exception):
15 """Raised when the server-sent event stream is malformed.""" 14 """Raised when the server-sent event stream is malformed."""
16 pass 15 pass
@@ -24,7 +23,7 @@ class StreamListener(object):
24 23
25 def on_update(self, status): 24 def on_update(self, status):
26 """A new status has appeared! 'status' is the parsed JSON dictionary 25 """A new status has appeared! 'status' is the parsed JSON dictionary
27describing the status.""" 26 describing the status."""
28 pass 27 pass
29 28
30 def on_notification(self, notification): 29 def on_notification(self, notification):
@@ -40,7 +39,8 @@ describing the status."""
40 """The server has sent us a keep-alive message. This callback may be 39 """The server has sent us a keep-alive message. This callback may be
41 useful to carry out periodic housekeeping tasks, or just to confirm 40 useful to carry out periodic housekeeping tasks, or just to confirm
42 that the connection is still open.""" 41 that the connection is still open."""
43 42 pass
43
44 def handle_stream(self, lines): 44 def handle_stream(self, lines):
45 """ 45 """
46 Handles a stream of events from the Mastodon server. When each event 46 Handles a stream of events from the Mastodon server. When each event
@@ -63,7 +63,7 @@ describing the status."""
63 self.handle_heartbeat() 63 self.handle_heartbeat()
64 elif line == '': 64 elif line == '':
65 # end of event 65 # end of event
66 self._despatch(event) 66 self._dispatch(event)
67 event = {} 67 event = {}
68 else: 68 else:
69 key, value = line.split(': ', 1) 69 key, value = line.split(': ', 1)
@@ -78,24 +78,24 @@ describing the status."""
78 if event: 78 if event:
79 log.warn("outstanding partial event at end of stream: %s", event) 79 log.warn("outstanding partial event at end of stream: %s", event)
80 80
81 def _despatch(self, event): 81 def _dispatch(self, event):
82 try: 82 try:
83 name = event['event'] 83 name = event['event']
84 data = event['data'] 84 data = event['data']
85 payload = json.loads(data) 85 payload = json.loads(data, object_hook = Mastodon._Mastodon__json_hooks)
86 except KeyError as err: 86 except KeyError as err:
87 six.raise_from( 87 six.raise_from(
88 MalformedEventError('Missing field', err.args[0], event), 88 MalformedEventError('Missing field', err.args[0], event),
89 err 89 err
90 ) 90 )
91 except ValueError as err: 91 except ValueError as err:
92 # py2: plain ValueError 92 # py2: plain ValueError
93 # py3: json.JSONDecodeError, a subclass of ValueError 93 # py3: json.JSONDecodeError, a subclass of ValueError
94 six.raise_from( 94 six.raise_from(
95 MalformedEventError('Bad JSON', data), 95 MalformedEventError('Bad JSON', data),
96 err 96 err
97 ) 97 )
98 98
99 handler_name = 'on_' + name 99 handler_name = 'on_' + name
100 try: 100 try:
101 handler = getattr(self, handler_name) 101 handler = getattr(self, handler_name)
Powered by cgit v1.2.3 (git 2.41.0)