/gdata/contacts/client.py

http://radioappz.googlecode.com/ · Python · 474 lines · 414 code · 19 blank · 41 comment · 8 complexity · 220092d5135d324182fbaa3c7e334f3a MD5 · raw file

  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2009 Google Inc.
  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. from types import ListType, DictionaryType
  17. """Contains a client to communicate with the Contacts servers.
  18. For documentation on the Contacts API, see:
  19. http://code.google.com/apis/contatcs/
  20. """
  21. __author__ = 'vinces1979@gmail.com (Vince Spicer)'
  22. import gdata.client
  23. import gdata.contacts.data
  24. import atom.data
  25. import atom.http_core
  26. import gdata.gauth
  27. class ContactsClient(gdata.client.GDClient):
  28. api_version = '3'
  29. auth_service = 'cp'
  30. server = "www.google.com"
  31. contact_list = "default"
  32. auth_scopes = gdata.gauth.AUTH_SCOPES['cp']
  33. def get_feed_uri(self, kind='contacts', contact_list=None, projection='full',
  34. scheme="http"):
  35. """Builds a feed URI.
  36. Args:
  37. kind: The type of feed to return, typically 'groups' or 'contacts'.
  38. Default value: 'contacts'.
  39. contact_list: The contact list to return a feed for.
  40. Default value: self.contact_list.
  41. projection: The projection to apply to the feed contents, for example
  42. 'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.
  43. scheme: The URL scheme such as 'http' or 'https', None to return a
  44. relative URI without hostname.
  45. Returns:
  46. A feed URI using the given kind, contact list, and projection.
  47. Example: '/m8/feeds/contacts/default/full'.
  48. """
  49. contact_list = contact_list or self.contact_list
  50. if kind == 'profiles':
  51. contact_list = 'domain/%s' % contact_list
  52. prefix = scheme and '%s://%s' % (scheme, self.server) or ''
  53. return '%s/m8/feeds/%s/%s/%s' % (prefix, kind, contact_list, projection)
  54. GetFeedUri = get_feed_uri
  55. def get_contact(self, uri, desired_class=gdata.contacts.data.ContactEntry,
  56. auth_token=None, **kwargs):
  57. return self.get_feed(uri, auth_token=auth_token,
  58. desired_class=desired_class, **kwargs)
  59. GetContact = get_contact
  60. def create_contact(self, new_contact, insert_uri=None, auth_token=None, **kwargs):
  61. """Adds an new contact to Google Contacts.
  62. Args:
  63. new_contact: atom.Entry or subclass A new contact which is to be added to
  64. Google Contacts.
  65. insert_uri: the URL to post new contacts to the feed
  66. url_params: dict (optional) Additional URL parameters to be included
  67. in the insertion request.
  68. escape_params: boolean (optional) If true, the url_parameters will be
  69. escaped before they are included in the request.
  70. Returns:
  71. On successful insert, an entry containing the contact created
  72. On failure, a RequestError is raised of the form:
  73. {'status': HTTP status code from server,
  74. 'reason': HTTP reason from the server,
  75. 'body': HTTP body of the server's response}
  76. """
  77. insert_uri = insert_uri or self.GetFeedUri()
  78. return self.Post(new_contact, insert_uri,
  79. auth_token=auth_token, **kwargs)
  80. CreateContact = create_contact
  81. def add_contact(self, new_contact, insert_uri=None, auth_token=None,
  82. billing_information=None, birthday=None, calendar_link=None, **kwargs):
  83. """Adds an new contact to Google Contacts.
  84. Args:
  85. new_contact: atom.Entry or subclass A new contact which is to be added to
  86. Google Contacts.
  87. insert_uri: the URL to post new contacts to the feed
  88. url_params: dict (optional) Additional URL parameters to be included
  89. in the insertion request.
  90. escape_params: boolean (optional) If true, the url_parameters will be
  91. escaped before they are included in the request.
  92. Returns:
  93. On successful insert, an entry containing the contact created
  94. On failure, a RequestError is raised of the form:
  95. {'status': HTTP status code from server,
  96. 'reason': HTTP reason from the server,
  97. 'body': HTTP body of the server's response}
  98. """
  99. contact = gdata.contacts.data.ContactEntry()
  100. if billing_information is not None:
  101. if not isinstance(billing_information, gdata.contacts.data.BillingInformation):
  102. billing_information = gdata.contacts.data.BillingInformation(text=billing_information)
  103. contact.billing_information = billing_information
  104. if birthday is not None:
  105. if not isinstance(birthday, gdata.contacts.data.Birthday):
  106. birthday = gdata.contacts.data.Birthday(when=birthday)
  107. contact.birthday = birthday
  108. if calendar_link is not None:
  109. if type(calendar_link) is not ListType:
  110. calendar_link = [calendar_link]
  111. for link in calendar_link:
  112. if not isinstance(link, gdata.contacts.data.CalendarLink):
  113. if type(link) is not DictionaryType:
  114. raise TypeError, "calendar_link Requires dictionary not %s" % type(link)
  115. link = gdata.contacts.data.CalendarLink(
  116. rel=link.get("rel", None),
  117. label=link.get("label", None),
  118. primary=link.get("primary", None),
  119. href=link.get("href", None),
  120. )
  121. contact.calendar_link.append(link)
  122. insert_uri = insert_uri or self.GetFeedUri()
  123. return self.Post(contact, insert_uri,
  124. auth_token=auth_token, **kwargs)
  125. AddContact = add_contact
  126. def get_contacts(self, desired_class=gdata.contacts.data.ContactsFeed,
  127. auth_token=None, **kwargs):
  128. """Obtains a feed with the contacts belonging to the current user.
  129. Args:
  130. auth_token: An object which sets the Authorization HTTP header in its
  131. modify_request method. Recommended classes include
  132. gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
  133. among others. Represents the current user. Defaults to None
  134. and if None, this method will look for a value in the
  135. auth_token member of SpreadsheetsClient.
  136. desired_class: class descended from atom.core.XmlElement to which a
  137. successful response should be converted. If there is no
  138. converter function specified (desired_class=None) then the
  139. desired_class will be used in calling the
  140. atom.core.parse function. If neither
  141. the desired_class nor the converter is specified, an
  142. HTTP reponse object will be returned. Defaults to
  143. gdata.spreadsheets.data.SpreadsheetsFeed.
  144. """
  145. return self.get_feed(self.GetFeedUri(), auth_token=auth_token,
  146. desired_class=desired_class, **kwargs)
  147. GetContacts = get_contacts
  148. def get_group(self, uri=None, desired_class=gdata.contacts.data.GroupEntry,
  149. auth_token=None, **kwargs):
  150. """ Get a single groups details
  151. Args:
  152. uri: the group uri or id
  153. """
  154. return self.get(uri, desired_class=desired_class, auth_token=auth_token, **kwargs)
  155. GetGroup = get_group
  156. def get_groups(self, uri=None, desired_class=gdata.contacts.data.GroupsFeed,
  157. auth_token=None, **kwargs):
  158. uri = uri or self.GetFeedUri('groups')
  159. return self.get_feed(uri, desired_class=desired_class, auth_token=auth_token, **kwargs)
  160. GetGroups = get_groups
  161. def create_group(self, new_group, insert_uri=None, url_params=None,
  162. desired_class=None):
  163. insert_uri = insert_uri or self.GetFeedUri('groups')
  164. return self.Post(new_group, insert_uri, url_params=url_params,
  165. desired_class=desired_class)
  166. CreateGroup = create_group
  167. def update_group(self, edit_uri, updated_group, url_params=None,
  168. escape_params=True, desired_class=None):
  169. return self.Put(updated_group, self._CleanUri(edit_uri),
  170. url_params=url_params,
  171. escape_params=escape_params,
  172. desired_class=desired_class)
  173. UpdateGroup = update_group
  174. def delete_group(self, edit_uri, extra_headers=None,
  175. url_params=None, escape_params=True):
  176. return self.Delete(self._CleanUri(edit_uri),
  177. url_params=url_params, escape_params=escape_params)
  178. DeleteGroup = delete_group
  179. def change_photo(self, media, contact_entry_or_url, content_type=None,
  180. content_length=None):
  181. """Change the photo for the contact by uploading a new photo.
  182. Performs a PUT against the photo edit URL to send the binary data for the
  183. photo.
  184. Args:
  185. media: filename, file-like-object, or a gdata.MediaSource object to send.
  186. contact_entry_or_url: ContactEntry or str If it is a ContactEntry, this
  187. method will search for an edit photo link URL and
  188. perform a PUT to the URL.
  189. content_type: str (optional) the mime type for the photo data. This is
  190. necessary if media is a file or file name, but if media
  191. is a MediaSource object then the media object can contain
  192. the mime type. If media_type is set, it will override the
  193. mime type in the media object.
  194. content_length: int or str (optional) Specifying the content length is
  195. only required if media is a file-like object. If media
  196. is a filename, the length is determined using
  197. os.path.getsize. If media is a MediaSource object, it is
  198. assumed that it already contains the content length.
  199. """
  200. if isinstance(contact_entry_or_url, gdata.contacts.data.ContactEntry):
  201. url = contact_entry_or_url.GetPhotoEditLink().href
  202. else:
  203. url = contact_entry_or_url
  204. if isinstance(media, gdata.MediaSource):
  205. payload = media
  206. # If the media object is a file-like object, then use it as the file
  207. # handle in the in the MediaSource.
  208. elif hasattr(media, 'read'):
  209. payload = gdata.MediaSource(file_handle=media,
  210. content_type=content_type, content_length=content_length)
  211. # Assume that the media object is a file name.
  212. else:
  213. payload = gdata.MediaSource(content_type=content_type,
  214. content_length=content_length, file_path=media)
  215. return self.Put(payload, url)
  216. ChangePhoto = change_photo
  217. def get_photo(self, contact_entry_or_url):
  218. """Retrives the binary data for the contact's profile photo as a string.
  219. Args:
  220. contact_entry_or_url: a gdata.contacts.ContactEntry objecr or a string
  221. containing the photo link's URL. If the contact entry does not
  222. contain a photo link, the image will not be fetched and this method
  223. will return None.
  224. """
  225. # TODO: add the ability to write out the binary image data to a file,
  226. # reading and writing a chunk at a time to avoid potentially using up
  227. # large amounts of memory.
  228. url = None
  229. if isinstance(contact_entry_or_url, gdata.contacts.data.ContactEntry):
  230. photo_link = contact_entry_or_url.GetPhotoLink()
  231. if photo_link:
  232. url = photo_link.href
  233. else:
  234. url = contact_entry_or_url
  235. if url:
  236. return self.Get(url, desired_class=str)
  237. else:
  238. return None
  239. GetPhoto = get_photo
  240. def delete_photo(self, contact_entry_or_url):
  241. url = None
  242. if isinstance(contact_entry_or_url, gdata.contacts.data.ContactEntry):
  243. url = contact_entry_or_url.GetPhotoEditLink().href
  244. else:
  245. url = contact_entry_or_url
  246. if url:
  247. self.Delete(url)
  248. DeletePhoto = delete_photo
  249. def get_profiles_feed(self, uri=None):
  250. """Retrieves a feed containing all domain's profiles.
  251. Args:
  252. uri: string (optional) the URL to retrieve the profiles feed,
  253. for example /m8/feeds/profiles/default/full
  254. Returns:
  255. On success, a ProfilesFeed containing the profiles.
  256. On failure, raises a RequestError.
  257. """
  258. uri = uri or self.GetFeedUri('profiles')
  259. return self.Get(uri,
  260. desired_class=gdata.contacts.data.ProfilesFeedFromString)
  261. GetProfilesFeed = get_profiles_feed
  262. def get_profile(self, uri):
  263. """Retrieves a domain's profile for the user.
  264. Args:
  265. uri: string the URL to retrieve the profiles feed,
  266. for example /m8/feeds/profiles/default/full/username
  267. Returns:
  268. On success, a ProfileEntry containing the profile for the user.
  269. On failure, raises a RequestError
  270. """
  271. return self.Get(uri,
  272. desired_class=gdata.contacts.data.ProfileEntryFromString)
  273. GetProfile = get_profile
  274. def update_profile(self, edit_uri, updated_profile, auth_token=None, **kwargs):
  275. """Updates an existing profile.
  276. Args:
  277. edit_uri: string The edit link URI for the element being updated
  278. updated_profile: string atom.Entry or subclass containing
  279. the Atom Entry which will replace the profile which is
  280. stored at the edit_url.
  281. url_params: dict (optional) Additional URL parameters to be included
  282. in the update request.
  283. escape_params: boolean (optional) If true, the url_params will be
  284. escaped before they are included in the request.
  285. Returns:
  286. On successful update, a httplib.HTTPResponse containing the server's
  287. response to the PUT request.
  288. On failure, raises a RequestError.
  289. """
  290. return self.Put(updated_profile, self._CleanUri(edit_uri),
  291. desired_class=gdata.contacts.data.ProfileEntryFromString)
  292. UpdateProfile = update_profile
  293. def execute_batch(self, batch_feed, url, desired_class=None):
  294. """Sends a batch request feed to the server.
  295. Args:
  296. batch_feed: gdata.contacts.ContactFeed A feed containing batch
  297. request entries. Each entry contains the operation to be performed
  298. on the data contained in the entry. For example an entry with an
  299. operation type of insert will be used as if the individual entry
  300. had been inserted.
  301. url: str The batch URL to which these operations should be applied.
  302. converter: Function (optional) The function used to convert the server's
  303. response to an object.
  304. Returns:
  305. The results of the batch request's execution on the server. If the
  306. default converter is used, this is stored in a ContactsFeed.
  307. """
  308. return self.Post(batch_feed, url, desired_class=desired_class)
  309. ExecuteBatch = execute_batch
  310. def execute_batch_profiles(self, batch_feed, url,
  311. desired_class=gdata.contacts.data.ProfilesFeedFromString):
  312. """Sends a batch request feed to the server.
  313. Args:
  314. batch_feed: gdata.profiles.ProfilesFeed A feed containing batch
  315. request entries. Each entry contains the operation to be performed
  316. on the data contained in the entry. For example an entry with an
  317. operation type of insert will be used as if the individual entry
  318. had been inserted.
  319. url: string The batch URL to which these operations should be applied.
  320. converter: Function (optional) The function used to convert the server's
  321. response to an object. The default value is
  322. gdata.profiles.ProfilesFeedFromString.
  323. Returns:
  324. The results of the batch request's execution on the server. If the
  325. default converter is used, this is stored in a ProfilesFeed.
  326. """
  327. return self.Post(batch_feed, url, desired_class=desired_class)
  328. ExecuteBatchProfiles = execute_batch_profiles
  329. class ContactsQuery(gdata.client.Query):
  330. """
  331. Create a custom Contacts Query
  332. Full specs can be found at: U{Contacts query parameters reference
  333. <http://code.google.com/apis/contacts/docs/3.0/reference.html#Parameters>}
  334. """
  335. def __init__(self, feed=None, group=None, orderby=None, showdeleted=None,
  336. sortorder=None, requirealldeleted=None, **kwargs):
  337. """
  338. @param max_results: The maximum number of entries to return. If you want
  339. to receive all of the contacts, rather than only the default maximum, you
  340. can specify a very large number for max-results.
  341. @param start-index: The 1-based index of the first result to be retrieved.
  342. @param updated-min: The lower bound on entry update dates.
  343. @param group: Constrains the results to only the contacts belonging to the
  344. group specified. Value of this parameter specifies group ID
  345. @param orderby: Sorting criterion. The only supported value is
  346. lastmodified.
  347. @param showdeleted: Include deleted contacts in the returned contacts feed
  348. @pram sortorder: Sorting order direction. Can be either ascending or
  349. descending.
  350. @param requirealldeleted: Only relevant if showdeleted and updated-min
  351. are also provided. It dictates the behavior of the server in case it
  352. detects that placeholders of some entries deleted since the point in
  353. time specified as updated-min may have been lost.
  354. """
  355. gdata.client.Query.__init__(self, **kwargs)
  356. self.group = group
  357. self.orderby = orderby
  358. self.sortorder = sortorder
  359. self.showdeleted = showdeleted
  360. def modify_request(self, http_request):
  361. if self.group:
  362. gdata.client._add_query_param('group', self.group, http_request)
  363. if self.orderby:
  364. gdata.client._add_query_param('orderby', self.orderby, http_request)
  365. if self.sortorder:
  366. gdata.client._add_query_param('sortorder', self.sortorder, http_request)
  367. if self.showdeleted:
  368. gdata.client._add_query_param('showdeleted', self.showdeleted, http_request)
  369. gdata.client.Query.modify_request(self, http_request)
  370. ModifyRequest = modify_request
  371. class ProfilesQuery(gdata.client.Query):
  372. def __init__(self, feed=None):
  373. self.feed = feed or 'http://www.google.com/m8/feeds/profiles/default/full'
  374. def _CleanUri(self, uri):
  375. """Sanitizes a feed URI.
  376. Args:
  377. uri: The URI to sanitize, can be relative or absolute.
  378. Returns:
  379. The given URI without its http://server prefix, if any.
  380. Keeps the leading slash of the URI.
  381. """
  382. url_prefix = 'http://%s' % self.server
  383. if uri.startswith(url_prefix):
  384. uri = uri[len(url_prefix):]
  385. return uri