diff options
-rw-r--r-- | mastodon/streaming.py | 37 |
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'] |