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()
24 def update(self, force=False):
25 if not force and self._contacts:
27 oldContacts = self._contacts
28 oldContactIds = set(self.get_contacts())
31 self._populate_contacts()
32 newContactIds = set(self.get_contacts())
34 self._addedContacts = newContactIds - oldContactIds
35 self._removedContacts = oldContactIds - newContactIds
36 self._changedContacts = set(
38 for contactId in newContactIds.intersection(oldContactIds)
39 if self._has_contact_changed(contactId, oldContacts)
42 if self._addedContacts or self._removedContacts or self._changedContacts:
43 message = self, self._addedContacts, self._removedContacts, self._changedContacts
44 self.updateSignalHandler.stage.send(message)
46 def get_contacts(self):
47 return self._contacts.iterkeys()
49 def get_contact_name(self, contactId):
50 return self._contacts[contactId][0]
52 def get_contact_details(self, contactId):
53 self._populate_contact_details(contactId)
54 return self._get_contact_details(contactId)
56 def _populate_contacts(self):
59 contacts = self._backend.get_contacts()
60 for contactId, contactName in contacts:
61 self._contacts[contactId] = (contactName, [])
63 def _populate_contact_details(self, contactId):
64 if self._get_contact_details(contactId):
66 self._get_contact_details(contactId).extend(
67 self._backend.get_contact_details(contactId)
70 def _get_contact_details(self, contactId):
71 return self._contacts[contactId][1]
73 def _has_contact_changed(self, contactId, oldContacts):
74 oldContact = oldContacts[contactId]
75 oldContactName = oldContact[0]
76 oldContactDetails = oldContact[1]
77 if oldContactName != self.get_contact_name(contactId):
79 if not oldContactDetails:
81 # if its already in the old cache, purposefully add it into the new cache
82 return oldContactDetails != self.get_contact_details(contactId)