Reimplementation of {c:8a0b67} following garage/git cock-up. Better
[hermes] / package / src / org / maemo / hermes / engine / twitter / api.py
1 from org.maemo.hermes.engine.twitter.user import User
2 import urllib, urllib2
3 import base64
4 import simplejson
5 import urlparse
6
7 class TwitterApi():
8     """Twitter backend for Hermes. Inspired by
9           http://code.google.com/p/python-twitter/source/browse/twitter.py
10        
11        Copyright (c) Andrew Flegg <andrew@bleb.org> 2010.
12        Released under the Artistic Licence."""
13        
14        
15     # -----------------------------------------------------------------------
16     def __init__(self, make_api_request):
17         self._make_api_request = make_api_request
18
19
20     # -----------------------------------------------------------------------
21     def get_friends(self):
22         '''Return the full list of people being followed by 'username'.'''
23
24         url = 'https://twitter.com/statuses/friends.json?cursor=%d'
25         cursor = -1
26         users = []
27         while True:
28             json = self._make_api_request(url % (cursor))
29             data = simplejson.loads(json)
30             if 'error' in data:
31                 if data['error'] == 'This method requires authentication.':
32                     raise CredentialsExpiredException('Twitter')
33                 else:
34                     raise Exception(data['error'])
35
36             for x in data['users']:
37                 users.append(User.NewFromJsonDict(x))
38
39             cursor = data['next_cursor']
40             if cursor <= data['previous_cursor']:
41                 break
42
43         return users
44     
45     
46     # -----------------------------------------------------------------------
47     def get_user(self):
48         """Return the name of the authenticated user."""
49         
50         url = 'https://api.twitter.com/1/account/verify_credentials.json'
51         json = self._make_api_request(url)
52         user = simplejson.loads(json)
53 #        if 'name' in user and user['name']:
54 #            return user['name']
55         return user['screen_name']