PageRenderTime 43ms CodeModel.GetById 2ms app.highlight 34ms RepoModel.GetById 2ms app.codeStats 0ms

/gdata/health/service.py

http://radioappz.googlecode.com/
Python | 263 lines | 195 code | 10 blank | 58 comment | 1 complexity | 3180466087854fe3126dc609b0808c38 MD5 | raw file
  1#!/usr/bin/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
 17"""HealthService extends GDataService to streamline Google Health API access.
 18
 19  HealthService: Provides methods to interact with the profile, profile list,
 20                 and register/notices feeds. Extends GDataService.
 21
 22  HealthProfileQuery: Queries the Google Health Profile feed.
 23
 24  HealthProfileListQuery: Queries the Google Health Profile list feed.
 25"""
 26
 27__author__ = 'api.eric@google.com (Eric Bidelman)'
 28
 29
 30import atom
 31import gdata.health
 32import gdata.service
 33
 34
 35class HealthService(gdata.service.GDataService):
 36
 37  """Client extension for the Google Health service Document List feed."""
 38
 39  def __init__(self, email=None, password=None, source=None,
 40               use_h9_sandbox=False, server='www.google.com',
 41               additional_headers=None, **kwargs):
 42    """Creates a client for the Google Health service.
 43
 44    Args:
 45      email: string (optional) The user's email address, used for
 46          authentication.
 47      password: string (optional) The user's password.
 48      source: string (optional) The name of the user's application.
 49      use_h9_sandbox: boolean (optional) True to issue requests against the
 50          /h9 developer's sandbox.
 51      server: string (optional) The name of the server to which a connection
 52          will be opened.
 53      additional_headers: dictionary (optional) Any additional headers which
 54          should be included with CRUD operations.
 55      kwargs: The other parameters to pass to gdata.service.GDataService
 56          constructor.
 57    """
 58    service = use_h9_sandbox and 'weaver' or 'health'
 59    gdata.service.GDataService.__init__(
 60        self, email=email, password=password, service=service, source=source,
 61        server=server, additional_headers=additional_headers, **kwargs)
 62    self.ssl = True
 63    self.use_h9_sandbox = use_h9_sandbox
 64
 65  def __get_service(self):
 66    return self.use_h9_sandbox and 'h9' or 'health'
 67
 68  def GetProfileFeed(self, query=None, profile_id=None):
 69    """Fetches the users Google Health profile feed.
 70
 71    Args:
 72      query: HealthProfileQuery or string (optional) A query to use on the
 73          profile feed.  If None, a HealthProfileQuery is constructed.
 74      profile_id: string (optional) The profile id to query the profile feed
 75          with when using ClientLogin.  Note: this parameter is ignored if
 76          query is set.
 77
 78    Returns:
 79      A gdata.health.ProfileFeed object containing the user's Health profile.
 80    """
 81    if query is None:
 82      projection = profile_id and 'ui' or 'default'
 83      uri = HealthProfileQuery(
 84          service=self.__get_service(), projection=projection,
 85          profile_id=profile_id).ToUri()
 86    elif isinstance(query, HealthProfileQuery):
 87      uri = query.ToUri()
 88    else:
 89      uri = query
 90
 91    return self.GetFeed(uri, converter=gdata.health.ProfileFeedFromString)
 92
 93  def GetProfileListFeed(self, query=None):
 94    """Fetches the users Google Health profile feed.
 95
 96    Args:
 97      query: HealthProfileListQuery or string (optional) A query to use
 98          on the profile list feed.  If None, a HealthProfileListQuery is
 99          constructed to /health/feeds/profile/list or /h9/feeds/profile/list.
100
101    Returns:
102      A gdata.health.ProfileListFeed object containing the user's list
103      of profiles.
104    """
105    if not query:
106      uri = HealthProfileListQuery(service=self.__get_service()).ToUri()
107    elif isinstance(query, HealthProfileListQuery):
108      uri = query.ToUri()
109    else:
110      uri = query
111
112    return self.GetFeed(uri, converter=gdata.health.ProfileListFeedFromString)
113
114  def SendNotice(self, subject, body=None, content_type='html',
115                 ccr=None, profile_id=None):
116    """Sends (posts) a notice to the user's Google Health profile.
117
118    Args:
119      subject: A string representing the message's subject line.
120      body: string (optional) The message body.
121      content_type: string (optional) The content type of the notice message
122          body.  This parameter is only honored when a message body is
123          specified.
124      ccr: string (optional) The CCR XML document to reconcile into the
125          user's profile.
126      profile_id: string (optional) The profile id to work with when using
127          ClientLogin.  Note: this parameter is ignored if query is set.
128
129    Returns:
130      A gdata.health.ProfileEntry object of the posted entry.
131    """
132    if body:
133      content = atom.Content(content_type=content_type, text=body)
134    else:
135      content = body
136
137    entry = gdata.GDataEntry(
138        title=atom.Title(text=subject), content=content,
139        extension_elements=[atom.ExtensionElementFromString(ccr)])
140
141    projection = profile_id and 'ui' or 'default'
142    query = HealthRegisterQuery(service=self.__get_service(),
143                                projection=projection, profile_id=profile_id)
144    return self.Post(entry, query.ToUri(),
145                     converter=gdata.health.ProfileEntryFromString)
146
147
148class HealthProfileQuery(gdata.service.Query):
149
150  """Object used to construct a URI to query the Google Health profile feed."""
151
152  def __init__(self, service='health', feed='feeds/profile',
153               projection='default', profile_id=None, text_query=None,
154               params=None, categories=None):
155    """Constructor for Health profile feed query.
156
157    Args:
158      service: string (optional) The service to query. Either 'health' or 'h9'.
159      feed: string (optional) The path for the feed. The default value is
160          'feeds/profile'.
161      projection: string (optional) The visibility of the data. Possible values
162          are 'default' for AuthSub and 'ui' for ClientLogin.  If this value
163          is set to 'ui', the profile_id parameter should also be set.
164      profile_id: string (optional) The profile id to query.  This should only
165          be used when using ClientLogin.
166      text_query: str (optional) The contents of the q query parameter. The
167          contents of the text_query are URL escaped upon conversion to a URI.
168          Note: this parameter can only be used on the register feed using
169          ClientLogin.
170      params: dict (optional) Parameter value string pairs which become URL
171          params when translated to a URI. These parameters are added to
172          the query's items.
173      categories: list (optional) List of category strings which should be
174          included as query categories. See gdata.service.Query for
175          additional documentation.
176    """
177    self.service = service
178    self.profile_id = profile_id
179    self.projection = projection
180    gdata.service.Query.__init__(self, feed=feed, text_query=text_query,
181                                 params=params, categories=categories)
182
183  def ToUri(self):
184    """Generates a URI from the query parameters set in the object.
185
186    Returns:
187      A string containing the URI used to retrieve entries from the Health
188      profile feed.
189    """
190    old_feed = self.feed
191    self.feed = '/'.join([self.service, old_feed, self.projection])
192
193    if self.profile_id:
194      self.feed += '/' + self.profile_id
195    self.feed = '/%s' % (self.feed,)
196
197    new_feed = gdata.service.Query.ToUri(self)
198    self.feed = old_feed
199    return new_feed
200
201
202class HealthProfileListQuery(gdata.service.Query):
203
204  """Object used to construct a URI to query a Health profile list feed."""
205
206  def __init__(self, service='health', feed='feeds/profile/list'):
207    """Constructor for Health profile list feed query.
208
209    Args:
210      service: string (optional) The service to query. Either 'health' or 'h9'.
211      feed: string (optional) The path for the feed.  The default value is
212          'feeds/profile/list'.
213    """
214    gdata.service.Query.__init__(self, feed)
215    self.service = service
216
217  def ToUri(self):
218    """Generates a URI from the query parameters set in the object.
219
220    Returns:
221      A string containing the URI used to retrieve entries from the
222      profile list feed.
223    """
224    return '/%s' % ('/'.join([self.service, self.feed]),)
225
226
227class HealthRegisterQuery(gdata.service.Query):
228
229  """Object used to construct a URI to query a Health register/notice feed."""
230
231  def __init__(self, service='health', feed='feeds/register',
232               projection='default', profile_id=None):
233    """Constructor for Health profile list feed query.
234
235    Args:
236      service: string (optional) The service to query. Either 'health' or 'h9'.
237      feed: string (optional) The path for the feed.  The default value is
238          'feeds/register'.
239      projection: string (optional) The visibility of the data. Possible values
240          are 'default' for AuthSub and 'ui' for ClientLogin.  If this value
241          is set to 'ui', the profile_id parameter should also be set.
242      profile_id: string (optional) The profile id to query.  This should only
243          be used when using ClientLogin.
244    """
245    gdata.service.Query.__init__(self, feed)
246    self.service = service
247    self.projection = projection
248    self.profile_id = profile_id
249
250  def ToUri(self):
251    """Generates a URI from the query parameters set in the object.
252
253    Returns:
254      A string containing the URI needed to interact with the register feed.
255    """
256    old_feed = self.feed
257    self.feed = '/'.join([self.service, old_feed, self.projection])
258    new_feed = gdata.service.Query.ToUri(self)
259    self.feed = old_feed
260
261    if self.profile_id:
262      new_feed += '/' + self.profile_id
263    return '/%s' % (new_feed,)