Switching away from using contact ids
[theonering] / src / gvoice / addressbook.py
1 #!/usr/bin/python
2
3
4 import logging
5
6 import util.coroutines as coroutines
7 import util.misc as util_misc
8
9
10 _moduleLogger = logging.getLogger("gvoice.addressbook")
11
12
13 class Addressbook(object):
14
15         def __init__(self, backend):
16                 self._backend = backend
17                 self._numbers = {}
18
19                 self.updateSignalHandler = coroutines.CoTee()
20
21         def update(self, force=False):
22                 if not force and self._numbers:
23                         return
24                 oldContacts = self._numbers
25                 oldContactNumbers = set(self.get_numbers())
26
27                 self._numbers = {}
28                 self._populate_contacts()
29                 newContactNumbers = set(self.get_numbers())
30
31                 addedContacts = newContactNumbers - oldContactNumbers
32                 removedContacts = oldContactNumbers - newContactNumbers
33                 changedContacts = set(
34                         contactNumber
35                         for contactNumber in newContactNumbers.intersection(oldContactNumbers)
36                         if self._numbers[contactNumber] != oldContacts[contactNumber]
37                 )
38
39                 if addedContacts or removedContacts or changedContacts:
40                         message = self, addedContacts, removedContacts, changedContacts
41                         self.updateSignalHandler.stage.send(message)
42
43         def get_numbers(self):
44                 return self._numbers.iterkeys()
45
46         def get_contact_name(self, strippedNumber):
47                 return self._numbers[strippedNumber][0]
48
49         def get_phone_type(self, strippedNumber):
50                 return self._numbers[strippedNumber][1]
51
52         def _populate_contacts(self):
53                 if self._numbers:
54                         return
55                 contacts = self._backend.get_contacts()
56                 for contactId, contactDetails in contacts:
57                         contactName = contactDetails["name"]
58                         contactNumbers = (
59                                 (
60                                         numberDetails.get("phoneType", "Mobile"),
61                                         util_misc.normalize_number(numberDetails["phoneNumber"]),
62                                 )
63                                 for numberDetails in contactDetails["numbers"]
64                         )
65                         self._numbers.update(
66                                 (number, (contactName, phoneType))
67                                 for (phoneType, number) in contactNumbers
68                         )