/gdata/contacts/service.py

http://radioappz.googlecode.com/ · Python · 427 lines · 343 code · 27 blank · 57 comment · 10 complexity · 34e41ced316941233a74fb17fc278eb1 MD5 · raw file

  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2009 Google Inc. All Rights Reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """ContactsService extends the GDataService for Google Contacts operations.
  17. ContactsService: Provides methods to query feeds and manipulate items.
  18. Extends GDataService.
  19. DictionaryToParamList: Function which converts a dictionary into a list of
  20. URL arguments (represented as strings). This is a
  21. utility function used in CRUD operations.
  22. """
  23. __author__ = 'dbrattli (Dag Brattli)'
  24. import gdata
  25. import gdata.calendar
  26. import gdata.service
  27. DEFAULT_BATCH_URL = ('http://www.google.com/m8/feeds/contacts/default/full'
  28. '/batch')
  29. DEFAULT_PROFILES_BATCH_URL = ('http://www.google.com'
  30. '/m8/feeds/profiles/default/full/batch')
  31. GDATA_VER_HEADER = 'GData-Version'
  32. class Error(Exception):
  33. pass
  34. class RequestError(Error):
  35. pass
  36. class ContactsService(gdata.service.GDataService):
  37. """Client for the Google Contacts service."""
  38. def __init__(self, email=None, password=None, source=None,
  39. server='www.google.com', additional_headers=None,
  40. contact_list='default', **kwargs):
  41. """Creates a client for the Contacts service.
  42. Args:
  43. email: string (optional) The user's email address, used for
  44. authentication.
  45. password: string (optional) The user's password.
  46. source: string (optional) The name of the user's application.
  47. server: string (optional) The name of the server to which a connection
  48. will be opened. Default value: 'www.google.com'.
  49. contact_list: string (optional) The name of the default contact list to
  50. use when no URI is specified to the methods of the service.
  51. Default value: 'default' (the logged in user's contact list).
  52. **kwargs: The other parameters to pass to gdata.service.GDataService
  53. constructor.
  54. """
  55. self.contact_list = contact_list
  56. gdata.service.GDataService.__init__(
  57. self, email=email, password=password, service='cp', source=source,
  58. server=server, additional_headers=additional_headers, **kwargs)
  59. def GetFeedUri(self, kind='contacts', contact_list=None, projection='full',
  60. scheme=None):
  61. """Builds a feed URI.
  62. Args:
  63. kind: The type of feed to return, typically 'groups' or 'contacts'.
  64. Default value: 'contacts'.
  65. contact_list: The contact list to return a feed for.
  66. Default value: self.contact_list.
  67. projection: The projection to apply to the feed contents, for example
  68. 'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.
  69. scheme: The URL scheme such as 'http' or 'https', None to return a
  70. relative URI without hostname.
  71. Returns:
  72. A feed URI using the given kind, contact list, and projection.
  73. Example: '/m8/feeds/contacts/default/full'.
  74. """
  75. contact_list = contact_list or self.contact_list
  76. if kind == 'profiles':
  77. contact_list = 'domain/%s' % contact_list
  78. prefix = scheme and '%s://%s' % (scheme, self.server) or ''
  79. return '%s/m8/feeds/%s/%s/%s' % (prefix, kind, contact_list, projection)
  80. def GetContactsFeed(self, uri=None):
  81. uri = uri or self.GetFeedUri()
  82. return self.Get(uri, converter=gdata.contacts.ContactsFeedFromString)
  83. def GetContact(self, uri):
  84. return self.Get(uri, converter=gdata.contacts.ContactEntryFromString)
  85. def CreateContact(self, new_contact, insert_uri=None, url_params=None,
  86. escape_params=True):
  87. """Adds an new contact to Google Contacts.
  88. Args:
  89. new_contact: atom.Entry or subclass A new contact which is to be added to
  90. Google Contacts.
  91. insert_uri: the URL to post new contacts to the feed
  92. url_params: dict (optional) Additional URL parameters to be included
  93. in the insertion request.
  94. escape_params: boolean (optional) If true, the url_parameters will be
  95. escaped before they are included in the request.
  96. Returns:
  97. On successful insert, an entry containing the contact created
  98. On failure, a RequestError is raised of the form:
  99. {'status': HTTP status code from server,
  100. 'reason': HTTP reason from the server,
  101. 'body': HTTP body of the server's response}
  102. """
  103. insert_uri = insert_uri or self.GetFeedUri()
  104. return self.Post(new_contact, insert_uri, url_params=url_params,
  105. escape_params=escape_params,
  106. converter=gdata.contacts.ContactEntryFromString)
  107. def UpdateContact(self, edit_uri, updated_contact, url_params=None,
  108. escape_params=True):
  109. """Updates an existing contact.
  110. Args:
  111. edit_uri: string The edit link URI for the element being updated
  112. updated_contact: string, atom.Entry or subclass containing
  113. the Atom Entry which will replace the contact which is
  114. stored at the edit_url
  115. url_params: dict (optional) Additional URL parameters to be included
  116. in the update request.
  117. escape_params: boolean (optional) If true, the url_parameters will be
  118. escaped before they are included in the request.
  119. Returns:
  120. On successful update, a httplib.HTTPResponse containing the server's
  121. response to the PUT request.
  122. On failure, a RequestError is raised of the form:
  123. {'status': HTTP status code from server,
  124. 'reason': HTTP reason from the server,
  125. 'body': HTTP body of the server's response}
  126. """
  127. return self.Put(updated_contact, self._CleanUri(edit_uri),
  128. url_params=url_params,
  129. escape_params=escape_params,
  130. converter=gdata.contacts.ContactEntryFromString)
  131. def DeleteContact(self, edit_uri, extra_headers=None,
  132. url_params=None, escape_params=True):
  133. """Removes an contact with the specified ID from Google Contacts.
  134. Args:
  135. edit_uri: string The edit URL of the entry to be deleted. Example:
  136. '/m8/feeds/contacts/default/full/xxx/yyy'
  137. url_params: dict (optional) Additional URL parameters to be included
  138. in the deletion request.
  139. escape_params: boolean (optional) If true, the url_parameters will be
  140. escaped before they are included in the request.
  141. Returns:
  142. On successful delete, a httplib.HTTPResponse containing the server's
  143. response to the DELETE request.
  144. On failure, a RequestError is raised of the form:
  145. {'status': HTTP status code from server,
  146. 'reason': HTTP reason from the server,
  147. 'body': HTTP body of the server's response}
  148. """
  149. return self.Delete(self._CleanUri(edit_uri),
  150. url_params=url_params, escape_params=escape_params)
  151. def GetGroupsFeed(self, uri=None):
  152. uri = uri or self.GetFeedUri('groups')
  153. return self.Get(uri, converter=gdata.contacts.GroupsFeedFromString)
  154. def CreateGroup(self, new_group, insert_uri=None, url_params=None,
  155. escape_params=True):
  156. insert_uri = insert_uri or self.GetFeedUri('groups')
  157. return self.Post(new_group, insert_uri, url_params=url_params,
  158. escape_params=escape_params,
  159. converter=gdata.contacts.GroupEntryFromString)
  160. def UpdateGroup(self, edit_uri, updated_group, url_params=None,
  161. escape_params=True):
  162. return self.Put(updated_group, self._CleanUri(edit_uri),
  163. url_params=url_params,
  164. escape_params=escape_params,
  165. converter=gdata.contacts.GroupEntryFromString)
  166. def DeleteGroup(self, edit_uri, extra_headers=None,
  167. url_params=None, escape_params=True):
  168. return self.Delete(self._CleanUri(edit_uri),
  169. url_params=url_params, escape_params=escape_params)
  170. def ChangePhoto(self, media, contact_entry_or_url, content_type=None,
  171. content_length=None):
  172. """Change the photo for the contact by uploading a new photo.
  173. Performs a PUT against the photo edit URL to send the binary data for the
  174. photo.
  175. Args:
  176. media: filename, file-like-object, or a gdata.MediaSource object to send.
  177. contact_entry_or_url: ContactEntry or str If it is a ContactEntry, this
  178. method will search for an edit photo link URL and
  179. perform a PUT to the URL.
  180. content_type: str (optional) the mime type for the photo data. This is
  181. necessary if media is a file or file name, but if media
  182. is a MediaSource object then the media object can contain
  183. the mime type. If media_type is set, it will override the
  184. mime type in the media object.
  185. content_length: int or str (optional) Specifying the content length is
  186. only required if media is a file-like object. If media
  187. is a filename, the length is determined using
  188. os.path.getsize. If media is a MediaSource object, it is
  189. assumed that it already contains the content length.
  190. """
  191. if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
  192. url = contact_entry_or_url.GetPhotoEditLink().href
  193. else:
  194. url = contact_entry_or_url
  195. if isinstance(media, gdata.MediaSource):
  196. payload = media
  197. # If the media object is a file-like object, then use it as the file
  198. # handle in the in the MediaSource.
  199. elif hasattr(media, 'read'):
  200. payload = gdata.MediaSource(file_handle=media,
  201. content_type=content_type, content_length=content_length)
  202. # Assume that the media object is a file name.
  203. else:
  204. payload = gdata.MediaSource(content_type=content_type,
  205. content_length=content_length, file_path=media)
  206. return self.Put(payload, url)
  207. def GetPhoto(self, contact_entry_or_url):
  208. """Retrives the binary data for the contact's profile photo as a string.
  209. Args:
  210. contact_entry_or_url: a gdata.contacts.ContactEntry objecr or a string
  211. containing the photo link's URL. If the contact entry does not
  212. contain a photo link, the image will not be fetched and this method
  213. will return None.
  214. """
  215. # TODO: add the ability to write out the binary image data to a file,
  216. # reading and writing a chunk at a time to avoid potentially using up
  217. # large amounts of memory.
  218. url = None
  219. if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
  220. photo_link = contact_entry_or_url.GetPhotoLink()
  221. if photo_link:
  222. url = photo_link.href
  223. else:
  224. url = contact_entry_or_url
  225. if url:
  226. return self.Get(url, converter=str)
  227. else:
  228. return None
  229. def DeletePhoto(self, contact_entry_or_url):
  230. url = None
  231. if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
  232. url = contact_entry_or_url.GetPhotoEditLink().href
  233. else:
  234. url = contact_entry_or_url
  235. if url:
  236. self.Delete(url)
  237. def GetProfilesFeed(self, uri=None):
  238. """Retrieves a feed containing all domain's profiles.
  239. Args:
  240. uri: string (optional) the URL to retrieve the profiles feed,
  241. for example /m8/feeds/profiles/default/full
  242. Returns:
  243. On success, a ProfilesFeed containing the profiles.
  244. On failure, raises a RequestError.
  245. """
  246. uri = uri or self.GetFeedUri('profiles')
  247. return self.Get(uri,
  248. converter=gdata.contacts.ProfilesFeedFromString)
  249. def GetProfile(self, uri):
  250. """Retrieves a domain's profile for the user.
  251. Args:
  252. uri: string the URL to retrieve the profiles feed,
  253. for example /m8/feeds/profiles/default/full/username
  254. Returns:
  255. On success, a ProfileEntry containing the profile for the user.
  256. On failure, raises a RequestError
  257. """
  258. return self.Get(uri,
  259. converter=gdata.contacts.ProfileEntryFromString)
  260. def UpdateProfile(self, edit_uri, updated_profile, url_params=None,
  261. escape_params=True):
  262. """Updates an existing profile.
  263. Args:
  264. edit_uri: string The edit link URI for the element being updated
  265. updated_profile: string atom.Entry or subclass containing
  266. the Atom Entry which will replace the profile which is
  267. stored at the edit_url.
  268. url_params: dict (optional) Additional URL parameters to be included
  269. in the update request.
  270. escape_params: boolean (optional) If true, the url_params will be
  271. escaped before they are included in the request.
  272. Returns:
  273. On successful update, a httplib.HTTPResponse containing the server's
  274. response to the PUT request.
  275. On failure, raises a RequestError.
  276. """
  277. return self.Put(updated_profile, self._CleanUri(edit_uri),
  278. url_params=url_params, escape_params=escape_params,
  279. converter=gdata.contacts.ProfileEntryFromString)
  280. def ExecuteBatch(self, batch_feed, url,
  281. converter=gdata.contacts.ContactsFeedFromString):
  282. """Sends a batch request feed to the server.
  283. Args:
  284. batch_feed: gdata.contacts.ContactFeed A feed containing batch
  285. request entries. Each entry contains the operation to be performed
  286. on the data contained in the entry. For example an entry with an
  287. operation type of insert will be used as if the individual entry
  288. had been inserted.
  289. url: str The batch URL to which these operations should be applied.
  290. converter: Function (optional) The function used to convert the server's
  291. response to an object. The default value is ContactsFeedFromString.
  292. Returns:
  293. The results of the batch request's execution on the server. If the
  294. default converter is used, this is stored in a ContactsFeed.
  295. """
  296. return self.Post(batch_feed, url, converter=converter)
  297. def ExecuteBatchProfiles(self, batch_feed, url,
  298. converter=gdata.contacts.ProfilesFeedFromString):
  299. """Sends a batch request feed to the server.
  300. Args:
  301. batch_feed: gdata.profiles.ProfilesFeed A feed containing batch
  302. request entries. Each entry contains the operation to be performed
  303. on the data contained in the entry. For example an entry with an
  304. operation type of insert will be used as if the individual entry
  305. had been inserted.
  306. url: string The batch URL to which these operations should be applied.
  307. converter: Function (optional) The function used to convert the server's
  308. response to an object. The default value is
  309. gdata.profiles.ProfilesFeedFromString.
  310. Returns:
  311. The results of the batch request's execution on the server. If the
  312. default converter is used, this is stored in a ProfilesFeed.
  313. """
  314. return self.Post(batch_feed, url, converter=converter)
  315. def _CleanUri(self, uri):
  316. """Sanitizes a feed URI.
  317. Args:
  318. uri: The URI to sanitize, can be relative or absolute.
  319. Returns:
  320. The given URI without its http://server prefix, if any.
  321. Keeps the leading slash of the URI.
  322. """
  323. url_prefix = 'http://%s' % self.server
  324. if uri.startswith(url_prefix):
  325. uri = uri[len(url_prefix):]
  326. return uri
  327. class ContactsQuery(gdata.service.Query):
  328. def __init__(self, feed=None, text_query=None, params=None,
  329. categories=None, group=None):
  330. self.feed = feed or '/m8/feeds/contacts/default/full'
  331. if group:
  332. self._SetGroup(group)
  333. gdata.service.Query.__init__(self, feed=self.feed, text_query=text_query,
  334. params=params, categories=categories)
  335. def _GetGroup(self):
  336. if 'group' in self:
  337. return self['group']
  338. else:
  339. return None
  340. def _SetGroup(self, group_id):
  341. self['group'] = group_id
  342. group = property(_GetGroup, _SetGroup,
  343. doc='The group query parameter to find only contacts in this group')
  344. class GroupsQuery(gdata.service.Query):
  345. def __init__(self, feed=None, text_query=None, params=None,
  346. categories=None):
  347. self.feed = feed or '/m8/feeds/groups/default/full'
  348. gdata.service.Query.__init__(self, feed=self.feed, text_query=text_query,
  349. params=params, categories=categories)
  350. class ProfilesQuery(gdata.service.Query):
  351. """Constructs a query object for the profiles feed."""
  352. def __init__(self, feed=None, text_query=None, params=None,
  353. categories=None):
  354. self.feed = feed or '/m8/feeds/profiles/default/full'
  355. gdata.service.Query.__init__(self, feed=self.feed, text_query=text_query,
  356. params=params, categories=categories)