Merge lp:~gtg-user/gtg/identica-backend into lp:~gtg/gtg/old-trunk
- identica-backend
- Merge into old-trunk
Proposed by
Luca Invernizzi
Status: | Merged |
---|---|
Merged at revision: | 880 |
Proposed branch: | lp:~gtg-user/gtg/identica-backend |
Merge into: | lp:~gtg/gtg/old-trunk |
Diff against target: |
2839 lines (+2827/-0) 2 files modified
GTG/backends/backend_identica.py (+280/-0) GTG/backends/twitter.py (+2547/-0) |
To merge this branch: | bzr merge lp:~gtg-user/gtg/identica-backend |
Related bugs: |
Reviewer | Review Type | Date Requested | Status |
---|---|---|---|
Gtg developers | Pending | ||
Review via email: mp+33479@code.launchpad.net |
Commit message
Description of the change
identi.ca backend, which follows the lines of the twitter backend, but does not authenticate through oauth (and uses a different library).
Note: i've added a branch with all my merge requests merged. https:/
To post a comment you must log in.
- 876. By Luca Invernizzi
-
removed print statements
- 877. By Luca Invernizzi
-
merge w/ trunk
Preview Diff
[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1 | === added file 'GTG/backends/backend_identica.py' | |||
2 | --- GTG/backends/backend_identica.py 1970-01-01 00:00:00 +0000 | |||
3 | +++ GTG/backends/backend_identica.py 2010-08-25 16:29:48 +0000 | |||
4 | @@ -0,0 +1,280 @@ | |||
5 | 1 | # -*- coding: utf-8 -*- | ||
6 | 2 | # ----------------------------------------------------------------------------- | ||
7 | 3 | # Getting Things Gnome! - a personal organizer for the GNOME desktop | ||
8 | 4 | # Copyright (c) 2008-2009 - Lionel Dricot & Bertrand Rousseau | ||
9 | 5 | # | ||
10 | 6 | # This program is free software: you can redistribute it and/or modify it under | ||
11 | 7 | # the terms of the GNU General Public License as published by the Free Software | ||
12 | 8 | # Foundation, either version 3 of the License, or (at your option) any later | ||
13 | 9 | # version. | ||
14 | 10 | # | ||
15 | 11 | # This program is distributed in the hope that it will be useful, but WITHOUT | ||
16 | 12 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS | ||
17 | 13 | # FOR A PARTICULAR PURPOSE. See the GNU General Public License for more | ||
18 | 14 | # details. | ||
19 | 15 | # | ||
20 | 16 | # You should have received a copy of the GNU General Public License along with | ||
21 | 17 | # this program. If not, see <http://www.gnu.org/licenses/>. | ||
22 | 18 | # ----------------------------------------------------------------------------- | ||
23 | 19 | |||
24 | 20 | ''' | ||
25 | 21 | Identi.ca backend: imports direct messages, replies and/or the user timeline. | ||
26 | 22 | ''' | ||
27 | 23 | |||
28 | 24 | import os | ||
29 | 25 | import re | ||
30 | 26 | import sys | ||
31 | 27 | import uuid | ||
32 | 28 | import urllib2 | ||
33 | 29 | |||
34 | 30 | from GTG import _ | ||
35 | 31 | from GTG.backends.genericbackend import GenericBackend | ||
36 | 32 | from GTG.core import CoreConfig | ||
37 | 33 | from GTG.backends.backendsignals import BackendSignals | ||
38 | 34 | from GTG.backends.periodicimportbackend import PeriodicImportBackend | ||
39 | 35 | from GTG.backends.syncengine import SyncEngine | ||
40 | 36 | from GTG.tools.logger import Log | ||
41 | 37 | |||
42 | 38 | #The Ubuntu version of python twitter is not updated: | ||
43 | 39 | # it does not have identi.ca support. Meanwhile, we ship the right version | ||
44 | 40 | # with our code. | ||
45 | 41 | import GTG.backends.twitter as twitter | ||
46 | 42 | |||
47 | 43 | |||
48 | 44 | |||
49 | 45 | class Backend(PeriodicImportBackend): | ||
50 | 46 | ''' | ||
51 | 47 | Identi.ca backend: imports direct messages, replies and/or the user | ||
52 | 48 | timeline. | ||
53 | 49 | ''' | ||
54 | 50 | |||
55 | 51 | |||
56 | 52 | _general_description = { \ | ||
57 | 53 | GenericBackend.BACKEND_NAME: "backend_identica", \ | ||
58 | 54 | GenericBackend.BACKEND_HUMAN_NAME: _("Identi.ca"), \ | ||
59 | 55 | GenericBackend.BACKEND_AUTHORS: ["Luca Invernizzi"], \ | ||
60 | 56 | GenericBackend.BACKEND_TYPE: GenericBackend.TYPE_IMPORT, \ | ||
61 | 57 | GenericBackend.BACKEND_DESCRIPTION: \ | ||
62 | 58 | _("Imports your identi.ca messages into your GTG " + \ | ||
63 | 59 | "tasks. You can choose to either import all your " + \ | ||
64 | 60 | "messages or just those with a set of hash tags. \n" + \ | ||
65 | 61 | "The message will be interpreted following this" + \ | ||
66 | 62 | " format: \n" + \ | ||
67 | 63 | "<b>my task title, task description #tag @anothertag</b>\n" + \ | ||
68 | 64 | " Tags can be anywhere in the message"),\ | ||
69 | 65 | } | ||
70 | 66 | |||
71 | 67 | base_url = "http://identi.ca/api/" | ||
72 | 68 | |||
73 | 69 | _static_parameters = { \ | ||
74 | 70 | "username": { \ | ||
75 | 71 | GenericBackend.PARAM_TYPE: GenericBackend.TYPE_STRING, \ | ||
76 | 72 | GenericBackend.PARAM_DEFAULT_VALUE: "", }, | ||
77 | 73 | "password": { \ | ||
78 | 74 | GenericBackend.PARAM_TYPE: GenericBackend.TYPE_PASSWORD, \ | ||
79 | 75 | GenericBackend.PARAM_DEFAULT_VALUE: "", }, | ||
80 | 76 | "period": { \ | ||
81 | 77 | GenericBackend.PARAM_TYPE: GenericBackend.TYPE_INT, \ | ||
82 | 78 | GenericBackend.PARAM_DEFAULT_VALUE: 2, }, | ||
83 | 79 | "import-tags": { \ | ||
84 | 80 | GenericBackend.PARAM_TYPE: GenericBackend.TYPE_LIST_OF_STRINGS, \ | ||
85 | 81 | GenericBackend.PARAM_DEFAULT_VALUE: ["#todo"], }, | ||
86 | 82 | "import-from-replies": { \ | ||
87 | 83 | GenericBackend.PARAM_TYPE: GenericBackend.TYPE_BOOL, \ | ||
88 | 84 | GenericBackend.PARAM_DEFAULT_VALUE: False, }, | ||
89 | 85 | "import-from-my-tweets": { \ | ||
90 | 86 | GenericBackend.PARAM_TYPE: GenericBackend.TYPE_BOOL, \ | ||
91 | 87 | GenericBackend.PARAM_DEFAULT_VALUE: False, }, | ||
92 | 88 | "import-from-direct-messages": { \ | ||
93 | 89 | GenericBackend.PARAM_TYPE: GenericBackend.TYPE_BOOL, \ | ||
94 | 90 | GenericBackend.PARAM_DEFAULT_VALUE: True, }, | ||
95 | 91 | } | ||
96 | 92 | |||
97 | 93 | def __init__(self, parameters): | ||
98 | 94 | ''' | ||
99 | 95 | See GenericBackend for an explanation of this function. | ||
100 | 96 | Re-loads the saved state of the synchronization | ||
101 | 97 | ''' | ||
102 | 98 | super(Backend, self).__init__(parameters) | ||
103 | 99 | #loading the list of already imported tasks | ||
104 | 100 | self.data_path = os.path.join('backends/identica/', "tasks_dict-%s" %\ | ||
105 | 101 | self.get_id()) | ||
106 | 102 | self.sync_engine = self._load_pickled_file(self.data_path, \ | ||
107 | 103 | SyncEngine()) | ||
108 | 104 | |||
109 | 105 | def save_state(self): | ||
110 | 106 | ''' | ||
111 | 107 | See GenericBackend for an explanation of this function. | ||
112 | 108 | Saves the state of the synchronization. | ||
113 | 109 | ''' | ||
114 | 110 | self._store_pickled_file(self.data_path, self.sync_engine) | ||
115 | 111 | |||
116 | 112 | def do_periodic_import(self): | ||
117 | 113 | ''' | ||
118 | 114 | See GenericBackend for an explanation of this function. | ||
119 | 115 | ''' | ||
120 | 116 | #we need to authenticate only to see the direct messages or the replies | ||
121 | 117 | # (why the replies? Don't know. But python-twitter requires that) | ||
122 | 118 | # (invernizzi) | ||
123 | 119 | with self.controlled_execution(self._parameters['username'],\ | ||
124 | 120 | self._parameters['password'], \ | ||
125 | 121 | self.base_url, \ | ||
126 | 122 | self) as api: | ||
127 | 123 | #select what to import | ||
128 | 124 | tweets_to_import = [] | ||
129 | 125 | if self._parameters["import-from-direct-messages"]: | ||
130 | 126 | tweets_to_import += api.GetDirectMessages() | ||
131 | 127 | if self._parameters["import-from-my-tweets"]: | ||
132 | 128 | tweets_to_import += \ | ||
133 | 129 | api.GetUserTimeline(self._parameters["username"]) | ||
134 | 130 | if self._parameters["import-from-replies"]: | ||
135 | 131 | tweets_to_import += \ | ||
136 | 132 | api.GetReplies(self._parameters["username"]) | ||
137 | 133 | #do the import | ||
138 | 134 | for tweet in tweets_to_import: | ||
139 | 135 | self._process_tweet(tweet) | ||
140 | 136 | |||
141 | 137 | def _process_tweet(self, tweet): | ||
142 | 138 | ''' | ||
143 | 139 | Given a tweet, checks if a task representing it must be | ||
144 | 140 | created in GTG and, if so, it creates it. | ||
145 | 141 | |||
146 | 142 | @param tweet: a tweet. | ||
147 | 143 | ''' | ||
148 | 144 | self.cancellation_point() | ||
149 | 145 | tweet_id = str(tweet.GetId()) | ||
150 | 146 | is_syncable = self._is_tweet_syncable(tweet) | ||
151 | 147 | #the "lambda" is because we don't consider tweets deletion (to be | ||
152 | 148 | # faster) | ||
153 | 149 | action, tid = self.sync_engine.analyze_remote_id(\ | ||
154 | 150 | tweet_id, \ | ||
155 | 151 | self.datastore.has_task, \ | ||
156 | 152 | lambda tweet_id: True, \ | ||
157 | 153 | is_syncable) | ||
158 | 154 | Log.debug("processing tweet (%s, %s)" % (action, is_syncable)) | ||
159 | 155 | |||
160 | 156 | self.cancellation_point() | ||
161 | 157 | if action == None or action == SyncEngine.UPDATE: | ||
162 | 158 | return | ||
163 | 159 | |||
164 | 160 | elif action == SyncEngine.ADD: | ||
165 | 161 | tid = str(uuid.uuid4()) | ||
166 | 162 | task = self.datastore.task_factory(tid) | ||
167 | 163 | self._populate_task(task, tweet) | ||
168 | 164 | #we care only to add tweets and if the list of tags which must be | ||
169 | 165 | #imported changes (lost-syncability can happen). Thus, we don't | ||
170 | 166 | # care about SyncMeme(s) | ||
171 | 167 | self.sync_engine.record_relationship(local_id = tid,\ | ||
172 | 168 | remote_id = tweet_id, \ | ||
173 | 169 | meme = None) | ||
174 | 170 | self.datastore.push_task(task) | ||
175 | 171 | |||
176 | 172 | elif action == SyncEngine.LOST_SYNCABILITY: | ||
177 | 173 | self.sync_engine.break_relationship(remote_id = tweet_id) | ||
178 | 174 | self.datastore.request_task_deletion(tid) | ||
179 | 175 | |||
180 | 176 | self.save_state() | ||
181 | 177 | |||
182 | 178 | def _populate_task(self, task, message): | ||
183 | 179 | ''' | ||
184 | 180 | Given a twitter message and a GTG task, fills the task with the content | ||
185 | 181 | of the message | ||
186 | 182 | ''' | ||
187 | 183 | try: | ||
188 | 184 | #this works only for some messages | ||
189 | 185 | task.add_tag("@" + message.GetSenderScreenName()) | ||
190 | 186 | except: | ||
191 | 187 | pass | ||
192 | 188 | text = message.GetText() | ||
193 | 189 | |||
194 | 190 | #convert #hastags to @tags | ||
195 | 191 | matches = re.finditer("(?<![^|\s])(#\w+)", text) | ||
196 | 192 | for g in matches: | ||
197 | 193 | text = text[:g.start()] + '@' + text[g.start() + 1:] | ||
198 | 194 | #add tags objects (it's not enough to have @tag in the text to add a | ||
199 | 195 | # tag | ||
200 | 196 | for tag in self._extract_tags_from_text(text): | ||
201 | 197 | task.add_tag(tag) | ||
202 | 198 | |||
203 | 199 | split_text = text.split(",", 1) | ||
204 | 200 | task.set_title(split_text[0]) | ||
205 | 201 | if len(split_text) > 1: | ||
206 | 202 | task.set_text(split_text[1]) | ||
207 | 203 | |||
208 | 204 | task.add_remote_id(self.get_id(), str(message.GetId())) | ||
209 | 205 | |||
210 | 206 | def _is_tweet_syncable(self, tweet): | ||
211 | 207 | ''' | ||
212 | 208 | Returns True if the given tweet matches the user-specified tags to be | ||
213 | 209 | synced | ||
214 | 210 | |||
215 | 211 | @param tweet: a tweet | ||
216 | 212 | ''' | ||
217 | 213 | if CoreConfig.ALLTASKS_TAG in self._parameters["import-tags"]: | ||
218 | 214 | return True | ||
219 | 215 | else: | ||
220 | 216 | tags = set(Backend._extract_tags_from_text(tweet.GetText())) | ||
221 | 217 | return tags.intersection(set(self._parameters["import-tags"])) \ | ||
222 | 218 | != set() | ||
223 | 219 | |||
224 | 220 | @staticmethod | ||
225 | 221 | def _extract_tags_from_text(text): | ||
226 | 222 | ''' | ||
227 | 223 | Given a string, returns a list of @tags and #hashtags | ||
228 | 224 | ''' | ||
229 | 225 | return list(re.findall(r'(?:^|[\s])((?:#|@)\w+)', text)) | ||
230 | 226 | |||
231 | 227 | ############################################################################### | ||
232 | 228 | ### AUTHENTICATION ############################################################ | ||
233 | 229 | ############################################################################### | ||
234 | 230 | |||
235 | 231 | class controlled_execution(object): | ||
236 | 232 | ''' | ||
237 | 233 | This class performs the login to identica and execute the appropriate | ||
238 | 234 | response if something goes wrong during authentication or at network | ||
239 | 235 | level | ||
240 | 236 | ''' | ||
241 | 237 | |||
242 | 238 | def __init__(self, username, password, base_url, backend): | ||
243 | 239 | ''' | ||
244 | 240 | Sets the login parameters | ||
245 | 241 | ''' | ||
246 | 242 | self.username = username | ||
247 | 243 | self.password = password | ||
248 | 244 | self.backend = backend | ||
249 | 245 | self.base_url = base_url | ||
250 | 246 | |||
251 | 247 | def __enter__(self): | ||
252 | 248 | ''' | ||
253 | 249 | Logins to identica and returns the Api object | ||
254 | 250 | ''' | ||
255 | 251 | return twitter.Api(self.username, self.password, \ | ||
256 | 252 | base_url = self.base_url) | ||
257 | 253 | |||
258 | 254 | def __exit__(self, type, value, traceback): | ||
259 | 255 | ''' | ||
260 | 256 | Analyzes the eventual exception risen during the connection to | ||
261 | 257 | identica | ||
262 | 258 | ''' | ||
263 | 259 | if isinstance(value, urllib2.HTTPError): | ||
264 | 260 | if value.getcode() == 401: | ||
265 | 261 | self.signal_authentication_wrong() | ||
266 | 262 | if value.getcode() in [502, 404]: | ||
267 | 263 | self.signal_network_down() | ||
268 | 264 | elif isinstance(value, twitter.TwitterError): | ||
269 | 265 | self.signal_authentication_wrong() | ||
270 | 266 | elif isinstance(value, urllib2.URLError): | ||
271 | 267 | self.signal_network_down() | ||
272 | 268 | else: | ||
273 | 269 | return False | ||
274 | 270 | return True | ||
275 | 271 | |||
276 | 272 | def signal_authentication_wrong(self): | ||
277 | 273 | self.backend.quit(disable = True) | ||
278 | 274 | BackendSignals().backend_failed(self.backend.get_id(), \ | ||
279 | 275 | BackendSignals.ERRNO_AUTHENTICATION) | ||
280 | 276 | |||
281 | 277 | def signal_network_down(self): | ||
282 | 278 | BackendSignals().backend_failed(self.backend.get_id(), \ | ||
283 | 279 | BackendSignals.ERRNO_NETWORK) | ||
284 | 280 | |||
285 | 0 | 281 | ||
286 | === added file 'GTG/backends/twitter.py' | |||
287 | --- GTG/backends/twitter.py 1970-01-01 00:00:00 +0000 | |||
288 | +++ GTG/backends/twitter.py 2010-08-25 16:29:48 +0000 | |||
289 | @@ -0,0 +1,2547 @@ | |||
290 | 1 | #!/usr/bin/python2.4 | ||
291 | 2 | # | ||
292 | 3 | # Copyright 2007 Google Inc. All Rights Reserved. | ||
293 | 4 | # | ||
294 | 5 | # Licensed under the Apache License, Version 2.0 (the "License"); | ||
295 | 6 | # you may not use this file except in compliance with the License. | ||
296 | 7 | # You may obtain a copy of the License at | ||
297 | 8 | # | ||
298 | 9 | # http://www.apache.org/licenses/LICENSE-2.0 | ||
299 | 10 | # | ||
300 | 11 | # Unless required by applicable law or agreed to in writing, software | ||
301 | 12 | # distributed under the License is distributed on an "AS IS" BASIS, | ||
302 | 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
303 | 14 | # See the License for the specific language governing permissions and | ||
304 | 15 | # limitations under the License. | ||
305 | 16 | |||
306 | 17 | '''A library that provides a python interface to the Twitter API''' | ||
307 | 18 | |||
308 | 19 | __author__ = 'dewitt@google.com' | ||
309 | 20 | __version__ = '0.7-devel' | ||
310 | 21 | |||
311 | 22 | |||
312 | 23 | import base64 | ||
313 | 24 | import calendar | ||
314 | 25 | import httplib | ||
315 | 26 | import os | ||
316 | 27 | import rfc822 | ||
317 | 28 | import simplejson | ||
318 | 29 | import sys | ||
319 | 30 | import tempfile | ||
320 | 31 | import textwrap | ||
321 | 32 | import time | ||
322 | 33 | import urllib | ||
323 | 34 | import urllib2 | ||
324 | 35 | import urlparse | ||
325 | 36 | import gzip | ||
326 | 37 | import StringIO | ||
327 | 38 | |||
328 | 39 | try: | ||
329 | 40 | from hashlib import md5 | ||
330 | 41 | except ImportError: | ||
331 | 42 | from md5 import md5 | ||
332 | 43 | |||
333 | 44 | |||
334 | 45 | CHARACTER_LIMIT = 140 | ||
335 | 46 | |||
336 | 47 | # A singleton representing a lazily instantiated FileCache. | ||
337 | 48 | DEFAULT_CACHE = object() | ||
338 | 49 | |||
339 | 50 | |||
340 | 51 | class TwitterError(Exception): | ||
341 | 52 | '''Base class for Twitter errors''' | ||
342 | 53 | |||
343 | 54 | @property | ||
344 | 55 | def message(self): | ||
345 | 56 | '''Returns the first argument used to construct this error.''' | ||
346 | 57 | return self.args[0] | ||
347 | 58 | |||
348 | 59 | |||
349 | 60 | class Status(object): | ||
350 | 61 | '''A class representing the Status structure used by the twitter API. | ||
351 | 62 | |||
352 | 63 | The Status structure exposes the following properties: | ||
353 | 64 | |||
354 | 65 | status.created_at | ||
355 | 66 | status.created_at_in_seconds # read only | ||
356 | 67 | status.favorited | ||
357 | 68 | status.in_reply_to_screen_name | ||
358 | 69 | status.in_reply_to_user_id | ||
359 | 70 | status.in_reply_to_status_id | ||
360 | 71 | status.truncated | ||
361 | 72 | status.source | ||
362 | 73 | status.id | ||
363 | 74 | status.text | ||
364 | 75 | status.location | ||
365 | 76 | status.relative_created_at # read only | ||
366 | 77 | status.user | ||
367 | 78 | ''' | ||
368 | 79 | def __init__(self, | ||
369 | 80 | created_at=None, | ||
370 | 81 | favorited=None, | ||
371 | 82 | id=None, | ||
372 | 83 | text=None, | ||
373 | 84 | location=None, | ||
374 | 85 | user=None, | ||
375 | 86 | in_reply_to_screen_name=None, | ||
376 | 87 | in_reply_to_user_id=None, | ||
377 | 88 | in_reply_to_status_id=None, | ||
378 | 89 | truncated=None, | ||
379 | 90 | source=None, | ||
380 | 91 | now=None): | ||
381 | 92 | '''An object to hold a Twitter status message. | ||
382 | 93 | |||
383 | 94 | This class is normally instantiated by the twitter.Api class and | ||
384 | 95 | returned in a sequence. | ||
385 | 96 | |||
386 | 97 | Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007" | ||
387 | 98 | |||
388 | 99 | Args: | ||
389 | 100 | created_at: The time this status message was posted | ||
390 | 101 | favorited: Whether this is a favorite of the authenticated user | ||
391 | 102 | id: The unique id of this status message | ||
392 | 103 | text: The text of this status message | ||
393 | 104 | location: the geolocation string associated with this message | ||
394 | 105 | relative_created_at: | ||
395 | 106 | A human readable string representing the posting time | ||
396 | 107 | user: | ||
397 | 108 | A twitter.User instance representing the person posting the message | ||
398 | 109 | now: | ||
399 | 110 | The current time, if the client choses to set it. Defaults to the | ||
400 | 111 | wall clock time. | ||
401 | 112 | ''' | ||
402 | 113 | self.created_at = created_at | ||
403 | 114 | self.favorited = favorited | ||
404 | 115 | self.id = id | ||
405 | 116 | self.text = text | ||
406 | 117 | self.location = location | ||
407 | 118 | self.user = user | ||
408 | 119 | self.now = now | ||
409 | 120 | self.in_reply_to_screen_name = in_reply_to_screen_name | ||
410 | 121 | self.in_reply_to_user_id = in_reply_to_user_id | ||
411 | 122 | self.in_reply_to_status_id = in_reply_to_status_id | ||
412 | 123 | self.truncated = truncated | ||
413 | 124 | self.source = source | ||
414 | 125 | |||
415 | 126 | def GetCreatedAt(self): | ||
416 | 127 | '''Get the time this status message was posted. | ||
417 | 128 | |||
418 | 129 | Returns: | ||
419 | 130 | The time this status message was posted | ||
420 | 131 | ''' | ||
421 | 132 | return self._created_at | ||
422 | 133 | |||
423 | 134 | def SetCreatedAt(self, created_at): | ||
424 | 135 | '''Set the time this status message was posted. | ||
425 | 136 | |||
426 | 137 | Args: | ||
427 | 138 | created_at: The time this status message was created | ||
428 | 139 | ''' | ||
429 | 140 | self._created_at = created_at | ||
430 | 141 | |||
431 | 142 | created_at = property(GetCreatedAt, SetCreatedAt, | ||
432 | 143 | doc='The time this status message was posted.') | ||
433 | 144 | |||
434 | 145 | def GetCreatedAtInSeconds(self): | ||
435 | 146 | '''Get the time this status message was posted, in seconds since the epoch. | ||
436 | 147 | |||
437 | 148 | Returns: | ||
438 | 149 | The time this status message was posted, in seconds since the epoch. | ||
439 | 150 | ''' | ||
440 | 151 | return calendar.timegm(rfc822.parsedate(self.created_at)) | ||
441 | 152 | |||
442 | 153 | created_at_in_seconds = property(GetCreatedAtInSeconds, | ||
443 | 154 | doc="The time this status message was " | ||
444 | 155 | "posted, in seconds since the epoch") | ||
445 | 156 | |||
446 | 157 | def GetFavorited(self): | ||
447 | 158 | '''Get the favorited setting of this status message. | ||
448 | 159 | |||
449 | 160 | Returns: | ||
450 | 161 | True if this status message is favorited; False otherwise | ||
451 | 162 | ''' | ||
452 | 163 | return self._favorited | ||
453 | 164 | |||
454 | 165 | def SetFavorited(self, favorited): | ||
455 | 166 | '''Set the favorited state of this status message. | ||
456 | 167 | |||
457 | 168 | Args: | ||
458 | 169 | favorited: boolean True/False favorited state of this status message | ||
459 | 170 | ''' | ||
460 | 171 | self._favorited = favorited | ||
461 | 172 | |||
462 | 173 | favorited = property(GetFavorited, SetFavorited, | ||
463 | 174 | doc='The favorited state of this status message.') | ||
464 | 175 | |||
465 | 176 | def GetId(self): | ||
466 | 177 | '''Get the unique id of this status message. | ||
467 | 178 | |||
468 | 179 | Returns: | ||
469 | 180 | The unique id of this status message | ||
470 | 181 | ''' | ||
471 | 182 | return self._id | ||
472 | 183 | |||
473 | 184 | def SetId(self, id): | ||
474 | 185 | '''Set the unique id of this status message. | ||
475 | 186 | |||
476 | 187 | Args: | ||
477 | 188 | id: The unique id of this status message | ||
478 | 189 | ''' | ||
479 | 190 | self._id = id | ||
480 | 191 | |||
481 | 192 | id = property(GetId, SetId, | ||
482 | 193 | doc='The unique id of this status message.') | ||
483 | 194 | |||
484 | 195 | def GetInReplyToScreenName(self): | ||
485 | 196 | return self._in_reply_to_screen_name | ||
486 | 197 | |||
487 | 198 | def SetInReplyToScreenName(self, in_reply_to_screen_name): | ||
488 | 199 | self._in_reply_to_screen_name = in_reply_to_screen_name | ||
489 | 200 | |||
490 | 201 | in_reply_to_screen_name = property(GetInReplyToScreenName, SetInReplyToScreenName, | ||
491 | 202 | doc='') | ||
492 | 203 | |||
493 | 204 | def GetInReplyToUserId(self): | ||
494 | 205 | return self._in_reply_to_user_id | ||
495 | 206 | |||
496 | 207 | def SetInReplyToUserId(self, in_reply_to_user_id): | ||
497 | 208 | self._in_reply_to_user_id = in_reply_to_user_id | ||
498 | 209 | |||
499 | 210 | in_reply_to_user_id = property(GetInReplyToUserId, SetInReplyToUserId, | ||
500 | 211 | doc='') | ||
501 | 212 | |||
502 | 213 | def GetInReplyToStatusId(self): | ||
503 | 214 | return self._in_reply_to_status_id | ||
504 | 215 | |||
505 | 216 | def SetInReplyToStatusId(self, in_reply_to_status_id): | ||
506 | 217 | self._in_reply_to_status_id = in_reply_to_status_id | ||
507 | 218 | |||
508 | 219 | in_reply_to_status_id = property(GetInReplyToStatusId, SetInReplyToStatusId, | ||
509 | 220 | doc='') | ||
510 | 221 | |||
511 | 222 | def GetTruncated(self): | ||
512 | 223 | return self._truncated | ||
513 | 224 | |||
514 | 225 | def SetTruncated(self, truncated): | ||
515 | 226 | self._truncated = truncated | ||
516 | 227 | |||
517 | 228 | truncated = property(GetTruncated, SetTruncated, | ||
518 | 229 | doc='') | ||
519 | 230 | |||
520 | 231 | def GetSource(self): | ||
521 | 232 | return self._source | ||
522 | 233 | |||
523 | 234 | def SetSource(self, source): | ||
524 | 235 | self._source = source | ||
525 | 236 | |||
526 | 237 | source = property(GetSource, SetSource, | ||
527 | 238 | doc='') | ||
528 | 239 | |||
529 | 240 | def GetText(self): | ||
530 | 241 | '''Get the text of this status message. | ||
531 | 242 | |||
532 | 243 | Returns: | ||
533 | 244 | The text of this status message. | ||
534 | 245 | ''' | ||
535 | 246 | return self._text | ||
536 | 247 | |||
537 | 248 | def SetText(self, text): | ||
538 | 249 | '''Set the text of this status message. | ||
539 | 250 | |||
540 | 251 | Args: | ||
541 | 252 | text: The text of this status message | ||
542 | 253 | ''' | ||
543 | 254 | self._text = text | ||
544 | 255 | |||
545 | 256 | text = property(GetText, SetText, | ||
546 | 257 | doc='The text of this status message') | ||
547 | 258 | |||
548 | 259 | def GetLocation(self): | ||
549 | 260 | '''Get the geolocation associated with this status message | ||
550 | 261 | |||
551 | 262 | Returns: | ||
552 | 263 | The geolocation string of this status message. | ||
553 | 264 | ''' | ||
554 | 265 | return self._location | ||
555 | 266 | |||
556 | 267 | def SetLocation(self, location): | ||
557 | 268 | '''Set the geolocation associated with this status message | ||
558 | 269 | |||
559 | 270 | Args: | ||
560 | 271 | location: The geolocation string of this status message | ||
561 | 272 | ''' | ||
562 | 273 | self._location = location | ||
563 | 274 | |||
564 | 275 | location = property(GetLocation, SetLocation, | ||
565 | 276 | doc='The geolocation string of this status message') | ||
566 | 277 | |||
567 | 278 | def GetRelativeCreatedAt(self): | ||
568 | 279 | '''Get a human redable string representing the posting time | ||
569 | 280 | |||
570 | 281 | Returns: | ||
571 | 282 | A human readable string representing the posting time | ||
572 | 283 | ''' | ||
573 | 284 | fudge = 1.25 | ||
574 | 285 | delta = long(self.now) - long(self.created_at_in_seconds) | ||
575 | 286 | |||
576 | 287 | if delta < (1 * fudge): | ||
577 | 288 | return 'about a second ago' | ||
578 | 289 | elif delta < (60 * (1/fudge)): | ||
579 | 290 | return 'about %d seconds ago' % (delta) | ||
580 | 291 | elif delta < (60 * fudge): | ||
581 | 292 | return 'about a minute ago' | ||
582 | 293 | elif delta < (60 * 60 * (1/fudge)): | ||
583 | 294 | return 'about %d minutes ago' % (delta / 60) | ||
584 | 295 | elif delta < (60 * 60 * fudge) or delta / (60 * 60) == 1: | ||
585 | 296 | return 'about an hour ago' | ||
586 | 297 | elif delta < (60 * 60 * 24 * (1/fudge)): | ||
587 | 298 | return 'about %d hours ago' % (delta / (60 * 60)) | ||
588 | 299 | elif delta < (60 * 60 * 24 * fudge) or delta / (60 * 60 * 24) == 1: | ||
589 | 300 | return 'about a day ago' | ||
590 | 301 | else: | ||
591 | 302 | return 'about %d days ago' % (delta / (60 * 60 * 24)) | ||
592 | 303 | |||
593 | 304 | relative_created_at = property(GetRelativeCreatedAt, | ||
594 | 305 | doc='Get a human readable string representing' | ||
595 | 306 | 'the posting time') | ||
596 | 307 | |||
597 | 308 | def GetUser(self): | ||
598 | 309 | '''Get a twitter.User reprenting the entity posting this status message. | ||
599 | 310 | |||
600 | 311 | Returns: | ||
601 | 312 | A twitter.User reprenting the entity posting this status message | ||
602 | 313 | ''' | ||
603 | 314 | return self._user | ||
604 | 315 | |||
605 | 316 | def SetUser(self, user): | ||
606 | 317 | '''Set a twitter.User reprenting the entity posting this status message. | ||
607 | 318 | |||
608 | 319 | Args: | ||
609 | 320 | user: A twitter.User reprenting the entity posting this status message | ||
610 | 321 | ''' | ||
611 | 322 | self._user = user | ||
612 | 323 | |||
613 | 324 | user = property(GetUser, SetUser, | ||
614 | 325 | doc='A twitter.User reprenting the entity posting this ' | ||
615 | 326 | 'status message') | ||
616 | 327 | |||
617 | 328 | def GetNow(self): | ||
618 | 329 | '''Get the wallclock time for this status message. | ||
619 | 330 | |||
620 | 331 | Used to calculate relative_created_at. Defaults to the time | ||
621 | 332 | the object was instantiated. | ||
622 | 333 | |||
623 | 334 | Returns: | ||
624 | 335 | Whatever the status instance believes the current time to be, | ||
625 | 336 | in seconds since the epoch. | ||
626 | 337 | ''' | ||
627 | 338 | if self._now is None: | ||
628 | 339 | self._now = time.time() | ||
629 | 340 | return self._now | ||
630 | 341 | |||
631 | 342 | def SetNow(self, now): | ||
632 | 343 | '''Set the wallclock time for this status message. | ||
633 | 344 | |||
634 | 345 | Used to calculate relative_created_at. Defaults to the time | ||
635 | 346 | the object was instantiated. | ||
636 | 347 | |||
637 | 348 | Args: | ||
638 | 349 | now: The wallclock time for this instance. | ||
639 | 350 | ''' | ||
640 | 351 | self._now = now | ||
641 | 352 | |||
642 | 353 | now = property(GetNow, SetNow, | ||
643 | 354 | doc='The wallclock time for this status instance.') | ||
644 | 355 | |||
645 | 356 | |||
646 | 357 | def __ne__(self, other): | ||
647 | 358 | return not self.__eq__(other) | ||
648 | 359 | |||
649 | 360 | def __eq__(self, other): | ||
650 | 361 | try: | ||
651 | 362 | return other and \ | ||
652 | 363 | self.created_at == other.created_at and \ | ||
653 | 364 | self.id == other.id and \ | ||
654 | 365 | self.text == other.text and \ | ||
655 | 366 | self.location == other.location and \ | ||
656 | 367 | self.user == other.user and \ | ||
657 | 368 | self.in_reply_to_screen_name == other.in_reply_to_screen_name and \ | ||
658 | 369 | self.in_reply_to_user_id == other.in_reply_to_user_id and \ | ||
659 | 370 | self.in_reply_to_status_id == other.in_reply_to_status_id and \ | ||
660 | 371 | self.truncated == other.truncated and \ | ||
661 | 372 | self.favorited == other.favorited and \ | ||
662 | 373 | self.source == other.source | ||
663 | 374 | except AttributeError: | ||
664 | 375 | return False | ||
665 | 376 | |||
666 | 377 | def __str__(self): | ||
667 | 378 | '''A string representation of this twitter.Status instance. | ||
668 | 379 | |||
669 | 380 | The return value is the same as the JSON string representation. | ||
670 | 381 | |||
671 | 382 | Returns: | ||
672 | 383 | A string representation of this twitter.Status instance. | ||
673 | 384 | ''' | ||
674 | 385 | return self.AsJsonString() | ||
675 | 386 | |||
676 | 387 | def AsJsonString(self): | ||
677 | 388 | '''A JSON string representation of this twitter.Status instance. | ||
678 | 389 | |||
679 | 390 | Returns: | ||
680 | 391 | A JSON string representation of this twitter.Status instance | ||
681 | 392 | ''' | ||
682 | 393 | return simplejson.dumps(self.AsDict(), sort_keys=True) | ||
683 | 394 | |||
684 | 395 | def AsDict(self): | ||
685 | 396 | '''A dict representation of this twitter.Status instance. | ||
686 | 397 | |||
687 | 398 | The return value uses the same key names as the JSON representation. | ||
688 | 399 | |||
689 | 400 | Return: | ||
690 | 401 | A dict representing this twitter.Status instance | ||
691 | 402 | ''' | ||
692 | 403 | data = {} | ||
693 | 404 | if self.created_at: | ||
694 | 405 | data['created_at'] = self.created_at | ||
695 | 406 | if self.favorited: | ||
696 | 407 | data['favorited'] = self.favorited | ||
697 | 408 | if self.id: | ||
698 | 409 | data['id'] = self.id | ||
699 | 410 | if self.text: | ||
700 | 411 | data['text'] = self.text | ||
701 | 412 | if self.location: | ||
702 | 413 | data['location'] = self.location | ||
703 | 414 | if self.user: | ||
704 | 415 | data['user'] = self.user.AsDict() | ||
705 | 416 | if self.in_reply_to_screen_name: | ||
706 | 417 | data['in_reply_to_screen_name'] = self.in_reply_to_screen_name | ||
707 | 418 | if self.in_reply_to_user_id: | ||
708 | 419 | data['in_reply_to_user_id'] = self.in_reply_to_user_id | ||
709 | 420 | if self.in_reply_to_status_id: | ||
710 | 421 | data['in_reply_to_status_id'] = self.in_reply_to_status_id | ||
711 | 422 | if self.truncated is not None: | ||
712 | 423 | data['truncated'] = self.truncated | ||
713 | 424 | if self.favorited is not None: | ||
714 | 425 | data['favorited'] = self.favorited | ||
715 | 426 | if self.source: | ||
716 | 427 | data['source'] = self.source | ||
717 | 428 | return data | ||
718 | 429 | |||
719 | 430 | @staticmethod | ||
720 | 431 | def NewFromJsonDict(data): | ||
721 | 432 | '''Create a new instance based on a JSON dict. | ||
722 | 433 | |||
723 | 434 | Args: | ||
724 | 435 | data: A JSON dict, as converted from the JSON in the twitter API | ||
725 | 436 | Returns: | ||
726 | 437 | A twitter.Status instance | ||
727 | 438 | ''' | ||
728 | 439 | if 'user' in data: | ||
729 | 440 | user = User.NewFromJsonDict(data['user']) | ||
730 | 441 | else: | ||
731 | 442 | user = None | ||
732 | 443 | return Status(created_at=data.get('created_at', None), | ||
733 | 444 | favorited=data.get('favorited', None), | ||
734 | 445 | id=data.get('id', None), | ||
735 | 446 | text=data.get('text', None), | ||
736 | 447 | location=data.get('location', None), | ||
737 | 448 | in_reply_to_screen_name=data.get('in_reply_to_screen_name', None), | ||
738 | 449 | in_reply_to_user_id=data.get('in_reply_to_user_id', None), | ||
739 | 450 | in_reply_to_status_id=data.get('in_reply_to_status_id', None), | ||
740 | 451 | truncated=data.get('truncated', None), | ||
741 | 452 | source=data.get('source', None), | ||
742 | 453 | user=user) | ||
743 | 454 | |||
744 | 455 | |||
745 | 456 | class User(object): | ||
746 | 457 | '''A class representing the User structure used by the twitter API. | ||
747 | 458 | |||
748 | 459 | The User structure exposes the following properties: | ||
749 | 460 | |||
750 | 461 | user.id | ||
751 | 462 | user.name | ||
752 | 463 | user.screen_name | ||
753 | 464 | user.location | ||
754 | 465 | user.description | ||
755 | 466 | user.profile_image_url | ||
756 | 467 | user.profile_background_tile | ||
757 | 468 | user.profile_background_image_url | ||
758 | 469 | user.profile_sidebar_fill_color | ||
759 | 470 | user.profile_background_color | ||
760 | 471 | user.profile_link_color | ||
761 | 472 | user.profile_text_color | ||
762 | 473 | user.protected | ||
763 | 474 | user.utc_offset | ||
764 | 475 | user.time_zone | ||
765 | 476 | user.url | ||
766 | 477 | user.status | ||
767 | 478 | user.statuses_count | ||
768 | 479 | user.followers_count | ||
769 | 480 | user.friends_count | ||
770 | 481 | user.favourites_count | ||
771 | 482 | ''' | ||
772 | 483 | def __init__(self, | ||
773 | 484 | id=None, | ||
774 | 485 | name=None, | ||
775 | 486 | screen_name=None, | ||
776 | 487 | location=None, | ||
777 | 488 | description=None, | ||
778 | 489 | profile_image_url=None, | ||
779 | 490 | profile_background_tile=None, | ||
780 | 491 | profile_background_image_url=None, | ||
781 | 492 | profile_sidebar_fill_color=None, | ||
782 | 493 | profile_background_color=None, | ||
783 | 494 | profile_link_color=None, | ||
784 | 495 | profile_text_color=None, | ||
785 | 496 | protected=None, | ||
786 | 497 | utc_offset=None, | ||
787 | 498 | time_zone=None, | ||
788 | 499 | followers_count=None, | ||
789 | 500 | friends_count=None, | ||
790 | 501 | statuses_count=None, | ||
791 | 502 | favourites_count=None, | ||
792 | 503 | url=None, | ||
793 | 504 | status=None): | ||
794 | 505 | self.id = id | ||
795 | 506 | self.name = name | ||
796 | 507 | self.screen_name = screen_name | ||
797 | 508 | self.location = location | ||
798 | 509 | self.description = description | ||
799 | 510 | self.profile_image_url = profile_image_url | ||
800 | 511 | self.profile_background_tile = profile_background_tile | ||
801 | 512 | self.profile_background_image_url = profile_background_image_url | ||
802 | 513 | self.profile_sidebar_fill_color = profile_sidebar_fill_color | ||
803 | 514 | self.profile_background_color = profile_background_color | ||
804 | 515 | self.profile_link_color = profile_link_color | ||
805 | 516 | self.profile_text_color = profile_text_color | ||
806 | 517 | self.protected = protected | ||
807 | 518 | self.utc_offset = utc_offset | ||
808 | 519 | self.time_zone = time_zone | ||
809 | 520 | self.followers_count = followers_count | ||
810 | 521 | self.friends_count = friends_count | ||
811 | 522 | self.statuses_count = statuses_count | ||
812 | 523 | self.favourites_count = favourites_count | ||
813 | 524 | self.url = url | ||
814 | 525 | self.status = status | ||
815 | 526 | |||
816 | 527 | |||
817 | 528 | def GetId(self): | ||
818 | 529 | '''Get the unique id of this user. | ||
819 | 530 | |||
820 | 531 | Returns: | ||
821 | 532 | The unique id of this user | ||
822 | 533 | ''' | ||
823 | 534 | return self._id | ||
824 | 535 | |||
825 | 536 | def SetId(self, id): | ||
826 | 537 | '''Set the unique id of this user. | ||
827 | 538 | |||
828 | 539 | Args: | ||
829 | 540 | id: The unique id of this user. | ||
830 | 541 | ''' | ||
831 | 542 | self._id = id | ||
832 | 543 | |||
833 | 544 | id = property(GetId, SetId, | ||
834 | 545 | doc='The unique id of this user.') | ||
835 | 546 | |||
836 | 547 | def GetName(self): | ||
837 | 548 | '''Get the real name of this user. | ||
838 | 549 | |||
839 | 550 | Returns: | ||
840 | 551 | The real name of this user | ||
841 | 552 | ''' | ||
842 | 553 | return self._name | ||
843 | 554 | |||
844 | 555 | def SetName(self, name): | ||
845 | 556 | '''Set the real name of this user. | ||
846 | 557 | |||
847 | 558 | Args: | ||
848 | 559 | name: The real name of this user | ||
849 | 560 | ''' | ||
850 | 561 | self._name = name | ||
851 | 562 | |||
852 | 563 | name = property(GetName, SetName, | ||
853 | 564 | doc='The real name of this user.') | ||
854 | 565 | |||
855 | 566 | def GetScreenName(self): | ||
856 | 567 | '''Get the short username of this user. | ||
857 | 568 | |||
858 | 569 | Returns: | ||
859 | 570 | The short username of this user | ||
860 | 571 | ''' | ||
861 | 572 | return self._screen_name | ||
862 | 573 | |||
863 | 574 | def SetScreenName(self, screen_name): | ||
864 | 575 | '''Set the short username of this user. | ||
865 | 576 | |||
866 | 577 | Args: | ||
867 | 578 | screen_name: the short username of this user | ||
868 | 579 | ''' | ||
869 | 580 | self._screen_name = screen_name | ||
870 | 581 | |||
871 | 582 | screen_name = property(GetScreenName, SetScreenName, | ||
872 | 583 | doc='The short username of this user.') | ||
873 | 584 | |||
874 | 585 | def GetLocation(self): | ||
875 | 586 | '''Get the geographic location of this user. | ||
876 | 587 | |||
877 | 588 | Returns: | ||
878 | 589 | The geographic location of this user | ||
879 | 590 | ''' | ||
880 | 591 | return self._location | ||
881 | 592 | |||
882 | 593 | def SetLocation(self, location): | ||
883 | 594 | '''Set the geographic location of this user. | ||
884 | 595 | |||
885 | 596 | Args: | ||
886 | 597 | location: The geographic location of this user | ||
887 | 598 | ''' | ||
888 | 599 | self._location = location | ||
889 | 600 | |||
890 | 601 | location = property(GetLocation, SetLocation, | ||
891 | 602 | doc='The geographic location of this user.') | ||
892 | 603 | |||
893 | 604 | def GetDescription(self): | ||
894 | 605 | '''Get the short text description of this user. | ||
895 | 606 | |||
896 | 607 | Returns: | ||
897 | 608 | The short text description of this user | ||
898 | 609 | ''' | ||
899 | 610 | return self._description | ||
900 | 611 | |||
901 | 612 | def SetDescription(self, description): | ||
902 | 613 | '''Set the short text description of this user. | ||
903 | 614 | |||
904 | 615 | Args: | ||
905 | 616 | description: The short text description of this user | ||
906 | 617 | ''' | ||
907 | 618 | self._description = description | ||
908 | 619 | |||
909 | 620 | description = property(GetDescription, SetDescription, | ||
910 | 621 | doc='The short text description of this user.') | ||
911 | 622 | |||
912 | 623 | def GetUrl(self): | ||
913 | 624 | '''Get the homepage url of this user. | ||
914 | 625 | |||
915 | 626 | Returns: | ||
916 | 627 | The homepage url of this user | ||
917 | 628 | ''' | ||
918 | 629 | return self._url | ||
919 | 630 | |||
920 | 631 | def SetUrl(self, url): | ||
921 | 632 | '''Set the homepage url of this user. | ||
922 | 633 | |||
923 | 634 | Args: | ||
924 | 635 | url: The homepage url of this user | ||
925 | 636 | ''' | ||
926 | 637 | self._url = url | ||
927 | 638 | |||
928 | 639 | url = property(GetUrl, SetUrl, | ||
929 | 640 | doc='The homepage url of this user.') | ||
930 | 641 | |||
931 | 642 | def GetProfileImageUrl(self): | ||
932 | 643 | '''Get the url of the thumbnail of this user. | ||
933 | 644 | |||
934 | 645 | Returns: | ||
935 | 646 | The url of the thumbnail of this user | ||
936 | 647 | ''' | ||
937 | 648 | return self._profile_image_url | ||
938 | 649 | |||
939 | 650 | def SetProfileImageUrl(self, profile_image_url): | ||
940 | 651 | '''Set the url of the thumbnail of this user. | ||
941 | 652 | |||
942 | 653 | Args: | ||
943 | 654 | profile_image_url: The url of the thumbnail of this user | ||
944 | 655 | ''' | ||
945 | 656 | self._profile_image_url = profile_image_url | ||
946 | 657 | |||
947 | 658 | profile_image_url= property(GetProfileImageUrl, SetProfileImageUrl, | ||
948 | 659 | doc='The url of the thumbnail of this user.') | ||
949 | 660 | |||
950 | 661 | def GetProfileBackgroundTile(self): | ||
951 | 662 | '''Boolean for whether to tile the profile background image. | ||
952 | 663 | |||
953 | 664 | Returns: | ||
954 | 665 | True if the background is to be tiled, False if not, None if unset. | ||
955 | 666 | ''' | ||
956 | 667 | return self._profile_background_tile | ||
957 | 668 | |||
958 | 669 | def SetProfileBackgroundTile(self, profile_background_tile): | ||
959 | 670 | '''Set the boolean flag for whether to tile the profile background image. | ||
960 | 671 | |||
961 | 672 | Args: | ||
962 | 673 | profile_background_tile: Boolean flag for whether to tile or not. | ||
963 | 674 | ''' | ||
964 | 675 | self._profile_background_tile = profile_background_tile | ||
965 | 676 | |||
966 | 677 | profile_background_tile = property(GetProfileBackgroundTile, SetProfileBackgroundTile, | ||
967 | 678 | doc='Boolean for whether to tile the background image.') | ||
968 | 679 | |||
969 | 680 | def GetProfileBackgroundImageUrl(self): | ||
970 | 681 | return self._profile_background_image_url | ||
971 | 682 | |||
972 | 683 | def SetProfileBackgroundImageUrl(self, profile_background_image_url): | ||
973 | 684 | self._profile_background_image_url = profile_background_image_url | ||
974 | 685 | |||
975 | 686 | profile_background_image_url = property(GetProfileBackgroundImageUrl, SetProfileBackgroundImageUrl, | ||
976 | 687 | doc='The url of the profile background of this user.') | ||
977 | 688 | |||
978 | 689 | def GetProfileSidebarFillColor(self): | ||
979 | 690 | return self._profile_sidebar_fill_color | ||
980 | 691 | |||
981 | 692 | def SetProfileSidebarFillColor(self, profile_sidebar_fill_color): | ||
982 | 693 | self._profile_sidebar_fill_color = profile_sidebar_fill_color | ||
983 | 694 | |||
984 | 695 | profile_sidebar_fill_color = property(GetProfileSidebarFillColor, SetProfileSidebarFillColor) | ||
985 | 696 | |||
986 | 697 | def GetProfileBackgroundColor(self): | ||
987 | 698 | return self._profile_background_color | ||
988 | 699 | |||
989 | 700 | def SetProfileBackgroundColor(self, profile_background_color): | ||
990 | 701 | self._profile_background_color = profile_background_color | ||
991 | 702 | |||
992 | 703 | profile_background_color = property(GetProfileBackgroundColor, SetProfileBackgroundColor) | ||
993 | 704 | |||
994 | 705 | def GetProfileLinkColor(self): | ||
995 | 706 | return self._profile_link_color | ||
996 | 707 | |||
997 | 708 | def SetProfileLinkColor(self, profile_link_color): | ||
998 | 709 | self._profile_link_color = profile_link_color | ||
999 | 710 | |||
1000 | 711 | profile_link_color = property(GetProfileLinkColor, SetProfileLinkColor) | ||
1001 | 712 | |||
1002 | 713 | def GetProfileTextColor(self): | ||
1003 | 714 | return self._profile_text_color | ||
1004 | 715 | |||
1005 | 716 | def SetProfileTextColor(self, profile_text_color): | ||
1006 | 717 | self._profile_text_color = profile_text_color | ||
1007 | 718 | |||
1008 | 719 | profile_text_color = property(GetProfileTextColor, SetProfileTextColor) | ||
1009 | 720 | |||
1010 | 721 | def GetProtected(self): | ||
1011 | 722 | return self._protected | ||
1012 | 723 | |||
1013 | 724 | def SetProtected(self, protected): | ||
1014 | 725 | self._protected = protected | ||
1015 | 726 | |||
1016 | 727 | protected = property(GetProtected, SetProtected) | ||
1017 | 728 | |||
1018 | 729 | def GetUtcOffset(self): | ||
1019 | 730 | return self._utc_offset | ||
1020 | 731 | |||
1021 | 732 | def SetUtcOffset(self, utc_offset): | ||
1022 | 733 | self._utc_offset = utc_offset | ||
1023 | 734 | |||
1024 | 735 | utc_offset = property(GetUtcOffset, SetUtcOffset) | ||
1025 | 736 | |||
1026 | 737 | def GetTimeZone(self): | ||
1027 | 738 | '''Returns the current time zone string for the user. | ||
1028 | 739 | |||
1029 | 740 | Returns: | ||
1030 | 741 | The descriptive time zone string for the user. | ||
1031 | 742 | ''' | ||
1032 | 743 | return self._time_zone | ||
1033 | 744 | |||
1034 | 745 | def SetTimeZone(self, time_zone): | ||
1035 | 746 | '''Sets the user's time zone string. | ||
1036 | 747 | |||
1037 | 748 | Args: | ||
1038 | 749 | time_zone: The descriptive time zone to assign for the user. | ||
1039 | 750 | ''' | ||
1040 | 751 | self._time_zone = time_zone | ||
1041 | 752 | |||
1042 | 753 | time_zone = property(GetTimeZone, SetTimeZone) | ||
1043 | 754 | |||
1044 | 755 | def GetStatus(self): | ||
1045 | 756 | '''Get the latest twitter.Status of this user. | ||
1046 | 757 | |||
1047 | 758 | Returns: | ||
1048 | 759 | The latest twitter.Status of this user | ||
1049 | 760 | ''' | ||
1050 | 761 | return self._status | ||
1051 | 762 | |||
1052 | 763 | def SetStatus(self, status): | ||
1053 | 764 | '''Set the latest twitter.Status of this user. | ||
1054 | 765 | |||
1055 | 766 | Args: | ||
1056 | 767 | status: The latest twitter.Status of this user | ||
1057 | 768 | ''' | ||
1058 | 769 | self._status = status | ||
1059 | 770 | |||
1060 | 771 | status = property(GetStatus, SetStatus, | ||
1061 | 772 | doc='The latest twitter.Status of this user.') | ||
1062 | 773 | |||
1063 | 774 | def GetFriendsCount(self): | ||
1064 | 775 | '''Get the friend count for this user. | ||
1065 | 776 | |||
1066 | 777 | Returns: | ||
1067 | 778 | The number of users this user has befriended. | ||
1068 | 779 | ''' | ||
1069 | 780 | return self._friends_count | ||
1070 | 781 | |||
1071 | 782 | def SetFriendsCount(self, count): | ||
1072 | 783 | '''Set the friend count for this user. | ||
1073 | 784 | |||
1074 | 785 | Args: | ||
1075 | 786 | count: The number of users this user has befriended. | ||
1076 | 787 | ''' | ||
1077 | 788 | self._friends_count = count | ||
1078 | 789 | |||
1079 | 790 | friends_count = property(GetFriendsCount, SetFriendsCount, | ||
1080 | 791 | doc='The number of friends for this user.') | ||
1081 | 792 | |||
1082 | 793 | def GetFollowersCount(self): | ||
1083 | 794 | '''Get the follower count for this user. | ||
1084 | 795 | |||
1085 | 796 | Returns: | ||
1086 | 797 | The number of users following this user. | ||
1087 | 798 | ''' | ||
1088 | 799 | return self._followers_count | ||
1089 | 800 | |||
1090 | 801 | def SetFollowersCount(self, count): | ||
1091 | 802 | '''Set the follower count for this user. | ||
1092 | 803 | |||
1093 | 804 | Args: | ||
1094 | 805 | count: The number of users following this user. | ||
1095 | 806 | ''' | ||
1096 | 807 | self._followers_count = count | ||
1097 | 808 | |||
1098 | 809 | followers_count = property(GetFollowersCount, SetFollowersCount, | ||
1099 | 810 | doc='The number of users following this user.') | ||
1100 | 811 | |||
1101 | 812 | def GetStatusesCount(self): | ||
1102 | 813 | '''Get the number of status updates for this user. | ||
1103 | 814 | |||
1104 | 815 | Returns: | ||
1105 | 816 | The number of status updates for this user. | ||
1106 | 817 | ''' | ||
1107 | 818 | return self._statuses_count | ||
1108 | 819 | |||
1109 | 820 | def SetStatusesCount(self, count): | ||
1110 | 821 | '''Set the status update count for this user. | ||
1111 | 822 | |||
1112 | 823 | Args: | ||
1113 | 824 | count: The number of updates for this user. | ||
1114 | 825 | ''' | ||
1115 | 826 | self._statuses_count = count | ||
1116 | 827 | |||
1117 | 828 | statuses_count = property(GetStatusesCount, SetStatusesCount, | ||
1118 | 829 | doc='The number of updates for this user.') | ||
1119 | 830 | |||
1120 | 831 | def GetFavouritesCount(self): | ||
1121 | 832 | '''Get the number of favourites for this user. | ||
1122 | 833 | |||
1123 | 834 | Returns: | ||
1124 | 835 | The number of favourites for this user. | ||
1125 | 836 | ''' | ||
1126 | 837 | return self._favourites_count | ||
1127 | 838 | |||
1128 | 839 | def SetFavouritesCount(self, count): | ||
1129 | 840 | '''Set the favourite count for this user. | ||
1130 | 841 | |||
1131 | 842 | Args: | ||
1132 | 843 | count: The number of favourites for this user. | ||
1133 | 844 | ''' | ||
1134 | 845 | self._favourites_count = count | ||
1135 | 846 | |||
1136 | 847 | favourites_count = property(GetFavouritesCount, SetFavouritesCount, | ||
1137 | 848 | doc='The number of favourites for this user.') | ||
1138 | 849 | |||
1139 | 850 | def __ne__(self, other): | ||
1140 | 851 | return not self.__eq__(other) | ||
1141 | 852 | |||
1142 | 853 | def __eq__(self, other): | ||
1143 | 854 | try: | ||
1144 | 855 | return other and \ | ||
1145 | 856 | self.id == other.id and \ | ||
1146 | 857 | self.name == other.name and \ | ||
1147 | 858 | self.screen_name == other.screen_name and \ | ||
1148 | 859 | self.location == other.location and \ | ||
1149 | 860 | self.description == other.description and \ | ||
1150 | 861 | self.profile_image_url == other.profile_image_url and \ | ||
1151 | 862 | self.profile_background_tile == other.profile_background_tile and \ | ||
1152 | 863 | self.profile_background_image_url == other.profile_background_image_url and \ | ||
1153 | 864 | self.profile_sidebar_fill_color == other.profile_sidebar_fill_color and \ | ||
1154 | 865 | self.profile_background_color == other.profile_background_color and \ | ||
1155 | 866 | self.profile_link_color == other.profile_link_color and \ | ||
1156 | 867 | self.profile_text_color == other.profile_text_color and \ | ||
1157 | 868 | self.protected == other.protected and \ | ||
1158 | 869 | self.utc_offset == other.utc_offset and \ | ||
1159 | 870 | self.time_zone == other.time_zone and \ | ||
1160 | 871 | self.url == other.url and \ | ||
1161 | 872 | self.statuses_count == other.statuses_count and \ | ||
1162 | 873 | self.followers_count == other.followers_count and \ | ||
1163 | 874 | self.favourites_count == other.favourites_count and \ | ||
1164 | 875 | self.friends_count == other.friends_count and \ | ||
1165 | 876 | self.status == other.status | ||
1166 | 877 | except AttributeError: | ||
1167 | 878 | return False | ||
1168 | 879 | |||
1169 | 880 | def __str__(self): | ||
1170 | 881 | '''A string representation of this twitter.User instance. | ||
1171 | 882 | |||
1172 | 883 | The return value is the same as the JSON string representation. | ||
1173 | 884 | |||
1174 | 885 | Returns: | ||
1175 | 886 | A string representation of this twitter.User instance. | ||
1176 | 887 | ''' | ||
1177 | 888 | return self.AsJsonString() | ||
1178 | 889 | |||
1179 | 890 | def AsJsonString(self): | ||
1180 | 891 | '''A JSON string representation of this twitter.User instance. | ||
1181 | 892 | |||
1182 | 893 | Returns: | ||
1183 | 894 | A JSON string representation of this twitter.User instance | ||
1184 | 895 | ''' | ||
1185 | 896 | return simplejson.dumps(self.AsDict(), sort_keys=True) | ||
1186 | 897 | |||
1187 | 898 | def AsDict(self): | ||
1188 | 899 | '''A dict representation of this twitter.User instance. | ||
1189 | 900 | |||
1190 | 901 | The return value uses the same key names as the JSON representation. | ||
1191 | 902 | |||
1192 | 903 | Return: | ||
1193 | 904 | A dict representing this twitter.User instance | ||
1194 | 905 | ''' | ||
1195 | 906 | data = {} | ||
1196 | 907 | if self.id: | ||
1197 | 908 | data['id'] = self.id | ||
1198 | 909 | if self.name: | ||
1199 | 910 | data['name'] = self.name | ||
1200 | 911 | if self.screen_name: | ||
1201 | 912 | data['screen_name'] = self.screen_name | ||
1202 | 913 | if self.location: | ||
1203 | 914 | data['location'] = self.location | ||
1204 | 915 | if self.description: | ||
1205 | 916 | data['description'] = self.description | ||
1206 | 917 | if self.profile_image_url: | ||
1207 | 918 | data['profile_image_url'] = self.profile_image_url | ||
1208 | 919 | if self.profile_background_tile is not None: | ||
1209 | 920 | data['profile_background_tile'] = self.profile_background_tile | ||
1210 | 921 | if self.profile_background_image_url: | ||
1211 | 922 | data['profile_sidebar_fill_color'] = self.profile_background_image_url | ||
1212 | 923 | if self.profile_background_color: | ||
1213 | 924 | data['profile_background_color'] = self.profile_background_color | ||
1214 | 925 | if self.profile_link_color: | ||
1215 | 926 | data['profile_link_color'] = self.profile_link_color | ||
1216 | 927 | if self.profile_text_color: | ||
1217 | 928 | data['profile_text_color'] = self.profile_text_color | ||
1218 | 929 | if self.protected is not None: | ||
1219 | 930 | data['protected'] = self.protected | ||
1220 | 931 | if self.utc_offset: | ||
1221 | 932 | data['utc_offset'] = self.utc_offset | ||
1222 | 933 | if self.time_zone: | ||
1223 | 934 | data['time_zone'] = self.time_zone | ||
1224 | 935 | if self.url: | ||
1225 | 936 | data['url'] = self.url | ||
1226 | 937 | if self.status: | ||
1227 | 938 | data['status'] = self.status.AsDict() | ||
1228 | 939 | if self.friends_count: | ||
1229 | 940 | data['friends_count'] = self.friends_count | ||
1230 | 941 | if self.followers_count: | ||
1231 | 942 | data['followers_count'] = self.followers_count | ||
1232 | 943 | if self.statuses_count: | ||
1233 | 944 | data['statuses_count'] = self.statuses_count | ||
1234 | 945 | if self.favourites_count: | ||
1235 | 946 | data['favourites_count'] = self.favourites_count | ||
1236 | 947 | return data | ||
1237 | 948 | |||
1238 | 949 | @staticmethod | ||
1239 | 950 | def NewFromJsonDict(data): | ||
1240 | 951 | '''Create a new instance based on a JSON dict. | ||
1241 | 952 | |||
1242 | 953 | Args: | ||
1243 | 954 | data: A JSON dict, as converted from the JSON in the twitter API | ||
1244 | 955 | Returns: | ||
1245 | 956 | A twitter.User instance | ||
1246 | 957 | ''' | ||
1247 | 958 | if 'status' in data: | ||
1248 | 959 | status = Status.NewFromJsonDict(data['status']) | ||
1249 | 960 | else: | ||
1250 | 961 | status = None | ||
1251 | 962 | return User(id=data.get('id', None), | ||
1252 | 963 | name=data.get('name', None), | ||
1253 | 964 | screen_name=data.get('screen_name', None), | ||
1254 | 965 | location=data.get('location', None), | ||
1255 | 966 | description=data.get('description', None), | ||
1256 | 967 | statuses_count=data.get('statuses_count', None), | ||
1257 | 968 | followers_count=data.get('followers_count', None), | ||
1258 | 969 | favourites_count=data.get('favourites_count', None), | ||
1259 | 970 | friends_count=data.get('friends_count', None), | ||
1260 | 971 | profile_image_url=data.get('profile_image_url', None), | ||
1261 | 972 | profile_background_tile = data.get('profile_background_tile', None), | ||
1262 | 973 | profile_background_image_url = data.get('profile_background_image_url', None), | ||
1263 | 974 | profile_sidebar_fill_color = data.get('profile_sidebar_fill_color', None), | ||
1264 | 975 | profile_background_color = data.get('profile_background_color', None), | ||
1265 | 976 | profile_link_color = data.get('profile_link_color', None), | ||
1266 | 977 | profile_text_color = data.get('profile_text_color', None), | ||
1267 | 978 | protected = data.get('protected', None), | ||
1268 | 979 | utc_offset = data.get('utc_offset', None), | ||
1269 | 980 | time_zone = data.get('time_zone', None), | ||
1270 | 981 | url=data.get('url', None), | ||
1271 | 982 | status=status) | ||
1272 | 983 | |||
1273 | 984 | class DirectMessage(object): | ||
1274 | 985 | '''A class representing the DirectMessage structure used by the twitter API. | ||
1275 | 986 | |||
1276 | 987 | The DirectMessage structure exposes the following properties: | ||
1277 | 988 | |||
1278 | 989 | direct_message.id | ||
1279 | 990 | direct_message.created_at | ||
1280 | 991 | direct_message.created_at_in_seconds # read only | ||
1281 | 992 | direct_message.sender_id | ||
1282 | 993 | direct_message.sender_screen_name | ||
1283 | 994 | direct_message.recipient_id | ||
1284 | 995 | direct_message.recipient_screen_name | ||
1285 | 996 | direct_message.text | ||
1286 | 997 | ''' | ||
1287 | 998 | |||
1288 | 999 | def __init__(self, | ||
1289 | 1000 | id=None, | ||
1290 | 1001 | created_at=None, | ||
1291 | 1002 | sender_id=None, | ||
1292 | 1003 | sender_screen_name=None, | ||
1293 | 1004 | recipient_id=None, | ||
1294 | 1005 | recipient_screen_name=None, | ||
1295 | 1006 | text=None): | ||
1296 | 1007 | '''An object to hold a Twitter direct message. | ||
1297 | 1008 | |||
1298 | 1009 | This class is normally instantiated by the twitter.Api class and | ||
1299 | 1010 | returned in a sequence. | ||
1300 | 1011 | |||
1301 | 1012 | Note: Dates are posted in the form "Sat Jan 27 04:17:38 +0000 2007" | ||
1302 | 1013 | |||
1303 | 1014 | Args: | ||
1304 | 1015 | id: The unique id of this direct message | ||
1305 | 1016 | created_at: The time this direct message was posted | ||
1306 | 1017 | sender_id: The id of the twitter user that sent this message | ||
1307 | 1018 | sender_screen_name: The name of the twitter user that sent this message | ||
1308 | 1019 | recipient_id: The id of the twitter that received this message | ||
1309 | 1020 | recipient_screen_name: The name of the twitter that received this message | ||
1310 | 1021 | text: The text of this direct message | ||
1311 | 1022 | ''' | ||
1312 | 1023 | self.id = id | ||
1313 | 1024 | self.created_at = created_at | ||
1314 | 1025 | self.sender_id = sender_id | ||
1315 | 1026 | self.sender_screen_name = sender_screen_name | ||
1316 | 1027 | self.recipient_id = recipient_id | ||
1317 | 1028 | self.recipient_screen_name = recipient_screen_name | ||
1318 | 1029 | self.text = text | ||
1319 | 1030 | |||
1320 | 1031 | def GetId(self): | ||
1321 | 1032 | '''Get the unique id of this direct message. | ||
1322 | 1033 | |||
1323 | 1034 | Returns: | ||
1324 | 1035 | The unique id of this direct message | ||
1325 | 1036 | ''' | ||
1326 | 1037 | return self._id | ||
1327 | 1038 | |||
1328 | 1039 | def SetId(self, id): | ||
1329 | 1040 | '''Set the unique id of this direct message. | ||
1330 | 1041 | |||
1331 | 1042 | Args: | ||
1332 | 1043 | id: The unique id of this direct message | ||
1333 | 1044 | ''' | ||
1334 | 1045 | self._id = id | ||
1335 | 1046 | |||
1336 | 1047 | id = property(GetId, SetId, | ||
1337 | 1048 | doc='The unique id of this direct message.') | ||
1338 | 1049 | |||
1339 | 1050 | def GetCreatedAt(self): | ||
1340 | 1051 | '''Get the time this direct message was posted. | ||
1341 | 1052 | |||
1342 | 1053 | Returns: | ||
1343 | 1054 | The time this direct message was posted | ||
1344 | 1055 | ''' | ||
1345 | 1056 | return self._created_at | ||
1346 | 1057 | |||
1347 | 1058 | def SetCreatedAt(self, created_at): | ||
1348 | 1059 | '''Set the time this direct message was posted. | ||
1349 | 1060 | |||
1350 | 1061 | Args: | ||
1351 | 1062 | created_at: The time this direct message was created | ||
1352 | 1063 | ''' | ||
1353 | 1064 | self._created_at = created_at | ||
1354 | 1065 | |||
1355 | 1066 | created_at = property(GetCreatedAt, SetCreatedAt, | ||
1356 | 1067 | doc='The time this direct message was posted.') | ||
1357 | 1068 | |||
1358 | 1069 | def GetCreatedAtInSeconds(self): | ||
1359 | 1070 | '''Get the time this direct message was posted, in seconds since the epoch. | ||
1360 | 1071 | |||
1361 | 1072 | Returns: | ||
1362 | 1073 | The time this direct message was posted, in seconds since the epoch. | ||
1363 | 1074 | ''' | ||
1364 | 1075 | return calendar.timegm(rfc822.parsedate(self.created_at)) | ||
1365 | 1076 | |||
1366 | 1077 | created_at_in_seconds = property(GetCreatedAtInSeconds, | ||
1367 | 1078 | doc="The time this direct message was " | ||
1368 | 1079 | "posted, in seconds since the epoch") | ||
1369 | 1080 | |||
1370 | 1081 | def GetSenderId(self): | ||
1371 | 1082 | '''Get the unique sender id of this direct message. | ||
1372 | 1083 | |||
1373 | 1084 | Returns: | ||
1374 | 1085 | The unique sender id of this direct message | ||
1375 | 1086 | ''' | ||
1376 | 1087 | return self._sender_id | ||
1377 | 1088 | |||
1378 | 1089 | def SetSenderId(self, sender_id): | ||
1379 | 1090 | '''Set the unique sender id of this direct message. | ||
1380 | 1091 | |||
1381 | 1092 | Args: | ||
1382 | 1093 | sender id: The unique sender id of this direct message | ||
1383 | 1094 | ''' | ||
1384 | 1095 | self._sender_id = sender_id | ||
1385 | 1096 | |||
1386 | 1097 | sender_id = property(GetSenderId, SetSenderId, | ||
1387 | 1098 | doc='The unique sender id of this direct message.') | ||
1388 | 1099 | |||
1389 | 1100 | def GetSenderScreenName(self): | ||
1390 | 1101 | '''Get the unique sender screen name of this direct message. | ||
1391 | 1102 | |||
1392 | 1103 | Returns: | ||
1393 | 1104 | The unique sender screen name of this direct message | ||
1394 | 1105 | ''' | ||
1395 | 1106 | return self._sender_screen_name | ||
1396 | 1107 | |||
1397 | 1108 | def SetSenderScreenName(self, sender_screen_name): | ||
1398 | 1109 | '''Set the unique sender screen name of this direct message. | ||
1399 | 1110 | |||
1400 | 1111 | Args: | ||
1401 | 1112 | sender_screen_name: The unique sender screen name of this direct message | ||
1402 | 1113 | ''' | ||
1403 | 1114 | self._sender_screen_name = sender_screen_name | ||
1404 | 1115 | |||
1405 | 1116 | sender_screen_name = property(GetSenderScreenName, SetSenderScreenName, | ||
1406 | 1117 | doc='The unique sender screen name of this direct message.') | ||
1407 | 1118 | |||
1408 | 1119 | def GetRecipientId(self): | ||
1409 | 1120 | '''Get the unique recipient id of this direct message. | ||
1410 | 1121 | |||
1411 | 1122 | Returns: | ||
1412 | 1123 | The unique recipient id of this direct message | ||
1413 | 1124 | ''' | ||
1414 | 1125 | return self._recipient_id | ||
1415 | 1126 | |||
1416 | 1127 | def SetRecipientId(self, recipient_id): | ||
1417 | 1128 | '''Set the unique recipient id of this direct message. | ||
1418 | 1129 | |||
1419 | 1130 | Args: | ||
1420 | 1131 | recipient id: The unique recipient id of this direct message | ||
1421 | 1132 | ''' | ||
1422 | 1133 | self._recipient_id = recipient_id | ||
1423 | 1134 | |||
1424 | 1135 | recipient_id = property(GetRecipientId, SetRecipientId, | ||
1425 | 1136 | doc='The unique recipient id of this direct message.') | ||
1426 | 1137 | |||
1427 | 1138 | def GetRecipientScreenName(self): | ||
1428 | 1139 | '''Get the unique recipient screen name of this direct message. | ||
1429 | 1140 | |||
1430 | 1141 | Returns: | ||
1431 | 1142 | The unique recipient screen name of this direct message | ||
1432 | 1143 | ''' | ||
1433 | 1144 | return self._recipient_screen_name | ||
1434 | 1145 | |||
1435 | 1146 | def SetRecipientScreenName(self, recipient_screen_name): | ||
1436 | 1147 | '''Set the unique recipient screen name of this direct message. | ||
1437 | 1148 | |||
1438 | 1149 | Args: | ||
1439 | 1150 | recipient_screen_name: The unique recipient screen name of this direct message | ||
1440 | 1151 | ''' | ||
1441 | 1152 | self._recipient_screen_name = recipient_screen_name | ||
1442 | 1153 | |||
1443 | 1154 | recipient_screen_name = property(GetRecipientScreenName, SetRecipientScreenName, | ||
1444 | 1155 | doc='The unique recipient screen name of this direct message.') | ||
1445 | 1156 | |||
1446 | 1157 | def GetText(self): | ||
1447 | 1158 | '''Get the text of this direct message. | ||
1448 | 1159 | |||
1449 | 1160 | Returns: | ||
1450 | 1161 | The text of this direct message. | ||
1451 | 1162 | ''' | ||
1452 | 1163 | return self._text | ||
1453 | 1164 | |||
1454 | 1165 | def SetText(self, text): | ||
1455 | 1166 | '''Set the text of this direct message. | ||
1456 | 1167 | |||
1457 | 1168 | Args: | ||
1458 | 1169 | text: The text of this direct message | ||
1459 | 1170 | ''' | ||
1460 | 1171 | self._text = text | ||
1461 | 1172 | |||
1462 | 1173 | text = property(GetText, SetText, | ||
1463 | 1174 | doc='The text of this direct message') | ||
1464 | 1175 | |||
1465 | 1176 | def __ne__(self, other): | ||
1466 | 1177 | return not self.__eq__(other) | ||
1467 | 1178 | |||
1468 | 1179 | def __eq__(self, other): | ||
1469 | 1180 | try: | ||
1470 | 1181 | return other and \ | ||
1471 | 1182 | self.id == other.id and \ | ||
1472 | 1183 | self.created_at == other.created_at and \ | ||
1473 | 1184 | self.sender_id == other.sender_id and \ | ||
1474 | 1185 | self.sender_screen_name == other.sender_screen_name and \ | ||
1475 | 1186 | self.recipient_id == other.recipient_id and \ | ||
1476 | 1187 | self.recipient_screen_name == other.recipient_screen_name and \ | ||
1477 | 1188 | self.text == other.text | ||
1478 | 1189 | except AttributeError: | ||
1479 | 1190 | return False | ||
1480 | 1191 | |||
1481 | 1192 | def __str__(self): | ||
1482 | 1193 | '''A string representation of this twitter.DirectMessage instance. | ||
1483 | 1194 | |||
1484 | 1195 | The return value is the same as the JSON string representation. | ||
1485 | 1196 | |||
1486 | 1197 | Returns: | ||
1487 | 1198 | A string representation of this twitter.DirectMessage instance. | ||
1488 | 1199 | ''' | ||
1489 | 1200 | return self.AsJsonString() | ||
1490 | 1201 | |||
1491 | 1202 | def AsJsonString(self): | ||
1492 | 1203 | '''A JSON string representation of this twitter.DirectMessage instance. | ||
1493 | 1204 | |||
1494 | 1205 | Returns: | ||
1495 | 1206 | A JSON string representation of this twitter.DirectMessage instance | ||
1496 | 1207 | ''' | ||
1497 | 1208 | return simplejson.dumps(self.AsDict(), sort_keys=True) | ||
1498 | 1209 | |||
1499 | 1210 | def AsDict(self): | ||
1500 | 1211 | '''A dict representation of this twitter.DirectMessage instance. | ||
1501 | 1212 | |||
1502 | 1213 | The return value uses the same key names as the JSON representation. | ||
1503 | 1214 | |||
1504 | 1215 | Return: | ||
1505 | 1216 | A dict representing this twitter.DirectMessage instance | ||
1506 | 1217 | ''' | ||
1507 | 1218 | data = {} | ||
1508 | 1219 | if self.id: | ||
1509 | 1220 | data['id'] = self.id | ||
1510 | 1221 | if self.created_at: | ||
1511 | 1222 | data['created_at'] = self.created_at | ||
1512 | 1223 | if self.sender_id: | ||
1513 | 1224 | data['sender_id'] = self.sender_id | ||
1514 | 1225 | if self.sender_screen_name: | ||
1515 | 1226 | data['sender_screen_name'] = self.sender_screen_name | ||
1516 | 1227 | if self.recipient_id: | ||
1517 | 1228 | data['recipient_id'] = self.recipient_id | ||
1518 | 1229 | if self.recipient_screen_name: | ||
1519 | 1230 | data['recipient_screen_name'] = self.recipient_screen_name | ||
1520 | 1231 | if self.text: | ||
1521 | 1232 | data['text'] = self.text | ||
1522 | 1233 | return data | ||
1523 | 1234 | |||
1524 | 1235 | @staticmethod | ||
1525 | 1236 | def NewFromJsonDict(data): | ||
1526 | 1237 | '''Create a new instance based on a JSON dict. | ||
1527 | 1238 | |||
1528 | 1239 | Args: | ||
1529 | 1240 | data: A JSON dict, as converted from the JSON in the twitter API | ||
1530 | 1241 | Returns: | ||
1531 | 1242 | A twitter.DirectMessage instance | ||
1532 | 1243 | ''' | ||
1533 | 1244 | return DirectMessage(created_at=data.get('created_at', None), | ||
1534 | 1245 | recipient_id=data.get('recipient_id', None), | ||
1535 | 1246 | sender_id=data.get('sender_id', None), | ||
1536 | 1247 | text=data.get('text', None), | ||
1537 | 1248 | sender_screen_name=data.get('sender_screen_name', None), | ||
1538 | 1249 | id=data.get('id', None), | ||
1539 | 1250 | recipient_screen_name=data.get('recipient_screen_name', None)) | ||
1540 | 1251 | |||
1541 | 1252 | class Api(object): | ||
1542 | 1253 | '''A python interface into the Twitter API | ||
1543 | 1254 | |||
1544 | 1255 | By default, the Api caches results for 1 minute. | ||
1545 | 1256 | |||
1546 | 1257 | Example usage: | ||
1547 | 1258 | |||
1548 | 1259 | To create an instance of the twitter.Api class, with no authentication: | ||
1549 | 1260 | |||
1550 | 1261 | >>> import twitter | ||
1551 | 1262 | >>> api = twitter.Api() | ||
1552 | 1263 | |||
1553 | 1264 | To fetch the most recently posted public twitter status messages: | ||
1554 | 1265 | |||
1555 | 1266 | >>> statuses = api.GetPublicTimeline() | ||
1556 | 1267 | >>> print [s.user.name for s in statuses] | ||
1557 | 1268 | [u'DeWitt', u'Kesuke Miyagi', u'ev', u'Buzz Andersen', u'Biz Stone'] #... | ||
1558 | 1269 | |||
1559 | 1270 | To fetch a single user's public status messages, where "user" is either | ||
1560 | 1271 | a Twitter "short name" or their user id. | ||
1561 | 1272 | |||
1562 | 1273 | >>> statuses = api.GetUserTimeline(user) | ||
1563 | 1274 | >>> print [s.text for s in statuses] | ||
1564 | 1275 | |||
1565 | 1276 | To use authentication, instantiate the twitter.Api class with a | ||
1566 | 1277 | username and password: | ||
1567 | 1278 | |||
1568 | 1279 | >>> api = twitter.Api(username='twitter user', password='twitter pass') | ||
1569 | 1280 | |||
1570 | 1281 | To fetch your friends (after being authenticated): | ||
1571 | 1282 | |||
1572 | 1283 | >>> users = api.GetFriends() | ||
1573 | 1284 | >>> print [u.name for u in users] | ||
1574 | 1285 | |||
1575 | 1286 | To post a twitter status message (after being authenticated): | ||
1576 | 1287 | |||
1577 | 1288 | >>> status = api.PostUpdate('I love python-twitter!') | ||
1578 | 1289 | >>> print status.text | ||
1579 | 1290 | I love python-twitter! | ||
1580 | 1291 | |||
1581 | 1292 | There are many other methods, including: | ||
1582 | 1293 | |||
1583 | 1294 | >>> api.PostUpdates(status) | ||
1584 | 1295 | >>> api.PostDirectMessage(user, text) | ||
1585 | 1296 | >>> api.GetUser(user) | ||
1586 | 1297 | >>> api.GetReplies() | ||
1587 | 1298 | >>> api.GetUserTimeline(user) | ||
1588 | 1299 | >>> api.GetStatus(id) | ||
1589 | 1300 | >>> api.DestroyStatus(id) | ||
1590 | 1301 | >>> api.GetFriendsTimeline(user) | ||
1591 | 1302 | >>> api.GetFriends(user) | ||
1592 | 1303 | >>> api.GetFollowers() | ||
1593 | 1304 | >>> api.GetFeatured() | ||
1594 | 1305 | >>> api.GetDirectMessages() | ||
1595 | 1306 | >>> api.PostDirectMessage(user, text) | ||
1596 | 1307 | >>> api.DestroyDirectMessage(id) | ||
1597 | 1308 | >>> api.DestroyFriendship(user) | ||
1598 | 1309 | >>> api.CreateFriendship(user) | ||
1599 | 1310 | >>> api.GetUserByEmail(email) | ||
1600 | 1311 | >>> api.VerifyCredentials() | ||
1601 | 1312 | ''' | ||
1602 | 1313 | |||
1603 | 1314 | DEFAULT_CACHE_TIMEOUT = 60 # cache for 1 minute | ||
1604 | 1315 | |||
1605 | 1316 | _API_REALM = 'Twitter API' | ||
1606 | 1317 | |||
1607 | 1318 | def __init__(self, | ||
1608 | 1319 | username=None, | ||
1609 | 1320 | password=None, | ||
1610 | 1321 | input_encoding=None, | ||
1611 | 1322 | request_headers=None, | ||
1612 | 1323 | cache=DEFAULT_CACHE, | ||
1613 | 1324 | shortner=None, | ||
1614 | 1325 | base_url=None, | ||
1615 | 1326 | use_gzip_compression=False): | ||
1616 | 1327 | '''Instantiate a new twitter.Api object. | ||
1617 | 1328 | |||
1618 | 1329 | Args: | ||
1619 | 1330 | username: | ||
1620 | 1331 | The username of the twitter account. [optional] | ||
1621 | 1332 | password: | ||
1622 | 1333 | The password for the twitter account. [optional] | ||
1623 | 1334 | input_encoding: | ||
1624 | 1335 | The encoding used to encode input strings. [optional] | ||
1625 | 1336 | request_header: | ||
1626 | 1337 | A dictionary of additional HTTP request headers. [optional] | ||
1627 | 1338 | cache: | ||
1628 | 1339 | The cache instance to use. Defaults to DEFAULT_CACHE. | ||
1629 | 1340 | Use None to disable caching. [optional] | ||
1630 | 1341 | shortner: | ||
1631 | 1342 | The shortner instance to use. Defaults to None. | ||
1632 | 1343 | See shorten_url.py for an example shortner. [optional] | ||
1633 | 1344 | base_url: | ||
1634 | 1345 | The base URL to use to contact the Twitter API. | ||
1635 | 1346 | Defaults to https://twitter.com. [optional] | ||
1636 | 1347 | use_gzip_compression: | ||
1637 | 1348 | Set to True to tell enable gzip compression for any call | ||
1638 | 1349 | made to Twitter. Defaults to False. [optional] | ||
1639 | 1350 | ''' | ||
1640 | 1351 | self.SetCache(cache) | ||
1641 | 1352 | self._urllib = urllib2 | ||
1642 | 1353 | self._cache_timeout = Api.DEFAULT_CACHE_TIMEOUT | ||
1643 | 1354 | self._InitializeRequestHeaders(request_headers) | ||
1644 | 1355 | self._InitializeUserAgent() | ||
1645 | 1356 | self._InitializeDefaultParameters() | ||
1646 | 1357 | self._input_encoding = input_encoding | ||
1647 | 1358 | self._use_gzip = use_gzip_compression | ||
1648 | 1359 | self.SetCredentials(username, password) | ||
1649 | 1360 | if base_url is None: | ||
1650 | 1361 | self.base_url = 'https://twitter.com' | ||
1651 | 1362 | else: | ||
1652 | 1363 | self.base_url = base_url | ||
1653 | 1364 | |||
1654 | 1365 | def GetPublicTimeline(self, | ||
1655 | 1366 | since_id=None): | ||
1656 | 1367 | '''Fetch the sequnce of public twitter.Status message for all users. | ||
1657 | 1368 | |||
1658 | 1369 | Args: | ||
1659 | 1370 | since_id: | ||
1660 | 1371 | Returns only public statuses with an ID greater than | ||
1661 | 1372 | (that is, more recent than) the specified ID. [optional] | ||
1662 | 1373 | |||
1663 | 1374 | Returns: | ||
1664 | 1375 | An sequence of twitter.Status instances, one for each message | ||
1665 | 1376 | ''' | ||
1666 | 1377 | parameters = {} | ||
1667 | 1378 | |||
1668 | 1379 | if since_id: | ||
1669 | 1380 | parameters['since_id'] = since_id | ||
1670 | 1381 | |||
1671 | 1382 | url = '%s/statuses/public_timeline.json' % self.base_url | ||
1672 | 1383 | json = self._FetchUrl(url, parameters=parameters) | ||
1673 | 1384 | data = simplejson.loads(json) | ||
1674 | 1385 | |||
1675 | 1386 | self._CheckForTwitterError(data) | ||
1676 | 1387 | |||
1677 | 1388 | return [Status.NewFromJsonDict(x) for x in data] | ||
1678 | 1389 | |||
1679 | 1390 | def FilterPublicTimeline(self, | ||
1680 | 1391 | term, | ||
1681 | 1392 | since_id=None): | ||
1682 | 1393 | '''Filter the public twitter timeline by a given search term on | ||
1683 | 1394 | the local machine. | ||
1684 | 1395 | |||
1685 | 1396 | Args: | ||
1686 | 1397 | term: | ||
1687 | 1398 | term to search by. | ||
1688 | 1399 | since_id: | ||
1689 | 1400 | Returns only public statuses with an ID greater than | ||
1690 | 1401 | (that is, more recent than) the specified ID. [optional] | ||
1691 | 1402 | |||
1692 | 1403 | Returns: | ||
1693 | 1404 | A sequence of twitter.Status instances, one for each message | ||
1694 | 1405 | containing the term | ||
1695 | 1406 | ''' | ||
1696 | 1407 | statuses = self.GetPublicTimeline(since_id) | ||
1697 | 1408 | results = [] | ||
1698 | 1409 | |||
1699 | 1410 | for s in statuses: | ||
1700 | 1411 | if s.text.lower().find(term.lower()) != -1: | ||
1701 | 1412 | results.append(s) | ||
1702 | 1413 | |||
1703 | 1414 | return results | ||
1704 | 1415 | |||
1705 | 1416 | def GetSearch(self, | ||
1706 | 1417 | term, | ||
1707 | 1418 | geocode=None, | ||
1708 | 1419 | since_id=None, | ||
1709 | 1420 | per_page=15, | ||
1710 | 1421 | page=1, | ||
1711 | 1422 | lang="en", | ||
1712 | 1423 | show_user="true", | ||
1713 | 1424 | query_users=False): | ||
1714 | 1425 | '''Return twitter search results for a given term. | ||
1715 | 1426 | |||
1716 | 1427 | Args: | ||
1717 | 1428 | term: | ||
1718 | 1429 | term to search by. | ||
1719 | 1430 | since_id: | ||
1720 | 1431 | Returns only public statuses with an ID greater than | ||
1721 | 1432 | (that is, more recent than) the specified ID. [optional] | ||
1722 | 1433 | geocode: | ||
1723 | 1434 | geolocation information in the form (latitude, longitude, radius) | ||
1724 | 1435 | [optional] | ||
1725 | 1436 | per_page: | ||
1726 | 1437 | number of results to return. Default is 15 [optional] | ||
1727 | 1438 | page: | ||
1728 | 1439 | which page of search results to return | ||
1729 | 1440 | lang: | ||
1730 | 1441 | language for results. Default is English [optional] | ||
1731 | 1442 | show_user: | ||
1732 | 1443 | prefixes screen name in status | ||
1733 | 1444 | query_users: | ||
1734 | 1445 | If set to False, then all users only have screen_name and | ||
1735 | 1446 | profile_image_url available. | ||
1736 | 1447 | If set to True, all information of users are available, | ||
1737 | 1448 | but it uses lots of request quota, one per status. | ||
1738 | 1449 | Returns: | ||
1739 | 1450 | A sequence of twitter.Status instances, one for each message containing | ||
1740 | 1451 | the term | ||
1741 | 1452 | ''' | ||
1742 | 1453 | # Build request parameters | ||
1743 | 1454 | parameters = {} | ||
1744 | 1455 | |||
1745 | 1456 | if since_id: | ||
1746 | 1457 | parameters['since_id'] = since_id | ||
1747 | 1458 | |||
1748 | 1459 | if not term: | ||
1749 | 1460 | return [] | ||
1750 | 1461 | |||
1751 | 1462 | parameters['q'] = urllib.quote_plus(term) | ||
1752 | 1463 | parameters['show_user'] = show_user | ||
1753 | 1464 | parameters['lang'] = lang | ||
1754 | 1465 | parameters['rpp'] = per_page | ||
1755 | 1466 | parameters['page'] = page | ||
1756 | 1467 | |||
1757 | 1468 | if geocode is not None: | ||
1758 | 1469 | parameters['geocode'] = ','.join(map(str, geocode)) | ||
1759 | 1470 | |||
1760 | 1471 | # Make and send requests | ||
1761 | 1472 | url = 'http://search.twitter.com/search.json' | ||
1762 | 1473 | json = self._FetchUrl(url, parameters=parameters) | ||
1763 | 1474 | data = simplejson.loads(json) | ||
1764 | 1475 | |||
1765 | 1476 | self._CheckForTwitterError(data) | ||
1766 | 1477 | |||
1767 | 1478 | results = [] | ||
1768 | 1479 | |||
1769 | 1480 | for x in data['results']: | ||
1770 | 1481 | temp = Status.NewFromJsonDict(x) | ||
1771 | 1482 | |||
1772 | 1483 | if query_users: | ||
1773 | 1484 | # Build user object with new request | ||
1774 | 1485 | temp.user = self.GetUser(urllib.quote(x['from_user'])) | ||
1775 | 1486 | else: | ||
1776 | 1487 | temp.user = User(screen_name=x['from_user'], profile_image_url=x['profile_image_url']) | ||
1777 | 1488 | |||
1778 | 1489 | results.append(temp) | ||
1779 | 1490 | |||
1780 | 1491 | # Return built list of statuses | ||
1781 | 1492 | return results # [Status.NewFromJsonDict(x) for x in data['results']] | ||
1782 | 1493 | |||
1783 | 1494 | def GetFriendsTimeline(self, | ||
1784 | 1495 | user=None, | ||
1785 | 1496 | count=None, | ||
1786 | 1497 | since=None, | ||
1787 | 1498 | since_id=None): | ||
1788 | 1499 | '''Fetch the sequence of twitter.Status messages for a user's friends | ||
1789 | 1500 | |||
1790 | 1501 | The twitter.Api instance must be authenticated if the user is private. | ||
1791 | 1502 | |||
1792 | 1503 | Args: | ||
1793 | 1504 | user: | ||
1794 | 1505 | Specifies the ID or screen name of the user for whom to return | ||
1795 | 1506 | the friends_timeline. If unspecified, the username and password | ||
1796 | 1507 | must be set in the twitter.Api instance. [Optional] | ||
1797 | 1508 | count: | ||
1798 | 1509 | Specifies the number of statuses to retrieve. May not be | ||
1799 | 1510 | greater than 200. [Optional] | ||
1800 | 1511 | since: | ||
1801 | 1512 | Narrows the returned results to just those statuses created | ||
1802 | 1513 | after the specified HTTP-formatted date. [Optional] | ||
1803 | 1514 | since_id: | ||
1804 | 1515 | Returns only public statuses with an ID greater than (that is, | ||
1805 | 1516 | more recent than) the specified ID. [Optional] | ||
1806 | 1517 | |||
1807 | 1518 | Returns: | ||
1808 | 1519 | A sequence of twitter.Status instances, one for each message | ||
1809 | 1520 | ''' | ||
1810 | 1521 | if not user and not self._username: | ||
1811 | 1522 | raise TwitterError("User must be specified if API is not authenticated.") | ||
1812 | 1523 | if user: | ||
1813 | 1524 | url = '%s/statuses/friends_timeline/%s.json' % (self.base_url, user) | ||
1814 | 1525 | else: | ||
1815 | 1526 | url = '%s/statuses/friends_timeline.json' % self.base_url | ||
1816 | 1527 | parameters = {} | ||
1817 | 1528 | if count is not None: | ||
1818 | 1529 | try: | ||
1819 | 1530 | if int(count) > 200: | ||
1820 | 1531 | raise TwitterError("'count' may not be greater than 200") | ||
1821 | 1532 | except ValueError: | ||
1822 | 1533 | raise TwitterError("'count' must be an integer") | ||
1823 | 1534 | parameters['count'] = count | ||
1824 | 1535 | if since: | ||
1825 | 1536 | parameters['since'] = since | ||
1826 | 1537 | if since_id: | ||
1827 | 1538 | parameters['since_id'] = since_id | ||
1828 | 1539 | json = self._FetchUrl(url, parameters=parameters) | ||
1829 | 1540 | data = simplejson.loads(json) | ||
1830 | 1541 | self._CheckForTwitterError(data) | ||
1831 | 1542 | return [Status.NewFromJsonDict(x) for x in data] | ||
1832 | 1543 | |||
1833 | 1544 | def GetUserTimeline(self, | ||
1834 | 1545 | id=None, | ||
1835 | 1546 | user_id=None, | ||
1836 | 1547 | screen_name=None, | ||
1837 | 1548 | since_id=None, | ||
1838 | 1549 | max_id=None, | ||
1839 | 1550 | count=None, | ||
1840 | 1551 | page=None): | ||
1841 | 1552 | '''Fetch the sequence of public Status messages for a single user. | ||
1842 | 1553 | |||
1843 | 1554 | The twitter.Api instance must be authenticated if the user is private. | ||
1844 | 1555 | |||
1845 | 1556 | Args: | ||
1846 | 1557 | id: | ||
1847 | 1558 | Specifies the ID or screen name of the user for whom to return | ||
1848 | 1559 | the user_timeline. [optional] | ||
1849 | 1560 | user_id: | ||
1850 | 1561 | Specfies the ID of the user for whom to return the | ||
1851 | 1562 | user_timeline. Helpful for disambiguating when a valid user ID | ||
1852 | 1563 | is also a valid screen name. [optional] | ||
1853 | 1564 | screen_name: | ||
1854 | 1565 | Specfies the screen name of the user for whom to return the | ||
1855 | 1566 | user_timeline. Helpful for disambiguating when a valid screen | ||
1856 | 1567 | name is also a user ID. [optional] | ||
1857 | 1568 | since_id: | ||
1858 | 1569 | Returns only public statuses with an ID greater than (that is, | ||
1859 | 1570 | more recent than) the specified ID. [optional] | ||
1860 | 1571 | max_id: | ||
1861 | 1572 | Returns only statuses with an ID less than (that is, older | ||
1862 | 1573 | than) or equal to the specified ID. [optional] | ||
1863 | 1574 | count: | ||
1864 | 1575 | Specifies the number of statuses to retrieve. May not be | ||
1865 | 1576 | greater than 200. [optional] | ||
1866 | 1577 | page: | ||
1867 | 1578 | Specifies the page of results to retrieve. Note: there are | ||
1868 | 1579 | pagination limits. [optional] | ||
1869 | 1580 | |||
1870 | 1581 | Returns: | ||
1871 | 1582 | A sequence of Status instances, one for each message up to count | ||
1872 | 1583 | ''' | ||
1873 | 1584 | parameters = {} | ||
1874 | 1585 | |||
1875 | 1586 | if id: | ||
1876 | 1587 | url = '%s/statuses/user_timeline/%s.json' % (self.base_url, id) | ||
1877 | 1588 | elif user_id: | ||
1878 | 1589 | url = '%s/statuses/user_timeline.json?user_id=%d' % (self.base_url, user_id) | ||
1879 | 1590 | elif screen_name: | ||
1880 | 1591 | url = ('%s/statuses/user_timeline.json?screen_name=%s' % (self.base_url, | ||
1881 | 1592 | screen_name)) | ||
1882 | 1593 | elif not self._username: | ||
1883 | 1594 | raise TwitterError("User must be specified if API is not authenticated.") | ||
1884 | 1595 | else: | ||
1885 | 1596 | url = '%s/statuses/user_timeline.json' % self.base_url | ||
1886 | 1597 | |||
1887 | 1598 | if since_id: | ||
1888 | 1599 | try: | ||
1889 | 1600 | parameters['since_id'] = long(since_id) | ||
1890 | 1601 | except: | ||
1891 | 1602 | raise TwitterError("since_id must be an integer") | ||
1892 | 1603 | |||
1893 | 1604 | if max_id: | ||
1894 | 1605 | try: | ||
1895 | 1606 | parameters['max_id'] = long(max_id) | ||
1896 | 1607 | except: | ||
1897 | 1608 | raise TwitterError("max_id must be an integer") | ||
1898 | 1609 | |||
1899 | 1610 | if count: | ||
1900 | 1611 | try: | ||
1901 | 1612 | parameters['count'] = int(count) | ||
1902 | 1613 | except: | ||
1903 | 1614 | raise TwitterError("count must be an integer") | ||
1904 | 1615 | |||
1905 | 1616 | if page: | ||
1906 | 1617 | try: | ||
1907 | 1618 | parameters['page'] = int(page) | ||
1908 | 1619 | except: | ||
1909 | 1620 | raise TwitterError("page must be an integer") | ||
1910 | 1621 | |||
1911 | 1622 | json = self._FetchUrl(url, parameters=parameters) | ||
1912 | 1623 | data = simplejson.loads(json) | ||
1913 | 1624 | self._CheckForTwitterError(data) | ||
1914 | 1625 | return [Status.NewFromJsonDict(x) for x in data] | ||
1915 | 1626 | |||
1916 | 1627 | def GetStatus(self, id): | ||
1917 | 1628 | '''Returns a single status message. | ||
1918 | 1629 | |||
1919 | 1630 | The twitter.Api instance must be authenticated if the status message is private. | ||
1920 | 1631 | |||
1921 | 1632 | Args: | ||
1922 | 1633 | id: The numerical ID of the status you're trying to retrieve. | ||
1923 | 1634 | |||
1924 | 1635 | Returns: | ||
1925 | 1636 | A twitter.Status instance representing that status message | ||
1926 | 1637 | ''' | ||
1927 | 1638 | try: | ||
1928 | 1639 | if id: | ||
1929 | 1640 | long(id) | ||
1930 | 1641 | except: | ||
1931 | 1642 | raise TwitterError("id must be an long integer") | ||
1932 | 1643 | url = '%s/statuses/show/%s.json' % (self.base_url, id) | ||
1933 | 1644 | json = self._FetchUrl(url) | ||
1934 | 1645 | data = simplejson.loads(json) | ||
1935 | 1646 | self._CheckForTwitterError(data) | ||
1936 | 1647 | return Status.NewFromJsonDict(data) | ||
1937 | 1648 | |||
1938 | 1649 | def DestroyStatus(self, id): | ||
1939 | 1650 | '''Destroys the status specified by the required ID parameter. | ||
1940 | 1651 | |||
1941 | 1652 | The twitter.Api instance must be authenticated and thee | ||
1942 | 1653 | authenticating user must be the author of the specified status. | ||
1943 | 1654 | |||
1944 | 1655 | Args: | ||
1945 | 1656 | id: The numerical ID of the status you're trying to destroy. | ||
1946 | 1657 | |||
1947 | 1658 | Returns: | ||
1948 | 1659 | A twitter.Status instance representing the destroyed status message | ||
1949 | 1660 | ''' | ||
1950 | 1661 | try: | ||
1951 | 1662 | if id: | ||
1952 | 1663 | long(id) | ||
1953 | 1664 | except: | ||
1954 | 1665 | raise TwitterError("id must be an integer") | ||
1955 | 1666 | url = '%s/statuses/destroy/%s.json' % (self.base_url, id) | ||
1956 | 1667 | json = self._FetchUrl(url, post_data={}) | ||
1957 | 1668 | data = simplejson.loads(json) | ||
1958 | 1669 | self._CheckForTwitterError(data) | ||
1959 | 1670 | return Status.NewFromJsonDict(data) | ||
1960 | 1671 | |||
1961 | 1672 | def PostUpdate(self, status, in_reply_to_status_id=None): | ||
1962 | 1673 | '''Post a twitter status message from the authenticated user. | ||
1963 | 1674 | |||
1964 | 1675 | The twitter.Api instance must be authenticated. | ||
1965 | 1676 | |||
1966 | 1677 | Args: | ||
1967 | 1678 | status: | ||
1968 | 1679 | The message text to be posted. Must be less than or equal to | ||
1969 | 1680 | 140 characters. | ||
1970 | 1681 | in_reply_to_status_id: | ||
1971 | 1682 | The ID of an existing status that the status to be posted is | ||
1972 | 1683 | in reply to. This implicitly sets the in_reply_to_user_id | ||
1973 | 1684 | attribute of the resulting status to the user ID of the | ||
1974 | 1685 | message being replied to. Invalid/missing status IDs will be | ||
1975 | 1686 | ignored. [Optional] | ||
1976 | 1687 | Returns: | ||
1977 | 1688 | A twitter.Status instance representing the message posted. | ||
1978 | 1689 | ''' | ||
1979 | 1690 | if not self._username: | ||
1980 | 1691 | raise TwitterError("The twitter.Api instance must be authenticated.") | ||
1981 | 1692 | |||
1982 | 1693 | url = '%s/statuses/update.json' % self.base_url | ||
1983 | 1694 | |||
1984 | 1695 | if len(status) > CHARACTER_LIMIT: | ||
1985 | 1696 | raise TwitterError("Text must be less than or equal to %d characters. " | ||
1986 | 1697 | "Consider using PostUpdates." % CHARACTER_LIMIT) | ||
1987 | 1698 | |||
1988 | 1699 | data = {'status': status} | ||
1989 | 1700 | if in_reply_to_status_id: | ||
1990 | 1701 | data['in_reply_to_status_id'] = in_reply_to_status_id | ||
1991 | 1702 | json = self._FetchUrl(url, post_data=data) | ||
1992 | 1703 | data = simplejson.loads(json) | ||
1993 | 1704 | self._CheckForTwitterError(data) | ||
1994 | 1705 | return Status.NewFromJsonDict(data) | ||
1995 | 1706 | |||
1996 | 1707 | def PostUpdates(self, status, continuation=None, **kwargs): | ||
1997 | 1708 | '''Post one or more twitter status messages from the authenticated user. | ||
1998 | 1709 | |||
1999 | 1710 | Unlike api.PostUpdate, this method will post multiple status updates | ||
2000 | 1711 | if the message is longer than 140 characters. | ||
2001 | 1712 | |||
2002 | 1713 | The twitter.Api instance must be authenticated. | ||
2003 | 1714 | |||
2004 | 1715 | Args: | ||
2005 | 1716 | status: | ||
2006 | 1717 | The message text to be posted. May be longer than 140 characters. | ||
2007 | 1718 | continuation: | ||
2008 | 1719 | The character string, if any, to be appended to all but the | ||
2009 | 1720 | last message. Note that Twitter strips trailing '...' strings | ||
2010 | 1721 | from messages. Consider using the unicode \u2026 character | ||
2011 | 1722 | (horizontal ellipsis) instead. [Defaults to None] | ||
2012 | 1723 | **kwargs: | ||
2013 | 1724 | See api.PostUpdate for a list of accepted parameters. | ||
2014 | 1725 | Returns: | ||
2015 | 1726 | A of list twitter.Status instance representing the messages posted. | ||
2016 | 1727 | ''' | ||
2017 | 1728 | results = list() | ||
2018 | 1729 | if continuation is None: | ||
2019 | 1730 | continuation = '' | ||
2020 | 1731 | line_length = CHARACTER_LIMIT - len(continuation) | ||
2021 | 1732 | lines = textwrap.wrap(status, line_length) | ||
2022 | 1733 | for line in lines[0:-1]: | ||
2023 | 1734 | results.append(self.PostUpdate(line + continuation, **kwargs)) | ||
2024 | 1735 | results.append(self.PostUpdate(lines[-1], **kwargs)) | ||
2025 | 1736 | return results | ||
2026 | 1737 | |||
2027 | 1738 | def GetReplies(self, since=None, since_id=None, page=None): | ||
2028 | 1739 | '''Get a sequence of status messages representing the 20 most recent | ||
2029 | 1740 | replies (status updates prefixed with @username) to the authenticating | ||
2030 | 1741 | user. | ||
2031 | 1742 | |||
2032 | 1743 | Args: | ||
2033 | 1744 | page: | ||
2034 | 1745 | since: | ||
2035 | 1746 | Narrows the returned results to just those statuses created | ||
2036 | 1747 | after the specified HTTP-formatted date. [optional] | ||
2037 | 1748 | since_id: | ||
2038 | 1749 | Returns only public statuses with an ID greater than (that is, | ||
2039 | 1750 | more recent than) the specified ID. [Optional] | ||
2040 | 1751 | |||
2041 | 1752 | Returns: | ||
2042 | 1753 | A sequence of twitter.Status instances, one for each reply to the user. | ||
2043 | 1754 | ''' | ||
2044 | 1755 | url = '%s/statuses/replies.json' % self.base_url | ||
2045 | 1756 | if not self._username: | ||
2046 | 1757 | raise TwitterError("The twitter.Api instance must be authenticated.") | ||
2047 | 1758 | parameters = {} | ||
2048 | 1759 | if since: | ||
2049 | 1760 | parameters['since'] = since | ||
2050 | 1761 | if since_id: | ||
2051 | 1762 | parameters['since_id'] = since_id | ||
2052 | 1763 | if page: | ||
2053 | 1764 | parameters['page'] = page | ||
2054 | 1765 | json = self._FetchUrl(url, parameters=parameters) | ||
2055 | 1766 | data = simplejson.loads(json) | ||
2056 | 1767 | self._CheckForTwitterError(data) | ||
2057 | 1768 | return [Status.NewFromJsonDict(x) for x in data] | ||
2058 | 1769 | |||
2059 | 1770 | def GetFriends(self, user=None, page=None): | ||
2060 | 1771 | '''Fetch the sequence of twitter.User instances, one for each friend. | ||
2061 | 1772 | |||
2062 | 1773 | Args: | ||
2063 | 1774 | user: the username or id of the user whose friends you are fetching. If | ||
2064 | 1775 | not specified, defaults to the authenticated user. [optional] | ||
2065 | 1776 | |||
2066 | 1777 | The twitter.Api instance must be authenticated. | ||
2067 | 1778 | |||
2068 | 1779 | Returns: | ||
2069 | 1780 | A sequence of twitter.User instances, one for each friend | ||
2070 | 1781 | ''' | ||
2071 | 1782 | if not user and not self._username: | ||
2072 | 1783 | raise TwitterError("twitter.Api instance must be authenticated") | ||
2073 | 1784 | if user: | ||
2074 | 1785 | url = '%s/statuses/friends/%s.json' % (self.base_url, user) | ||
2075 | 1786 | else: | ||
2076 | 1787 | url = '%s/statuses/friends.json' % self.base_url | ||
2077 | 1788 | parameters = {} | ||
2078 | 1789 | if page: | ||
2079 | 1790 | parameters['page'] = page | ||
2080 | 1791 | json = self._FetchUrl(url, parameters=parameters) | ||
2081 | 1792 | data = simplejson.loads(json) | ||
2082 | 1793 | self._CheckForTwitterError(data) | ||
2083 | 1794 | return [User.NewFromJsonDict(x) for x in data] | ||
2084 | 1795 | |||
2085 | 1796 | def GetFriendIDs(self, user=None, page=None): | ||
2086 | 1797 | '''Returns a list of twitter user id's for every person | ||
2087 | 1798 | the specified user is following. | ||
2088 | 1799 | |||
2089 | 1800 | Args: | ||
2090 | 1801 | user: | ||
2091 | 1802 | The id or screen_name of the user to retrieve the id list for | ||
2092 | 1803 | [optional] | ||
2093 | 1804 | page: | ||
2094 | 1805 | Specifies the page number of the results beginning at 1. | ||
2095 | 1806 | A single page contains 5000 ids. This is recommended for users | ||
2096 | 1807 | with large id lists. If not provided all id's are returned. | ||
2097 | 1808 | (Please note that the result set isn't guaranteed to be 5000 | ||
2098 | 1809 | every time as suspended users will be filtered.) | ||
2099 | 1810 | [optional] | ||
2100 | 1811 | |||
2101 | 1812 | Returns: | ||
2102 | 1813 | A list of integers, one for each user id. | ||
2103 | 1814 | ''' | ||
2104 | 1815 | if not user and not self._username: | ||
2105 | 1816 | raise TwitterError("twitter.Api instance must be authenticated") | ||
2106 | 1817 | if user: | ||
2107 | 1818 | url = '%s/friends/ids/%s.json' % (self.base_url, user) | ||
2108 | 1819 | else: | ||
2109 | 1820 | url = '%s/friends/ids.json' % self.base_url | ||
2110 | 1821 | parameters = {} | ||
2111 | 1822 | if page: | ||
2112 | 1823 | parameters['page'] = page | ||
2113 | 1824 | json = self._FetchUrl(url, parameters=parameters) | ||
2114 | 1825 | data = simplejson.loads(json) | ||
2115 | 1826 | self._CheckForTwitterError(data) | ||
2116 | 1827 | return data | ||
2117 | 1828 | |||
2118 | 1829 | def GetFollowers(self, page=None): | ||
2119 | 1830 | '''Fetch the sequence of twitter.User instances, one for each follower | ||
2120 | 1831 | |||
2121 | 1832 | The twitter.Api instance must be authenticated. | ||
2122 | 1833 | |||
2123 | 1834 | Returns: | ||
2124 | 1835 | A sequence of twitter.User instances, one for each follower | ||
2125 | 1836 | ''' | ||
2126 | 1837 | if not self._username: | ||
2127 | 1838 | raise TwitterError("twitter.Api instance must be authenticated") | ||
2128 | 1839 | url = '%s/statuses/followers.json' % self.base_url | ||
2129 | 1840 | parameters = {} | ||
2130 | 1841 | if page: | ||
2131 | 1842 | parameters['page'] = page | ||
2132 | 1843 | json = self._FetchUrl(url, parameters=parameters) | ||
2133 | 1844 | data = simplejson.loads(json) | ||
2134 | 1845 | self._CheckForTwitterError(data) | ||
2135 | 1846 | return [User.NewFromJsonDict(x) for x in data] | ||
2136 | 1847 | |||
2137 | 1848 | def GetFeatured(self): | ||
2138 | 1849 | '''Fetch the sequence of twitter.User instances featured on twitter.com | ||
2139 | 1850 | |||
2140 | 1851 | The twitter.Api instance must be authenticated. | ||
2141 | 1852 | |||
2142 | 1853 | Returns: | ||
2143 | 1854 | A sequence of twitter.User instances | ||
2144 | 1855 | ''' | ||
2145 | 1856 | url = '%s/statuses/featured.json' % self.base_url | ||
2146 | 1857 | json = self._FetchUrl(url) | ||
2147 | 1858 | data = simplejson.loads(json) | ||
2148 | 1859 | self._CheckForTwitterError(data) | ||
2149 | 1860 | return [User.NewFromJsonDict(x) for x in data] | ||
2150 | 1861 | |||
2151 | 1862 | def GetUser(self, user): | ||
2152 | 1863 | '''Returns a single user. | ||
2153 | 1864 | |||
2154 | 1865 | The twitter.Api instance must be authenticated. | ||
2155 | 1866 | |||
2156 | 1867 | Args: | ||
2157 | 1868 | user: The username or id of the user to retrieve. | ||
2158 | 1869 | |||
2159 | 1870 | Returns: | ||
2160 | 1871 | A twitter.User instance representing that user | ||
2161 | 1872 | ''' | ||
2162 | 1873 | url = '%s/users/show/%s.json' % (self.base_url, user) | ||
2163 | 1874 | json = self._FetchUrl(url) | ||
2164 | 1875 | data = simplejson.loads(json) | ||
2165 | 1876 | self._CheckForTwitterError(data) | ||
2166 | 1877 | return User.NewFromJsonDict(data) | ||
2167 | 1878 | |||
2168 | 1879 | def GetDirectMessages(self, since=None, since_id=None, page=None): | ||
2169 | 1880 | '''Returns a list of the direct messages sent to the authenticating user. | ||
2170 | 1881 | |||
2171 | 1882 | The twitter.Api instance must be authenticated. | ||
2172 | 1883 | |||
2173 | 1884 | Args: | ||
2174 | 1885 | since: | ||
2175 | 1886 | Narrows the returned results to just those statuses created | ||
2176 | 1887 | after the specified HTTP-formatted date. [optional] | ||
2177 | 1888 | since_id: | ||
2178 | 1889 | Returns only public statuses with an ID greater than (that is, | ||
2179 | 1890 | more recent than) the specified ID. [Optional] | ||
2180 | 1891 | |||
2181 | 1892 | Returns: | ||
2182 | 1893 | A sequence of twitter.DirectMessage instances | ||
2183 | 1894 | ''' | ||
2184 | 1895 | url = '%s/direct_messages.json' % self.base_url | ||
2185 | 1896 | if not self._username: | ||
2186 | 1897 | raise TwitterError("The twitter.Api instance must be authenticated.") | ||
2187 | 1898 | parameters = {} | ||
2188 | 1899 | if since: | ||
2189 | 1900 | parameters['since'] = since | ||
2190 | 1901 | if since_id: | ||
2191 | 1902 | parameters['since_id'] = since_id | ||
2192 | 1903 | if page: | ||
2193 | 1904 | parameters['page'] = page | ||
2194 | 1905 | json = self._FetchUrl(url, parameters=parameters) | ||
2195 | 1906 | data = simplejson.loads(json) | ||
2196 | 1907 | self._CheckForTwitterError(data) | ||
2197 | 1908 | return [DirectMessage.NewFromJsonDict(x) for x in data] | ||
2198 | 1909 | |||
2199 | 1910 | def PostDirectMessage(self, user, text): | ||
2200 | 1911 | '''Post a twitter direct message from the authenticated user | ||
2201 | 1912 | |||
2202 | 1913 | The twitter.Api instance must be authenticated. | ||
2203 | 1914 | |||
2204 | 1915 | Args: | ||
2205 | 1916 | user: The ID or screen name of the recipient user. | ||
2206 | 1917 | text: The message text to be posted. Must be less than 140 characters. | ||
2207 | 1918 | |||
2208 | 1919 | Returns: | ||
2209 | 1920 | A twitter.DirectMessage instance representing the message posted | ||
2210 | 1921 | ''' | ||
2211 | 1922 | if not self._username: | ||
2212 | 1923 | raise TwitterError("The twitter.Api instance must be authenticated.") | ||
2213 | 1924 | url = '%s/direct_messages/new.json' % self.base_url | ||
2214 | 1925 | data = {'text': text, 'user': user} | ||
2215 | 1926 | json = self._FetchUrl(url, post_data=data) | ||
2216 | 1927 | data = simplejson.loads(json) | ||
2217 | 1928 | self._CheckForTwitterError(data) | ||
2218 | 1929 | return DirectMessage.NewFromJsonDict(data) | ||
2219 | 1930 | |||
2220 | 1931 | def DestroyDirectMessage(self, id): | ||
2221 | 1932 | '''Destroys the direct message specified in the required ID parameter. | ||
2222 | 1933 | |||
2223 | 1934 | The twitter.Api instance must be authenticated, and the | ||
2224 | 1935 | authenticating user must be the recipient of the specified direct | ||
2225 | 1936 | message. | ||
2226 | 1937 | |||
2227 | 1938 | Args: | ||
2228 | 1939 | id: The id of the direct message to be destroyed | ||
2229 | 1940 | |||
2230 | 1941 | Returns: | ||
2231 | 1942 | A twitter.DirectMessage instance representing the message destroyed | ||
2232 | 1943 | ''' | ||
2233 | 1944 | url = '%s/direct_messages/destroy/%s.json' % (self.base_url, id) | ||
2234 | 1945 | json = self._FetchUrl(url, post_data={}) | ||
2235 | 1946 | data = simplejson.loads(json) | ||
2236 | 1947 | self._CheckForTwitterError(data) | ||
2237 | 1948 | return DirectMessage.NewFromJsonDict(data) | ||
2238 | 1949 | |||
2239 | 1950 | def CreateFriendship(self, user): | ||
2240 | 1951 | '''Befriends the user specified in the user parameter as the authenticating user. | ||
2241 | 1952 | |||
2242 | 1953 | The twitter.Api instance must be authenticated. | ||
2243 | 1954 | |||
2244 | 1955 | Args: | ||
2245 | 1956 | The ID or screen name of the user to befriend. | ||
2246 | 1957 | Returns: | ||
2247 | 1958 | A twitter.User instance representing the befriended user. | ||
2248 | 1959 | ''' | ||
2249 | 1960 | url = '%s/friendships/create/%s.json' % (self.base_url, user) | ||
2250 | 1961 | json = self._FetchUrl(url, post_data={}) | ||
2251 | 1962 | data = simplejson.loads(json) | ||
2252 | 1963 | self._CheckForTwitterError(data) | ||
2253 | 1964 | return User.NewFromJsonDict(data) | ||
2254 | 1965 | |||
2255 | 1966 | def DestroyFriendship(self, user): | ||
2256 | 1967 | '''Discontinues friendship with the user specified in the user parameter. | ||
2257 | 1968 | |||
2258 | 1969 | The twitter.Api instance must be authenticated. | ||
2259 | 1970 | |||
2260 | 1971 | Args: | ||
2261 | 1972 | The ID or screen name of the user with whom to discontinue friendship. | ||
2262 | 1973 | Returns: | ||
2263 | 1974 | A twitter.User instance representing the discontinued friend. | ||
2264 | 1975 | ''' | ||
2265 | 1976 | url = '%s/friendships/destroy/%s.json' % (self.base_url, user) | ||
2266 | 1977 | json = self._FetchUrl(url, post_data={}) | ||
2267 | 1978 | data = simplejson.loads(json) | ||
2268 | 1979 | self._CheckForTwitterError(data) | ||
2269 | 1980 | return User.NewFromJsonDict(data) | ||
2270 | 1981 | |||
2271 | 1982 | def CreateFavorite(self, status): | ||
2272 | 1983 | '''Favorites the status specified in the status parameter as the authenticating user. | ||
2273 | 1984 | Returns the favorite status when successful. | ||
2274 | 1985 | |||
2275 | 1986 | The twitter.Api instance must be authenticated. | ||
2276 | 1987 | |||
2277 | 1988 | Args: | ||
2278 | 1989 | The twitter.Status instance to mark as a favorite. | ||
2279 | 1990 | Returns: | ||
2280 | 1991 | A twitter.Status instance representing the newly-marked favorite. | ||
2281 | 1992 | ''' | ||
2282 | 1993 | url = '%s/favorites/create/%s.json' % (self.base_url, status.id) | ||
2283 | 1994 | json = self._FetchUrl(url, post_data={}) | ||
2284 | 1995 | data = simplejson.loads(json) | ||
2285 | 1996 | self._CheckForTwitterError(data) | ||
2286 | 1997 | return Status.NewFromJsonDict(data) | ||
2287 | 1998 | |||
2288 | 1999 | def DestroyFavorite(self, status): | ||
2289 | 2000 | '''Un-favorites the status specified in the ID parameter as the authenticating user. | ||
2290 | 2001 | Returns the un-favorited status in the requested format when successful. | ||
2291 | 2002 | |||
2292 | 2003 | The twitter.Api instance must be authenticated. | ||
2293 | 2004 | |||
2294 | 2005 | Args: | ||
2295 | 2006 | The twitter.Status to unmark as a favorite. | ||
2296 | 2007 | Returns: | ||
2297 | 2008 | A twitter.Status instance representing the newly-unmarked favorite. | ||
2298 | 2009 | ''' | ||
2299 | 2010 | url = '%s/favorites/destroy/%s.json' % (self.base_url, status.id) | ||
2300 | 2011 | json = self._FetchUrl(url, post_data={}) | ||
2301 | 2012 | data = simplejson.loads(json) | ||
2302 | 2013 | self._CheckForTwitterError(data) | ||
2303 | 2014 | return Status.NewFromJsonDict(data) | ||
2304 | 2015 | |||
2305 | 2016 | def GetFavorites(self, | ||
2306 | 2017 | user=None, | ||
2307 | 2018 | page=None): | ||
2308 | 2019 | '''Return a list of Status objects representing favorited tweets. | ||
2309 | 2020 | By default, returns the (up to) 20 most recent tweets for the | ||
2310 | 2021 | authenticated user. | ||
2311 | 2022 | |||
2312 | 2023 | Args: | ||
2313 | 2024 | user: | ||
2314 | 2025 | The username or id of the user whose favorites you are fetching. | ||
2315 | 2026 | If not specified, defaults to the authenticated user. [optional] | ||
2316 | 2027 | |||
2317 | 2028 | page: | ||
2318 | 2029 | Retrieves the 20 next most recent favorite statuses. [optional] | ||
2319 | 2030 | ''' | ||
2320 | 2031 | parameters = {} | ||
2321 | 2032 | |||
2322 | 2033 | if page: | ||
2323 | 2034 | parameters['page'] = page | ||
2324 | 2035 | |||
2325 | 2036 | if user: | ||
2326 | 2037 | url = '%s/favorites/%s.json' % (self.base_url, user) | ||
2327 | 2038 | elif not user and not self._username: | ||
2328 | 2039 | raise TwitterError("User must be specified if API is not authenticated.") | ||
2329 | 2040 | else: | ||
2330 | 2041 | url = '%s/favorites.json' % self.base_url | ||
2331 | 2042 | |||
2332 | 2043 | json = self._FetchUrl(url, parameters=parameters) | ||
2333 | 2044 | data = simplejson.loads(json) | ||
2334 | 2045 | |||
2335 | 2046 | self._CheckForTwitterError(data) | ||
2336 | 2047 | |||
2337 | 2048 | return [Status.NewFromJsonDict(x) for x in data] | ||
2338 | 2049 | |||
2339 | 2050 | def GetMentions(self, | ||
2340 | 2051 | since_id=None, | ||
2341 | 2052 | max_id=None, | ||
2342 | 2053 | page=None): | ||
2343 | 2054 | '''Returns the 20 most recent mentions (status containing @username) | ||
2344 | 2055 | for the authenticating user. | ||
2345 | 2056 | |||
2346 | 2057 | Args: | ||
2347 | 2058 | since_id: | ||
2348 | 2059 | Returns only public statuses with an ID greater than | ||
2349 | 2060 | (that is, more recent than) the specified ID. [optional] | ||
2350 | 2061 | |||
2351 | 2062 | max_id: | ||
2352 | 2063 | Returns only statuses with an ID less than | ||
2353 | 2064 | (that is, older than) the specified ID. [optional] | ||
2354 | 2065 | |||
2355 | 2066 | page: | ||
2356 | 2067 | Retrieves the 20 next most recent replies. [optional] | ||
2357 | 2068 | |||
2358 | 2069 | Returns: | ||
2359 | 2070 | A sequence of twitter.Status instances, one for each mention of the user. | ||
2360 | 2071 | see: http://apiwiki.twitter.com/REST-API-Documentation#statuses/mentions | ||
2361 | 2072 | ''' | ||
2362 | 2073 | |||
2363 | 2074 | url = '%s/statuses/mentions.json' % self.base_url | ||
2364 | 2075 | |||
2365 | 2076 | if not self._username: | ||
2366 | 2077 | raise TwitterError("The twitter.Api instance must be authenticated.") | ||
2367 | 2078 | |||
2368 | 2079 | parameters = {} | ||
2369 | 2080 | |||
2370 | 2081 | if since_id: | ||
2371 | 2082 | parameters['since_id'] = since_id | ||
2372 | 2083 | if max_id: | ||
2373 | 2084 | parameters['max_id'] = max_id | ||
2374 | 2085 | if page: | ||
2375 | 2086 | parameters['page'] = page | ||
2376 | 2087 | |||
2377 | 2088 | json = self._FetchUrl(url, parameters=parameters) | ||
2378 | 2089 | data = simplejson.loads(json) | ||
2379 | 2090 | |||
2380 | 2091 | self._CheckForTwitterError(data) | ||
2381 | 2092 | |||
2382 | 2093 | return [Status.NewFromJsonDict(x) for x in data] | ||
2383 | 2094 | |||
2384 | 2095 | def GetUserByEmail(self, email): | ||
2385 | 2096 | '''Returns a single user by email address. | ||
2386 | 2097 | |||
2387 | 2098 | Args: | ||
2388 | 2099 | email: The email of the user to retrieve. | ||
2389 | 2100 | Returns: | ||
2390 | 2101 | A twitter.User instance representing that user | ||
2391 | 2102 | ''' | ||
2392 | 2103 | url = '%s/users/show.json?email=%s' % (self.base_url, email) | ||
2393 | 2104 | json = self._FetchUrl(url) | ||
2394 | 2105 | data = simplejson.loads(json) | ||
2395 | 2106 | self._CheckForTwitterError(data) | ||
2396 | 2107 | return User.NewFromJsonDict(data) | ||
2397 | 2108 | |||
2398 | 2109 | def VerifyCredentials(self): | ||
2399 | 2110 | '''Returns a twitter.User instance if the authenticating user is valid. | ||
2400 | 2111 | |||
2401 | 2112 | Returns: | ||
2402 | 2113 | A twitter.User instance representing that user if the | ||
2403 | 2114 | credentials are valid, None otherwise. | ||
2404 | 2115 | ''' | ||
2405 | 2116 | if not self._username: | ||
2406 | 2117 | raise TwitterError("Api instance must first be given user credentials.") | ||
2407 | 2118 | url = '%s/account/verify_credentials.json' % self.base_url | ||
2408 | 2119 | try: | ||
2409 | 2120 | json = self._FetchUrl(url, no_cache=True) | ||
2410 | 2121 | except urllib2.HTTPError, http_error: | ||
2411 | 2122 | if http_error.code == httplib.UNAUTHORIZED: | ||
2412 | 2123 | return None | ||
2413 | 2124 | else: | ||
2414 | 2125 | raise http_error | ||
2415 | 2126 | data = simplejson.loads(json) | ||
2416 | 2127 | self._CheckForTwitterError(data) | ||
2417 | 2128 | return User.NewFromJsonDict(data) | ||
2418 | 2129 | |||
2419 | 2130 | def SetCredentials(self, username, password): | ||
2420 | 2131 | '''Set the username and password for this instance | ||
2421 | 2132 | |||
2422 | 2133 | Args: | ||
2423 | 2134 | username: The twitter username. | ||
2424 | 2135 | password: The twitter password. | ||
2425 | 2136 | ''' | ||
2426 | 2137 | self._username = username | ||
2427 | 2138 | self._password = password | ||
2428 | 2139 | |||
2429 | 2140 | def ClearCredentials(self): | ||
2430 | 2141 | '''Clear the username and password for this instance | ||
2431 | 2142 | ''' | ||
2432 | 2143 | self._username = None | ||
2433 | 2144 | self._password = None | ||
2434 | 2145 | |||
2435 | 2146 | def SetCache(self, cache): | ||
2436 | 2147 | '''Override the default cache. Set to None to prevent caching. | ||
2437 | 2148 | |||
2438 | 2149 | Args: | ||
2439 | 2150 | cache: an instance that supports the same API as the twitter._FileCache | ||
2440 | 2151 | ''' | ||
2441 | 2152 | if cache == DEFAULT_CACHE: | ||
2442 | 2153 | self._cache = _FileCache() | ||
2443 | 2154 | else: | ||
2444 | 2155 | self._cache = cache | ||
2445 | 2156 | |||
2446 | 2157 | def SetUrllib(self, urllib): | ||
2447 | 2158 | '''Override the default urllib implementation. | ||
2448 | 2159 | |||
2449 | 2160 | Args: | ||
2450 | 2161 | urllib: an instance that supports the same API as the urllib2 module | ||
2451 | 2162 | ''' | ||
2452 | 2163 | self._urllib = urllib | ||
2453 | 2164 | |||
2454 | 2165 | def SetCacheTimeout(self, cache_timeout): | ||
2455 | 2166 | '''Override the default cache timeout. | ||
2456 | 2167 | |||
2457 | 2168 | Args: | ||
2458 | 2169 | cache_timeout: time, in seconds, that responses should be reused. | ||
2459 | 2170 | ''' | ||
2460 | 2171 | self._cache_timeout = cache_timeout | ||
2461 | 2172 | |||
2462 | 2173 | def SetUserAgent(self, user_agent): | ||
2463 | 2174 | '''Override the default user agent | ||
2464 | 2175 | |||
2465 | 2176 | Args: | ||
2466 | 2177 | user_agent: a string that should be send to the server as the User-agent | ||
2467 | 2178 | ''' | ||
2468 | 2179 | self._request_headers['User-Agent'] = user_agent | ||
2469 | 2180 | |||
2470 | 2181 | def SetXTwitterHeaders(self, client, url, version): | ||
2471 | 2182 | '''Set the X-Twitter HTTP headers that will be sent to the server. | ||
2472 | 2183 | |||
2473 | 2184 | Args: | ||
2474 | 2185 | client: | ||
2475 | 2186 | The client name as a string. Will be sent to the server as | ||
2476 | 2187 | the 'X-Twitter-Client' header. | ||
2477 | 2188 | url: | ||
2478 | 2189 | The URL of the meta.xml as a string. Will be sent to the server | ||
2479 | 2190 | as the 'X-Twitter-Client-URL' header. | ||
2480 | 2191 | version: | ||
2481 | 2192 | The client version as a string. Will be sent to the server | ||
2482 | 2193 | as the 'X-Twitter-Client-Version' header. | ||
2483 | 2194 | ''' | ||
2484 | 2195 | self._request_headers['X-Twitter-Client'] = client | ||
2485 | 2196 | self._request_headers['X-Twitter-Client-URL'] = url | ||
2486 | 2197 | self._request_headers['X-Twitter-Client-Version'] = version | ||
2487 | 2198 | |||
2488 | 2199 | def SetSource(self, source): | ||
2489 | 2200 | '''Suggest the "from source" value to be displayed on the Twitter web site. | ||
2490 | 2201 | |||
2491 | 2202 | The value of the 'source' parameter must be first recognized by | ||
2492 | 2203 | the Twitter server. New source values are authorized on a case by | ||
2493 | 2204 | case basis by the Twitter development team. | ||
2494 | 2205 | |||
2495 | 2206 | Args: | ||
2496 | 2207 | source: | ||
2497 | 2208 | The source name as a string. Will be sent to the server as | ||
2498 | 2209 | the 'source' parameter. | ||
2499 | 2210 | ''' | ||
2500 | 2211 | self._default_params['source'] = source | ||
2501 | 2212 | |||
2502 | 2213 | def GetRateLimitStatus(self): | ||
2503 | 2214 | '''Fetch the rate limit status for the currently authorized user. | ||
2504 | 2215 | |||
2505 | 2216 | Returns: | ||
2506 | 2217 | A dictionary containing the time the limit will reset (reset_time), | ||
2507 | 2218 | the number of remaining hits allowed before the reset (remaining_hits), | ||
2508 | 2219 | the number of hits allowed in a 60-minute period (hourly_limit), and the | ||
2509 | 2220 | time of the reset in seconds since The Epoch (reset_time_in_seconds). | ||
2510 | 2221 | ''' | ||
2511 | 2222 | url = '%s/account/rate_limit_status.json' % self.base_url | ||
2512 | 2223 | json = self._FetchUrl(url, no_cache=True) | ||
2513 | 2224 | data = simplejson.loads(json) | ||
2514 | 2225 | |||
2515 | 2226 | self._CheckForTwitterError(data) | ||
2516 | 2227 | |||
2517 | 2228 | return data | ||
2518 | 2229 | |||
2519 | 2230 | def MaximumHitFrequency(self): | ||
2520 | 2231 | '''Determines the minimum number of seconds that a program must wait before | ||
2521 | 2232 | hitting the server again without exceeding the rate_limit imposed for the | ||
2522 | 2233 | currently authenticated user. | ||
2523 | 2234 | |||
2524 | 2235 | Returns: | ||
2525 | 2236 | The minimum second interval that a program must use so as to not exceed | ||
2526 | 2237 | the rate_limit imposed for the user. | ||
2527 | 2238 | ''' | ||
2528 | 2239 | rate_status = self.GetRateLimitStatus() | ||
2529 | 2240 | reset_time = rate_status.get('reset_time', None) | ||
2530 | 2241 | limit = rate_status.get('remaining_hits', None) | ||
2531 | 2242 | |||
2532 | 2243 | if reset_time and limit: | ||
2533 | 2244 | # put the reset time into a datetime object | ||
2534 | 2245 | reset = datetime.datetime(*rfc822.parsedate(reset_time)[:7]) | ||
2535 | 2246 | |||
2536 | 2247 | # find the difference in time between now and the reset time + 1 hour | ||
2537 | 2248 | delta = reset + datetime.timedelta(hours=1) - datetime.datetime.utcnow() | ||
2538 | 2249 | |||
2539 | 2250 | # determine the minimum number of seconds allowed as a regular interval | ||
2540 | 2251 | max_frequency = int(delta.seconds / limit) | ||
2541 | 2252 | |||
2542 | 2253 | # return the number of seconds | ||
2543 | 2254 | return max_frequency | ||
2544 | 2255 | |||
2545 | 2256 | return 0 | ||
2546 | 2257 | |||
2547 | 2258 | def _BuildUrl(self, url, path_elements=None, extra_params=None): | ||
2548 | 2259 | # Break url into consituent parts | ||
2549 | 2260 | (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url) | ||
2550 | 2261 | |||
2551 | 2262 | # Add any additional path elements to the path | ||
2552 | 2263 | if path_elements: | ||
2553 | 2264 | # Filter out the path elements that have a value of None | ||
2554 | 2265 | p = [i for i in path_elements if i] | ||
2555 | 2266 | if not path.endswith('/'): | ||
2556 | 2267 | path += '/' | ||
2557 | 2268 | path += '/'.join(p) | ||
2558 | 2269 | |||
2559 | 2270 | # Add any additional query parameters to the query string | ||
2560 | 2271 | if extra_params and len(extra_params) > 0: | ||
2561 | 2272 | extra_query = self._EncodeParameters(extra_params) | ||
2562 | 2273 | # Add it to the existing query | ||
2563 | 2274 | if query: | ||
2564 | 2275 | query += '&' + extra_query | ||
2565 | 2276 | else: | ||
2566 | 2277 | query = extra_query | ||
2567 | 2278 | |||
2568 | 2279 | # Return the rebuilt URL | ||
2569 | 2280 | return urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) | ||
2570 | 2281 | |||
2571 | 2282 | def _InitializeRequestHeaders(self, request_headers): | ||
2572 | 2283 | if request_headers: | ||
2573 | 2284 | self._request_headers = request_headers | ||
2574 | 2285 | else: | ||
2575 | 2286 | self._request_headers = {} | ||
2576 | 2287 | |||
2577 | 2288 | def _InitializeUserAgent(self): | ||
2578 | 2289 | user_agent = 'Python-urllib/%s (python-twitter/%s)' % \ | ||
2579 | 2290 | (self._urllib.__version__, __version__) | ||
2580 | 2291 | self.SetUserAgent(user_agent) | ||
2581 | 2292 | |||
2582 | 2293 | def _InitializeDefaultParameters(self): | ||
2583 | 2294 | self._default_params = {} | ||
2584 | 2295 | |||
2585 | 2296 | def _AddAuthorizationHeader(self, username, password): | ||
2586 | 2297 | if username and password: | ||
2587 | 2298 | basic_auth = base64.encodestring('%s:%s' % (username, password))[:-1] | ||
2588 | 2299 | self._request_headers['Authorization'] = 'Basic %s' % basic_auth | ||
2589 | 2300 | |||
2590 | 2301 | def _RemoveAuthorizationHeader(self): | ||
2591 | 2302 | if self._request_headers and 'Authorization' in self._request_headers: | ||
2592 | 2303 | del self._request_headers['Authorization'] | ||
2593 | 2304 | |||
2594 | 2305 | def _DecompressGzippedResponse(self, response): | ||
2595 | 2306 | raw_data = response.read() | ||
2596 | 2307 | if response.headers.get('content-encoding', None) == 'gzip': | ||
2597 | 2308 | url_data = gzip.GzipFile(fileobj=StringIO.StringIO(raw_data)).read() | ||
2598 | 2309 | else: | ||
2599 | 2310 | url_data = raw_data | ||
2600 | 2311 | return url_data | ||
2601 | 2312 | |||
2602 | 2313 | def _GetOpener(self, url, username=None, password=None): | ||
2603 | 2314 | if username and password: | ||
2604 | 2315 | self._AddAuthorizationHeader(username, password) | ||
2605 | 2316 | handler = self._urllib.HTTPBasicAuthHandler() | ||
2606 | 2317 | (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(url) | ||
2607 | 2318 | handler.add_password(Api._API_REALM, netloc, username, password) | ||
2608 | 2319 | opener = self._urllib.build_opener(handler) | ||
2609 | 2320 | else: | ||
2610 | 2321 | opener = self._urllib.build_opener() | ||
2611 | 2322 | opener.addheaders = self._request_headers.items() | ||
2612 | 2323 | return opener | ||
2613 | 2324 | |||
2614 | 2325 | def _Encode(self, s): | ||
2615 | 2326 | if self._input_encoding: | ||
2616 | 2327 | return unicode(s, self._input_encoding).encode('utf-8') | ||
2617 | 2328 | else: | ||
2618 | 2329 | return unicode(s).encode('utf-8') | ||
2619 | 2330 | |||
2620 | 2331 | def _EncodeParameters(self, parameters): | ||
2621 | 2332 | '''Return a string in key=value&key=value form | ||
2622 | 2333 | |||
2623 | 2334 | Values of None are not included in the output string. | ||
2624 | 2335 | |||
2625 | 2336 | Args: | ||
2626 | 2337 | parameters: | ||
2627 | 2338 | A dict of (key, value) tuples, where value is encoded as | ||
2628 | 2339 | specified by self._encoding | ||
2629 | 2340 | Returns: | ||
2630 | 2341 | A URL-encoded string in "key=value&key=value" form | ||
2631 | 2342 | ''' | ||
2632 | 2343 | if parameters is None: | ||
2633 | 2344 | return None | ||
2634 | 2345 | else: | ||
2635 | 2346 | return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in parameters.items() if v is not None])) | ||
2636 | 2347 | |||
2637 | 2348 | def _EncodePostData(self, post_data): | ||
2638 | 2349 | '''Return a string in key=value&key=value form | ||
2639 | 2350 | |||
2640 | 2351 | Values are assumed to be encoded in the format specified by self._encoding, | ||
2641 | 2352 | and are subsequently URL encoded. | ||
2642 | 2353 | |||
2643 | 2354 | Args: | ||
2644 | 2355 | post_data: | ||
2645 | 2356 | A dict of (key, value) tuples, where value is encoded as | ||
2646 | 2357 | specified by self._encoding | ||
2647 | 2358 | Returns: | ||
2648 | 2359 | A URL-encoded string in "key=value&key=value" form | ||
2649 | 2360 | ''' | ||
2650 | 2361 | if post_data is None: | ||
2651 | 2362 | return None | ||
2652 | 2363 | else: | ||
2653 | 2364 | return urllib.urlencode(dict([(k, self._Encode(v)) for k, v in post_data.items()])) | ||
2654 | 2365 | |||
2655 | 2366 | def _CheckForTwitterError(self, data): | ||
2656 | 2367 | """Raises a TwitterError if twitter returns an error message. | ||
2657 | 2368 | |||
2658 | 2369 | Args: | ||
2659 | 2370 | data: A python dict created from the Twitter json response | ||
2660 | 2371 | Raises: | ||
2661 | 2372 | TwitterError wrapping the twitter error message if one exists. | ||
2662 | 2373 | """ | ||
2663 | 2374 | # Twitter errors are relatively unlikely, so it is faster | ||
2664 | 2375 | # to check first, rather than try and catch the exception | ||
2665 | 2376 | if 'error' in data: | ||
2666 | 2377 | raise TwitterError(data['error']) | ||
2667 | 2378 | |||
2668 | 2379 | def _FetchUrl(self, | ||
2669 | 2380 | url, | ||
2670 | 2381 | post_data=None, | ||
2671 | 2382 | parameters=None, | ||
2672 | 2383 | no_cache=None, | ||
2673 | 2384 | use_gzip_compression=None): | ||
2674 | 2385 | '''Fetch a URL, optionally caching for a specified time. | ||
2675 | 2386 | |||
2676 | 2387 | Args: | ||
2677 | 2388 | url: | ||
2678 | 2389 | The URL to retrieve | ||
2679 | 2390 | post_data: | ||
2680 | 2391 | A dict of (str, unicode) key/value pairs. | ||
2681 | 2392 | If set, POST will be used. | ||
2682 | 2393 | parameters: | ||
2683 | 2394 | A dict whose key/value pairs should encoded and added | ||
2684 | 2395 | to the query string. [optional] | ||
2685 | 2396 | no_cache: | ||
2686 | 2397 | If true, overrides the cache on the current request | ||
2687 | 2398 | use_gzip_compression: | ||
2688 | 2399 | If True, tells the server to gzip-compress the response. | ||
2689 | 2400 | It does not apply to POST requests. | ||
2690 | 2401 | Defaults to None, which will get the value to use from | ||
2691 | 2402 | the instance variable self._use_gzip [optional] | ||
2692 | 2403 | |||
2693 | 2404 | Returns: | ||
2694 | 2405 | A string containing the body of the response. | ||
2695 | 2406 | ''' | ||
2696 | 2407 | # Build the extra parameters dict | ||
2697 | 2408 | extra_params = {} | ||
2698 | 2409 | if self._default_params: | ||
2699 | 2410 | extra_params.update(self._default_params) | ||
2700 | 2411 | if parameters: | ||
2701 | 2412 | extra_params.update(parameters) | ||
2702 | 2413 | |||
2703 | 2414 | # Add key/value parameters to the query string of the url | ||
2704 | 2415 | url = self._BuildUrl(url, extra_params=extra_params) | ||
2705 | 2416 | |||
2706 | 2417 | # Get a url opener that can handle basic auth | ||
2707 | 2418 | opener = self._GetOpener(url, username=self._username, password=self._password) | ||
2708 | 2419 | |||
2709 | 2420 | if use_gzip_compression is None: | ||
2710 | 2421 | use_gzip = self._use_gzip | ||
2711 | 2422 | else: | ||
2712 | 2423 | use_gzip = use_gzip_compression | ||
2713 | 2424 | |||
2714 | 2425 | # Set up compression | ||
2715 | 2426 | if use_gzip and not post_data: | ||
2716 | 2427 | opener.addheaders.append(('Accept-Encoding', 'gzip')) | ||
2717 | 2428 | |||
2718 | 2429 | encoded_post_data = self._EncodePostData(post_data) | ||
2719 | 2430 | |||
2720 | 2431 | # Open and return the URL immediately if we're not going to cache | ||
2721 | 2432 | if encoded_post_data or no_cache or not self._cache or not self._cache_timeout: | ||
2722 | 2433 | response = opener.open(url, encoded_post_data) | ||
2723 | 2434 | url_data = self._DecompressGzippedResponse(response) | ||
2724 | 2435 | opener.close() | ||
2725 | 2436 | else: | ||
2726 | 2437 | # Unique keys are a combination of the url and the username | ||
2727 | 2438 | if self._username: | ||
2728 | 2439 | key = self._username + ':' + url | ||
2729 | 2440 | else: | ||
2730 | 2441 | key = url | ||
2731 | 2442 | |||
2732 | 2443 | # See if it has been cached before | ||
2733 | 2444 | last_cached = self._cache.GetCachedTime(key) | ||
2734 | 2445 | |||
2735 | 2446 | # If the cached version is outdated then fetch another and store it | ||
2736 | 2447 | if not last_cached or time.time() >= last_cached + self._cache_timeout: | ||
2737 | 2448 | response = opener.open(url, encoded_post_data) | ||
2738 | 2449 | url_data = self._DecompressGzippedResponse(response) | ||
2739 | 2450 | opener.close() | ||
2740 | 2451 | self._cache.Set(key, url_data) | ||
2741 | 2452 | else: | ||
2742 | 2453 | url_data = self._cache.Get(key) | ||
2743 | 2454 | |||
2744 | 2455 | # Always return the latest version | ||
2745 | 2456 | return url_data | ||
2746 | 2457 | |||
2747 | 2458 | |||
2748 | 2459 | class _FileCacheError(Exception): | ||
2749 | 2460 | '''Base exception class for FileCache related errors''' | ||
2750 | 2461 | |||
2751 | 2462 | class _FileCache(object): | ||
2752 | 2463 | |||
2753 | 2464 | DEPTH = 3 | ||
2754 | 2465 | |||
2755 | 2466 | def __init__(self,root_directory=None): | ||
2756 | 2467 | self._InitializeRootDirectory(root_directory) | ||
2757 | 2468 | |||
2758 | 2469 | def Get(self,key): | ||
2759 | 2470 | path = self._GetPath(key) | ||
2760 | 2471 | if os.path.exists(path): | ||
2761 | 2472 | return open(path).read() | ||
2762 | 2473 | else: | ||
2763 | 2474 | return None | ||
2764 | 2475 | |||
2765 | 2476 | def Set(self,key,data): | ||
2766 | 2477 | path = self._GetPath(key) | ||
2767 | 2478 | directory = os.path.dirname(path) | ||
2768 | 2479 | if not os.path.exists(directory): | ||
2769 | 2480 | os.makedirs(directory) | ||
2770 | 2481 | if not os.path.isdir(directory): | ||
2771 | 2482 | raise _FileCacheError('%s exists but is not a directory' % directory) | ||
2772 | 2483 | temp_fd, temp_path = tempfile.mkstemp() | ||
2773 | 2484 | temp_fp = os.fdopen(temp_fd, 'w') | ||
2774 | 2485 | temp_fp.write(data) | ||
2775 | 2486 | temp_fp.close() | ||
2776 | 2487 | if not path.startswith(self._root_directory): | ||
2777 | 2488 | raise _FileCacheError('%s does not appear to live under %s' % | ||
2778 | 2489 | (path, self._root_directory)) | ||
2779 | 2490 | if os.path.exists(path): | ||
2780 | 2491 | os.remove(path) | ||
2781 | 2492 | os.rename(temp_path, path) | ||
2782 | 2493 | |||
2783 | 2494 | def Remove(self,key): | ||
2784 | 2495 | path = self._GetPath(key) | ||
2785 | 2496 | if not path.startswith(self._root_directory): | ||
2786 | 2497 | raise _FileCacheError('%s does not appear to live under %s' % | ||
2787 | 2498 | (path, self._root_directory )) | ||
2788 | 2499 | if os.path.exists(path): | ||
2789 | 2500 | os.remove(path) | ||
2790 | 2501 | |||
2791 | 2502 | def GetCachedTime(self,key): | ||
2792 | 2503 | path = self._GetPath(key) | ||
2793 | 2504 | if os.path.exists(path): | ||
2794 | 2505 | return os.path.getmtime(path) | ||
2795 | 2506 | else: | ||
2796 | 2507 | return None | ||
2797 | 2508 | |||
2798 | 2509 | def _GetUsername(self): | ||
2799 | 2510 | '''Attempt to find the username in a cross-platform fashion.''' | ||
2800 | 2511 | try: | ||
2801 | 2512 | return os.getenv('USER') or \ | ||
2802 | 2513 | os.getenv('LOGNAME') or \ | ||
2803 | 2514 | os.getenv('USERNAME') or \ | ||
2804 | 2515 | os.getlogin() or \ | ||
2805 | 2516 | 'nobody' | ||
2806 | 2517 | except (IOError, OSError), e: | ||
2807 | 2518 | return 'nobody' | ||
2808 | 2519 | |||
2809 | 2520 | def _GetTmpCachePath(self): | ||
2810 | 2521 | username = self._GetUsername() | ||
2811 | 2522 | cache_directory = 'python.cache_' + username | ||
2812 | 2523 | return os.path.join(tempfile.gettempdir(), cache_directory) | ||
2813 | 2524 | |||
2814 | 2525 | def _InitializeRootDirectory(self, root_directory): | ||
2815 | 2526 | if not root_directory: | ||
2816 | 2527 | root_directory = self._GetTmpCachePath() | ||
2817 | 2528 | root_directory = os.path.abspath(root_directory) | ||
2818 | 2529 | if not os.path.exists(root_directory): | ||
2819 | 2530 | os.mkdir(root_directory) | ||
2820 | 2531 | if not os.path.isdir(root_directory): | ||
2821 | 2532 | raise _FileCacheError('%s exists but is not a directory' % | ||
2822 | 2533 | root_directory) | ||
2823 | 2534 | self._root_directory = root_directory | ||
2824 | 2535 | |||
2825 | 2536 | def _GetPath(self,key): | ||
2826 | 2537 | try: | ||
2827 | 2538 | hashed_key = md5(key).hexdigest() | ||
2828 | 2539 | except TypeError: | ||
2829 | 2540 | hashed_key = md5.new(key).hexdigest() | ||
2830 | 2541 | |||
2831 | 2542 | return os.path.join(self._root_directory, | ||
2832 | 2543 | self._GetPrefix(hashed_key), | ||
2833 | 2544 | hashed_key) | ||
2834 | 2545 | |||
2835 | 2546 | def _GetPrefix(self,hashed_key): | ||
2836 | 2547 | return os.path.sep.join(hashed_key[0:_FileCache.DEPTH]) | ||
2837 | 0 | 2548 | ||
2838 | === added file 'data/icons/hicolor/scalable/apps/backend_identica.png' | |||
2839 | 1 | Binary files data/icons/hicolor/scalable/apps/backend_identica.png 1970-01-01 00:00:00 +0000 and data/icons/hicolor/scalable/apps/backend_identica.png 2010-08-25 16:29:48 +0000 differ | 2549 | Binary files data/icons/hicolor/scalable/apps/backend_identica.png 1970-01-01 00:00:00 +0000 and data/icons/hicolor/scalable/apps/backend_identica.png 2010-08-25 16:29:48 +0000 differ |