6 import util.coroutines as coroutines
9 _moduleLogger = logging.getLogger("gvoice.addressbook")
12 class Addressbook(object):
14 def __init__(self, backend):
15 self._backend = backend
17 self._addedContacts = set()
18 self._removedContacts = set()
19 self._changedContacts = set()
21 self.updateSignalHandler = coroutines.CoTee()
23 def update(self, force=False):
24 if not force and self._contacts:
26 oldContacts = self._contacts
27 oldContactIds = set(self.get_contacts())
30 self._populate_contacts()
31 newContactIds = set(self.get_contacts())
33 self._addedContacts = newContactIds - oldContactIds
34 self._removedContacts = oldContactIds - newContactIds
35 self._changedContacts = set(
37 for contactId in newContactIds.intersection(oldContactIds)
38 if self._has_contact_changed(contactId, oldContacts)
41 if self._addedContacts or self._removedContacts or self._changedContacts:
42 message = self, self._addedContacts, self._removedContacts, self._changedContacts
43 self.updateSignalHandler.stage.send(message)
45 def get_contacts(self):
46 return self._contacts.iterkeys()
48 def get_contact_name(self, contactId):
49 return self._contacts[contactId][0]
51 def get_contact_details(self, contactId):
52 self._populate_contact_details(contactId)
53 return self._get_contact_details(contactId)
55 def _populate_contacts(self):
58 contacts = self._backend.get_contacts()
59 for contactId, contactName in contacts:
60 self._contacts[contactId] = (contactName, [])
62 def _populate_contact_details(self, contactId):
63 if self._get_contact_details(contactId):
65 self._get_contact_details(contactId).extend(
66 self._backend.get_contact_details(contactId)
69 def _get_contact_details(self, contactId):
70 return self._contacts[contactId][1]
72 def _has_contact_changed(self, contactId, oldContacts):
73 oldContact = oldContacts[contactId]
74 oldContactName = oldContact[0]
75 oldContactDetails = oldContact[1]
76 if oldContactName != self.get_contact_name(contactId):
78 if not oldContactDetails:
80 # if its already in the old cache, purposefully add it into the new cache
81 return oldContactDetails != self.get_contact_details(contactId)