If a friend retrieved from Facebook has a picture, replace the URL with
[hermes] / package / src / org / maemo / hermes / engine / facebook / api.py
1 import urllib, urllib2
2 import simplejson
3
4 class FacebookApi():
5     """Facebook backend for Hermes, using the Graph API:
6     
7           http://developers.facebook.com/docs/reference/api/
8        
9        Copyright (c) Andrew Flegg <andrew@bleb.org> 2010.
10        Released under the Artistic Licence."""
11        
12        
13     # -----------------------------------------------------------------------
14     def __init__(self, oauth):
15         self._oauth = oauth
16
17
18     # -----------------------------------------------------------------------
19     def authenticate(self):
20         '''Authenticate the user with Facebook.'''
21         
22         self._oauth.authorise('https://graph.facebook.com/oauth/authorize',
23                               'https://graph.facebook.com/oauth/access_token',
24                               {'scope': 'user_about_me,friends_about_me,user_birthday,friends_birthday,user_website,friends_website,user_work_history,friends_work_history'})
25
26
27     # -----------------------------------------------------------------------
28     def get_user(self):
29         '''Return the name of the authenticated user.'''
30         
31         data = self._request('https://graph.facebook.com/me')
32         return data['name']
33
34
35     # -----------------------------------------------------------------------
36     def get_friends(self):
37         '''Return the full list of people being followed by the user.
38         
39            The result is a list of users:
40            http://developers.facebook.com/docs/reference/api/user/'''
41
42         users = self._request('https://graph.facebook.com/me/friends', {'fields': 'id,name,link,birthday,website,picture'})['data']
43         for user in users:
44             if 'picture' in user:
45                 user['picture'] = 'https://graph.facebook.com/%s/picture?type=large&access_token=%s' % (user['id'], self._oauth.get_access_token())
46         return users
47     
48     
49     # -----------------------------------------------------------------------
50     def _request(self, url, args = None):
51         """Make an authenticated request to Facebook and check the
52            JSON response. Return the dictionary if no errors."""
53         
54         json = self._oauth.request(url, args)
55 #        print json
56         data = simplejson.loads(json)
57         if 'error' in data:
58             raise Exception(data['error'])
59         
60         return data