Return 'None' when no photo, and ensure paletted images are converted to
[hermes] / package / src / org / maemo / hermes / engine / contact.py
1 import urllib
2 import Image
3 import ImageOps
4 import StringIO
5 import datetime
6 import re
7 from org.maemo.hermes.engine.names import canonical, variants
8 from pygobject import *
9 from ctypes import *
10
11 # Constants from http://library.gnome.org/devel/libebook/stable/EContact.html#EContactField
12 ebook = CDLL('libebook-1.2.so.5')
13 E_CONTACT_HOMEPAGE_URL = 42
14 E_CONTACT_PHOTO = 94
15 E_CONTACT_EMAIL = 97
16 E_CONTACT_BIRTHDAY_DATE = 107
17
18
19 class Contact:
20     """Provide an abstraction of contact, working around limitations
21        in the evolution-python bindings. Properties are defined at:
22        
23           http://library.gnome.org/devel/libebook/stable/EContact.html#id3066469
24
25        Copyright (c) Andrew Flegg <andrew@bleb.org> 2009.
26        Released under the Artistic Licence."""
27
28        
29     # -----------------------------------------------------------------------
30     def __init__(self, book, econtact):
31         """Create a new contact store for modifying contacts in the given
32            EBook."""
33         
34         self._book = book
35         self._contact = econtact
36         self._identifiers = self._find_ids()
37         self._mapped_to = set([])
38         
39         
40     # -----------------------------------------------------------------------
41     def _find_ids(self):
42         """Return a set of the identifiers which should be used to match this
43            contact. Includes variants of first name, last name, nickname and
44            email address. These are all Unicode-normalised into the traditional
45            US-ASCII namespace"""
46            
47         result = set()
48         for name in variants(self._contact.get_name()):
49             result.add(canonical(name))
50             
51         for name in variants(self._contact.get_property('nickname')):
52             result.add(canonical(name))
53             
54         for email in self.get_emails():
55             user = canonical(email.split('@')[0])
56             if len(user) > 4:
57                 result.add(user)
58
59         return result
60     
61     
62     # -----------------------------------------------------------------------
63     def get_name(self):
64         """Return this contact's name."""
65         
66         return self._contact.get_name() or self._contact.get_property('nickname')
67     
68     
69     # -----------------------------------------------------------------------
70     def get_identifiers(self):
71         """Return the lowercase, Unicode-normalised, all-alphabetic
72            versions of identifiers for this contact."""
73            
74         return self._identifiers
75
76     
77     # -----------------------------------------------------------------------
78     def get_econtact(self):
79         """Return the EContact which backs this contact."""
80         
81         return self._contact
82     
83     
84     # -----------------------------------------------------------------------
85     def add_mapping(self, id):
86         """Record the fact that this contact is mapped against a provider.
87            'id' MUST match the string returned by Provider.get_id()."""
88         
89         self._mapped_to.add(id)
90         
91         
92     # ----------------------------------------------------------------------
93     def get_mappings(self):
94         """Return the set of IDs of providers which are mapped to this contact.
95            The data can only be relied upon after services have run."""
96            
97         return self._mapped_to
98
99
100     # -----------------------------------------------------------------------
101     def get_photo(self):
102         """Return the photo property, or None. The result is of type
103         EContactPhoto."""
104         
105         photo = self._contact.get_property('photo')
106         pi = cast(c_void_p(hash(photo)), POINTER(EContactPhoto))
107         if photo is None or pi.contents.data.uri == '':
108             return None
109         else:
110             return pi
111     
112     
113     # -----------------------------------------------------------------------
114     def set_photo(self, url):
115         """Set the given contact's photo to the picture found at the URL. If the
116            photo is wider than it is tall, it will be cropped with a bias towards
117            the top of the photo."""
118         
119         try:
120             f = urllib.urlopen(url)
121             data = ''
122             while True:
123                 read_data = f.read()
124                 data += read_data
125                 if not read_data:
126                     break
127             
128             im = Image.open(StringIO.StringIO(data))
129             if im.mode != 'RGB':
130                 im.convert('RGB')
131                 
132             (w, h) = im.size
133             if (h > w):
134                 ##print u"Shrinking photo for %s as it's %d x %d" % (self._contact.get_name(), w, h)
135                 im = ImageOps.fit(im, (w, w), Image.NEAREST, 0, (0, 0.1))
136               
137             ## print u"Updating photo for %s" % (self._contact.get_name())
138             f = StringIO.StringIO()
139             im.save(f, "JPEG")
140             image_data = f.getvalue()
141             photo = EContactPhoto()
142             photo.type = 0
143             photo.data = EContactPhoto_data()
144             photo.data.inlined = EContactPhoto_inlined()
145             photo.data.inlined.mime_type = cast(create_string_buffer("image/jpeg"), c_char_p)
146             photo.data.inlined.length = len(image_data)
147             photo.data.inlined.data = cast(create_string_buffer(image_data), c_void_p)
148             ebook.e_contact_set(hash(self._contact), E_CONTACT_PHOTO, addressof(photo))
149             return True
150         except:
151             print "FAILED to get photo from URL %s" % url
152             return False
153       
154       
155     # -----------------------------------------------------------------------
156     def set_birthday(self, day, month, year = 0):
157         """Set the birthday for this contact to the given day, month and year."""
158         
159         if year == 0:
160             year = datetime.date.today().year
161           
162         birthday = EContactDate()
163         birthday.year = year
164         birthday.month = month
165         birthday.day = day
166         print u"Setting birthday for [%s] to %d-%d-%d" % (self._contact.get_name(), year, month, day)
167         ebook.e_contact_set(hash(self._contact), E_CONTACT_BIRTHDAY_DATE, addressof(birthday))
168         return True
169     
170     
171     # -----------------------------------------------------------------------
172     def get_birthday(self):
173         photo = self._contact.get_property('birth-date')
174         return cast(c_void_p(hash(photo)), POINTER(EContactDate))
175         
176     
177     # -----------------------------------------------------------------------
178     def set_nickname(self, nickname):
179         """Set the nickname for this contact to the given nickname."""
180         
181         # FIXME does this work?
182         self._contact.set_property('nickname', nickname)
183         #ebook.e_contact_set(hash(self._contact), E_NICKNAME, addressof(nickname))
184     
185     
186     # -----------------------------------------------------------------------
187     def get_nickname(self):
188         """Get the nickname for this contact."""
189         
190         return self._contact.get_property('nickname')
191     
192     
193     # -----------------------------------------------------------------------
194     def get_emails(self):
195         """Return the email addresses associated with this contact."""
196         
197         emails = []
198         ai = GList.new(ebook.e_contact_get_attributes(hash(self._contact), E_CONTACT_EMAIL))
199         while ai.has_next():
200             attr = ai.next(as_a = EVCardAttribute)
201             if not attr:
202                 raise Exception(u"Unexpected null attribute for [" + self._contact.get_name() + "] with emails " + emails)
203             emails.append(string_at(attr.value().next()))
204           
205         return emails
206         
207       
208       
209     # -----------------------------------------------------------------------
210     def get_urls(self):
211         """Return a list of URLs which are associated with this contact."""
212         
213         urls = []
214         ai = GList.new(ebook.e_contact_get_attributes(hash(self._contact), E_CONTACT_HOMEPAGE_URL))
215         while ai.has_next():
216             attr = ai.next(as_a = EVCardAttribute)
217             if not attr:
218                 raise Exception(u"Unexpected null attribute for [" + self._contact.get_name() + "] with URLs " + urls)
219             urls.append(string_at(attr.value().next()))
220           
221         return urls
222     
223       
224     # -----------------------------------------------------------------------
225     def add_url(self, str, unique = ''):
226         """Add a new URL to the set of URLs for the given contact."""
227         
228         urls = re.findall('(?:(?:ftp|https?):\/\/|\\bwww\.|\\bftp\.)[,\w\.\-\/@:%?&=%+#~_$\*]+[\w=\/&=+#]', str, re.I | re.S)
229         updated = False
230         for url in urls:
231             updated = self._add_url(url, unique or re.sub('(?:.*://)?(\w+(?:[\w\.])*).*', '\\1', url)) or updated
232         
233         return updated
234     
235     
236     # -----------------------------------------------------------------------
237     def _add_url(self, url, unique):
238         """Do the work of adding a unique URL to a contact."""
239         
240         url_attr = None
241         ai = GList.new(ebook.e_contact_get_attributes(hash(self._contact), E_CONTACT_HOMEPAGE_URL))
242         while ai.has_next():
243             attr = ai.next(as_a = EVCardAttribute)
244             existing = string_at(attr.value().next())
245             #print "Existing URL [%s] when adding [%s] to [%s] with constraint [%s]" % (existing, url, contact.get_name(), unique)
246             if existing == unique or existing == url:
247                 return False
248             elif existing.find(unique) > -1:
249                 url_attr = attr
250           
251         if not url_attr:
252             ai.add()
253             url_attr = EVCardAttribute()
254             url_attr.group = ''
255             url_attr.name = 'URL'
256         
257         val = GList()
258         ##print u"Setting URL for [%s] to [%s]" % (self._contact.get_name(), url)
259         val.set(create_string_buffer(url))
260         ai.set(addressof(url_attr))
261         url_attr.values = cast(addressof(val), POINTER(GList))
262         ebook.e_contact_set_attributes(hash(self._contact), E_CONTACT_HOMEPAGE_URL, addressof(ai))
263         return True
264