streaming.py 6 KB
Newer Older
1
# Tweepy
2
3
# Copyright 2009-2010 Joshua Roesslein
# See LICENSE for details.
4
5

import httplib
6
from socket import timeout
7
from threading import Thread
8
from time import sleep
9
import urllib
10

Josh Roesslein's avatar
Josh Roesslein committed
11
from tweepy.auth import BasicAuthHandler
12
from tweepy.models import Status
Josh Roesslein's avatar
Josh Roesslein committed
13
14
from tweepy.api import API
from tweepy.error import TweepError
15

16
17
from tweepy.utils import import_simplejson
json = import_simplejson()
18

19
20
STREAM_VERSION = 1

Josh Roesslein's avatar
Josh Roesslein committed
21

22
23
class StreamListener(object):

24
25
    def __init__(self, api=None):
        self.api = api or API()
26
27
28
29
30
31
32
33
34

    def on_data(self, data):
        """Called when raw data is received from connection.

        Override this method if you wish to manually handle
        the stream data. Return False to stop stream and close connection.
        """

        if 'in_reply_to_status_id' in data:
35
            status = Status.parse(self.api, json.loads(data))
36
37
38
39
40
41
42
43
44
45
            if self.on_status(status) is False:
                return False
        elif 'delete' in data:
            delete = json.loads(data)['delete']['status']
            if self.on_delete(delete['id'], delete['user_id']) is False:
                return False
        elif 'limit' in data:
            if self.on_limit(json.loads(data)['limit']['track']) is False:
                return False

Josh Roesslein's avatar
Josh Roesslein committed
46
47
48
49
50
51
52
    def on_status(self, status):
        """Called when a new status arrives"""
        return

    def on_delete(self, status_id, user_id):
        """Called when a delete notice arrives for a status"""
        return
53

Josh Roesslein's avatar
Josh Roesslein committed
54
55
56
    def on_limit(self, track):
        """Called when a limitation notice arrvies"""
        return
57

Josh Roesslein's avatar
Josh Roesslein committed
58
59
60
    def on_error(self, status_code):
        """Called when a non-200 status code is returned"""
        return False
61

Josh Roesslein's avatar
Josh Roesslein committed
62
63
64
    def on_timeout(self):
        """Called when stream connection times out"""
        return
65

66

67
68
class Stream(object):

Josh Roesslein's avatar
Josh Roesslein committed
69
70
71
    host = 'stream.twitter.com'

    def __init__(self, username, password, listener, timeout=5.0, retry_count = None,
72
                    retry_time = 10.0, snooze_time = 5.0, buffer_size=1500, headers=None):
Josh Roesslein's avatar
Josh Roesslein committed
73
74
75
76
77
78
79
80
81
        self.auth = BasicAuthHandler(username, password)
        self.running = False
        self.timeout = timeout
        self.retry_count = retry_count
        self.retry_time = retry_time
        self.snooze_time = snooze_time
        self.buffer_size = buffer_size
        self.listener = listener
        self.api = API()
82
        self.headers = headers or {}
83
        self.body = None
Josh Roesslein's avatar
Josh Roesslein committed
84
85
86

    def _run(self):
        # setup
87
        self.auth.apply_auth(None, None, self.headers, None)
Josh Roesslein's avatar
Josh Roesslein committed
88
89
90
91
92
93
94
95
96
97
98
99

        # enter loop
        error_counter = 0
        conn = None
        while self.running:
            if self.retry_count and error_counter > self.retry_count:
                # quit if error count greater than retry count
                break
            try:
                conn = httplib.HTTPConnection(self.host)
                conn.connect()
                conn.sock.settimeout(self.timeout)
100
                conn.request('POST', self.url, self.body, headers=self.headers)
Josh Roesslein's avatar
Josh Roesslein committed
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
                resp = conn.getresponse()
                if resp.status != 200:
                    if self.listener.on_error(resp.status) is False:
                        break
                    error_counter += 1
                    sleep(self.retry_time)
                else:
                    error_counter = 0
                    self._read_loop(resp)
            except timeout:
                if self.listener.on_timeout() == False:
                    break
                if self.running is False:
                    break
                conn.close()
                sleep(self.snooze_time)
            except Exception:
                # any other exception is fatal, so kill loop
                break

        # cleanup
        self.running = False
        if conn:
            conn.close()

    def _read_loop(self, resp):
        data = ''
        while self.running:
            if resp.isclosed():
                break

            # read length
            length = ''
            while True:
                c = resp.read(1)
                if c == '\n':
                    break
                length += c
            length = length.strip()
            if length.isdigit():
                length = int(length)
            else:
                continue

145
            # read data and pass into listener
Josh Roesslein's avatar
Josh Roesslein committed
146
            data = resp.read(length)
147
148
            if self.listener.on_data(data) is False:
                self.running = False
Josh Roesslein's avatar
Josh Roesslein committed
149

150
151
152
153
154
155
156
157
    def _start(self, async):
        self.running = True
        if async:
            Thread(target=self._run).start()
        else:
            self._run()

    def firehose(self, count=None, async=False):
Josh Roesslein's avatar
Josh Roesslein committed
158
159
160
161
162
        if self.running:
            raise TweepError('Stream object already connected!')
        self.url = '/%i/statuses/firehose.json?delimited=length' % STREAM_VERSION
        if count:
            self.url += '&count=%s' % count
163
        self._start(async)
Josh Roesslein's avatar
Josh Roesslein committed
164

165
    def retweet(self, async=False):
166
167
168
        if self.running:
            raise TweepError('Stream object already connected!')
        self.url = '/%i/statuses/retweet.json?delimited=length' % STREAM_VERSION
169
        self._start(async)
170

171
    def sample(self, count=None, async=False):
Josh Roesslein's avatar
Josh Roesslein committed
172
173
174
175
176
        if self.running:
            raise TweepError('Stream object already connected!')
        self.url = '/%i/statuses/sample.json?delimited=length' % STREAM_VERSION
        if count:
            self.url += '&count=%s' % count
177
        self._start(async)
Josh Roesslein's avatar
Josh Roesslein committed
178

179
    def filter(self, follow=None, track=None, async=False):
180
181
        params = {}
        self.headers['Content-type'] = "application/x-www-form-urlencoded"
Josh Roesslein's avatar
Josh Roesslein committed
182
183
184
185
        if self.running:
            raise TweepError('Stream object already connected!')
        self.url = '/%i/statuses/filter.json?delimited=length' % STREAM_VERSION
        if follow:
186
            params['follow'] = ','.join(map(str, follow))
Josh Roesslein's avatar
Josh Roesslein committed
187
        if track:
188
189
            params['track'] = ','.join(map(str, track))
        self.body = urllib.urlencode(params)
190
        self._start(async)
Josh Roesslein's avatar
Josh Roesslein committed
191
192

    def disconnect(self):
193
        if self.running is False:
Josh Roesslein's avatar
Josh Roesslein committed
194
195
196
            return
        self.running = False