Re-implement Facebook service to use OAuth2 and Graph API. This allows
[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         def copy(data, from_key, to, to_key = None):
43             if not to_key:
44                 to_key = from_key
45                 
46             if from_key in data:
47                 to[to_key] = data[from_key]
48
49         users = self._request('https://graph.facebook.com/me/friends', {'fields': 'id,name,link,birthday,website,picture', 'type': 'large'})
50         return users['data']
51     
52     
53     # -----------------------------------------------------------------------
54     def _request(self, url, args = None):
55         """Make an authenticated request to Facebook and check the
56            JSON response. Return the dictionary if no errors."""
57         
58         json = self._oauth.request(url, args)
59 #        print json
60         data = simplejson.loads(json)
61         if 'error' in data:
62             raise Exception(data['error'])
63         
64         return data