3 from facebook import Facebook, FacebookError
7 from contacts import ContactStore
11 """Encapsulate the process of syncing Facebook friends' information with the
12 Evolution contacts' database. This should be used as follows:
14 * Initialise, passing in a callback (methods: need_auth(),
15 block_for_auth(), use_twitter(), use_facebook()).
16 * Call load_friends().
17 * Call sync_contacts().
18 * Retrieve information on changes effected.
20 This requires two gconf paths to contain Facebook application keys:
21 /apps/maemo/hermes/key_app
22 /apps/maemo/hermes/key_secret
24 Copyright (c) Andrew Flegg <andrew@bleb.org> 2009.
25 Released under the Artistic Licence."""
28 # -----------------------------------------------------------------------
29 def __init__(self, callback, twitter = None, facebook = False):
30 """Constructor. Passed a callback which must implement three informational
33 need_auth() - called to indicate a login is about to occur. The user
36 block_for_auth() - prompt the user to take some action once they have
37 successfully logged in to Facebook.
39 progress(i, j) - the application is currently processing friend 'i' of
40 'j'. Should be used to provide the user a progress bar.
43 twitter - a username/password tuple or None if Twitter should not be
44 used. Defaults to None.
46 facebook - boolean indicating if Facebook should be used. Defaults to
50 self.gc = gnome.gconf.client_get_default()
51 self.callback = callback
52 self.twitter = twitter
53 self.facebook = facebook
55 # -- Check the environment is going to work...
57 if (self.gc.get_string('/desktop/gnome/url-handlers/http/command') == 'epiphany %s'):
58 raise Exception('Browser in gconf invalid (see NB#136012). Installation error.')
60 # -- Get private keys for this app...
62 key_app = self.gc.get_string('/apps/maemo/hermes/key_app')
63 key_secret = self.gc.get_string('/apps/maemo/hermes/key_secret')
64 if (key_app is None or key_secret is None):
65 raise Exception('No Facebook application keys found. Installation error.')
67 self.fb = Facebook(key_app, key_secret)
68 self.fb.desktop = True
71 # -----------------------------------------------------------------------
72 def do_fb_login(self):
73 """Perform authentication against Facebook and store the result in gconf
74 for later use. Uses the 'need_auth' and 'block_for_auth' methods on
75 the callback class. The former allows a message to warn the user
76 about what is about to happen to be shown; the second is to wait
77 for the user to confirm they have logged in."""
78 self.fb.session_key = None
82 self.callback.need_auth()
83 self.fb.auth.createToken()
85 self.callback.block_for_auth()
86 session = self.fb.auth.getSession()
88 self.gc.set_string('/apps/maemo/hermes/session_key', session['session_key'])
89 self.gc.set_string('/apps/maemo/hermes/secret_key', session['secret'])
90 self.gc.set_int('/apps/maemo/hermes/uid', session['uid'])
93 # -----------------------------------------------------------------------
94 def load_friends(self):
95 """Load information on the authenticated user's friends. If no user is
96 currently authenticated, prompts for a login."""
99 self.blocked_pictures = []
100 self.callback.progress(0, 0)
102 # -- Get a user session and retrieve Facebook friends...
105 if self.fb.session_key is None:
106 self.fb.session_key = self.gc.get_string('/apps/maemo/hermes/session_key')
107 self.fb.secret = self.gc.get_string('/apps/maemo/hermes/secret_key')
108 self.fb.uid = self.gc.get_int('/apps/maemo/hermes/uid')
110 # Check the available session is still valid...
113 if self.fb.users.getLoggedInUser() and self.fb.session_key:
115 except FacebookError:
119 # Get the list of friends...
120 attrs = ['uid', 'name', 'pic_big', 'birthday_date', 'profile_url']
121 for friend in self.fb.users.getInfo(self.fb.friends.get(), attrs):
122 friend['name'] = unicodedata.normalize('NFKD', unicode(friend['name']))
123 friend['pic'] = friend[attrs[2]]
124 self.friends[friend['name']] = friend
125 if not friend['pic']:
126 self.blocked_pictures.append(friend)
128 # -- Retrieve following information from Twitter...
130 if self.twitter is not None:
131 (user, passwd) = self.twitter
132 api = twitter.Api(username=user, password=passwd)
133 users = api.GetFriends()
134 for friend in api.GetFriends():
135 self.friends[friend.name] = {'name': unicodedata.normalize('NFKD', unicode(friend.name)), 'pic': friend.profile_image_url, 'birthday_date': None, 'twitter_url': 'http://twitter.com/%s' % (friend.screen_name), 'homepage' : friend.url}
137 # TODO What if the user has *no* contacts?
140 # -----------------------------------------------------------------------
141 def sync_contacts(self, resync = False):
142 """Synchronise Facebook profiles to contact database. If resync is false,
143 no existing information will be overwritten."""
145 # -- Find addresses...
147 print "+++ Syncing contacts..."
148 addresses = evolution.ebook.open_addressbook('default')
149 print "+++ Addressbook opened..."
150 store = ContactStore(addresses)
151 print "+++ Contact store created..."
155 contacts = addresses.get_all_contacts()
156 contacts.sort(key=lambda obj: obj.get_name())
158 maximum = len(contacts)
159 for contact in contacts:
161 self.callback.progress(current, maximum)
163 for name in names.variants(contact.get_name()):
164 if name in self.friends:
165 friend = self.friends[name]
169 if friend['pic'] and (resync or contact.get_property('photo') is None):
170 updated = store.set_photo(contact, friend['pic']) or updated
172 if friend['birthday_date'] and (resync or contact.get_property('birth-date') is None):
173 date_str = friend['birthday_date'].split('/')
175 updated = store.set_birthday(contact, int(date_str[1]),
177 int(date_str[2])) or updated
179 if 'profile_url' in friend and friend['profile_url']:
180 updated = store.add_url(contact, friend['profile_url'], unique='facebook.com') or updated
182 if 'twitter_url' in friend and friend['twitter_url']:
183 updated = store.add_url(contact, friend['twitter_url'], unique='twitter.com') or updated
185 if 'homepage' in friend and friend['homepage']:
186 updated = store.add_url(contact, friend['homepage']) or updated
189 self.updated.append(contact)
190 addresses.commit_contact(contact)
191 print "Saved changes to [%s]" % (contact.get_name())
196 self.matched.append(contact)
198 self.unmatched.append(contact)