aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLorenz Diener <[email protected]>2018-01-29 12:24:53 +0100
committerLorenz Diener <[email protected]>2018-01-29 12:24:53 +0100
commit791439d96b28d5dd1b9d20d2921bd93ff02521fa (patch)
tree054d6579c7fc133727090712196a996ce6ccc21c /mastodon/streaming.py
parent42b1d8fa5895f416853311db220cf9412ad8fd13 (diff)
downloadmastodon.py-791439d96b28d5dd1b9d20d2921bd93ff02521fa.tar.gz
Remove state from handle_stream, fixes #119
Diffstat (limited to 'mastodon/streaming.py')
-rw-r--r--mastodon/streaming.py37
1 files changed, 18 insertions, 19 deletions
diff --git a/mastodon/streaming.py b/mastodon/streaming.py
index 4941ace..16b5375 100644
--- a/mastodon/streaming.py
+++ b/mastodon/streaming.py
@@ -41,40 +41,39 @@ class StreamListener(object):
41 41
42 response; a requests response object with the open stream for reading. 42 response; a requests response object with the open stream for reading.
43 """ 43 """
44 self.event = {} 44 event = {}
45 line_buffer = bytearray() 45 line_buffer = bytearray()
46 for chunk in response.iter_content(chunk_size = 1): 46 for chunk in response.iter_content(chunk_size = 1):
47 if chunk: 47 if chunk:
48 if chunk == b'\n': 48 if chunk == b'\n':
49 self.handle_line(line_buffer) 49 try:
50 line = line_buffer.decode('utf-8')
51 except UnicodeDecodeError as err:
52 six.raise_from(
53 MastodonMalformedEventError("Malformed UTF-8"),
54 err
55 )
56 if line == '':
57 self._dispatch(event)
58 else:
59 event = self._parse_line(line, event)
50 line_buffer = bytearray() 60 line_buffer = bytearray()
51 else: 61 else:
52 line_buffer.extend(chunk) 62 line_buffer.extend(chunk)
53 63
54 def handle_line(self, raw_line): 64 def _parse_line(self, line, event):
55 try:
56 line = raw_line.decode('utf-8')
57 except UnicodeDecodeError as err:
58 six.raise_from(
59 MastodonMalformedEventError("Malformed UTF-8"),
60 err
61 )
62
63 if line.startswith(':'): 65 if line.startswith(':'):
64 self.handle_heartbeat() 66 self.handle_heartbeat()
65 elif line == '':
66 # end of event
67 self._dispatch(self.event)
68 self.event = {}
69 else: 67 else:
70 key, value = line.split(': ', 1) 68 key, value = line.split(': ', 1)
71 # According to the MDN spec, repeating the 'data' key 69 # According to the MDN spec, repeating the 'data' key
72 # represents a newline(!) 70 # represents a newline(!)
73 if key in self.event: 71 if key in event:
74 self.event[key] += '\n' + value 72 event[key] += '\n' + value
75 else: 73 else:
76 self.event[key] = value 74 event[key] = value
77 75 return event
76
78 def _dispatch(self, event): 77 def _dispatch(self, event):
79 try: 78 try:
80 name = event['event'] 79 name = event['event']
Powered by cgit v1.2.3 (git 2.41.0)