home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / share / pyshared / gdata / service.py < prev    next >
Encoding:
Python Source  |  2010-04-02  |  67.7 KB  |  1,712 lines

  1. #
  2. # Copyright (C) 2006,2008 Google Inc.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. #      http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15.  
  16.  
  17. """GDataService provides CRUD ops. and programmatic login for GData services.
  18.  
  19.   Error: A base exception class for all exceptions in the gdata_client
  20.          module.
  21.  
  22.   CaptchaRequired: This exception is thrown when a login attempt results in a
  23.                    captcha challenge from the ClientLogin service. When this
  24.                    exception is thrown, the captcha_token and captcha_url are
  25.                    set to the values provided in the server's response.
  26.  
  27.   BadAuthentication: Raised when a login attempt is made with an incorrect
  28.                      username or password.
  29.  
  30.   NotAuthenticated: Raised if an operation requiring authentication is called
  31.                     before a user has authenticated.
  32.  
  33.   NonAuthSubToken: Raised if a method to modify an AuthSub token is used when
  34.                    the user is either not authenticated or is authenticated
  35.                    through another authentication mechanism.
  36.  
  37.   NonOAuthToken: Raised if a method to modify an OAuth token is used when the
  38.                  user is either not authenticated or is authenticated through
  39.                  another authentication mechanism.
  40.  
  41.   RequestError: Raised if a CRUD request returned a non-success code.
  42.  
  43.   UnexpectedReturnType: Raised if the response from the server was not of the
  44.                         desired type. For example, this would be raised if the
  45.                         server sent a feed when the client requested an entry.
  46.  
  47.   GDataService: Encapsulates user credentials needed to perform insert, update
  48.                 and delete operations with the GData API. An instance can
  49.                 perform user authentication, query, insertion, deletion, and 
  50.                 update.
  51.  
  52.   Query: Eases query URI creation by allowing URI parameters to be set as 
  53.          dictionary attributes. For example a query with a feed of 
  54.          '/base/feeds/snippets' and ['bq'] set to 'digital camera' will 
  55.          produce '/base/feeds/snippets?bq=digital+camera' when .ToUri() is 
  56.          called on it.
  57. """
  58.  
  59.  
  60. __author__ = 'api.jscudder (Jeffrey Scudder)'
  61.  
  62. import re
  63. import urllib
  64. import urlparse
  65. try:
  66.   from xml.etree import cElementTree as ElementTree
  67. except ImportError:
  68.   try:
  69.     import cElementTree as ElementTree
  70.   except ImportError:
  71.     try:
  72.       from xml.etree import ElementTree
  73.     except ImportError:
  74.       from elementtree import ElementTree
  75. import atom.service
  76. import gdata
  77. import atom
  78. import atom.http_interface
  79. import atom.token_store
  80. import gdata.auth
  81. import gdata.gauth
  82.  
  83.  
  84. AUTH_SERVER_HOST = 'https://www.google.com'
  85.  
  86.  
  87. # When requesting an AuthSub token, it is often helpful to track the scope
  88. # which is being requested. One way to accomplish this is to add a URL 
  89. # parameter to the 'next' URL which contains the requested scope. This
  90. # constant is the default name (AKA key) for the URL parameter.
  91. SCOPE_URL_PARAM_NAME = 'authsub_token_scope'
  92. # When requesting an OAuth access token or authorization of an existing OAuth
  93. # request token, it is often helpful to track the scope(s) which is/are being
  94. # requested. One way to accomplish this is to add a URL parameter to the
  95. # 'callback' URL which contains the requested scope. This constant is the
  96. # default name (AKA key) for the URL parameter.
  97. OAUTH_SCOPE_URL_PARAM_NAME = 'oauth_token_scope'
  98. # Maps the service names used in ClientLogin to scope URLs.
  99. CLIENT_LOGIN_SCOPES = gdata.gauth.AUTH_SCOPES
  100. # Default parameters for GDataService.GetWithRetries method
  101. DEFAULT_NUM_RETRIES = 3
  102. DEFAULT_DELAY = 1
  103. DEFAULT_BACKOFF = 2
  104.  
  105.  
  106. def lookup_scopes(service_name):
  107.   """Finds the scope URLs for the desired service.
  108.  
  109.   In some cases, an unknown service may be used, and in those cases this
  110.   function will return None.
  111.   """
  112.   if service_name in CLIENT_LOGIN_SCOPES:
  113.     return CLIENT_LOGIN_SCOPES[service_name]
  114.   return None
  115.  
  116.  
  117. # Module level variable specifies which module should be used by GDataService
  118. # objects to make HttpRequests. This setting can be overridden on each 
  119. # instance of GDataService.
  120. # This module level variable is deprecated. Reassign the http_client member
  121. # of a GDataService object instead.
  122. http_request_handler = atom.service
  123.  
  124.  
  125. class Error(Exception):
  126.   pass
  127.  
  128.  
  129. class CaptchaRequired(Error):
  130.   pass
  131.  
  132.  
  133. class BadAuthentication(Error):
  134.   pass
  135.  
  136.  
  137. class NotAuthenticated(Error):
  138.   pass
  139.  
  140.  
  141. class NonAuthSubToken(Error):
  142.   pass
  143.  
  144.  
  145. class NonOAuthToken(Error):
  146.   pass
  147.  
  148.  
  149. class RequestError(Error):
  150.   pass
  151.  
  152.  
  153. class UnexpectedReturnType(Error):
  154.   pass
  155.  
  156.  
  157. class BadAuthenticationServiceURL(Error):
  158.   pass
  159.  
  160.  
  161. class FetchingOAuthRequestTokenFailed(RequestError):
  162.   pass
  163.  
  164.  
  165. class TokenUpgradeFailed(RequestError):
  166.   pass
  167.  
  168.  
  169. class RevokingOAuthTokenFailed(RequestError):
  170.   pass
  171.  
  172.  
  173. class AuthorizationRequired(Error):
  174.   pass
  175.  
  176.  
  177. class TokenHadNoScope(Error):
  178.   pass
  179.  
  180.  
  181. class RanOutOfTries(Error):
  182.   pass
  183.  
  184.  
  185. class GDataService(atom.service.AtomService):
  186.   """Contains elements needed for GData login and CRUD request headers.
  187.  
  188.   Maintains additional headers (tokens for example) needed for the GData 
  189.   services to allow a user to perform inserts, updates, and deletes.
  190.   """
  191.   # The hander member is deprecated, use http_client instead.
  192.   handler = None
  193.   # The auth_token member is deprecated, use the token_store instead.
  194.   auth_token = None
  195.   # The tokens dict is deprecated in favor of the token_store.
  196.   tokens = None
  197.  
  198.   def __init__(self, email=None, password=None, account_type='HOSTED_OR_GOOGLE',
  199.                service=None, auth_service_url=None, source=None, server=None, 
  200.                additional_headers=None, handler=None, tokens=None,
  201.                http_client=None, token_store=None):
  202.     """Creates an object of type GDataService.
  203.  
  204.     Args:
  205.       email: string (optional) The user's email address, used for
  206.           authentication.
  207.       password: string (optional) The user's password.
  208.       account_type: string (optional) The type of account to use. Use
  209.           'GOOGLE' for regular Google accounts or 'HOSTED' for Google
  210.           Apps accounts, or 'HOSTED_OR_GOOGLE' to try finding a HOSTED
  211.           account first and, if it doesn't exist, try finding a regular
  212.           GOOGLE account. Default value: 'HOSTED_OR_GOOGLE'.
  213.       service: string (optional) The desired service for which credentials
  214.           will be obtained.
  215.       auth_service_url: string (optional) User-defined auth token request URL
  216.           allows users to explicitly specify where to send auth token requests.
  217.       source: string (optional) The name of the user's application.
  218.       server: string (optional) The name of the server to which a connection
  219.           will be opened. Default value: 'base.google.com'.
  220.       additional_headers: dictionary (optional) Any additional headers which 
  221.           should be included with CRUD operations.
  222.       handler: module (optional) This parameter is deprecated and has been
  223.           replaced by http_client.
  224.       tokens: This parameter is deprecated, calls should be made to 
  225.           token_store instead.
  226.       http_client: An object responsible for making HTTP requests using a
  227.           request method. If none is provided, a new instance of
  228.           atom.http.ProxiedHttpClient will be used.
  229.       token_store: Keeps a collection of authorization tokens which can be
  230.           applied to requests for a specific URLs. Critical methods are
  231.           find_token based on a URL (atom.url.Url or a string), add_token,
  232.           and remove_token.
  233.     """
  234.     atom.service.AtomService.__init__(self, http_client=http_client, 
  235.         token_store=token_store)
  236.     self.email = email
  237.     self.password = password
  238.     self.account_type = account_type
  239.     self.service = service
  240.     self.auth_service_url = auth_service_url
  241.     self.server = server
  242.     self.additional_headers = additional_headers or {}
  243.     self._oauth_input_params = None
  244.     self.__SetSource(source)
  245.     self.__captcha_token = None
  246.     self.__captcha_url = None
  247.     self.__gsessionid = None
  248.  
  249.     if http_request_handler.__name__ == 'gdata.urlfetch':
  250.       import gdata.alt.appengine
  251.       self.http_client = gdata.alt.appengine.AppEngineHttpClient()
  252.  
  253.   def _SetSessionId(self, session_id):
  254.     """Used in unit tests to simulate a 302 which sets a gsessionid."""
  255.     self.__gsessionid = session_id
  256.  
  257.   # Define properties for GDataService
  258.   def _SetAuthSubToken(self, auth_token, scopes=None):
  259.     """Deprecated, use SetAuthSubToken instead."""
  260.     self.SetAuthSubToken(auth_token, scopes=scopes)
  261.  
  262.   def __SetAuthSubToken(self, auth_token, scopes=None):
  263.     """Deprecated, use SetAuthSubToken instead."""
  264.     self._SetAuthSubToken(auth_token, scopes=scopes)
  265.  
  266.   def _GetAuthToken(self):
  267.     """Returns the auth token used for authenticating requests.
  268.  
  269.     Returns:
  270.       string
  271.     """
  272.     current_scopes = lookup_scopes(self.service)
  273.     if current_scopes:
  274.       token = self.token_store.find_token(current_scopes[0])
  275.       if hasattr(token, 'auth_header'):
  276.         return token.auth_header
  277.     return None
  278.  
  279.   def _GetCaptchaToken(self):
  280.     """Returns a captcha token if the most recent login attempt generated one.
  281.  
  282.     The captcha token is only set if the Programmatic Login attempt failed 
  283.     because the Google service issued a captcha challenge.
  284.  
  285.     Returns:
  286.       string
  287.     """
  288.     return self.__captcha_token
  289.  
  290.   def __GetCaptchaToken(self):
  291.     return self._GetCaptchaToken()
  292.  
  293.   captcha_token = property(__GetCaptchaToken,
  294.       doc="""Get the captcha token for a login request.""")
  295.  
  296.   def _GetCaptchaURL(self):
  297.     """Returns the URL of the captcha image if a login attempt generated one.
  298.  
  299.     The captcha URL is only set if the Programmatic Login attempt failed
  300.     because the Google service issued a captcha challenge.
  301.  
  302.     Returns:
  303.       string
  304.     """
  305.     return self.__captcha_url
  306.  
  307.   def __GetCaptchaURL(self):
  308.     return self._GetCaptchaURL()
  309.  
  310.   captcha_url = property(__GetCaptchaURL,
  311.       doc="""Get the captcha URL for a login request.""")
  312.  
  313.   def GetGeneratorFromLinkFinder(self, link_finder, func, 
  314.                                  num_retries=DEFAULT_NUM_RETRIES,
  315.                                  delay=DEFAULT_DELAY,
  316.                                  backoff=DEFAULT_BACKOFF):
  317.     """returns a generator for pagination"""
  318.     yield link_finder
  319.     next = link_finder.GetNextLink()
  320.     while next is not None:
  321.       next_feed = func(str(self.GetWithRetries(
  322.             next.href, num_retries=num_retries, delay=delay, backoff=backoff)))
  323.       yield next_feed
  324.       next = next_feed.GetNextLink()
  325.  
  326.   def _GetElementGeneratorFromLinkFinder(self, link_finder, func,
  327.                                         num_retries=DEFAULT_NUM_RETRIES,
  328.                                         delay=DEFAULT_DELAY,
  329.                                         backoff=DEFAULT_BACKOFF):
  330.     for element in self.GetGeneratorFromLinkFinder(link_finder, func,
  331.                                                    num_retries=num_retries,
  332.                                                    delay=delay,
  333.                                                    backoff=backoff).entry:
  334.       yield element
  335.  
  336.   def GetOAuthInputParameters(self):
  337.     return self._oauth_input_params
  338.  
  339.   def SetOAuthInputParameters(self, signature_method, consumer_key,
  340.                               consumer_secret=None, rsa_key=None,
  341.                               two_legged_oauth=False, requestor_id=None):
  342.     """Sets parameters required for using OAuth authentication mechanism.
  343.  
  344.     NOTE: Though consumer_secret and rsa_key are optional, either of the two
  345.     is required depending on the value of the signature_method.
  346.  
  347.     Args:
  348.       signature_method: class which provides implementation for strategy class
  349.           oauth.oauth.OAuthSignatureMethod. Signature method to be used for
  350.           signing each request. Valid implementations are provided as the
  351.           constants defined by gdata.auth.OAuthSignatureMethod. Currently
  352.           they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and
  353.           gdata.auth.OAuthSignatureMethod.HMAC_SHA1
  354.       consumer_key: string Domain identifying third_party web application.
  355.       consumer_secret: string (optional) Secret generated during registration.
  356.           Required only for HMAC_SHA1 signature method.
  357.       rsa_key: string (optional) Private key required for RSA_SHA1 signature
  358.           method.
  359.       two_legged_oauth: boolean (optional) Enables two-legged OAuth process.
  360.       requestor_id: string (optional) User email adress to make requests on
  361.           their behalf.  This parameter should only be set when two_legged_oauth
  362.           is True.
  363.     """
  364.     self._oauth_input_params = gdata.auth.OAuthInputParams(
  365.         signature_method, consumer_key, consumer_secret=consumer_secret,
  366.         rsa_key=rsa_key, requestor_id=requestor_id)
  367.     if two_legged_oauth:
  368.       oauth_token = gdata.auth.OAuthToken(
  369.           oauth_input_params=self._oauth_input_params)
  370.       self.SetOAuthToken(oauth_token)
  371.  
  372.   def FetchOAuthRequestToken(self, scopes=None, extra_parameters=None,
  373.                              request_url='%s/accounts/OAuthGetRequestToken' % \
  374.                              AUTH_SERVER_HOST, oauth_callback=None):
  375.     """Fetches and sets the OAuth request token and returns it.
  376.  
  377.     Args:
  378.       scopes: string or list of string base URL(s) of the service(s) to be
  379.           accessed. If None, then this method tries to determine the
  380.           scope(s) from the current service.
  381.       extra_parameters: dict (optional) key-value pairs as any additional
  382.           parameters to be included in the URL and signature while making a
  383.           request for fetching an OAuth request token. All the OAuth parameters
  384.           are added by default. But if provided through this argument, any
  385.           default parameters will be overwritten. For e.g. a default parameter
  386.           oauth_version 1.0 can be overwritten if
  387.           extra_parameters = {'oauth_version': '2.0'}
  388.       request_url: Request token URL. The default is
  389.           'https://www.google.com/accounts/OAuthGetRequestToken'.
  390.       oauth_callback: str (optional) If set, it is assume the client is using
  391.           the OAuth v1.0a protocol where the callback url is sent in the
  392.           request token step.  If the oauth_callback is also set in
  393.           extra_params, this value will override that one.
  394.  
  395.     Returns:
  396.       The fetched request token as a gdata.auth.OAuthToken object.
  397.  
  398.     Raises:
  399.       FetchingOAuthRequestTokenFailed if the server responded to the request
  400.       with an error.
  401.     """
  402.     if scopes is None:
  403.       scopes = lookup_scopes(self.service)
  404.     if not isinstance(scopes, (list, tuple)):
  405.       scopes = [scopes,]
  406.     if oauth_callback:
  407.       if extra_parameters is not None:
  408.         extra_parameters['oauth_callback'] = oauth_callback
  409.       else:
  410.         extra_parameters = {'oauth_callback': oauth_callback}
  411.     request_token_url = gdata.auth.GenerateOAuthRequestTokenUrl(
  412.         self._oauth_input_params, scopes,
  413.         request_token_url=request_url,
  414.         extra_parameters=extra_parameters)
  415.     response = self.http_client.request('GET', str(request_token_url))
  416.     if response.status == 200:
  417.       token = gdata.auth.OAuthToken()
  418.       token.set_token_string(response.read())
  419.       token.scopes = scopes
  420.       token.oauth_input_params = self._oauth_input_params
  421.       self.SetOAuthToken(token)
  422.       return token
  423.     error = {
  424.         'status': response.status,
  425.         'reason': 'Non 200 response on fetch request token',
  426.         'body': response.read()
  427.         }
  428.     raise FetchingOAuthRequestTokenFailed(error)    
  429.   
  430.   def SetOAuthToken(self, oauth_token):
  431.     """Attempts to set the current token and add it to the token store.
  432.     
  433.     The oauth_token can be any OAuth token i.e. unauthorized request token,
  434.     authorized request token or access token.
  435.     This method also attempts to add the token to the token store.
  436.     Use this method any time you want the current token to point to the
  437.     oauth_token passed. For e.g. call this method with the request token
  438.     you receive from FetchOAuthRequestToken.
  439.     
  440.     Args:
  441.       request_token: gdata.auth.OAuthToken OAuth request token.
  442.     """
  443.     if self.auto_set_current_token:
  444.       self.current_token = oauth_token
  445.     if self.auto_store_tokens:
  446.       self.token_store.add_token(oauth_token)
  447.     
  448.   def GenerateOAuthAuthorizationURL(
  449.       self, request_token=None, callback_url=None, extra_params=None,
  450.       include_scopes_in_callback=False,
  451.       scopes_param_prefix=OAUTH_SCOPE_URL_PARAM_NAME,
  452.       request_url='%s/accounts/OAuthAuthorizeToken' % AUTH_SERVER_HOST):
  453.     """Generates URL at which user will login to authorize the request token.
  454.     
  455.     Args:
  456.       request_token: gdata.auth.OAuthToken (optional) OAuth request token.
  457.           If not specified, then the current token will be used if it is of
  458.           type <gdata.auth.OAuthToken>, else it is found by looking in the
  459.           token_store by looking for a token for the current scope.    
  460.       callback_url: string (optional) The URL user will be sent to after
  461.           logging in and granting access.
  462.       extra_params: dict (optional) Additional parameters to be sent.
  463.       include_scopes_in_callback: Boolean (default=False) if set to True, and
  464.           if 'callback_url' is present, the 'callback_url' will be modified to
  465.           include the scope(s) from the request token as a URL parameter. The
  466.           key for the 'callback' URL's scope parameter will be
  467.           OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as
  468.           a parameter to the 'callback' URL, is that the page which receives
  469.           the OAuth token will be able to tell which URLs the token grants
  470.           access to.
  471.       scopes_param_prefix: string (default='oauth_token_scope') The URL
  472.           parameter key which maps to the list of valid scopes for the token.
  473.           This URL parameter will be included in the callback URL along with
  474.           the scopes of the token as value if include_scopes_in_callback=True.
  475.       request_url: Authorization URL. The default is
  476.           'https://www.google.com/accounts/OAuthAuthorizeToken'.
  477.     Returns:
  478.       A string URL at which the user is required to login.
  479.     
  480.     Raises:
  481.       NonOAuthToken if the user's request token is not an OAuth token or if a
  482.       request token was not available.
  483.     """
  484.     if request_token and not isinstance(request_token, gdata.auth.OAuthToken):
  485.       raise NonOAuthToken
  486.     if not request_token:
  487.       if isinstance(self.current_token, gdata.auth.OAuthToken):
  488.         request_token = self.current_token
  489.       else:
  490.         current_scopes = lookup_scopes(self.service)
  491.         if current_scopes:
  492.           token = self.token_store.find_token(current_scopes[0])
  493.           if isinstance(token, gdata.auth.OAuthToken):
  494.             request_token = token
  495.     if not request_token:
  496.       raise NonOAuthToken
  497.     return str(gdata.auth.GenerateOAuthAuthorizationUrl(
  498.         request_token,
  499.         authorization_url=request_url,
  500.         callback_url=callback_url, extra_params=extra_params,
  501.         include_scopes_in_callback=include_scopes_in_callback,
  502.         scopes_param_prefix=scopes_param_prefix))   
  503.   
  504.   def UpgradeToOAuthAccessToken(self, authorized_request_token=None,
  505.                                 request_url='%s/accounts/OAuthGetAccessToken' \
  506.                                 % AUTH_SERVER_HOST, oauth_version='1.0',
  507.                                 oauth_verifier=None):
  508.     """Upgrades the authorized request token to an access token and returns it
  509.     
  510.     Args:
  511.       authorized_request_token: gdata.auth.OAuthToken (optional) OAuth request
  512.           token. If not specified, then the current token will be used if it is
  513.           of type <gdata.auth.OAuthToken>, else it is found by looking in the
  514.           token_store by looking for a token for the current scope.
  515.       request_url: Access token URL. The default is
  516.           'https://www.google.com/accounts/OAuthGetAccessToken'.
  517.       oauth_version: str (default='1.0') oauth_version parameter. All other
  518.           'oauth_' parameters are added by default. This parameter too, is
  519.           added by default but here you can override it's value.
  520.       oauth_verifier: str (optional) If present, it is assumed that the client
  521.         will use the OAuth v1.0a protocol which includes passing the
  522.         oauth_verifier (as returned by the SP) in the access token step.
  523.     
  524.     Returns:
  525.       Access token
  526.           
  527.     Raises:
  528.       NonOAuthToken if the user's authorized request token is not an OAuth
  529.       token or if an authorized request token was not available.
  530.       TokenUpgradeFailed if the server responded to the request with an 
  531.       error.
  532.     """
  533.     if (authorized_request_token and
  534.         not isinstance(authorized_request_token, gdata.auth.OAuthToken)):
  535.       raise NonOAuthToken
  536.     if not authorized_request_token:
  537.       if isinstance(self.current_token, gdata.auth.OAuthToken):
  538.         authorized_request_token = self.current_token
  539.       else:
  540.         current_scopes = lookup_scopes(self.service)
  541.         if current_scopes:
  542.           token = self.token_store.find_token(current_scopes[0])
  543.           if isinstance(token, gdata.auth.OAuthToken):
  544.             authorized_request_token = token
  545.     if not authorized_request_token:
  546.       raise NonOAuthToken
  547.     access_token_url = gdata.auth.GenerateOAuthAccessTokenUrl(
  548.         authorized_request_token,
  549.         self._oauth_input_params,
  550.         access_token_url=request_url,
  551.         oauth_version=oauth_version,
  552.         oauth_verifier=oauth_verifier)
  553.     response = self.http_client.request('GET', str(access_token_url))
  554.     if response.status == 200:
  555.       token = gdata.auth.OAuthTokenFromHttpBody(response.read())
  556.       token.scopes = authorized_request_token.scopes
  557.       token.oauth_input_params = authorized_request_token.oauth_input_params
  558.       self.SetOAuthToken(token)
  559.       return token
  560.     else:
  561.       raise TokenUpgradeFailed({'status': response.status,
  562.                                 'reason': 'Non 200 response on upgrade',
  563.                                 'body': response.read()})      
  564.   
  565.   def RevokeOAuthToken(self, request_url='%s/accounts/AuthSubRevokeToken' % \
  566.                        AUTH_SERVER_HOST):
  567.     """Revokes an existing OAuth token.
  568.  
  569.     request_url: Token revoke URL. The default is
  570.           'https://www.google.com/accounts/AuthSubRevokeToken'.
  571.     Raises:
  572.       NonOAuthToken if the user's auth token is not an OAuth token.
  573.       RevokingOAuthTokenFailed if request for revoking an OAuth token failed.
  574.     """
  575.     scopes = lookup_scopes(self.service)
  576.     token = self.token_store.find_token(scopes[0])
  577.     if not isinstance(token, gdata.auth.OAuthToken):
  578.       raise NonOAuthToken
  579.  
  580.     response = token.perform_request(self.http_client, 'GET', request_url,
  581.         headers={'Content-Type':'application/x-www-form-urlencoded'})
  582.     if response.status == 200:
  583.       self.token_store.remove_token(token)
  584.     else:
  585.       raise RevokingOAuthTokenFailed
  586.   
  587.   def GetAuthSubToken(self):
  588.     """Returns the AuthSub token as a string.
  589.      
  590.     If the token is an gdta.auth.AuthSubToken, the Authorization Label
  591.     ("AuthSub token") is removed.
  592.  
  593.     This method examines the current_token to see if it is an AuthSubToken
  594.     or SecureAuthSubToken. If not, it searches the token_store for a token
  595.     which matches the current scope.
  596.     
  597.     The current scope is determined by the service name string member.
  598.     
  599.     Returns:
  600.       If the current_token is set to an AuthSubToken/SecureAuthSubToken,
  601.       return the token string. If there is no current_token, a token string
  602.       for a token which matches the service object's default scope is returned.
  603.       If there are no tokens valid for the scope, returns None.
  604.     """
  605.     if isinstance(self.current_token, gdata.auth.AuthSubToken):
  606.       return self.current_token.get_token_string()
  607.     current_scopes = lookup_scopes(self.service)
  608.     if current_scopes:
  609.       token = self.token_store.find_token(current_scopes[0])
  610.       if isinstance(token, gdata.auth.AuthSubToken):
  611.         return token.get_token_string()
  612.     else:
  613.       token = self.token_store.find_token(atom.token_store.SCOPE_ALL)
  614.       if isinstance(token, gdata.auth.ClientLoginToken):
  615.         return token.get_token_string()
  616.       return None
  617.  
  618.   def SetAuthSubToken(self, token, scopes=None, rsa_key=None):
  619.     """Sets the token sent in requests to an AuthSub token.
  620.  
  621.     Sets the current_token and attempts to add the token to the token_store.
  622.     
  623.     Only use this method if you have received a token from the AuthSub
  624.     service. The auth token is set automatically when UpgradeToSessionToken()
  625.     is used. See documentation for Google AuthSub here:
  626.     http://code.google.com/apis/accounts/AuthForWebApps.html 
  627.  
  628.     Args:
  629.      token: gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken or string
  630.             The token returned by the AuthSub service. If the token is an
  631.             AuthSubToken or SecureAuthSubToken, the scope information stored in
  632.             the token is used. If the token is a string, the scopes parameter is
  633.             used to determine the valid scopes.
  634.      scopes: list of URLs for which the token is valid. This is only used
  635.              if the token parameter is a string.
  636.      rsa_key: string (optional) Private key required for RSA_SHA1 signature
  637.               method.  This parameter is necessary if the token is a string
  638.               representing a secure token.
  639.     """
  640.     if not isinstance(token, gdata.auth.AuthSubToken):
  641.       token_string = token
  642.       if rsa_key:
  643.         token = gdata.auth.SecureAuthSubToken(rsa_key)
  644.       else:
  645.         token = gdata.auth.AuthSubToken()
  646.  
  647.       token.set_token_string(token_string)
  648.         
  649.     # If no scopes were set for the token, use the scopes passed in, or
  650.     # try to determine the scopes based on the current service name. If
  651.     # all else fails, set the token to match all requests.
  652.     if not token.scopes:
  653.       if scopes is None:
  654.         scopes = lookup_scopes(self.service)
  655.         if scopes is None:
  656.           scopes = [atom.token_store.SCOPE_ALL]
  657.       token.scopes = scopes
  658.     if self.auto_set_current_token:
  659.       self.current_token = token
  660.     if self.auto_store_tokens:
  661.       self.token_store.add_token(token)
  662.  
  663.   def GetClientLoginToken(self):
  664.     """Returns the token string for the current token or a token matching the 
  665.     service scope.
  666.  
  667.     If the current_token is a ClientLoginToken, the token string for 
  668.     the current token is returned. If the current_token is not set, this method
  669.     searches for a token in the token_store which is valid for the service 
  670.     object's current scope.
  671.  
  672.     The current scope is determined by the service name string member.
  673.     The token string is the end of the Authorization header, it doesn not
  674.     include the ClientLogin label.
  675.     """
  676.     if isinstance(self.current_token, gdata.auth.ClientLoginToken):
  677.       return self.current_token.get_token_string()
  678.     current_scopes = lookup_scopes(self.service)
  679.     if current_scopes:
  680.       token = self.token_store.find_token(current_scopes[0])
  681.       if isinstance(token, gdata.auth.ClientLoginToken):
  682.         return token.get_token_string()
  683.     else:
  684.       token = self.token_store.find_token(atom.token_store.SCOPE_ALL)
  685.       if isinstance(token, gdata.auth.ClientLoginToken):
  686.         return token.get_token_string()
  687.       return None
  688.  
  689.   def SetClientLoginToken(self, token, scopes=None):
  690.     """Sets the token sent in requests to a ClientLogin token.
  691.  
  692.     This method sets the current_token to a new ClientLoginToken and it 
  693.     also attempts to add the ClientLoginToken to the token_store.
  694.     
  695.     Only use this method if you have received a token from the ClientLogin
  696.     service. The auth_token is set automatically when ProgrammaticLogin()
  697.     is used. See documentation for Google ClientLogin here:
  698.     http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html
  699.  
  700.     Args:
  701.       token: string or instance of a ClientLoginToken. 
  702.     """
  703.     if not isinstance(token, gdata.auth.ClientLoginToken):
  704.       token_string = token
  705.       token = gdata.auth.ClientLoginToken()
  706.       token.set_token_string(token_string)
  707.  
  708.     if not token.scopes:
  709.       if scopes is None:
  710.         scopes = lookup_scopes(self.service)
  711.         if scopes is None:
  712.           scopes = [atom.token_store.SCOPE_ALL]
  713.       token.scopes = scopes
  714.     if self.auto_set_current_token:
  715.       self.current_token = token
  716.     if self.auto_store_tokens:
  717.       self.token_store.add_token(token)
  718.  
  719.   # Private methods to create the source property.
  720.   def __GetSource(self):
  721.     return self.__source
  722.  
  723.   def __SetSource(self, new_source):
  724.     self.__source = new_source
  725.     # Update the UserAgent header to include the new application name.
  726.     self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % (
  727.         self.__source,)
  728.  
  729.   source = property(__GetSource, __SetSource, 
  730.       doc="""The source is the name of the application making the request. 
  731.              It should be in the form company_id-app_name-app_version""")
  732.  
  733.   # Authentication operations
  734.  
  735.   def ProgrammaticLogin(self, captcha_token=None, captcha_response=None):
  736.     """Authenticates the user and sets the GData Auth token.
  737.  
  738.     Login retreives a temporary auth token which must be used with all
  739.     requests to GData services. The auth token is stored in the GData client
  740.     object.
  741.  
  742.     Login is also used to respond to a captcha challenge. If the user's login
  743.     attempt failed with a CaptchaRequired error, the user can respond by
  744.     calling Login with the captcha token and the answer to the challenge.
  745.  
  746.     Args:
  747.       captcha_token: string (optional) The identifier for the captcha challenge
  748.                      which was presented to the user.
  749.       captcha_response: string (optional) The user's answer to the captch 
  750.                         challenge.
  751.  
  752.     Raises:
  753.       CaptchaRequired if the login service will require a captcha response
  754.       BadAuthentication if the login service rejected the username or password
  755.       Error if the login service responded with a 403 different from the above
  756.     """
  757.     request_body = gdata.auth.generate_client_login_request_body(self.email,
  758.         self.password, self.service, self.source, self.account_type,
  759.         captcha_token, captcha_response)
  760.  
  761.     # If the user has defined their own authentication service URL, 
  762.     # send the ClientLogin requests to this URL:
  763.     if not self.auth_service_url:
  764.         auth_request_url = AUTH_SERVER_HOST + '/accounts/ClientLogin' 
  765.     else:
  766.         auth_request_url = self.auth_service_url
  767.  
  768.     auth_response = self.http_client.request('POST', auth_request_url,
  769.         data=request_body, 
  770.         headers={'Content-Type':'application/x-www-form-urlencoded'})
  771.     response_body = auth_response.read()
  772.  
  773.     if auth_response.status == 200:
  774.       # TODO: insert the token into the token_store directly.
  775.       self.SetClientLoginToken(
  776.           gdata.auth.get_client_login_token(response_body))
  777.       self.__captcha_token = None
  778.       self.__captcha_url = None
  779.  
  780.     elif auth_response.status == 403:
  781.       # Examine each line to find the error type and the captcha token and
  782.       # captch URL if they are present.
  783.       captcha_parameters = gdata.auth.get_captcha_challenge(response_body,
  784.           captcha_base_url='%s/accounts/' % AUTH_SERVER_HOST)
  785.       if captcha_parameters:
  786.         self.__captcha_token = captcha_parameters['token']
  787.         self.__captcha_url = captcha_parameters['url']
  788.         raise CaptchaRequired, 'Captcha Required'
  789.       elif response_body.splitlines()[0] == 'Error=BadAuthentication':
  790.         self.__captcha_token = None
  791.         self.__captcha_url = None
  792.         raise BadAuthentication, 'Incorrect username or password'
  793.       else:
  794.         self.__captcha_token = None
  795.         self.__captcha_url = None
  796.         raise Error, 'Server responded with a 403 code'
  797.     elif auth_response.status == 302:
  798.       self.__captcha_token = None
  799.       self.__captcha_url = None
  800.       # Google tries to redirect all bad URLs back to 
  801.       # http://www.google.<locale>. If a redirect
  802.       # attempt is made, assume the user has supplied an incorrect authentication URL
  803.       raise BadAuthenticationServiceURL, 'Server responded with a 302 code.'
  804.  
  805.   def ClientLogin(self, username, password, account_type=None, service=None,
  806.       auth_service_url=None, source=None, captcha_token=None, 
  807.       captcha_response=None):
  808.     """Convenience method for authenticating using ProgrammaticLogin. 
  809.     
  810.     Sets values for email, password, and other optional members.
  811.  
  812.     Args:
  813.       username:
  814.       password:
  815.       account_type: string (optional)
  816.       service: string (optional)
  817.       auth_service_url: string (optional)
  818.       captcha_token: string (optional)
  819.       captcha_response: string (optional)
  820.     """
  821.     self.email = username
  822.     self.password = password
  823.  
  824.     if account_type:
  825.       self.account_type = account_type
  826.     if service:
  827.       self.service = service
  828.     if source:
  829.       self.source = source
  830.     if auth_service_url:
  831.       self.auth_service_url = auth_service_url
  832.  
  833.     self.ProgrammaticLogin(captcha_token, captcha_response)
  834.  
  835.   def GenerateAuthSubURL(self, next, scope, secure=False, session=True, 
  836.       domain='default'):
  837.     """Generate a URL at which the user will login and be redirected back.
  838.  
  839.     Users enter their credentials on a Google login page and a token is sent
  840.     to the URL specified in next. See documentation for AuthSub login at:
  841.     http://code.google.com/apis/accounts/docs/AuthSub.html
  842.  
  843.     Args:
  844.       next: string The URL user will be sent to after logging in.
  845.       scope: string or list of strings. The URLs of the services to be 
  846.              accessed.
  847.       secure: boolean (optional) Determines whether or not the issued token
  848.               is a secure token.
  849.       session: boolean (optional) Determines whether or not the issued token
  850.                can be upgraded to a session token.
  851.     """
  852.     if not isinstance(scope, (list, tuple)):
  853.       scope = (scope,)
  854.     return gdata.auth.generate_auth_sub_url(next, scope, secure=secure, 
  855.         session=session, 
  856.         request_url='%s/accounts/AuthSubRequest' % AUTH_SERVER_HOST, 
  857.         domain=domain)
  858.  
  859.   def UpgradeToSessionToken(self, token=None):
  860.     """Upgrades a single use AuthSub token to a session token.
  861.  
  862.     Args:
  863.       token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken
  864.              (optional) which is good for a single use but can be upgraded
  865.              to a session token. If no token is passed in, the token
  866.              is found by looking in the token_store by looking for a token
  867.              for the current scope.
  868.  
  869.     Raises:
  870.       NonAuthSubToken if the user's auth token is not an AuthSub token
  871.       TokenUpgradeFailed if the server responded to the request with an 
  872.       error.
  873.     """
  874.     if token is None:
  875.       scopes = lookup_scopes(self.service)
  876.       if scopes:
  877.         token = self.token_store.find_token(scopes[0])
  878.       else:
  879.         token = self.token_store.find_token(atom.token_store.SCOPE_ALL)
  880.     if not isinstance(token, gdata.auth.AuthSubToken):
  881.       raise NonAuthSubToken
  882.  
  883.     self.SetAuthSubToken(self.upgrade_to_session_token(token))
  884.  
  885.   def upgrade_to_session_token(self, token):
  886.     """Upgrades a single use AuthSub token to a session token.
  887.  
  888.     Args:
  889.       token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken
  890.              which is good for a single use but can be upgraded to a
  891.              session token.
  892.  
  893.     Returns:
  894.       The upgraded token as a gdata.auth.AuthSubToken object.
  895.  
  896.     Raises:
  897.       TokenUpgradeFailed if the server responded to the request with an 
  898.       error.
  899.     """
  900.     response = token.perform_request(self.http_client, 'GET', 
  901.         AUTH_SERVER_HOST + '/accounts/AuthSubSessionToken', 
  902.         headers={'Content-Type':'application/x-www-form-urlencoded'})
  903.     response_body = response.read()
  904.     if response.status == 200:
  905.       token.set_token_string(
  906.           gdata.auth.token_from_http_body(response_body))
  907.       return token
  908.     else:
  909.       raise TokenUpgradeFailed({'status': response.status,
  910.                                 'reason': 'Non 200 response on upgrade',
  911.                                 'body': response_body})
  912.  
  913.   def RevokeAuthSubToken(self):
  914.     """Revokes an existing AuthSub token.
  915.  
  916.     Raises:
  917.       NonAuthSubToken if the user's auth token is not an AuthSub token
  918.     """
  919.     scopes = lookup_scopes(self.service)
  920.     token = self.token_store.find_token(scopes[0])
  921.     if not isinstance(token, gdata.auth.AuthSubToken):
  922.       raise NonAuthSubToken
  923.  
  924.     response = token.perform_request(self.http_client, 'GET', 
  925.         AUTH_SERVER_HOST + '/accounts/AuthSubRevokeToken', 
  926.         headers={'Content-Type':'application/x-www-form-urlencoded'})
  927.     if response.status == 200:
  928.       self.token_store.remove_token(token)
  929.  
  930.   def AuthSubTokenInfo(self):
  931.     """Fetches the AuthSub token's metadata from the server.
  932.  
  933.     Raises:
  934.       NonAuthSubToken if the user's auth token is not an AuthSub token
  935.     """
  936.     scopes = lookup_scopes(self.service)
  937.     token = self.token_store.find_token(scopes[0])
  938.     if not isinstance(token, gdata.auth.AuthSubToken):
  939.       raise NonAuthSubToken
  940.  
  941.     response = token.perform_request(self.http_client, 'GET', 
  942.         AUTH_SERVER_HOST + '/accounts/AuthSubTokenInfo', 
  943.         headers={'Content-Type':'application/x-www-form-urlencoded'})
  944.     result_body = response.read()
  945.     if response.status == 200:
  946.       return result_body
  947.     else:
  948.       raise RequestError, {'status': response.status,
  949.           'body': result_body}
  950.  
  951.   def GetWithRetries(self, uri, extra_headers=None, redirects_remaining=4, 
  952.       encoding='UTF-8', converter=None, num_retries=DEFAULT_NUM_RETRIES,
  953.       delay=DEFAULT_DELAY, backoff=DEFAULT_BACKOFF, logger=None):
  954.     """This is a wrapper method for Get with retring capability.
  955.  
  956.     To avoid various errors while retrieving bulk entities by retring
  957.     specified times.
  958.  
  959.     Note this method relies on the time module and so may not be usable
  960.     by default in Python2.2.
  961.  
  962.     Args:
  963.       num_retries: integer The retry count.
  964.       delay: integer The initial delay for retring.
  965.       backoff: integer how much the delay should lengthen after each failure.
  966.       logger: an object which has a debug(str) method to receive logging
  967.               messages. Recommended that you pass in the logging module.
  968.     Raises:
  969.       ValueError if any of the parameters has an invalid value.
  970.       RanOutOfTries on failure after number of retries.
  971.     """
  972.     # Moved import for time module inside this method since time is not a
  973.     # default module in Python2.2. This method will not be usable in
  974.     # Python2.2.
  975.     import time
  976.     if backoff <= 1:
  977.       raise ValueError("backoff must be greater than 1")
  978.     num_retries = int(num_retries)
  979.  
  980.     if num_retries < 0:
  981.       raise ValueError("num_retries must be 0 or greater")
  982.  
  983.     if delay <= 0:
  984.       raise ValueError("delay must be greater than 0")
  985.  
  986.     # Let's start
  987.     mtries, mdelay = num_retries, delay
  988.     while mtries > 0:
  989.       if mtries != num_retries:
  990.         if logger:
  991.           logger.debug("Retrying...")
  992.       try:
  993.         rv = self.Get(uri, extra_headers=extra_headers,
  994.                       redirects_remaining=redirects_remaining,
  995.                       encoding=encoding, converter=converter)
  996.       except (SystemExit, RequestError):
  997.         # Allow these errors
  998.         raise
  999.       except Exception, e:
  1000.         if logger:
  1001.           logger.debug(e)
  1002.         mtries -= 1
  1003.         time.sleep(mdelay)
  1004.         mdelay *= backoff
  1005.       else:
  1006.         # This is the right path.
  1007.         if logger:
  1008.           logger.debug("Succeeeded...")
  1009.         return rv
  1010.     raise RanOutOfTries('Ran out of tries.')
  1011.  
  1012.   # CRUD operations
  1013.   def Get(self, uri, extra_headers=None, redirects_remaining=4, 
  1014.       encoding='UTF-8', converter=None):
  1015.     """Query the GData API with the given URI
  1016.  
  1017.     The uri is the portion of the URI after the server value 
  1018.     (ex: www.google.com).
  1019.  
  1020.     To perform a query against Google Base, set the server to 
  1021.     'base.google.com' and set the uri to '/base/feeds/...', where ... is 
  1022.     your query. For example, to find snippets for all digital cameras uri 
  1023.     should be set to: '/base/feeds/snippets?bq=digital+camera'
  1024.  
  1025.     Args:
  1026.       uri: string The query in the form of a URI. Example:
  1027.            '/base/feeds/snippets?bq=digital+camera'.
  1028.       extra_headers: dictionary (optional) Extra HTTP headers to be included
  1029.                      in the GET request. These headers are in addition to 
  1030.                      those stored in the client's additional_headers property.
  1031.                      The client automatically sets the Content-Type and 
  1032.                      Authorization headers.
  1033.       redirects_remaining: int (optional) Tracks the number of additional
  1034.           redirects this method will allow. If the service object receives
  1035.           a redirect and remaining is 0, it will not follow the redirect. 
  1036.           This was added to avoid infinite redirect loops.
  1037.       encoding: string (optional) The character encoding for the server's
  1038.           response. Default is UTF-8
  1039.       converter: func (optional) A function which will transform
  1040.           the server's results before it is returned. Example: use 
  1041.           GDataFeedFromString to parse the server response as if it
  1042.           were a GDataFeed.
  1043.  
  1044.     Returns:
  1045.       If there is no ResultsTransformer specified in the call, a GDataFeed 
  1046.       or GDataEntry depending on which is sent from the server. If the 
  1047.       response is niether a feed or entry and there is no ResultsTransformer,
  1048.       return a string. If there is a ResultsTransformer, the returned value 
  1049.       will be that of the ResultsTransformer function.
  1050.     """
  1051.  
  1052.     if extra_headers is None:
  1053.       extra_headers = {}
  1054.  
  1055.     if self.__gsessionid is not None:
  1056.       if uri.find('gsessionid=') < 0:
  1057.         if uri.find('?') > -1:
  1058.           uri += '&gsessionid=%s' % (self.__gsessionid,)
  1059.         else:
  1060.           uri += '?gsessionid=%s' % (self.__gsessionid,)
  1061.  
  1062.     server_response = self.request('GET', uri, 
  1063.         headers=extra_headers)
  1064.     result_body = server_response.read()
  1065.  
  1066.     if server_response.status == 200:
  1067.       if converter:
  1068.         return converter(result_body)
  1069.       # There was no ResultsTransformer specified, so try to convert the
  1070.       # server's response into a GDataFeed.
  1071.       feed = gdata.GDataFeedFromString(result_body)
  1072.       if not feed:
  1073.         # If conversion to a GDataFeed failed, try to convert the server's
  1074.         # response to a GDataEntry.
  1075.         entry = gdata.GDataEntryFromString(result_body)
  1076.         if not entry:
  1077.           # The server's response wasn't a feed, or an entry, so return the
  1078.           # response body as a string.
  1079.           return result_body
  1080.         return entry
  1081.       return feed
  1082.     elif server_response.status == 302:
  1083.       if redirects_remaining > 0:
  1084.         location = (server_response.getheader('Location')
  1085.                     or server_response.getheader('location'))
  1086.         if location is not None:
  1087.           m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
  1088.           if m is not None:
  1089.             self.__gsessionid = m.group(1)
  1090.           return GDataService.Get(self, location, extra_headers, redirects_remaining - 1, 
  1091.               encoding=encoding, converter=converter)
  1092.         else:
  1093.           raise RequestError, {'status': server_response.status,
  1094.               'reason': '302 received without Location header',
  1095.               'body': result_body}
  1096.       else:
  1097.         raise RequestError, {'status': server_response.status,
  1098.             'reason': 'Redirect received, but redirects_remaining <= 0',
  1099.             'body': result_body}
  1100.     else:
  1101.       raise RequestError, {'status': server_response.status,
  1102.           'reason': server_response.reason, 'body': result_body}
  1103.  
  1104.   def GetMedia(self, uri, extra_headers=None):
  1105.     """Returns a MediaSource containing media and its metadata from the given
  1106.     URI string.
  1107.     """
  1108.     response_handle = self.request('GET', uri,
  1109.         headers=extra_headers)
  1110.     return gdata.MediaSource(response_handle, response_handle.getheader(
  1111.             'Content-Type'),
  1112.         response_handle.getheader('Content-Length'))
  1113.  
  1114.   def GetEntry(self, uri, extra_headers=None):
  1115.     """Query the GData API with the given URI and receive an Entry.
  1116.     
  1117.     See also documentation for gdata.service.Get
  1118.  
  1119.     Args:
  1120.       uri: string The query in the form of a URI. Example:
  1121.            '/base/feeds/snippets?bq=digital+camera'.
  1122.       extra_headers: dictionary (optional) Extra HTTP headers to be included
  1123.                      in the GET request. These headers are in addition to
  1124.                      those stored in the client's additional_headers property.
  1125.                      The client automatically sets the Content-Type and
  1126.                      Authorization headers.
  1127.  
  1128.     Returns:
  1129.       A GDataEntry built from the XML in the server's response.
  1130.     """
  1131.  
  1132.     result = GDataService.Get(self, uri, extra_headers, 
  1133.         converter=atom.EntryFromString)
  1134.     if isinstance(result, atom.Entry):
  1135.       return result
  1136.     else:
  1137.       raise UnexpectedReturnType, 'Server did not send an entry' 
  1138.  
  1139.   def GetFeed(self, uri, extra_headers=None, 
  1140.               converter=gdata.GDataFeedFromString):
  1141.     """Query the GData API with the given URI and receive a Feed.
  1142.  
  1143.     See also documentation for gdata.service.Get
  1144.  
  1145.     Args:
  1146.       uri: string The query in the form of a URI. Example:
  1147.            '/base/feeds/snippets?bq=digital+camera'.
  1148.       extra_headers: dictionary (optional) Extra HTTP headers to be included
  1149.                      in the GET request. These headers are in addition to
  1150.                      those stored in the client's additional_headers property.
  1151.                      The client automatically sets the Content-Type and
  1152.                      Authorization headers.
  1153.  
  1154.     Returns:
  1155.       A GDataFeed built from the XML in the server's response.
  1156.     """
  1157.  
  1158.     result = GDataService.Get(self, uri, extra_headers, converter=converter)
  1159.     if isinstance(result, atom.Feed):
  1160.       return result
  1161.     else:
  1162.       raise UnexpectedReturnType, 'Server did not send a feed'  
  1163.  
  1164.   def GetNext(self, feed):
  1165.     """Requests the next 'page' of results in the feed.
  1166.     
  1167.     This method uses the feed's next link to request an additional feed
  1168.     and uses the class of the feed to convert the results of the GET request.
  1169.  
  1170.     Args:
  1171.       feed: atom.Feed or a subclass. The feed should contain a next link and
  1172.           the type of the feed will be applied to the results from the 
  1173.           server. The new feed which is returned will be of the same class
  1174.           as this feed which was passed in.
  1175.  
  1176.     Returns:
  1177.       A new feed representing the next set of results in the server's feed.
  1178.       The type of this feed will match that of the feed argument.
  1179.     """
  1180.     next_link = feed.GetNextLink()
  1181.     # Create a closure which will convert an XML string to the class of
  1182.     # the feed object passed in.
  1183.     def ConvertToFeedClass(xml_string):
  1184.       return atom.CreateClassFromXMLString(feed.__class__, xml_string)
  1185.     # Make a GET request on the next link and use the above closure for the
  1186.     # converted which processes the XML string from the server.
  1187.     if next_link and next_link.href:
  1188.       return GDataService.Get(self, next_link.href, 
  1189.           converter=ConvertToFeedClass)
  1190.     else:
  1191.       return None
  1192.  
  1193.   def Post(self, data, uri, extra_headers=None, url_params=None,
  1194.            escape_params=True, redirects_remaining=4, media_source=None,
  1195.            converter=None):
  1196.     """Insert or update  data into a GData service at the given URI.
  1197.  
  1198.     Args:
  1199.       data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The
  1200.             XML to be sent to the uri.
  1201.       uri: string The location (feed) to which the data should be inserted.
  1202.            Example: '/base/feeds/items'.
  1203.       extra_headers: dict (optional) HTTP headers which are to be included.
  1204.                      The client automatically sets the Content-Type,
  1205.                      Authorization, and Content-Length headers.
  1206.       url_params: dict (optional) Additional URL parameters to be included
  1207.                   in the URI. These are translated into query arguments
  1208.                   in the form '&dict_key=value&...'.
  1209.                   Example: {'max-results': '250'} becomes &max-results=250
  1210.       escape_params: boolean (optional) If false, the calling code has already
  1211.                      ensured that the query will form a valid URL (all
  1212.                      reserved characters have been escaped). If true, this
  1213.                      method will escape the query and any URL parameters
  1214.                      provided.
  1215.       media_source: MediaSource (optional) Container for the media to be sent
  1216.           along with the entry, if provided.
  1217.       converter: func (optional) A function which will be executed on the
  1218.           server's response. Often this is a function like
  1219.           GDataEntryFromString which will parse the body of the server's
  1220.           response and return a GDataEntry.
  1221.  
  1222.     Returns:
  1223.       If the post succeeded, this method will return a GDataFeed, GDataEntry,
  1224.       or the results of running converter on the server's result body (if
  1225.       converter was specified).
  1226.     """
  1227.     return GDataService.PostOrPut(self, 'POST', data, uri, 
  1228.         extra_headers=extra_headers, url_params=url_params, 
  1229.         escape_params=escape_params, redirects_remaining=redirects_remaining,
  1230.         media_source=media_source, converter=converter)
  1231.  
  1232.   def PostOrPut(self, verb, data, uri, extra_headers=None, url_params=None, 
  1233.            escape_params=True, redirects_remaining=4, media_source=None, 
  1234.            converter=None):
  1235.     """Insert data into a GData service at the given URI.
  1236.  
  1237.     Args:
  1238.       verb: string, either 'POST' or 'PUT'
  1239.       data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The
  1240.             XML to be sent to the uri. 
  1241.       uri: string The location (feed) to which the data should be inserted. 
  1242.            Example: '/base/feeds/items'. 
  1243.       extra_headers: dict (optional) HTTP headers which are to be included. 
  1244.                      The client automatically sets the Content-Type,
  1245.                      Authorization, and Content-Length headers.
  1246.       url_params: dict (optional) Additional URL parameters to be included
  1247.                   in the URI. These are translated into query arguments
  1248.                   in the form '&dict_key=value&...'.
  1249.                   Example: {'max-results': '250'} becomes &max-results=250
  1250.       escape_params: boolean (optional) If false, the calling code has already
  1251.                      ensured that the query will form a valid URL (all
  1252.                      reserved characters have been escaped). If true, this
  1253.                      method will escape the query and any URL parameters
  1254.                      provided.
  1255.       media_source: MediaSource (optional) Container for the media to be sent
  1256.           along with the entry, if provided.
  1257.       converter: func (optional) A function which will be executed on the 
  1258.           server's response. Often this is a function like 
  1259.           GDataEntryFromString which will parse the body of the server's 
  1260.           response and return a GDataEntry.
  1261.  
  1262.     Returns:
  1263.       If the post succeeded, this method will return a GDataFeed, GDataEntry,
  1264.       or the results of running converter on the server's result body (if
  1265.       converter was specified).
  1266.     """
  1267.     if extra_headers is None:
  1268.       extra_headers = {}
  1269.  
  1270.     if self.__gsessionid is not None:
  1271.       if uri.find('gsessionid=') < 0:
  1272.         if url_params is None:
  1273.           url_params = {}
  1274.         url_params['gsessionid'] = self.__gsessionid
  1275.  
  1276.     if data and media_source:
  1277.       if ElementTree.iselement(data):
  1278.         data_str = ElementTree.tostring(data)
  1279.       else:
  1280.         data_str = str(data)
  1281.         
  1282.       multipart = []
  1283.       multipart.append('Media multipart posting\r\n--END_OF_PART\r\n' + \
  1284.           'Content-Type: application/atom+xml\r\n\r\n')
  1285.       multipart.append('\r\n--END_OF_PART\r\nContent-Type: ' + \
  1286.           media_source.content_type+'\r\n\r\n')
  1287.       multipart.append('\r\n--END_OF_PART--\r\n')
  1288.         
  1289.       extra_headers['MIME-version'] = '1.0'
  1290.       extra_headers['Content-Length'] = str(len(multipart[0]) +
  1291.           len(multipart[1]) + len(multipart[2]) +
  1292.           len(data_str) + media_source.content_length)
  1293.  
  1294.       extra_headers['Content-Type'] = 'multipart/related; boundary=END_OF_PART'
  1295.       server_response = self.request(verb, uri, 
  1296.           data=[multipart[0], data_str, multipart[1], media_source.file_handle,
  1297.               multipart[2]], headers=extra_headers, url_params=url_params)
  1298.       result_body = server_response.read()
  1299.       
  1300.     elif media_source or isinstance(data, gdata.MediaSource):
  1301.       if isinstance(data, gdata.MediaSource):
  1302.         media_source = data
  1303.       extra_headers['Content-Length'] = str(media_source.content_length)
  1304.       extra_headers['Content-Type'] = media_source.content_type
  1305.       server_response = self.request(verb, uri, 
  1306.           data=media_source.file_handle, headers=extra_headers,
  1307.           url_params=url_params)
  1308.       result_body = server_response.read()
  1309.  
  1310.     else:
  1311.       http_data = data
  1312.       content_type = 'application/atom+xml'
  1313.       extra_headers['Content-Type'] = content_type
  1314.       server_response = self.request(verb, uri, data=http_data,
  1315.           headers=extra_headers, url_params=url_params)
  1316.       result_body = server_response.read()
  1317.  
  1318.     # Server returns 201 for most post requests, but when performing a batch
  1319.     # request the server responds with a 200 on success.
  1320.     if server_response.status == 201 or server_response.status == 200:
  1321.       if converter:
  1322.         return converter(result_body)
  1323.       feed = gdata.GDataFeedFromString(result_body)
  1324.       if not feed:
  1325.         entry = gdata.GDataEntryFromString(result_body)
  1326.         if not entry:
  1327.           return result_body
  1328.         return entry
  1329.       return feed
  1330.     elif server_response.status == 302:
  1331.       if redirects_remaining > 0:
  1332.         location = (server_response.getheader('Location')
  1333.                     or server_response.getheader('location'))
  1334.         if location is not None:
  1335.           m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
  1336.           if m is not None:
  1337.             self.__gsessionid = m.group(1) 
  1338.           return GDataService.PostOrPut(self, verb, data, location, 
  1339.               extra_headers, url_params, escape_params, 
  1340.               redirects_remaining - 1, media_source, converter=converter)
  1341.         else:
  1342.           raise RequestError, {'status': server_response.status,
  1343.               'reason': '302 received without Location header',
  1344.               'body': result_body}
  1345.       else:
  1346.         raise RequestError, {'status': server_response.status,
  1347.             'reason': 'Redirect received, but redirects_remaining <= 0',
  1348.             'body': result_body}
  1349.     else:
  1350.       raise RequestError, {'status': server_response.status,
  1351.           'reason': server_response.reason, 'body': result_body}
  1352.  
  1353.   def Put(self, data, uri, extra_headers=None, url_params=None, 
  1354.           escape_params=True, redirects_remaining=3, media_source=None,
  1355.           converter=None):
  1356.     """Updates an entry at the given URI.
  1357.      
  1358.     Args:
  1359.       data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The 
  1360.             XML containing the updated data.
  1361.       uri: string A URI indicating entry to which the update will be applied.
  1362.            Example: '/base/feeds/items/ITEM-ID'
  1363.       extra_headers: dict (optional) HTTP headers which are to be included.
  1364.                      The client automatically sets the Content-Type,
  1365.                      Authorization, and Content-Length headers.
  1366.       url_params: dict (optional) Additional URL parameters to be included
  1367.                   in the URI. These are translated into query arguments
  1368.                   in the form '&dict_key=value&...'.
  1369.                   Example: {'max-results': '250'} becomes &max-results=250
  1370.       escape_params: boolean (optional) If false, the calling code has already
  1371.                      ensured that the query will form a valid URL (all
  1372.                      reserved characters have been escaped). If true, this
  1373.                      method will escape the query and any URL parameters
  1374.                      provided.
  1375.       converter: func (optional) A function which will be executed on the 
  1376.           server's response. Often this is a function like 
  1377.           GDataEntryFromString which will parse the body of the server's 
  1378.           response and return a GDataEntry.
  1379.  
  1380.     Returns:
  1381.       If the put succeeded, this method will return a GDataFeed, GDataEntry,
  1382.       or the results of running converter on the server's result body (if
  1383.       converter was specified).
  1384.     """
  1385.     return GDataService.PostOrPut(self, 'PUT', data, uri, 
  1386.         extra_headers=extra_headers, url_params=url_params, 
  1387.         escape_params=escape_params, redirects_remaining=redirects_remaining,
  1388.         media_source=media_source, converter=converter)
  1389.  
  1390.   def Delete(self, uri, extra_headers=None, url_params=None, 
  1391.              escape_params=True, redirects_remaining=4):
  1392.     """Deletes the entry at the given URI.
  1393.  
  1394.     Args:
  1395.       uri: string The URI of the entry to be deleted. Example: 
  1396.            '/base/feeds/items/ITEM-ID'
  1397.       extra_headers: dict (optional) HTTP headers which are to be included.
  1398.                      The client automatically sets the Content-Type and
  1399.                      Authorization headers.
  1400.       url_params: dict (optional) Additional URL parameters to be included
  1401.                   in the URI. These are translated into query arguments
  1402.                   in the form '&dict_key=value&...'.
  1403.                   Example: {'max-results': '250'} becomes &max-results=250
  1404.       escape_params: boolean (optional) If false, the calling code has already
  1405.                      ensured that the query will form a valid URL (all
  1406.                      reserved characters have been escaped). If true, this
  1407.                      method will escape the query and any URL parameters
  1408.                      provided.
  1409.  
  1410.     Returns:
  1411.       True if the entry was deleted.
  1412.     """
  1413.     if extra_headers is None:
  1414.       extra_headers = {}
  1415.  
  1416.     if self.__gsessionid is not None:
  1417.       if uri.find('gsessionid=') < 0:
  1418.         if url_params is None:
  1419.           url_params = {}
  1420.         url_params['gsessionid'] = self.__gsessionid
  1421.  
  1422.     server_response = self.request('DELETE', uri, 
  1423.         headers=extra_headers, url_params=url_params)
  1424.     result_body = server_response.read()
  1425.  
  1426.     if server_response.status == 200:
  1427.       return True
  1428.     elif server_response.status == 302:
  1429.       if redirects_remaining > 0:
  1430.         location = (server_response.getheader('Location')
  1431.                     or server_response.getheader('location'))
  1432.         if location is not None:
  1433.           m = re.compile('[\?\&]gsessionid=(\w*)').search(location)
  1434.           if m is not None:
  1435.             self.__gsessionid = m.group(1) 
  1436.           return GDataService.Delete(self, location, extra_headers, 
  1437.               url_params, escape_params, redirects_remaining - 1)
  1438.         else:
  1439.           raise RequestError, {'status': server_response.status,
  1440.               'reason': '302 received without Location header',
  1441.               'body': result_body}
  1442.       else:
  1443.         raise RequestError, {'status': server_response.status,
  1444.             'reason': 'Redirect received, but redirects_remaining <= 0',
  1445.             'body': result_body}
  1446.     else:
  1447.       raise RequestError, {'status': server_response.status,
  1448.           'reason': server_response.reason, 'body': result_body}
  1449.  
  1450.  
  1451. def ExtractToken(url, scopes_included_in_next=True):
  1452.   """Gets the AuthSub token from the current page's URL.
  1453.  
  1454.   Designed to be used on the URL that the browser is sent to after the user
  1455.   authorizes this application at the page given by GenerateAuthSubRequestUrl.
  1456.  
  1457.   Args:
  1458.     url: The current page's URL. It should contain the token as a URL
  1459.         parameter. Example: 'http://example.com/?...&token=abcd435'
  1460.     scopes_included_in_next: If True, this function looks for a scope value
  1461.         associated with the token. The scope is a URL parameter with the
  1462.         key set to SCOPE_URL_PARAM_NAME. This parameter should be present
  1463.         if the AuthSub request URL was generated using
  1464.         GenerateAuthSubRequestUrl with include_scope_in_next set to True.
  1465.  
  1466.   Returns:
  1467.     A tuple containing the token string and a list of scope strings for which
  1468.     this token should be valid. If the scope was not included in the URL, the
  1469.     tuple will contain (token, None).
  1470.   """
  1471.   parsed = urlparse.urlparse(url)
  1472.   token = gdata.auth.AuthSubTokenFromUrl(parsed[4])
  1473.   scopes = ''
  1474.   if scopes_included_in_next:
  1475.     for pair in parsed[4].split('&'):
  1476.       if pair.startswith('%s=' % SCOPE_URL_PARAM_NAME):
  1477.         scopes = urllib.unquote_plus(pair.split('=')[1])
  1478.   return (token, scopes.split(' '))
  1479.  
  1480.  
  1481. def GenerateAuthSubRequestUrl(next, scopes, hd='default', secure=False,
  1482.     session=True, request_url='https://www.google.com/accounts/AuthSubRequest',
  1483.     include_scopes_in_next=True):
  1484.   """Creates a URL to request an AuthSub token to access Google services.
  1485.  
  1486.   For more details on AuthSub, see the documentation here:
  1487.   http://code.google.com/apis/accounts/docs/AuthSub.html
  1488.  
  1489.   Args:
  1490.     next: The URL where the browser should be sent after the user authorizes
  1491.         the application. This page is responsible for receiving the token
  1492.         which is embeded in the URL as a parameter.
  1493.     scopes: The base URL to which access will be granted. Example:
  1494.         'http://www.google.com/calendar/feeds' will grant access to all
  1495.         URLs in the Google Calendar data API. If you would like a token for
  1496.         multiple scopes, pass in a list of URL strings.
  1497.     hd: The domain to which the user's account belongs. This is set to the
  1498.         domain name if you are using Google Apps. Example: 'example.org'
  1499.         Defaults to 'default'
  1500.     secure: If set to True, all requests should be signed. The default is
  1501.         False.
  1502.     session: If set to True, the token received by the 'next' URL can be
  1503.         upgraded to a multiuse session token. If session is set to False, the
  1504.         token may only be used once and cannot be upgraded. Default is True.
  1505.     request_url: The base of the URL to which the user will be sent to
  1506.         authorize this application to access their data. The default is
  1507.         'https://www.google.com/accounts/AuthSubRequest'.
  1508.     include_scopes_in_next: Boolean if set to true, the 'next' parameter will
  1509.         be modified to include the requested scope as a URL parameter. The
  1510.         key for the next's scope parameter will be SCOPE_URL_PARAM_NAME. The
  1511.         benefit of including the scope URL as a parameter to the next URL, is
  1512.         that the page which receives the AuthSub token will be able to tell
  1513.         which URLs the token grants access to.
  1514.  
  1515.   Returns:
  1516.     A URL string to which the browser should be sent.
  1517.   """
  1518.   if isinstance(scopes, list):
  1519.     scope = ' '.join(scopes)
  1520.   else:
  1521.     scope = scopes
  1522.   if include_scopes_in_next:
  1523.     if next.find('?') > -1:
  1524.       next += '&%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope})
  1525.     else:
  1526.       next += '?%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope})
  1527.   return gdata.auth.GenerateAuthSubUrl(next=next, scope=scope, secure=secure,
  1528.       session=session, request_url=request_url, domain=hd)
  1529.  
  1530.  
  1531. class Query(dict):
  1532.   """Constructs a query URL to be used in GET requests
  1533.   
  1534.   Url parameters are created by adding key-value pairs to this object as a 
  1535.   dict. For example, to add &max-results=25 to the URL do
  1536.   my_query['max-results'] = 25
  1537.  
  1538.   Category queries are created by adding category strings to the categories
  1539.   member. All items in the categories list will be concatenated with the /
  1540.   symbol (symbolizing a category x AND y restriction). If you would like to OR
  1541.   2 categories, append them as one string with a | between the categories. 
  1542.   For example, do query.categories.append('Fritz|Laurie') to create a query
  1543.   like this feed/-/Fritz%7CLaurie . This query will look for results in both
  1544.   categories.
  1545.   """
  1546.  
  1547.   def __init__(self, feed=None, text_query=None, params=None, 
  1548.       categories=None):
  1549.     """Constructor for Query
  1550.     
  1551.     Args:
  1552.       feed: str (optional) The path for the feed (Examples: 
  1553.           '/base/feeds/snippets' or 'calendar/feeds/jo@gmail.com/private/full'
  1554.       text_query: str (optional) The contents of the q query parameter. The
  1555.           contents of the text_query are URL escaped upon conversion to a URI.
  1556.       params: dict (optional) Parameter value string pairs which become URL
  1557.           params when translated to a URI. These parameters are added to the
  1558.           query's items (key-value pairs).
  1559.       categories: list (optional) List of category strings which should be
  1560.           included as query categories. See 
  1561.           http://code.google.com/apis/gdata/reference.html#Queries for 
  1562.           details. If you want to get results from category A or B (both 
  1563.           categories), specify a single list item 'A|B'. 
  1564.     """
  1565.     
  1566.     self.feed = feed
  1567.     self.categories = []
  1568.     if text_query:
  1569.       self.text_query = text_query
  1570.     if isinstance(params, dict):
  1571.       for param in params:
  1572.         self[param] = params[param]
  1573.     if isinstance(categories, list):
  1574.       for category in categories:
  1575.         self.categories.append(category)
  1576.  
  1577.   def _GetTextQuery(self):
  1578.     if 'q' in self.keys():
  1579.       return self['q']
  1580.     else:
  1581.       return None
  1582.  
  1583.   def _SetTextQuery(self, query):
  1584.     self['q'] = query
  1585.  
  1586.   text_query = property(_GetTextQuery, _SetTextQuery, 
  1587.       doc="""The feed query's q parameter""")
  1588.  
  1589.   def _GetAuthor(self):
  1590.     if 'author' in self.keys():
  1591.       return self['author']
  1592.     else:
  1593.       return None
  1594.  
  1595.   def _SetAuthor(self, query):
  1596.     self['author'] = query
  1597.  
  1598.   author = property(_GetAuthor, _SetAuthor,
  1599.       doc="""The feed query's author parameter""")
  1600.  
  1601.   def _GetAlt(self):
  1602.     if 'alt' in self.keys():
  1603.       return self['alt']
  1604.     else:
  1605.       return None
  1606.  
  1607.   def _SetAlt(self, query):
  1608.     self['alt'] = query
  1609.  
  1610.   alt = property(_GetAlt, _SetAlt,
  1611.       doc="""The feed query's alt parameter""")
  1612.  
  1613.   def _GetUpdatedMin(self):
  1614.     if 'updated-min' in self.keys():
  1615.       return self['updated-min']
  1616.     else:
  1617.       return None
  1618.  
  1619.   def _SetUpdatedMin(self, query):
  1620.     self['updated-min'] = query
  1621.  
  1622.   updated_min = property(_GetUpdatedMin, _SetUpdatedMin,
  1623.       doc="""The feed query's updated-min parameter""")
  1624.  
  1625.   def _GetUpdatedMax(self):
  1626.     if 'updated-max' in self.keys():
  1627.       return self['updated-max']
  1628.     else:
  1629.       return None
  1630.  
  1631.   def _SetUpdatedMax(self, query):
  1632.     self['updated-max'] = query
  1633.  
  1634.   updated_max = property(_GetUpdatedMax, _SetUpdatedMax,
  1635.       doc="""The feed query's updated-max parameter""")
  1636.  
  1637.   def _GetPublishedMin(self):
  1638.     if 'published-min' in self.keys():
  1639.       return self['published-min']
  1640.     else:
  1641.       return None
  1642.  
  1643.   def _SetPublishedMin(self, query):
  1644.     self['published-min'] = query
  1645.  
  1646.   published_min = property(_GetPublishedMin, _SetPublishedMin,
  1647.       doc="""The feed query's published-min parameter""")
  1648.  
  1649.   def _GetPublishedMax(self):
  1650.     if 'published-max' in self.keys():
  1651.       return self['published-max']
  1652.     else:
  1653.       return None
  1654.  
  1655.   def _SetPublishedMax(self, query):
  1656.     self['published-max'] = query
  1657.  
  1658.   published_max = property(_GetPublishedMax, _SetPublishedMax,
  1659.       doc="""The feed query's published-max parameter""")
  1660.  
  1661.   def _GetStartIndex(self):
  1662.     if 'start-index' in self.keys():
  1663.       return self['start-index']
  1664.     else:
  1665.       return None
  1666.  
  1667.   def _SetStartIndex(self, query):
  1668.     if not isinstance(query, str):
  1669.       query = str(query)
  1670.     self['start-index'] = query
  1671.  
  1672.   start_index = property(_GetStartIndex, _SetStartIndex,
  1673.       doc="""The feed query's start-index parameter""")
  1674.  
  1675.   def _GetMaxResults(self):
  1676.     if 'max-results' in self.keys():
  1677.       return self['max-results']
  1678.     else:
  1679.       return None
  1680.  
  1681.   def _SetMaxResults(self, query):
  1682.     if not isinstance(query, str):
  1683.       query = str(query)
  1684.     self['max-results'] = query
  1685.  
  1686.   max_results = property(_GetMaxResults, _SetMaxResults,
  1687.       doc="""The feed query's max-results parameter""")
  1688.  
  1689.   def _GetOrderBy(self):
  1690.     if 'orderby' in self.keys():
  1691.       return self['orderby']
  1692.     else:
  1693.       return None
  1694.  
  1695.   def _SetOrderBy(self, query):
  1696.     self['orderby'] = query
  1697.   
  1698.   orderby = property(_GetOrderBy, _SetOrderBy, 
  1699.       doc="""The feed query's orderby parameter""")
  1700.  
  1701.   def ToUri(self):
  1702.     q_feed = self.feed or ''
  1703.     category_string = '/'.join(
  1704.         [urllib.quote_plus(c) for c in self.categories])
  1705.     # Add categories to the feed if there are any.
  1706.     if len(self.categories) > 0:
  1707.       q_feed = q_feed + '/-/' + category_string
  1708.     return atom.service.BuildUri(q_feed, self)
  1709.  
  1710.   def __str__(self):
  1711.     return self.ToUri()
  1712.