code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """CalendarResourceClient simplifies Calendar Resources API calls. CalendarResourceClient extends gdata.client.GDClient to ease interaction with the Google Apps Calendar Resources API. These interactions include the ability to create, retrieve, update, and delete calendar resources in a Google Apps domain. """ __author__ = 'Vic Fryzel <vf@google.com>' import gdata.calendar_resource.data import gdata.client import urllib # Feed URI template. This must end with a / # The strings in this template are eventually replaced with the API version # and Google Apps domain name, respectively. RESOURCE_FEED_TEMPLATE = '/a/feeds/calendar/resource/%s/%s/' class CalendarResourceClient(gdata.client.GDClient): """Client extension for the Google Calendar Resource API service. Attributes: host: string The hostname for the Calendar Resouce API service. api_version: string The version of the Calendar Resource API. """ host = 'apps-apis.google.com' api_version = '2.0' auth_service = 'apps' auth_scopes = gdata.gauth.AUTH_SCOPES['apps'] ssl = True def __init__(self, domain, auth_token=None, **kwargs): """Constructs a new client for the Calendar Resource API. Args: domain: string The Google Apps domain with Calendar Resources. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the calendar resource data. kwargs: The other parameters to pass to the gdata.client.GDClient constructor. """ gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs) self.domain = domain def make_resource_feed_uri(self, resource_id=None, params=None): """Creates a resource feed URI for the Calendar Resource API. Using this client's Google Apps domain, create a feed URI for calendar resources in that domain. If a resource_id is provided, return a URI for that specific resource. If params are provided, append them as GET params. Args: resource_id: string (optional) The ID of the calendar resource for which to make a feed URI. params: dict (optional) key -> value params to append as GET vars to the URI. Example: params={'start': 'my-resource-id'} Returns: A string giving the URI for calendar resources for this client's Google Apps domain. """ uri = RESOURCE_FEED_TEMPLATE % (self.api_version, self.domain) if resource_id: uri += resource_id if params: uri += '?' + urllib.urlencode(params) return uri MakeResourceFeedUri = make_resource_feed_uri def get_resource_feed(self, uri=None, **kwargs): """Fetches a ResourceFeed of calendar resources at the given URI. Args: uri: string The URI of the feed to pull. kwargs: The other parameters to pass to gdata.client.GDClient.get_feed(). Returns: A ResourceFeed object representing the feed at the given URI. """ if uri is None: uri = self.MakeResourceFeedUri() return self.get_feed( uri, desired_class=gdata.calendar_resource.data.CalendarResourceFeed, **kwargs) GetResourceFeed = get_resource_feed def get_resource(self, uri=None, resource_id=None, **kwargs): """Fetches a single calendar resource by resource ID. Args: uri: string The base URI of the feed from which to fetch the resource. resource_id: string The string ID of the Resource to fetch. kwargs: The other parameters to pass to gdata.client.GDClient.get_entry(). Returns: A Resource object representing the calendar resource with the given base URI and resource ID. """ if uri is None: uri = self.MakeResourceFeedUri(resource_id) return self.get_entry( uri, desired_class=gdata.calendar_resource.data.CalendarResourceEntry, **kwargs) GetResource = get_resource def create_resource(self, resource_id, resource_common_name=None, resource_description=None, resource_type=None, **kwargs): """Creates a calendar resource with the given properties. Args: resource_id: string The resource ID of the calendar resource. resource_common_name: string (optional) The common name of the resource. resource_description: string (optional) The description of the resource. resource_type: string (optional) The type of the resource. kwargs: The other parameters to pass to gdata.client.GDClient.post(). Returns: gdata.calendar_resource.data.CalendarResourceEntry of the new resource. """ new_resource = gdata.calendar_resource.data.CalendarResourceEntry( resource_id=resource_id, resource_common_name=resource_common_name, resource_description=resource_description, resource_type=resource_type) return self.post(new_resource, self.MakeResourceFeedUri(), **kwargs) CreateResource = create_resource def update_resource(self, resource_id, resource_common_name=None, resource_description=None, resource_type=None, **kwargs): """Updates the calendar resource with the given resource ID. Args: resource_id: string The resource ID of the calendar resource to update. resource_common_name: string (optional) The common name to give the resource. resource_description: string (optional) The description to give the resource. resource_type: string (optional) The type to give the resource. kwargs: The other parameters to pass to gdata.client.GDClient.update(). Returns: gdata.calendar_resource.data.CalendarResourceEntry of the updated resource. """ new_resource = gdata.calendar_resource.data.CalendarResourceEntry( resource_id=resource_id, resource_common_name=resource_common_name, resource_description=resource_description, resource_type=resource_type) return self.update( new_resource, **kwargs) UpdateResource = update_resource def delete_resource(self, resource_id, **kwargs): """Deletes the calendar resource with the given resource ID. Args: resource_id: string The resource ID of the calendar resource to delete. kwargs: The other parameters to pass to gdata.client.GDClient.delete() Returns: An HTTP response object. See gdata.client.request(). """ return self.delete(self.MakeResourceFeedUri(resource_id), **kwargs) DeleteResource = delete_resource
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model for parsing and generating XML for the Calendar Resource API.""" __author__ = 'Vic Fryzel <vf@google.com>' import atom.core import atom.data import gdata.apps import gdata.apps_property import gdata.data # This is required to work around a naming conflict between the Google # Spreadsheets API and Python's built-in property function pyproperty = property # The apps:property name of the resourceId property RESOURCE_ID_NAME = 'resourceId' # The apps:property name of the resourceCommonName property RESOURCE_COMMON_NAME_NAME = 'resourceCommonName' # The apps:property name of the resourceDescription property RESOURCE_DESCRIPTION_NAME = 'resourceDescription' # The apps:property name of the resourceType property RESOURCE_TYPE_NAME = 'resourceType' # The apps:property name of the resourceEmail property RESOURCE_EMAIL_NAME = 'resourceEmail' class CalendarResourceEntry(gdata.data.GDEntry): """Represents a Calendar Resource entry in object form.""" property = [gdata.apps_property.AppsProperty] def _GetProperty(self, name): """Get the apps:property value with the given name. Args: name: string Name of the apps:property value to get. Returns: The apps:property value with the given name, or None if the name was invalid. """ for p in self.property: if p.name == name: return p.value return None def _SetProperty(self, name, value): """Set the apps:property value with the given name to the given value. Args: name: string Name of the apps:property value to set. value: string Value to give the apps:property value with the given name. """ for i in range(len(self.property)): if self.property[i].name == name: self.property[i].value = value return self.property.append(gdata.apps_property.AppsProperty(name=name, value=value)) def GetResourceId(self): """Get the resource ID of this Calendar Resource object. Returns: The resource ID of this Calendar Resource object as a string or None. """ return self._GetProperty(RESOURCE_ID_NAME) def SetResourceId(self, value): """Set the resource ID of this Calendar Resource object. Args: value: string The new resource ID value to give this object. """ self._SetProperty(RESOURCE_ID_NAME, value) resource_id = pyproperty(GetResourceId, SetResourceId) def GetResourceCommonName(self): """Get the common name of this Calendar Resource object. Returns: The common name of this Calendar Resource object as a string or None. """ return self._GetProperty(RESOURCE_COMMON_NAME_NAME) def SetResourceCommonName(self, value): """Set the common name of this Calendar Resource object. Args: value: string The new common name value to give this object. """ self._SetProperty(RESOURCE_COMMON_NAME_NAME, value) resource_common_name = pyproperty( GetResourceCommonName, SetResourceCommonName) def GetResourceDescription(self): """Get the description of this Calendar Resource object. Returns: The description of this Calendar Resource object as a string or None. """ return self._GetProperty(RESOURCE_DESCRIPTION_NAME) def SetResourceDescription(self, value): """Set the description of this Calendar Resource object. Args: value: string The new description value to give this object. """ self._SetProperty(RESOURCE_DESCRIPTION_NAME, value) resource_description = pyproperty( GetResourceDescription, SetResourceDescription) def GetResourceType(self): """Get the type of this Calendar Resource object. Returns: The type of this Calendar Resource object as a string or None. """ return self._GetProperty(RESOURCE_TYPE_NAME) def SetResourceType(self, value): """Set the type value of this Calendar Resource object. Args: value: string The new type value to give this object. """ self._SetProperty(RESOURCE_TYPE_NAME, value) resource_type = pyproperty(GetResourceType, SetResourceType) def GetResourceEmail(self): """Get the email of this Calendar Resource object. Returns: The email of this Calendar Resource object as a string or None. """ return self._GetProperty(RESOURCE_EMAIL_NAME) resource_email = pyproperty(GetResourceEmail) def __init__(self, resource_id=None, resource_common_name=None, resource_description=None, resource_type=None, *args, **kwargs): """Constructs a new CalendarResourceEntry object with the given arguments. Args: resource_id: string (optional) The resource ID to give this new object. resource_common_name: string (optional) The common name to give this new object. resource_description: string (optional) The description to give this new object. resource_type: string (optional) The type to give this new object. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(CalendarResourceEntry, self).__init__(*args, **kwargs) if resource_id: self.resource_id = resource_id if resource_common_name: self.resource_common_name = resource_common_name if resource_description: self.resource_description = resource_description if resource_type: self.resource_type = resource_type class CalendarResourceFeed(gdata.data.GDFeed): """Represents a feed of CalendarResourceEntry objects.""" # Override entry so that this feed knows how to type its list of entries. entry = [CalendarResourceEntry]
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the data classes of the Google Notebook Data API""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import atom.data import gdata.data import gdata.opensearch.data NB_TEMPLATE = '{http://schemas.google.com/notes/2008/}%s' class ComesAfter(atom.core.XmlElement): """Preceding element.""" _qname = NB_TEMPLATE % 'comesAfter' id = 'id' class NoteEntry(gdata.data.GDEntry): """Describes a note entry in the feed of a user's notebook.""" class NotebookFeed(gdata.data.GDFeed): """Describes a notebook feed.""" entry = [NoteEntry] class NotebookListEntry(gdata.data.GDEntry): """Describes a note list entry in the feed of a user's list of public notebooks.""" class NotebookListFeed(gdata.data.GDFeed): """Describes a notebook list feed.""" entry = [NotebookListEntry]
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
Python
#!/usr/bin/python # # Copyright (C) 2006,2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """GDataService provides CRUD ops. and programmatic login for GData services. Error: A base exception class for all exceptions in the gdata_client module. CaptchaRequired: This exception is thrown when a login attempt results in a captcha challenge from the ClientLogin service. When this exception is thrown, the captcha_token and captcha_url are set to the values provided in the server's response. BadAuthentication: Raised when a login attempt is made with an incorrect username or password. NotAuthenticated: Raised if an operation requiring authentication is called before a user has authenticated. NonAuthSubToken: Raised if a method to modify an AuthSub token is used when the user is either not authenticated or is authenticated through another authentication mechanism. NonOAuthToken: Raised if a method to modify an OAuth token is used when the user is either not authenticated or is authenticated through another authentication mechanism. RequestError: Raised if a CRUD request returned a non-success code. UnexpectedReturnType: Raised if the response from the server was not of the desired type. For example, this would be raised if the server sent a feed when the client requested an entry. GDataService: Encapsulates user credentials needed to perform insert, update and delete operations with the GData API. An instance can perform user authentication, query, insertion, deletion, and update. Query: Eases query URI creation by allowing URI parameters to be set as dictionary attributes. For example a query with a feed of '/base/feeds/snippets' and ['bq'] set to 'digital camera' will produce '/base/feeds/snippets?bq=digital+camera' when .ToUri() is called on it. """ __author__ = 'api.jscudder (Jeffrey Scudder)' import re import urllib import urlparse try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom.service import gdata import atom import atom.http_interface import atom.token_store import gdata.auth import gdata.gauth AUTH_SERVER_HOST = 'https://www.google.com' # When requesting an AuthSub token, it is often helpful to track the scope # which is being requested. One way to accomplish this is to add a URL # parameter to the 'next' URL which contains the requested scope. This # constant is the default name (AKA key) for the URL parameter. SCOPE_URL_PARAM_NAME = 'authsub_token_scope' # When requesting an OAuth access token or authorization of an existing OAuth # request token, it is often helpful to track the scope(s) which is/are being # requested. One way to accomplish this is to add a URL parameter to the # 'callback' URL which contains the requested scope. This constant is the # default name (AKA key) for the URL parameter. OAUTH_SCOPE_URL_PARAM_NAME = 'oauth_token_scope' # Maps the service names used in ClientLogin to scope URLs. CLIENT_LOGIN_SCOPES = gdata.gauth.AUTH_SCOPES # Default parameters for GDataService.GetWithRetries method DEFAULT_NUM_RETRIES = 3 DEFAULT_DELAY = 1 DEFAULT_BACKOFF = 2 def lookup_scopes(service_name): """Finds the scope URLs for the desired service. In some cases, an unknown service may be used, and in those cases this function will return None. """ if service_name in CLIENT_LOGIN_SCOPES: return CLIENT_LOGIN_SCOPES[service_name] return None # Module level variable specifies which module should be used by GDataService # objects to make HttpRequests. This setting can be overridden on each # instance of GDataService. # This module level variable is deprecated. Reassign the http_client member # of a GDataService object instead. http_request_handler = atom.service class Error(Exception): pass class CaptchaRequired(Error): pass class BadAuthentication(Error): pass class NotAuthenticated(Error): pass class NonAuthSubToken(Error): pass class NonOAuthToken(Error): pass class RequestError(Error): pass class UnexpectedReturnType(Error): pass class BadAuthenticationServiceURL(Error): pass class FetchingOAuthRequestTokenFailed(RequestError): pass class TokenUpgradeFailed(RequestError): pass class RevokingOAuthTokenFailed(RequestError): pass class AuthorizationRequired(Error): pass class TokenHadNoScope(Error): pass class RanOutOfTries(Error): pass class GDataService(atom.service.AtomService): """Contains elements needed for GData login and CRUD request headers. Maintains additional headers (tokens for example) needed for the GData services to allow a user to perform inserts, updates, and deletes. """ # The hander member is deprecated, use http_client instead. handler = None # The auth_token member is deprecated, use the token_store instead. auth_token = None # The tokens dict is deprecated in favor of the token_store. tokens = None def __init__(self, email=None, password=None, account_type='HOSTED_OR_GOOGLE', service=None, auth_service_url=None, source=None, server=None, additional_headers=None, handler=None, tokens=None, http_client=None, token_store=None): """Creates an object of type GDataService. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. account_type: string (optional) The type of account to use. Use 'GOOGLE' for regular Google accounts or 'HOSTED' for Google Apps accounts, or 'HOSTED_OR_GOOGLE' to try finding a HOSTED account first and, if it doesn't exist, try finding a regular GOOGLE account. Default value: 'HOSTED_OR_GOOGLE'. service: string (optional) The desired service for which credentials will be obtained. auth_service_url: string (optional) User-defined auth token request URL allows users to explicitly specify where to send auth token requests. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'base.google.com'. additional_headers: dictionary (optional) Any additional headers which should be included with CRUD operations. handler: module (optional) This parameter is deprecated and has been replaced by http_client. tokens: This parameter is deprecated, calls should be made to token_store instead. http_client: An object responsible for making HTTP requests using a request method. If none is provided, a new instance of atom.http.ProxiedHttpClient will be used. token_store: Keeps a collection of authorization tokens which can be applied to requests for a specific URLs. Critical methods are find_token based on a URL (atom.url.Url or a string), add_token, and remove_token. """ atom.service.AtomService.__init__(self, http_client=http_client, token_store=token_store) self.email = email self.password = password self.account_type = account_type self.service = service self.auth_service_url = auth_service_url self.server = server self.additional_headers = additional_headers or {} self._oauth_input_params = None self.__SetSource(source) self.__captcha_token = None self.__captcha_url = None self.__gsessionid = None if http_request_handler.__name__ == 'gdata.urlfetch': import gdata.alt.appengine self.http_client = gdata.alt.appengine.AppEngineHttpClient() def _SetSessionId(self, session_id): """Used in unit tests to simulate a 302 which sets a gsessionid.""" self.__gsessionid = session_id # Define properties for GDataService def _SetAuthSubToken(self, auth_token, scopes=None): """Deprecated, use SetAuthSubToken instead.""" self.SetAuthSubToken(auth_token, scopes=scopes) def __SetAuthSubToken(self, auth_token, scopes=None): """Deprecated, use SetAuthSubToken instead.""" self._SetAuthSubToken(auth_token, scopes=scopes) def _GetAuthToken(self): """Returns the auth token used for authenticating requests. Returns: string """ current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if hasattr(token, 'auth_header'): return token.auth_header return None def _GetCaptchaToken(self): """Returns a captcha token if the most recent login attempt generated one. The captcha token is only set if the Programmatic Login attempt failed because the Google service issued a captcha challenge. Returns: string """ return self.__captcha_token def __GetCaptchaToken(self): return self._GetCaptchaToken() captcha_token = property(__GetCaptchaToken, doc="""Get the captcha token for a login request.""") def _GetCaptchaURL(self): """Returns the URL of the captcha image if a login attempt generated one. The captcha URL is only set if the Programmatic Login attempt failed because the Google service issued a captcha challenge. Returns: string """ return self.__captcha_url def __GetCaptchaURL(self): return self._GetCaptchaURL() captcha_url = property(__GetCaptchaURL, doc="""Get the captcha URL for a login request.""") def GetGeneratorFromLinkFinder(self, link_finder, func, num_retries=DEFAULT_NUM_RETRIES, delay=DEFAULT_DELAY, backoff=DEFAULT_BACKOFF): """returns a generator for pagination""" yield link_finder next = link_finder.GetNextLink() while next is not None: next_feed = func(str(self.GetWithRetries( next.href, num_retries=num_retries, delay=delay, backoff=backoff))) yield next_feed next = next_feed.GetNextLink() def _GetElementGeneratorFromLinkFinder(self, link_finder, func, num_retries=DEFAULT_NUM_RETRIES, delay=DEFAULT_DELAY, backoff=DEFAULT_BACKOFF): for element in self.GetGeneratorFromLinkFinder(link_finder, func, num_retries=num_retries, delay=delay, backoff=backoff).entry: yield element def GetOAuthInputParameters(self): return self._oauth_input_params def SetOAuthInputParameters(self, signature_method, consumer_key, consumer_secret=None, rsa_key=None, two_legged_oauth=False, requestor_id=None): """Sets parameters required for using OAuth authentication mechanism. NOTE: Though consumer_secret and rsa_key are optional, either of the two is required depending on the value of the signature_method. Args: signature_method: class which provides implementation for strategy class oauth.oauth.OAuthSignatureMethod. Signature method to be used for signing each request. Valid implementations are provided as the constants defined by gdata.auth.OAuthSignatureMethod. Currently they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and gdata.auth.OAuthSignatureMethod.HMAC_SHA1 consumer_key: string Domain identifying third_party web application. consumer_secret: string (optional) Secret generated during registration. Required only for HMAC_SHA1 signature method. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. two_legged_oauth: boolean (optional) Enables two-legged OAuth process. requestor_id: string (optional) User email adress to make requests on their behalf. This parameter should only be set when two_legged_oauth is True. """ self._oauth_input_params = gdata.auth.OAuthInputParams( signature_method, consumer_key, consumer_secret=consumer_secret, rsa_key=rsa_key, requestor_id=requestor_id) if two_legged_oauth: oauth_token = gdata.auth.OAuthToken( oauth_input_params=self._oauth_input_params) self.SetOAuthToken(oauth_token) def FetchOAuthRequestToken(self, scopes=None, extra_parameters=None, request_url='%s/accounts/OAuthGetRequestToken' % \ AUTH_SERVER_HOST, oauth_callback=None): """Fetches and sets the OAuth request token and returns it. Args: scopes: string or list of string base URL(s) of the service(s) to be accessed. If None, then this method tries to determine the scope(s) from the current service. extra_parameters: dict (optional) key-value pairs as any additional parameters to be included in the URL and signature while making a request for fetching an OAuth request token. All the OAuth parameters are added by default. But if provided through this argument, any default parameters will be overwritten. For e.g. a default parameter oauth_version 1.0 can be overwritten if extra_parameters = {'oauth_version': '2.0'} request_url: Request token URL. The default is 'https://www.google.com/accounts/OAuthGetRequestToken'. oauth_callback: str (optional) If set, it is assume the client is using the OAuth v1.0a protocol where the callback url is sent in the request token step. If the oauth_callback is also set in extra_params, this value will override that one. Returns: The fetched request token as a gdata.auth.OAuthToken object. Raises: FetchingOAuthRequestTokenFailed if the server responded to the request with an error. """ if scopes is None: scopes = lookup_scopes(self.service) if not isinstance(scopes, (list, tuple)): scopes = [scopes,] if oauth_callback: if extra_parameters is not None: extra_parameters['oauth_callback'] = oauth_callback else: extra_parameters = {'oauth_callback': oauth_callback} request_token_url = gdata.auth.GenerateOAuthRequestTokenUrl( self._oauth_input_params, scopes, request_token_url=request_url, extra_parameters=extra_parameters) response = self.http_client.request('GET', str(request_token_url)) if response.status == 200: token = gdata.auth.OAuthToken() token.set_token_string(response.read()) token.scopes = scopes token.oauth_input_params = self._oauth_input_params self.SetOAuthToken(token) return token error = { 'status': response.status, 'reason': 'Non 200 response on fetch request token', 'body': response.read() } raise FetchingOAuthRequestTokenFailed(error) def SetOAuthToken(self, oauth_token): """Attempts to set the current token and add it to the token store. The oauth_token can be any OAuth token i.e. unauthorized request token, authorized request token or access token. This method also attempts to add the token to the token store. Use this method any time you want the current token to point to the oauth_token passed. For e.g. call this method with the request token you receive from FetchOAuthRequestToken. Args: request_token: gdata.auth.OAuthToken OAuth request token. """ if self.auto_set_current_token: self.current_token = oauth_token if self.auto_store_tokens: self.token_store.add_token(oauth_token) def GenerateOAuthAuthorizationURL( self, request_token=None, callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix=OAUTH_SCOPE_URL_PARAM_NAME, request_url='%s/accounts/OAuthAuthorizeToken' % AUTH_SERVER_HOST): """Generates URL at which user will login to authorize the request token. Args: request_token: gdata.auth.OAuthToken (optional) OAuth request token. If not specified, then the current token will be used if it is of type <gdata.auth.OAuthToken>, else it is found by looking in the token_store by looking for a token for the current scope. callback_url: string (optional) The URL user will be sent to after logging in and granting access. extra_params: dict (optional) Additional parameters to be sent. include_scopes_in_callback: Boolean (default=False) if set to True, and if 'callback_url' is present, the 'callback_url' will be modified to include the scope(s) from the request token as a URL parameter. The key for the 'callback' URL's scope parameter will be OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as a parameter to the 'callback' URL, is that the page which receives the OAuth token will be able to tell which URLs the token grants access to. scopes_param_prefix: string (default='oauth_token_scope') The URL parameter key which maps to the list of valid scopes for the token. This URL parameter will be included in the callback URL along with the scopes of the token as value if include_scopes_in_callback=True. request_url: Authorization URL. The default is 'https://www.google.com/accounts/OAuthAuthorizeToken'. Returns: A string URL at which the user is required to login. Raises: NonOAuthToken if the user's request token is not an OAuth token or if a request token was not available. """ if request_token and not isinstance(request_token, gdata.auth.OAuthToken): raise NonOAuthToken if not request_token: if isinstance(self.current_token, gdata.auth.OAuthToken): request_token = self.current_token else: current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.OAuthToken): request_token = token if not request_token: raise NonOAuthToken return str(gdata.auth.GenerateOAuthAuthorizationUrl( request_token, authorization_url=request_url, callback_url=callback_url, extra_params=extra_params, include_scopes_in_callback=include_scopes_in_callback, scopes_param_prefix=scopes_param_prefix)) def UpgradeToOAuthAccessToken(self, authorized_request_token=None, request_url='%s/accounts/OAuthGetAccessToken' \ % AUTH_SERVER_HOST, oauth_version='1.0', oauth_verifier=None): """Upgrades the authorized request token to an access token and returns it Args: authorized_request_token: gdata.auth.OAuthToken (optional) OAuth request token. If not specified, then the current token will be used if it is of type <gdata.auth.OAuthToken>, else it is found by looking in the token_store by looking for a token for the current scope. request_url: Access token URL. The default is 'https://www.google.com/accounts/OAuthGetAccessToken'. oauth_version: str (default='1.0') oauth_version parameter. All other 'oauth_' parameters are added by default. This parameter too, is added by default but here you can override it's value. oauth_verifier: str (optional) If present, it is assumed that the client will use the OAuth v1.0a protocol which includes passing the oauth_verifier (as returned by the SP) in the access token step. Returns: Access token Raises: NonOAuthToken if the user's authorized request token is not an OAuth token or if an authorized request token was not available. TokenUpgradeFailed if the server responded to the request with an error. """ if (authorized_request_token and not isinstance(authorized_request_token, gdata.auth.OAuthToken)): raise NonOAuthToken if not authorized_request_token: if isinstance(self.current_token, gdata.auth.OAuthToken): authorized_request_token = self.current_token else: current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.OAuthToken): authorized_request_token = token if not authorized_request_token: raise NonOAuthToken access_token_url = gdata.auth.GenerateOAuthAccessTokenUrl( authorized_request_token, self._oauth_input_params, access_token_url=request_url, oauth_version=oauth_version, oauth_verifier=oauth_verifier) response = self.http_client.request('GET', str(access_token_url)) if response.status == 200: token = gdata.auth.OAuthTokenFromHttpBody(response.read()) token.scopes = authorized_request_token.scopes token.oauth_input_params = authorized_request_token.oauth_input_params self.SetOAuthToken(token) return token else: raise TokenUpgradeFailed({'status': response.status, 'reason': 'Non 200 response on upgrade', 'body': response.read()}) def RevokeOAuthToken(self, request_url='%s/accounts/AuthSubRevokeToken' % \ AUTH_SERVER_HOST): """Revokes an existing OAuth token. request_url: Token revoke URL. The default is 'https://www.google.com/accounts/AuthSubRevokeToken'. Raises: NonOAuthToken if the user's auth token is not an OAuth token. RevokingOAuthTokenFailed if request for revoking an OAuth token failed. """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.OAuthToken): raise NonOAuthToken response = token.perform_request(self.http_client, 'GET', request_url, headers={'Content-Type':'application/x-www-form-urlencoded'}) if response.status == 200: self.token_store.remove_token(token) else: raise RevokingOAuthTokenFailed def GetAuthSubToken(self): """Returns the AuthSub token as a string. If the token is an gdta.auth.AuthSubToken, the Authorization Label ("AuthSub token") is removed. This method examines the current_token to see if it is an AuthSubToken or SecureAuthSubToken. If not, it searches the token_store for a token which matches the current scope. The current scope is determined by the service name string member. Returns: If the current_token is set to an AuthSubToken/SecureAuthSubToken, return the token string. If there is no current_token, a token string for a token which matches the service object's default scope is returned. If there are no tokens valid for the scope, returns None. """ if isinstance(self.current_token, gdata.auth.AuthSubToken): return self.current_token.get_token_string() current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.AuthSubToken): return token.get_token_string() else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() return None def SetAuthSubToken(self, token, scopes=None, rsa_key=None): """Sets the token sent in requests to an AuthSub token. Sets the current_token and attempts to add the token to the token_store. Only use this method if you have received a token from the AuthSub service. The auth token is set automatically when UpgradeToSessionToken() is used. See documentation for Google AuthSub here: http://code.google.com/apis/accounts/AuthForWebApps.html Args: token: gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken or string The token returned by the AuthSub service. If the token is an AuthSubToken or SecureAuthSubToken, the scope information stored in the token is used. If the token is a string, the scopes parameter is used to determine the valid scopes. scopes: list of URLs for which the token is valid. This is only used if the token parameter is a string. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. This parameter is necessary if the token is a string representing a secure token. """ if not isinstance(token, gdata.auth.AuthSubToken): token_string = token if rsa_key: token = gdata.auth.SecureAuthSubToken(rsa_key) else: token = gdata.auth.AuthSubToken() token.set_token_string(token_string) # If no scopes were set for the token, use the scopes passed in, or # try to determine the scopes based on the current service name. If # all else fails, set the token to match all requests. if not token.scopes: if scopes is None: scopes = lookup_scopes(self.service) if scopes is None: scopes = [atom.token_store.SCOPE_ALL] token.scopes = scopes if self.auto_set_current_token: self.current_token = token if self.auto_store_tokens: self.token_store.add_token(token) def GetClientLoginToken(self): """Returns the token string for the current token or a token matching the service scope. If the current_token is a ClientLoginToken, the token string for the current token is returned. If the current_token is not set, this method searches for a token in the token_store which is valid for the service object's current scope. The current scope is determined by the service name string member. The token string is the end of the Authorization header, it doesn not include the ClientLogin label. """ if isinstance(self.current_token, gdata.auth.ClientLoginToken): return self.current_token.get_token_string() current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() return None def SetClientLoginToken(self, token, scopes=None): """Sets the token sent in requests to a ClientLogin token. This method sets the current_token to a new ClientLoginToken and it also attempts to add the ClientLoginToken to the token_store. Only use this method if you have received a token from the ClientLogin service. The auth_token is set automatically when ProgrammaticLogin() is used. See documentation for Google ClientLogin here: http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html Args: token: string or instance of a ClientLoginToken. """ if not isinstance(token, gdata.auth.ClientLoginToken): token_string = token token = gdata.auth.ClientLoginToken() token.set_token_string(token_string) if not token.scopes: if scopes is None: scopes = lookup_scopes(self.service) if scopes is None: scopes = [atom.token_store.SCOPE_ALL] token.scopes = scopes if self.auto_set_current_token: self.current_token = token if self.auto_store_tokens: self.token_store.add_token(token) # Private methods to create the source property. def __GetSource(self): return self.__source def __SetSource(self, new_source): self.__source = new_source # Update the UserAgent header to include the new application name. self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % ( self.__source,) source = property(__GetSource, __SetSource, doc="""The source is the name of the application making the request. It should be in the form company_id-app_name-app_version""") # Authentication operations def ProgrammaticLogin(self, captcha_token=None, captcha_response=None): """Authenticates the user and sets the GData Auth token. Login retreives a temporary auth token which must be used with all requests to GData services. The auth token is stored in the GData client object. Login is also used to respond to a captcha challenge. If the user's login attempt failed with a CaptchaRequired error, the user can respond by calling Login with the captcha token and the answer to the challenge. Args: captcha_token: string (optional) The identifier for the captcha challenge which was presented to the user. captcha_response: string (optional) The user's answer to the captch challenge. Raises: CaptchaRequired if the login service will require a captcha response BadAuthentication if the login service rejected the username or password Error if the login service responded with a 403 different from the above """ request_body = gdata.auth.generate_client_login_request_body(self.email, self.password, self.service, self.source, self.account_type, captcha_token, captcha_response) # If the user has defined their own authentication service URL, # send the ClientLogin requests to this URL: if not self.auth_service_url: auth_request_url = AUTH_SERVER_HOST + '/accounts/ClientLogin' else: auth_request_url = self.auth_service_url auth_response = self.http_client.request('POST', auth_request_url, data=request_body, headers={'Content-Type':'application/x-www-form-urlencoded'}) response_body = auth_response.read() if auth_response.status == 200: # TODO: insert the token into the token_store directly. self.SetClientLoginToken( gdata.auth.get_client_login_token(response_body)) self.__captcha_token = None self.__captcha_url = None elif auth_response.status == 403: # Examine each line to find the error type and the captcha token and # captch URL if they are present. captcha_parameters = gdata.auth.get_captcha_challenge(response_body, captcha_base_url='%s/accounts/' % AUTH_SERVER_HOST) if captcha_parameters: self.__captcha_token = captcha_parameters['token'] self.__captcha_url = captcha_parameters['url'] raise CaptchaRequired, 'Captcha Required' elif response_body.splitlines()[0] == 'Error=BadAuthentication': self.__captcha_token = None self.__captcha_url = None raise BadAuthentication, 'Incorrect username or password' else: self.__captcha_token = None self.__captcha_url = None raise Error, 'Server responded with a 403 code' elif auth_response.status == 302: self.__captcha_token = None self.__captcha_url = None # Google tries to redirect all bad URLs back to # http://www.google.<locale>. If a redirect # attempt is made, assume the user has supplied an incorrect authentication URL raise BadAuthenticationServiceURL, 'Server responded with a 302 code.' def ClientLogin(self, username, password, account_type=None, service=None, auth_service_url=None, source=None, captcha_token=None, captcha_response=None): """Convenience method for authenticating using ProgrammaticLogin. Sets values for email, password, and other optional members. Args: username: password: account_type: string (optional) service: string (optional) auth_service_url: string (optional) captcha_token: string (optional) captcha_response: string (optional) """ self.email = username self.password = password if account_type: self.account_type = account_type if service: self.service = service if source: self.source = source if auth_service_url: self.auth_service_url = auth_service_url self.ProgrammaticLogin(captcha_token, captcha_response) def GenerateAuthSubURL(self, next, scope, secure=False, session=True, domain='default'): """Generate a URL at which the user will login and be redirected back. Users enter their credentials on a Google login page and a token is sent to the URL specified in next. See documentation for AuthSub login at: http://code.google.com/apis/accounts/docs/AuthSub.html Args: next: string The URL user will be sent to after logging in. scope: string or list of strings. The URLs of the services to be accessed. secure: boolean (optional) Determines whether or not the issued token is a secure token. session: boolean (optional) Determines whether or not the issued token can be upgraded to a session token. """ if not isinstance(scope, (list, tuple)): scope = (scope,) return gdata.auth.generate_auth_sub_url(next, scope, secure=secure, session=session, request_url='%s/accounts/AuthSubRequest' % AUTH_SERVER_HOST, domain=domain) def UpgradeToSessionToken(self, token=None): """Upgrades a single use AuthSub token to a session token. Args: token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken (optional) which is good for a single use but can be upgraded to a session token. If no token is passed in, the token is found by looking in the token_store by looking for a token for the current scope. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token TokenUpgradeFailed if the server responded to the request with an error. """ if token is None: scopes = lookup_scopes(self.service) if scopes: token = self.token_store.find_token(scopes[0]) else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken self.SetAuthSubToken(self.upgrade_to_session_token(token)) def upgrade_to_session_token(self, token): """Upgrades a single use AuthSub token to a session token. Args: token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken which is good for a single use but can be upgraded to a session token. Returns: The upgraded token as a gdata.auth.AuthSubToken object. Raises: TokenUpgradeFailed if the server responded to the request with an error. """ response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubSessionToken', headers={'Content-Type':'application/x-www-form-urlencoded'}) response_body = response.read() if response.status == 200: token.set_token_string( gdata.auth.token_from_http_body(response_body)) return token else: raise TokenUpgradeFailed({'status': response.status, 'reason': 'Non 200 response on upgrade', 'body': response_body}) def RevokeAuthSubToken(self): """Revokes an existing AuthSub token. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubRevokeToken', headers={'Content-Type':'application/x-www-form-urlencoded'}) if response.status == 200: self.token_store.remove_token(token) def AuthSubTokenInfo(self): """Fetches the AuthSub token's metadata from the server. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubTokenInfo', headers={'Content-Type':'application/x-www-form-urlencoded'}) result_body = response.read() if response.status == 200: return result_body else: raise RequestError, {'status': response.status, 'body': result_body} def GetWithRetries(self, uri, extra_headers=None, redirects_remaining=4, encoding='UTF-8', converter=None, num_retries=DEFAULT_NUM_RETRIES, delay=DEFAULT_DELAY, backoff=DEFAULT_BACKOFF, logger=None): """This is a wrapper method for Get with retrying capability. To avoid various errors while retrieving bulk entities by retrying specified times. Note this method relies on the time module and so may not be usable by default in Python2.2. Args: num_retries: Integer; the retry count. delay: Integer; the initial delay for retrying. backoff: Integer; how much the delay should lengthen after each failure. logger: An object which has a debug(str) method to receive logging messages. Recommended that you pass in the logging module. Raises: ValueError if any of the parameters has an invalid value. RanOutOfTries on failure after number of retries. """ # Moved import for time module inside this method since time is not a # default module in Python2.2. This method will not be usable in # Python2.2. import time if backoff <= 1: raise ValueError("backoff must be greater than 1") num_retries = int(num_retries) if num_retries < 0: raise ValueError("num_retries must be 0 or greater") if delay <= 0: raise ValueError("delay must be greater than 0") # Let's start mtries, mdelay = num_retries, delay while mtries > 0: if mtries != num_retries: if logger: logger.debug("Retrying: %s" % uri) try: rv = self.Get(uri, extra_headers=extra_headers, redirects_remaining=redirects_remaining, encoding=encoding, converter=converter) except SystemExit: # Allow this error raise except RequestError, e: # Error 500 is 'internal server error' and warrants a retry # Error 503 is 'service unavailable' and warrants a retry if e[0]['status'] not in [500, 503]: raise e # Else, fall through to the retry code... except Exception, e: if logger: logger.debug(e) # Fall through to the retry code... else: # This is the right path. return rv mtries -= 1 time.sleep(mdelay) mdelay *= backoff raise RanOutOfTries('Ran out of tries.') # CRUD operations def Get(self, uri, extra_headers=None, redirects_remaining=4, encoding='UTF-8', converter=None): """Query the GData API with the given URI The uri is the portion of the URI after the server value (ex: www.google.com). To perform a query against Google Base, set the server to 'base.google.com' and set the uri to '/base/feeds/...', where ... is your query. For example, to find snippets for all digital cameras uri should be set to: '/base/feeds/snippets?bq=digital+camera' Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. redirects_remaining: int (optional) Tracks the number of additional redirects this method will allow. If the service object receives a redirect and remaining is 0, it will not follow the redirect. This was added to avoid infinite redirect loops. encoding: string (optional) The character encoding for the server's response. Default is UTF-8 converter: func (optional) A function which will transform the server's results before it is returned. Example: use GDataFeedFromString to parse the server response as if it were a GDataFeed. Returns: If there is no ResultsTransformer specified in the call, a GDataFeed or GDataEntry depending on which is sent from the server. If the response is niether a feed or entry and there is no ResultsTransformer, return a string. If there is a ResultsTransformer, the returned value will be that of the ResultsTransformer function. """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if uri.find('?') > -1: uri += '&gsessionid=%s' % (self.__gsessionid,) else: uri += '?gsessionid=%s' % (self.__gsessionid,) server_response = self.request('GET', uri, headers=extra_headers) result_body = server_response.read() if server_response.status == 200: if converter: return converter(result_body) # There was no ResultsTransformer specified, so try to convert the # server's response into a GDataFeed. feed = gdata.GDataFeedFromString(result_body) if not feed: # If conversion to a GDataFeed failed, try to convert the server's # response to a GDataEntry. entry = gdata.GDataEntryFromString(result_body) if not entry: # The server's response wasn't a feed, or an entry, so return the # response body as a string. return result_body return entry return feed elif server_response.status == 302: if redirects_remaining > 0: location = (server_response.getheader('Location') or server_response.getheader('location')) if location is not None: m = re.compile('[\?\&]gsessionid=(\w*\-)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.Get(self, location, extra_headers, redirects_remaining - 1, encoding=encoding, converter=converter) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def GetMedia(self, uri, extra_headers=None): """Returns a MediaSource containing media and its metadata from the given URI string. """ response_handle = self.request('GET', uri, headers=extra_headers) return gdata.MediaSource(response_handle, response_handle.getheader( 'Content-Type'), response_handle.getheader('Content-Length')) def GetEntry(self, uri, extra_headers=None): """Query the GData API with the given URI and receive an Entry. See also documentation for gdata.service.Get Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. Returns: A GDataEntry built from the XML in the server's response. """ result = GDataService.Get(self, uri, extra_headers, converter=atom.EntryFromString) if isinstance(result, atom.Entry): return result else: raise UnexpectedReturnType, 'Server did not send an entry' def GetFeed(self, uri, extra_headers=None, converter=gdata.GDataFeedFromString): """Query the GData API with the given URI and receive a Feed. See also documentation for gdata.service.Get Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. Returns: A GDataFeed built from the XML in the server's response. """ result = GDataService.Get(self, uri, extra_headers, converter=converter) if isinstance(result, atom.Feed): return result else: raise UnexpectedReturnType, 'Server did not send a feed' def GetNext(self, feed): """Requests the next 'page' of results in the feed. This method uses the feed's next link to request an additional feed and uses the class of the feed to convert the results of the GET request. Args: feed: atom.Feed or a subclass. The feed should contain a next link and the type of the feed will be applied to the results from the server. The new feed which is returned will be of the same class as this feed which was passed in. Returns: A new feed representing the next set of results in the server's feed. The type of this feed will match that of the feed argument. """ next_link = feed.GetNextLink() # Create a closure which will convert an XML string to the class of # the feed object passed in. def ConvertToFeedClass(xml_string): return atom.CreateClassFromXMLString(feed.__class__, xml_string) # Make a GET request on the next link and use the above closure for the # converted which processes the XML string from the server. if next_link and next_link.href: return GDataService.Get(self, next_link.href, converter=ConvertToFeedClass) else: return None def Post(self, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4, media_source=None, converter=None): """Insert or update data into a GData service at the given URI. Args: data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The XML to be sent to the uri. uri: string The location (feed) to which the data should be inserted. Example: '/base/feeds/items'. extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. media_source: MediaSource (optional) Container for the media to be sent along with the entry, if provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the post succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ return GDataService.PostOrPut(self, 'POST', data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, redirects_remaining=redirects_remaining, media_source=media_source, converter=converter) def PostOrPut(self, verb, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4, media_source=None, converter=None): """Insert data into a GData service at the given URI. Args: verb: string, either 'POST' or 'PUT' data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The XML to be sent to the uri. uri: string The location (feed) to which the data should be inserted. Example: '/base/feeds/items'. extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. media_source: MediaSource (optional) Container for the media to be sent along with the entry, if provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the post succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if url_params is None: url_params = {} url_params['gsessionid'] = self.__gsessionid if data and media_source: if ElementTree.iselement(data): data_str = ElementTree.tostring(data) else: data_str = str(data) multipart = [] multipart.append('Media multipart posting\r\n--END_OF_PART\r\n' + \ 'Content-Type: application/atom+xml\r\n\r\n') multipart.append('\r\n--END_OF_PART\r\nContent-Type: ' + \ media_source.content_type+'\r\n\r\n') multipart.append('\r\n--END_OF_PART--\r\n') extra_headers['MIME-version'] = '1.0' extra_headers['Content-Length'] = str(len(multipart[0]) + len(multipart[1]) + len(multipart[2]) + len(data_str) + media_source.content_length) extra_headers['Content-Type'] = 'multipart/related; boundary=END_OF_PART' server_response = self.request(verb, uri, data=[multipart[0], data_str, multipart[1], media_source.file_handle, multipart[2]], headers=extra_headers, url_params=url_params) result_body = server_response.read() elif media_source or isinstance(data, gdata.MediaSource): if isinstance(data, gdata.MediaSource): media_source = data extra_headers['Content-Length'] = str(media_source.content_length) extra_headers['Content-Type'] = media_source.content_type server_response = self.request(verb, uri, data=media_source.file_handle, headers=extra_headers, url_params=url_params) result_body = server_response.read() else: http_data = data if 'Content-Type' not in extra_headers: content_type = 'application/atom+xml' extra_headers['Content-Type'] = content_type server_response = self.request(verb, uri, data=http_data, headers=extra_headers, url_params=url_params) result_body = server_response.read() # Server returns 201 for most post requests, but when performing a batch # request the server responds with a 200 on success. if server_response.status == 201 or server_response.status == 200: if converter: return converter(result_body) feed = gdata.GDataFeedFromString(result_body) if not feed: entry = gdata.GDataEntryFromString(result_body) if not entry: return result_body return entry return feed elif server_response.status == 302: if redirects_remaining > 0: location = (server_response.getheader('Location') or server_response.getheader('location')) if location is not None: m = re.compile('[\?\&]gsessionid=(\w*\-)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.PostOrPut(self, verb, data, location, extra_headers, url_params, escape_params, redirects_remaining - 1, media_source, converter=converter) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def Put(self, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=3, media_source=None, converter=None): """Updates an entry at the given URI. Args: data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The XML containing the updated data. uri: string A URI indicating entry to which the update will be applied. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the put succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ return GDataService.PostOrPut(self, 'PUT', data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, redirects_remaining=redirects_remaining, media_source=media_source, converter=converter) def Delete(self, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4): """Deletes the entry at the given URI. Args: uri: string The URI of the entry to be deleted. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type and Authorization headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: True if the entry was deleted. """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if url_params is None: url_params = {} url_params['gsessionid'] = self.__gsessionid server_response = self.request('DELETE', uri, headers=extra_headers, url_params=url_params) result_body = server_response.read() if server_response.status == 200: return True elif server_response.status == 302: if redirects_remaining > 0: location = (server_response.getheader('Location') or server_response.getheader('location')) if location is not None: m = re.compile('[\?\&]gsessionid=(\w*\-)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.Delete(self, location, extra_headers, url_params, escape_params, redirects_remaining - 1) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def ExtractToken(url, scopes_included_in_next=True): """Gets the AuthSub token from the current page's URL. Designed to be used on the URL that the browser is sent to after the user authorizes this application at the page given by GenerateAuthSubRequestUrl. Args: url: The current page's URL. It should contain the token as a URL parameter. Example: 'http://example.com/?...&token=abcd435' scopes_included_in_next: If True, this function looks for a scope value associated with the token. The scope is a URL parameter with the key set to SCOPE_URL_PARAM_NAME. This parameter should be present if the AuthSub request URL was generated using GenerateAuthSubRequestUrl with include_scope_in_next set to True. Returns: A tuple containing the token string and a list of scope strings for which this token should be valid. If the scope was not included in the URL, the tuple will contain (token, None). """ parsed = urlparse.urlparse(url) token = gdata.auth.AuthSubTokenFromUrl(parsed[4]) scopes = '' if scopes_included_in_next: for pair in parsed[4].split('&'): if pair.startswith('%s=' % SCOPE_URL_PARAM_NAME): scopes = urllib.unquote_plus(pair.split('=')[1]) return (token, scopes.split(' ')) def GenerateAuthSubRequestUrl(next, scopes, hd='default', secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', include_scopes_in_next=True): """Creates a URL to request an AuthSub token to access Google services. For more details on AuthSub, see the documentation here: http://code.google.com/apis/accounts/docs/AuthSub.html Args: next: The URL where the browser should be sent after the user authorizes the application. This page is responsible for receiving the token which is embeded in the URL as a parameter. scopes: The base URL to which access will be granted. Example: 'http://www.google.com/calendar/feeds' will grant access to all URLs in the Google Calendar data API. If you would like a token for multiple scopes, pass in a list of URL strings. hd: The domain to which the user's account belongs. This is set to the domain name if you are using Google Apps. Example: 'example.org' Defaults to 'default' secure: If set to True, all requests should be signed. The default is False. session: If set to True, the token received by the 'next' URL can be upgraded to a multiuse session token. If session is set to False, the token may only be used once and cannot be upgraded. Default is True. request_url: The base of the URL to which the user will be sent to authorize this application to access their data. The default is 'https://www.google.com/accounts/AuthSubRequest'. include_scopes_in_next: Boolean if set to true, the 'next' parameter will be modified to include the requested scope as a URL parameter. The key for the next's scope parameter will be SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as a parameter to the next URL, is that the page which receives the AuthSub token will be able to tell which URLs the token grants access to. Returns: A URL string to which the browser should be sent. """ if isinstance(scopes, list): scope = ' '.join(scopes) else: scope = scopes if include_scopes_in_next: if next.find('?') > -1: next += '&%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope}) else: next += '?%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope}) return gdata.auth.GenerateAuthSubUrl(next=next, scope=scope, secure=secure, session=session, request_url=request_url, domain=hd) class Query(dict): """Constructs a query URL to be used in GET requests Url parameters are created by adding key-value pairs to this object as a dict. For example, to add &max-results=25 to the URL do my_query['max-results'] = 25 Category queries are created by adding category strings to the categories member. All items in the categories list will be concatenated with the / symbol (symbolizing a category x AND y restriction). If you would like to OR 2 categories, append them as one string with a | between the categories. For example, do query.categories.append('Fritz|Laurie') to create a query like this feed/-/Fritz%7CLaurie . This query will look for results in both categories. """ def __init__(self, feed=None, text_query=None, params=None, categories=None): """Constructor for Query Args: feed: str (optional) The path for the feed (Examples: '/base/feeds/snippets' or 'calendar/feeds/jo@gmail.com/private/full' text_query: str (optional) The contents of the q query parameter. The contents of the text_query are URL escaped upon conversion to a URI. params: dict (optional) Parameter value string pairs which become URL params when translated to a URI. These parameters are added to the query's items (key-value pairs). categories: list (optional) List of category strings which should be included as query categories. See http://code.google.com/apis/gdata/reference.html#Queries for details. If you want to get results from category A or B (both categories), specify a single list item 'A|B'. """ self.feed = feed self.categories = [] if text_query: self.text_query = text_query if isinstance(params, dict): for param in params: self[param] = params[param] if isinstance(categories, list): for category in categories: self.categories.append(category) def _GetTextQuery(self): if 'q' in self.keys(): return self['q'] else: return None def _SetTextQuery(self, query): self['q'] = query text_query = property(_GetTextQuery, _SetTextQuery, doc="""The feed query's q parameter""") def _GetAuthor(self): if 'author' in self.keys(): return self['author'] else: return None def _SetAuthor(self, query): self['author'] = query author = property(_GetAuthor, _SetAuthor, doc="""The feed query's author parameter""") def _GetAlt(self): if 'alt' in self.keys(): return self['alt'] else: return None def _SetAlt(self, query): self['alt'] = query alt = property(_GetAlt, _SetAlt, doc="""The feed query's alt parameter""") def _GetUpdatedMin(self): if 'updated-min' in self.keys(): return self['updated-min'] else: return None def _SetUpdatedMin(self, query): self['updated-min'] = query updated_min = property(_GetUpdatedMin, _SetUpdatedMin, doc="""The feed query's updated-min parameter""") def _GetUpdatedMax(self): if 'updated-max' in self.keys(): return self['updated-max'] else: return None def _SetUpdatedMax(self, query): self['updated-max'] = query updated_max = property(_GetUpdatedMax, _SetUpdatedMax, doc="""The feed query's updated-max parameter""") def _GetPublishedMin(self): if 'published-min' in self.keys(): return self['published-min'] else: return None def _SetPublishedMin(self, query): self['published-min'] = query published_min = property(_GetPublishedMin, _SetPublishedMin, doc="""The feed query's published-min parameter""") def _GetPublishedMax(self): if 'published-max' in self.keys(): return self['published-max'] else: return None def _SetPublishedMax(self, query): self['published-max'] = query published_max = property(_GetPublishedMax, _SetPublishedMax, doc="""The feed query's published-max parameter""") def _GetStartIndex(self): if 'start-index' in self.keys(): return self['start-index'] else: return None def _SetStartIndex(self, query): if not isinstance(query, str): query = str(query) self['start-index'] = query start_index = property(_GetStartIndex, _SetStartIndex, doc="""The feed query's start-index parameter""") def _GetMaxResults(self): if 'max-results' in self.keys(): return self['max-results'] else: return None def _SetMaxResults(self, query): if not isinstance(query, str): query = str(query) self['max-results'] = query max_results = property(_GetMaxResults, _SetMaxResults, doc="""The feed query's max-results parameter""") def _GetOrderBy(self): if 'orderby' in self.keys(): return self['orderby'] else: return None def _SetOrderBy(self, query): self['orderby'] = query orderby = property(_GetOrderBy, _SetOrderBy, doc="""The feed query's orderby parameter""") def ToUri(self): q_feed = self.feed or '' category_string = '/'.join( [urllib.quote_plus(c) for c in self.categories]) # Add categories to the feed if there are any. if len(self.categories) > 0: q_feed = q_feed + '/-/' + category_string return atom.service.BuildUri(q_feed, self) def __str__(self): return self.ToUri()
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """DocsService extends the GDataService to streamline Google Documents operations. DocsService: Provides methods to query feeds and manipulate items. Extends GDataService. DocumentQuery: Queries a Google Document list feed. DocumentAclQuery: Queries a Google Document Acl feed. """ __author__ = ('api.jfisher (Jeff Fisher), ' 'e.bidelman (Eric Bidelman)') import re import atom import gdata.service import gdata.docs import urllib # XML Namespaces used in Google Documents entities. DATA_KIND_SCHEME = gdata.GDATA_NAMESPACE + '#kind' DOCUMENT_LABEL = 'document' SPREADSHEET_LABEL = 'spreadsheet' PRESENTATION_LABEL = 'presentation' FOLDER_LABEL = 'folder' PDF_LABEL = 'pdf' LABEL_SCHEME = gdata.GDATA_NAMESPACE + '/labels' STARRED_LABEL_TERM = LABEL_SCHEME + '#starred' TRASHED_LABEL_TERM = LABEL_SCHEME + '#trashed' HIDDEN_LABEL_TERM = LABEL_SCHEME + '#hidden' MINE_LABEL_TERM = LABEL_SCHEME + '#mine' PRIVATE_LABEL_TERM = LABEL_SCHEME + '#private' SHARED_WITH_DOMAIN_LABEL_TERM = LABEL_SCHEME + '#shared-with-domain' VIEWED_LABEL_TERM = LABEL_SCHEME + '#viewed' FOLDERS_SCHEME_PREFIX = gdata.docs.DOCUMENTS_NAMESPACE + '/folders/' # File extensions of documents that are permitted to be uploaded or downloaded. SUPPORTED_FILETYPES = { 'CSV': 'text/csv', 'TSV': 'text/tab-separated-values', 'TAB': 'text/tab-separated-values', 'DOC': 'application/msword', 'DOCX': ('application/vnd.openxmlformats-officedocument.' 'wordprocessingml.document'), 'ODS': 'application/x-vnd.oasis.opendocument.spreadsheet', 'ODT': 'application/vnd.oasis.opendocument.text', 'RTF': 'application/rtf', 'SXW': 'application/vnd.sun.xml.writer', 'TXT': 'text/plain', 'XLS': 'application/vnd.ms-excel', 'XLSX': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'PDF': 'application/pdf', 'PNG': 'image/png', 'PPT': 'application/vnd.ms-powerpoint', 'PPS': 'application/vnd.ms-powerpoint', 'HTM': 'text/html', 'HTML': 'text/html', 'ZIP': 'application/zip', 'SWF': 'application/x-shockwave-flash' } class DocsService(gdata.service.GDataService): """Client extension for the Google Documents service Document List feed.""" __FILE_EXT_PATTERN = re.compile('.*\.([a-zA-Z]{3,}$)') __RESOURCE_ID_PATTERN = re.compile('^([a-z]*)(:|%3A)([\w-]*)$') def __init__(self, email=None, password=None, source=None, server='docs.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Documents service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'docs.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='writely', source=source, server=server, additional_headers=additional_headers, **kwargs) self.ssl = True def _MakeKindCategory(self, label): if label is None: return None return atom.Category(scheme=DATA_KIND_SCHEME, term=gdata.docs.DOCUMENTS_NAMESPACE + '#' + label, label=label) def _MakeContentLinkFromId(self, resource_id): match = self.__RESOURCE_ID_PATTERN.match(resource_id) label = match.group(1) doc_id = match.group(3) if label == DOCUMENT_LABEL: return '/feeds/download/documents/Export?docId=%s' % doc_id if label == PRESENTATION_LABEL: return '/feeds/download/presentations/Export?docId=%s' % doc_id if label == SPREADSHEET_LABEL: return ('https://spreadsheets.google.com/feeds/download/spreadsheets/' 'Export?key=%s' % doc_id) raise ValueError, 'Invalid resource id: %s' % resource_id def _UploadFile(self, media_source, title, category, folder_or_uri=None): """Uploads a file to the Document List feed. Args: media_source: A gdata.MediaSource object containing the file to be uploaded. title: string The title of the document on the server after being uploaded. category: An atom.Category object specifying the appropriate document type. folder_or_uri: DocumentListEntry or string (optional) An object with a link to a folder or a uri to a folder to upload to. Note: A valid uri for a folder is of the form: /feeds/folders/private/full/folder%3Afolder_id Returns: A DocumentListEntry containing information about the document created on the Google Documents service. """ if folder_or_uri: try: uri = folder_or_uri.content.src except AttributeError: uri = folder_or_uri else: uri = '/feeds/documents/private/full' entry = gdata.docs.DocumentListEntry() entry.title = atom.Title(text=title) if category is not None: entry.category.append(category) entry = self.Post(entry, uri, media_source=media_source, extra_headers={'Slug': media_source.file_name}, converter=gdata.docs.DocumentListEntryFromString) return entry def _DownloadFile(self, uri, file_path): """Downloads a file. Args: uri: string The full Export URL to download the file from. file_path: string The full path to save the file to. Raises: RequestError: on error response from server. """ server_response = self.request('GET', uri) response_body = server_response.read() timeout = 5 while server_response.status == 302 and timeout > 0: server_response = self.request('GET', server_response.getheader('Location')) response_body = server_response.read() timeout -= 1 if server_response.status != 200: raise gdata.service.RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': response_body} f = open(file_path, 'wb') f.write(response_body) f.flush() f.close() def MoveIntoFolder(self, source_entry, folder_entry): """Moves a document into a folder in the Document List Feed. Args: source_entry: DocumentListEntry An object representing the source document/folder. folder_entry: DocumentListEntry An object with a link to the destination folder. Returns: A DocumentListEntry containing information about the document created on the Google Documents service. """ entry = gdata.docs.DocumentListEntry() entry.id = source_entry.id entry = self.Post(entry, folder_entry.content.src, converter=gdata.docs.DocumentListEntryFromString) return entry def Query(self, uri, converter=gdata.docs.DocumentListFeedFromString): """Queries the Document List feed and returns the resulting feed of entries. Args: uri: string The full URI to be queried. This can contain query parameters, a hostname, or simply the relative path to a Document List feed. The DocumentQuery object is useful when constructing query parameters. converter: func (optional) A function which will be executed on the retrieved item, generally to render it into a Python object. By default the DocumentListFeedFromString function is used to return a DocumentListFeed object. This is because most feed queries will result in a feed and not a single entry. """ return self.Get(uri, converter=converter) def QueryDocumentListFeed(self, uri): """Retrieves a DocumentListFeed by retrieving a URI based off the Document List feed, including any query parameters. A DocumentQuery object can be used to construct these parameters. Args: uri: string The URI of the feed being retrieved possibly with query parameters. Returns: A DocumentListFeed object representing the feed returned by the server. """ return self.Get(uri, converter=gdata.docs.DocumentListFeedFromString) def GetDocumentListEntry(self, uri): """Retrieves a particular DocumentListEntry by its unique URI. Args: uri: string The unique URI of an entry in a Document List feed. Returns: A DocumentListEntry object representing the retrieved entry. """ return self.Get(uri, converter=gdata.docs.DocumentListEntryFromString) def GetDocumentListFeed(self, uri=None): """Retrieves a feed containing all of a user's documents. Args: uri: string A full URI to query the Document List feed. """ if not uri: uri = gdata.docs.service.DocumentQuery().ToUri() return self.QueryDocumentListFeed(uri) def GetDocumentListAclEntry(self, uri): """Retrieves a particular DocumentListAclEntry by its unique URI. Args: uri: string The unique URI of an entry in a Document List feed. Returns: A DocumentListAclEntry object representing the retrieved entry. """ return self.Get(uri, converter=gdata.docs.DocumentListAclEntryFromString) def GetDocumentListAclFeed(self, uri): """Retrieves a feed containing all of a user's documents. Args: uri: string The URI of a document's Acl feed to retrieve. Returns: A DocumentListAclFeed object representing the ACL feed returned by the server. """ return self.Get(uri, converter=gdata.docs.DocumentListAclFeedFromString) def Upload(self, media_source, title, folder_or_uri=None, label=None): """Uploads a document inside of a MediaSource object to the Document List feed with the given title. Args: media_source: MediaSource The gdata.MediaSource object containing a document file to be uploaded. title: string The title of the document on the server after being uploaded. folder_or_uri: DocumentListEntry or string (optional) An object with a link to a folder or a uri to a folder to upload to. Note: A valid uri for a folder is of the form: /feeds/folders/private/full/folder%3Afolder_id label: optional label describing the type of the document to be created. Returns: A DocumentListEntry containing information about the document created on the Google Documents service. """ return self._UploadFile(media_source, title, self._MakeKindCategory(label), folder_or_uri) def Download(self, entry_or_id_or_url, file_path, export_format=None, gid=None, extra_params=None): """Downloads a document from the Document List. Args: entry_or_id_or_url: a DocumentListEntry, or the resource id of an entry, or a url to download from (such as the content src). file_path: string The full path to save the file to. export_format: the format to convert to, if conversion is required. gid: grid id, for downloading a single grid of a spreadsheet extra_params: a map of any further parameters to control how the document is downloaded Raises: RequestError if the service does not respond with success """ if isinstance(entry_or_id_or_url, gdata.docs.DocumentListEntry): url = entry_or_id_or_url.content.src else: if self.__RESOURCE_ID_PATTERN.match(entry_or_id_or_url): url = self._MakeContentLinkFromId(entry_or_id_or_url) else: url = entry_or_id_or_url if export_format is not None: if url.find('/Export?') == -1: raise gdata.service.Error, ('This entry cannot be exported ' 'as a different format') url += '&exportFormat=%s' % export_format if gid is not None: if url.find('spreadsheets') == -1: raise gdata.service.Error, 'grid id param is not valid for this entry' url += '&gid=%s' % gid if extra_params: url += '&' + urllib.urlencode(extra_params) self._DownloadFile(url, file_path) def Export(self, entry_or_id_or_url, file_path, gid=None, extra_params=None): """Downloads a document from the Document List in a different format. Args: entry_or_id_or_url: a DocumentListEntry, or the resource id of an entry, or a url to download from (such as the content src). file_path: string The full path to save the file to. The export format is inferred from the the file extension. gid: grid id, for downloading a single grid of a spreadsheet extra_params: a map of any further parameters to control how the document is downloaded Raises: RequestError if the service does not respond with success """ ext = None match = self.__FILE_EXT_PATTERN.match(file_path) if match: ext = match.group(1) self.Download(entry_or_id_or_url, file_path, ext, gid, extra_params) def CreateFolder(self, title, folder_or_uri=None): """Creates a folder in the Document List feed. Args: title: string The title of the folder on the server after being created. folder_or_uri: DocumentListEntry or string (optional) An object with a link to a folder or a uri to a folder to upload to. Note: A valid uri for a folder is of the form: /feeds/folders/private/full/folder%3Afolder_id Returns: A DocumentListEntry containing information about the folder created on the Google Documents service. """ if folder_or_uri: try: uri = folder_or_uri.content.src except AttributeError: uri = folder_or_uri else: uri = '/feeds/documents/private/full' folder_entry = gdata.docs.DocumentListEntry() folder_entry.title = atom.Title(text=title) folder_entry.category.append(self._MakeKindCategory(FOLDER_LABEL)) folder_entry = self.Post(folder_entry, uri, converter=gdata.docs.DocumentListEntryFromString) return folder_entry def MoveOutOfFolder(self, source_entry): """Moves a document into a folder in the Document List Feed. Args: source_entry: DocumentListEntry An object representing the source document/folder. Returns: True if the entry was moved out. """ return self.Delete(source_entry.GetEditLink().href) # Deprecated methods #@atom.deprecated('Please use Upload instead') def UploadPresentation(self, media_source, title, folder_or_uri=None): """Uploads a presentation inside of a MediaSource object to the Document List feed with the given title. This method is deprecated, use Upload instead. Args: media_source: MediaSource The MediaSource object containing a presentation file to be uploaded. title: string The title of the presentation on the server after being uploaded. folder_or_uri: DocumentListEntry or string (optional) An object with a link to a folder or a uri to a folder to upload to. Note: A valid uri for a folder is of the form: /feeds/folders/private/full/folder%3Afolder_id Returns: A DocumentListEntry containing information about the presentation created on the Google Documents service. """ return self._UploadFile( media_source, title, self._MakeKindCategory(PRESENTATION_LABEL), folder_or_uri=folder_or_uri) UploadPresentation = atom.deprecated('Please use Upload instead')( UploadPresentation) #@atom.deprecated('Please use Upload instead') def UploadSpreadsheet(self, media_source, title, folder_or_uri=None): """Uploads a spreadsheet inside of a MediaSource object to the Document List feed with the given title. This method is deprecated, use Upload instead. Args: media_source: MediaSource The MediaSource object containing a spreadsheet file to be uploaded. title: string The title of the spreadsheet on the server after being uploaded. folder_or_uri: DocumentListEntry or string (optional) An object with a link to a folder or a uri to a folder to upload to. Note: A valid uri for a folder is of the form: /feeds/folders/private/full/folder%3Afolder_id Returns: A DocumentListEntry containing information about the spreadsheet created on the Google Documents service. """ return self._UploadFile( media_source, title, self._MakeKindCategory(SPREADSHEET_LABEL), folder_or_uri=folder_or_uri) UploadSpreadsheet = atom.deprecated('Please use Upload instead')( UploadSpreadsheet) #@atom.deprecated('Please use Upload instead') def UploadDocument(self, media_source, title, folder_or_uri=None): """Uploads a document inside of a MediaSource object to the Document List feed with the given title. This method is deprecated, use Upload instead. Args: media_source: MediaSource The gdata.MediaSource object containing a document file to be uploaded. title: string The title of the document on the server after being uploaded. folder_or_uri: DocumentListEntry or string (optional) An object with a link to a folder or a uri to a folder to upload to. Note: A valid uri for a folder is of the form: /feeds/folders/private/full/folder%3Afolder_id Returns: A DocumentListEntry containing information about the document created on the Google Documents service. """ return self._UploadFile( media_source, title, self._MakeKindCategory(DOCUMENT_LABEL), folder_or_uri=folder_or_uri) UploadDocument = atom.deprecated('Please use Upload instead')( UploadDocument) """Calling any of these functions is the same as calling Export""" DownloadDocument = atom.deprecated('Please use Export instead')(Export) DownloadPresentation = atom.deprecated('Please use Export instead')(Export) DownloadSpreadsheet = atom.deprecated('Please use Export instead')(Export) """Calling any of these functions is the same as calling MoveIntoFolder""" MoveDocumentIntoFolder = atom.deprecated( 'Please use MoveIntoFolder instead')(MoveIntoFolder) MovePresentationIntoFolder = atom.deprecated( 'Please use MoveIntoFolder instead')(MoveIntoFolder) MoveSpreadsheetIntoFolder = atom.deprecated( 'Please use MoveIntoFolder instead')(MoveIntoFolder) MoveFolderIntoFolder = atom.deprecated( 'Please use MoveIntoFolder instead')(MoveIntoFolder) class DocumentQuery(gdata.service.Query): """Object used to construct a URI to query the Google Document List feed""" def __init__(self, feed='/feeds/documents', visibility='private', projection='full', text_query=None, params=None, categories=None): """Constructor for Document List Query Args: feed: string (optional) The path for the feed. (e.g. '/feeds/documents') visibility: string (optional) The visibility chosen for the current feed. projection: string (optional) The projection chosen for the current feed. text_query: string (optional) The contents of the q query parameter. This string is URL escaped upon conversion to a URI. params: dict (optional) Parameter value string pairs which become URL params when translated to a URI. These parameters are added to the query's items. categories: list (optional) List of category strings which should be included as query categories. See gdata.service.Query for additional documentation. Yields: A DocumentQuery object used to construct a URI based on the Document List feed. """ self.visibility = visibility self.projection = projection gdata.service.Query.__init__(self, feed, text_query, params, categories) def ToUri(self): """Generates a URI from the query parameters set in the object. Returns: A string containing the URI used to retrieve entries from the Document List feed. """ old_feed = self.feed self.feed = '/'.join([old_feed, self.visibility, self.projection]) new_feed = gdata.service.Query.ToUri(self) self.feed = old_feed return new_feed def AddNamedFolder(self, email, folder_name): """Adds a named folder category, qualified by a schema. This function lets you query for documents that are contained inside a named folder without fear of collision with other categories. Args: email: string The email of the user who owns the folder. folder_name: string The name of the folder. Returns: The string of the category that was added to the object. """ category = '{%s%s}%s' % (FOLDERS_SCHEME_PREFIX, email, folder_name) self.categories.append(category) return category def RemoveNamedFolder(self, email, folder_name): """Removes a named folder category, qualified by a schema. Args: email: string The email of the user who owns the folder. folder_name: string The name of the folder. Returns: The string of the category that was removed to the object. """ category = '{%s%s}%s' % (FOLDERS_SCHEME_PREFIX, email, folder_name) self.categories.remove(category) return category class DocumentAclQuery(gdata.service.Query): """Object used to construct a URI to query a Document's ACL feed""" def __init__(self, resource_id, feed='/feeds/acl/private/full'): """Constructor for Document ACL Query Args: resource_id: string The resource id. (e.g. 'document%3Adocument_id', 'spreadsheet%3Aspreadsheet_id', etc.) feed: string (optional) The path for the feed. (e.g. '/feeds/acl/private/full') Yields: A DocumentAclQuery object used to construct a URI based on the Document ACL feed. """ self.resource_id = resource_id gdata.service.Query.__init__(self, feed) def ToUri(self): """Generates a URI from the query parameters set in the object. Returns: A string containing the URI used to retrieve entries from the Document ACL feed. """ return '%s/%s' % (gdata.service.Query.ToUri(self), self.resource_id)
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """DocsClient extends gdata.client.GDClient to streamline DocList API calls.""" __author__ = 'e.bidelman (Eric Bidelman)' import mimetypes import urllib import atom.data import atom.http_core import gdata.client import gdata.docs.data import gdata.gauth # Feed URI templates DOCLIST_FEED_URI = '/feeds/default/private/full/' FOLDERS_FEED_TEMPLATE = DOCLIST_FEED_URI + '%s/contents' ACL_FEED_TEMPLATE = DOCLIST_FEED_URI + '%s/acl' REVISIONS_FEED_TEMPLATE = DOCLIST_FEED_URI + '%s/revisions' class DocsClient(gdata.client.GDClient): """Client extension for the Google Documents List API.""" host = 'docs.google.com' # default server for the API api_version = '3.0' # default major version for the service. auth_service = 'writely' auth_scopes = gdata.gauth.AUTH_SCOPES['writely'] ssl = True def __init__(self, auth_token=None, **kwargs): """Constructs a new client for the DocList API. Args: auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: The other parameters to pass to gdata.client.GDClient constructor. """ gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs) def get_file_content(self, uri, auth_token=None, **kwargs): """Fetches the file content from the specified uri. This method is useful for downloading/exporting a file within enviornments like Google App Engine, where the user does not have the ability to write the file to a local disk. Args: uri: str The full URL to fetch the file contents from. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.request(). Returns: The binary file content. Raises: gdata.client.RequestError: on error response from server. """ server_response = self.request('GET', uri, auth_token=auth_token, **kwargs) if server_response.status != 200: raise gdata.client.RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': server_response.read()} return server_response.read() GetFileContent = get_file_content def _download_file(self, uri, file_path, auth_token=None, **kwargs): """Downloads a file to disk from the specified URI. Note: to download a file in memory, use the GetFileContent() method. Args: uri: str The full URL to download the file from. file_path: str The full path to save the file to. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_file_content(). Raises: gdata.client.RequestError: on error response from server. """ f = open(file_path, 'wb') try: f.write(self.get_file_content(uri, auth_token=auth_token, **kwargs)) except gdata.client.RequestError, e: f.close() raise e f.flush() f.close() _DownloadFile = _download_file def get_doclist(self, uri=None, limit=None, auth_token=None, **kwargs): """Retrieves the main doclist feed containing the user's items. Args: uri: str (optional) A URI to query the doclist feed. limit: int (optional) A maximum cap for the number of results to return in the feed. By default, the API returns a maximum of 100 per page. Thus, if you set limit=5000, you will get <= 5000 documents (guarenteed no more than 5000), and will need to follow the feed's next links (feed.GetNextLink()) to the rest. See get_everything(). Similarly, if you set limit=50, only <= 50 documents are returned. Note: if the max-results parameter is set in the uri parameter, it is chosen over a value set for limit. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_feed(). Returns: gdata.docs.data.DocList feed. """ if uri is None: uri = DOCLIST_FEED_URI if isinstance(uri, (str, unicode)): uri = atom.http_core.Uri.parse_uri(uri) # Add max-results param if it wasn't included in the uri. if limit is not None and not 'max-results' in uri.query: uri.query['max-results'] = limit return self.get_feed(uri, desired_class=gdata.docs.data.DocList, auth_token=auth_token, **kwargs) GetDocList = get_doclist def get_doc(self, resource_id, etag=None, auth_token=None, uri=None, **kwargs): """Retrieves a particular document given by its resource id. Args: resource_id: str The document/item's resource id. Example spreadsheet: 'spreadsheet%3A0A1234567890'. etag: str (optional) The document/item's etag value to be used in a conditional GET. See http://code.google.com/apis/documents/docs/3.0/ developers_guide_protocol.html#RetrievingCached. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. uri: (optional) URI to use for this request. Translates to uri + resource_id. kwargs: Other parameters to pass to self.get_entry(). Returns: A gdata.docs.data.DocsEntry object representing the retrieved entry. Raises: ValueError if the resource_id is not a valid format. """ match = gdata.docs.data.RESOURCE_ID_PATTERN.match(resource_id) if match is None: raise ValueError, 'Invalid resource id: %s' % resource_id if uri is None: uri = DOCLIST_FEED_URI return self.get_entry( uri + resource_id, etag=etag, desired_class=gdata.docs.data.DocsEntry, auth_token=auth_token, **kwargs) GetDoc = get_doc def get_everything(self, uri=None, auth_token=None, **kwargs): """Retrieves the user's entire doc list. The method makes multiple HTTP requests (by following the feed's next links) in order to fetch the user's entire document list. Args: uri: str (optional) A URI to query the doclist feed with. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.GetDocList(). Returns: A list of gdata.docs.data.DocsEntry objects representing the retrieved entries. """ if uri is None: uri = DOCLIST_FEED_URI feed = self.GetDocList(uri=uri, auth_token=auth_token, **kwargs) entries = feed.entry while feed.GetNextLink() is not None: feed = self.GetDocList( feed.GetNextLink().href, auth_token=auth_token, **kwargs) entries.extend(feed.entry) return entries GetEverything = get_everything def get_acl_permissions(self, resource_id, auth_token=None, uri=None, **kwargs): """Retrieves a the ACL sharing permissions for a document. Args: resource_id: str The document/item's resource id. Example for pdf: 'pdf%3A0A1234567890'. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. uri: (optional) URI to use when making this request. Must be a template, with a %s for where to put the resource_id. kwargs: Other parameters to pass to self.get_feed(). Returns: A gdata.docs.data.AclFeed object representing the document's ACL entries. Raises: ValueError if the resource_id is not a valid format. """ match = gdata.docs.data.RESOURCE_ID_PATTERN.match(resource_id) if match is None: raise ValueError, 'Invalid resource id: %s' % resource_id if uri is None: uri = ACL_FEED_TEMPLATE return self.get_feed( uri % resource_id, desired_class=gdata.docs.data.AclFeed, auth_token=auth_token, **kwargs) GetAclPermissions = get_acl_permissions def get_revisions(self, resource_id, auth_token=None, uri=None, **kwargs): """Retrieves the revision history for a document. Args: resource_id: str The document/item's resource id. Example for pdf: 'pdf%3A0A1234567890'. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. uri: (optional) URI to use when making this request. Must be a template, with a %s for where to put the resource_id. kwargs: Other parameters to pass to self.get_feed(). Returns: A gdata.docs.data.RevisionFeed representing the document's revisions. Raises: ValueError if the resource_id is not a valid format. """ match = gdata.docs.data.RESOURCE_ID_PATTERN.match(resource_id) if match is None: raise ValueError, 'Invalid resource id: %s' % resource_id if uri is None: uri = REVISIONS_FEED_TEMPLATE return self.get_feed( uri % resource_id, desired_class=gdata.docs.data.RevisionFeed, auth_token=auth_token, **kwargs) GetRevisions = get_revisions def create(self, doc_type, title, folder_or_id=None, writers_can_invite=None, auth_token=None, uri=None, **kwargs): """Creates a new item in the user's doclist. Args: doc_type: str The type of object to create. For example: 'document', 'spreadsheet', 'folder', 'presentation'. title: str A title for the document. folder_or_id: gdata.docs.data.DocsEntry or str (optional) Folder entry or the resouce id of a folder to create the object under. Note: A valid resource id for a folder is of the form: folder%3Afolder_id. writers_can_invite: bool (optional) False prevents collaborators from being able to invite others to edit or view the document. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. uri: (optional) URI to use when making this request. Must be a template, with a %s for where to put the resource_id. kwargs: Other parameters to pass to self.post(). Returns: gdata.docs.data.DocsEntry containing information newly created item. """ entry = gdata.docs.data.DocsEntry(title=atom.data.Title(text=title)) entry.category.append(gdata.docs.data.make_kind_category(doc_type)) if isinstance(writers_can_invite, gdata.docs.data.WritersCanInvite): entry.writers_can_invite = writers_can_invite elif isinstance(writers_can_invite, bool): entry.writers_can_invite = gdata.docs.data.WritersCanInvite( value=str(writers_can_invite).lower()) if uri is None: uri = DOCLIST_FEED_URI if folder_or_id is not None: if isinstance(folder_or_id, gdata.docs.data.DocsEntry): # Verify that we're uploading the resource into to a folder. if folder_or_id.get_document_type() == gdata.docs.data.FOLDER_LABEL: uri = folder_or_id.content.src else: raise gdata.client.Error, 'Trying to upload item to a non-folder.' else: uri = FOLDERS_FEED_TEMPLATE % folder_or_id return self.post(entry, uri, auth_token=auth_token, **kwargs) Create = create def copy(self, source_entry, title, auth_token=None, uri=None, **kwargs): """Copies a native Google document, spreadsheet, or presentation. Note: arbitrary file types and PDFs do not support this feature. Args: source_entry: gdata.docs.data.DocsEntry An object representing the source document/folder. title: str A title for the new document. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. uri: (optional) URI to use when making this request. Must be a template, with a %s for where to put the resource_id. kwargs: Other parameters to pass to self.post(). Returns: A gdata.docs.data.DocsEntry of the duplicated document. """ entry = gdata.docs.data.DocsEntry( title=atom.data.Title(text=title), id=atom.data.Id(text=source_entry.GetSelfLink().href)) if uri is None: uri = DOCLIST_FEED_URI return self.post(entry, uri, auth_token=auth_token, **kwargs) Copy = copy def move(self, source_entry, folder_entry=None, keep_in_folders=False, auth_token=None, delete_folder_uri=None, folder_uri=None, **kwargs): """Moves an item into a different folder (or to the root document list). Args: source_entry: gdata.docs.data.DocsEntry An object representing the source document/folder. folder_entry: gdata.docs.data.DocsEntry (optional) An object representing the destination folder. If None, set keep_in_folders to True to remove the item from all parent folders. keep_in_folders: boolean (optional) If True, the source entry is not removed from any existing parent folders it is in. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. delete_folder_uri: (optional) URI to use when making this request. Must be a template, with a %s for where to put the resource_id. folder_uri: (optional) URI to use when making this request. Must be a template, with a %s for where to put the resource_id. kwargs: Other parameters to pass to self.post(). Returns: A gdata.docs.data.DocsEntry of the moved entry or True if just moving the item out of all folders (e.g. Move(source_entry)). """ entry = gdata.docs.data.DocsEntry(id=source_entry.id) # Remove the item from any folders it is already in. if not keep_in_folders: construct_uri = False if delete_folder_uri is None: construct_uri = True for folder in source_entry.InFolders(): if construct_uri: uri = '%s/contents/%s' % ( folder.href, urllib.quote(source_entry.resource_id.text)) else: uri = delete_folder_uri % urllib.quote(source_entry.resource_id.text) self.delete(uri, force=True) # If we're moving the resource into a folder, verify it is a folder entry. if folder_entry is not None: if folder_entry.get_document_type() == gdata.docs.data.FOLDER_LABEL: if folder_uri is None: folder_uri = folder_entry.content.src return self.post(entry, folder_uri, auth_token=auth_token, **kwargs) else: raise gdata.client.Error, 'Trying to move item into a non-folder.' return True Move = move def upload(self, media, title, folder_or_uri=None, content_type=None, auth_token=None, **kwargs): """Uploads a file to Google Docs. Args: media: A gdata.data.MediaSource object containing the file to be uploaded or a string of the filepath. title: str The title of the document on the server after being uploaded. folder_or_uri: gdata.docs.data.DocsEntry or str (optional) An object with a link to the folder or the uri to upload the file to. Note: A valid uri for a folder is of the form: /feeds/default/private/full/folder%3Afolder_id/contents content_type: str (optional) The file's mimetype. If not provided, the one in the media source object is used or the mimetype is inferred from the filename (if media is a string). When media is a filename, it is always recommended to pass in a content type. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.post(). Returns: A gdata.docs.data.DocsEntry containing information about uploaded doc. """ uri = None if folder_or_uri is not None: if isinstance(folder_or_uri, gdata.docs.data.DocsEntry): # Verify that we're uploading the resource into to a folder. if folder_or_uri.get_document_type() == gdata.docs.data.FOLDER_LABEL: uri = folder_or_uri.content.src else: raise gdata.client.Error, 'Trying to upload item to a non-folder.' else: uri = folder_or_uri else: uri = DOCLIST_FEED_URI # Create media source if media is a filepath. if isinstance(media, (str, unicode)): mimetype = mimetypes.guess_type(media)[0] if mimetype is None and content_type is None: raise ValueError, ("Unknown mimetype. Please pass in the file's " "content_type") else: media = gdata.data.MediaSource(file_path=media, content_type=content_type) entry = gdata.docs.data.DocsEntry(title=atom.data.Title(text=title)) return self.post(entry, uri, media_source=media, desired_class=gdata.docs.data.DocsEntry, auth_token=auth_token, **kwargs) Upload = upload def download(self, entry_or_id_or_url, file_path, extra_params=None, auth_token=None, **kwargs): """Downloads a file from the Document List to local disk. Note: to download a file in memory, use the GetFileContent() method. Args: entry_or_id_or_url: gdata.docs.data.DocsEntry or string representing a resource id or URL to download the document from (such as the content src link). file_path: str The full path to save the file to. extra_params: dict (optional) A map of any further parameters to control how the document is downloaded/exported. For example, exporting a spreadsheet as a .csv: extra_params={'gid': 0, 'exportFormat': 'csv'} auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self._download_file(). Raises: gdata.client.RequestError if the download URL is malformed or the server's response was not successful. ValueError if entry_or_id_or_url was a resource id for a filetype in which the download link cannot be manually constructed (e.g. pdf). """ if isinstance(entry_or_id_or_url, gdata.docs.data.DocsEntry): url = entry_or_id_or_url.content.src else: if gdata.docs.data.RESOURCE_ID_PATTERN.match(entry_or_id_or_url): url = gdata.docs.data.make_content_link_from_resource_id( entry_or_id_or_url) else: url = entry_or_id_or_url if extra_params is not None: if 'exportFormat' in extra_params and url.find('/Export?') == -1: raise gdata.client.Error, ('This entry type cannot be exported ' 'as a different format.') if 'gid' in extra_params and url.find('spreadsheets') == -1: raise gdata.client.Error, 'gid param is not valid for this doc type.' url += '&' + urllib.urlencode(extra_params) self._download_file(url, file_path, auth_token=auth_token, **kwargs) Download = download def export(self, entry_or_id_or_url, file_path, gid=None, auth_token=None, **kwargs): """Exports a document from the Document List in a different format. Args: entry_or_id_or_url: gdata.docs.data.DocsEntry or string representing a resource id or URL to download the document from (such as the content src link). file_path: str The full path to save the file to. The export format is inferred from the the file extension. gid: str (optional) grid id for downloading a single grid of a spreadsheet. The param should only be used for .csv and .tsv spreadsheet exports. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.download(). Raises: gdata.client.RequestError if the download URL is malformed or the server's response was not successful. """ extra_params = {} match = gdata.docs.data.FILE_EXT_PATTERN.match(file_path) if match: extra_params['exportFormat'] = match.group(1) if gid is not None: extra_params['gid'] = gid self.download(entry_or_id_or_url, file_path, extra_params, auth_token=auth_token, **kwargs) Export = export class DocsQuery(gdata.client.Query): def __init__(self, title=None, title_exact=None, opened_min=None, opened_max=None, edited_min=None, edited_max=None, owner=None, writer=None, reader=None, show_folders=None, show_deleted=None, ocr=None, target_language=None, source_language=None, convert=None, **kwargs): """Constructs a query URL for the Google Documents List API. Args: title: str (optional) Specifies the search terms for the title of a document. This parameter used without title_exact will only submit partial queries, not exact queries. title_exact: str (optional) Meaningless without title. Possible values are 'true' and 'false'. Note: Matches are case-insensitive. opened_min: str (optional) Lower bound on the last time a document was opened by the current user. Use the RFC 3339 timestamp format. For example: opened_min='2005-08-09T09:57:00-08:00'. opened_max: str (optional) Upper bound on the last time a document was opened by the current user. (See also opened_min.) edited_min: str (optional) Lower bound on the last time a document was edited by the current user. This value corresponds to the edited.text value in the doc's entry object, which represents changes to the document's content or metadata. Use the RFC 3339 timestamp format. For example: edited_min='2005-08-09T09:57:00-08:00' edited_max: str (optional) Upper bound on the last time a document was edited by the user. (See also edited_min.) owner: str (optional) Searches for documents with a specific owner. Use the email address of the owner. For example: owner='user@gmail.com' writer: str (optional) Searches for documents which can be written to by specific users. Use a single email address or a comma separated list of email addresses. For example: writer='user1@gmail.com,user@example.com' reader: str (optional) Searches for documents which can be read by specific users. (See also writer.) show_folders: str (optional) Specifies whether the query should return folders as well as documents. Possible values are 'true' and 'false'. Default is false. show_deleted: str (optional) Specifies whether the query should return documents which are in the trash as well as other documents. Possible values are 'true' and 'false'. Default is false. ocr: str (optional) Specifies whether to attempt OCR on a .jpg, .png, or .gif upload. Possible values are 'true' and 'false'. Default is false. See OCR in the Protocol Guide: http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#OCR target_language: str (optional) Specifies the language to translate a document into. See Document Translation in the Protocol Guide for a table of possible values: http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#DocumentTranslation source_language: str (optional) Specifies the source language of the original document. Optional when using the translation service. If not provided, Google will attempt to auto-detect the source language. See Document Translation in the Protocol Guide for a table of possible values (link in target_language). convert: str (optional) Used when uploading arbitrary file types to specity if document-type uploads should convert to a native Google Docs format. Possible values are 'true' and 'false'. The default is 'true'. """ gdata.client.Query.__init__(self, **kwargs) self.convert = convert self.title = title self.title_exact = title_exact self.opened_min = opened_min self.opened_max = opened_max self.edited_min = edited_min self.edited_max = edited_max self.owner = owner self.writer = writer self.reader = reader self.show_folders = show_folders self.show_deleted = show_deleted self.ocr = ocr self.target_language = target_language self.source_language = source_language def modify_request(self, http_request): gdata.client._add_query_param('convert', self.convert, http_request) gdata.client._add_query_param('title', self.title, http_request) gdata.client._add_query_param('title-exact', self.title_exact, http_request) gdata.client._add_query_param('opened-min', self.opened_min, http_request) gdata.client._add_query_param('opened-max', self.opened_max, http_request) gdata.client._add_query_param('edited-min', self.edited_min, http_request) gdata.client._add_query_param('edited-max', self.edited_max, http_request) gdata.client._add_query_param('owner', self.owner, http_request) gdata.client._add_query_param('writer', self.writer, http_request) gdata.client._add_query_param('reader', self.reader, http_request) gdata.client._add_query_param('showfolders', self.show_folders, http_request) gdata.client._add_query_param('showdeleted', self.show_deleted, http_request) gdata.client._add_query_param('ocr', self.ocr, http_request) gdata.client._add_query_param('targetLanguage', self.target_language, http_request) gdata.client._add_query_param('sourceLanguage', self.source_language, http_request) gdata.client.Query.modify_request(self, http_request) ModifyRequest = modify_request
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model classes for parsing and generating XML for the DocList Data API""" __author__ = 'e.bidelman (Eric Bidelman)' import re import atom.core import atom.data import gdata.acl.data import gdata.data DOCUMENTS_NS = 'http://schemas.google.com/docs/2007' DOCUMENTS_TEMPLATE = '{http://schemas.google.com/docs/2007}%s' ACL_FEEDLINK_REL = 'http://schemas.google.com/acl/2007#accessControlList' REVISION_FEEDLINK_REL = DOCUMENTS_NS + '/revisions' # XML Namespaces used in Google Documents entities. DATA_KIND_SCHEME = 'http://schemas.google.com/g/2005#kind' DOCUMENT_LABEL = 'document' SPREADSHEET_LABEL = 'spreadsheet' PRESENTATION_LABEL = 'presentation' FOLDER_LABEL = 'folder' PDF_LABEL = 'pdf' LABEL_SCHEME = 'http://schemas.google.com/g/2005/labels' STARRED_LABEL_TERM = LABEL_SCHEME + '#starred' TRASHED_LABEL_TERM = LABEL_SCHEME + '#trashed' HIDDEN_LABEL_TERM = LABEL_SCHEME + '#hidden' MINE_LABEL_TERM = LABEL_SCHEME + '#mine' PRIVATE_LABEL_TERM = LABEL_SCHEME + '#private' SHARED_WITH_DOMAIN_LABEL_TERM = LABEL_SCHEME + '#shared-with-domain' VIEWED_LABEL_TERM = LABEL_SCHEME + '#viewed' DOCS_PARENT_LINK_REL = DOCUMENTS_NS + '#parent' DOCS_PUBLISH_LINK_REL = DOCUMENTS_NS + '#publish' FILE_EXT_PATTERN = re.compile('.*\.([a-zA-Z]{3,}$)') RESOURCE_ID_PATTERN = re.compile('^([a-z]*)(:|%3A)([\w-]*)$') # File extension/mimetype pairs of common format. MIMETYPES = { 'CSV': 'text/csv', 'TSV': 'text/tab-separated-values', 'TAB': 'text/tab-separated-values', 'DOC': 'application/msword', 'DOCX': ('application/vnd.openxmlformats-officedocument.' 'wordprocessingml.document'), 'ODS': 'application/x-vnd.oasis.opendocument.spreadsheet', 'ODT': 'application/vnd.oasis.opendocument.text', 'RTF': 'application/rtf', 'SXW': 'application/vnd.sun.xml.writer', 'TXT': 'text/plain', 'XLS': 'application/vnd.ms-excel', 'XLSX': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'PDF': 'application/pdf', 'PNG': 'image/png', 'PPT': 'application/vnd.ms-powerpoint', 'PPS': 'application/vnd.ms-powerpoint', 'HTM': 'text/html', 'HTML': 'text/html', 'ZIP': 'application/zip', 'SWF': 'application/x-shockwave-flash' } def make_kind_category(label): """Builds the appropriate atom.data.Category for the label passed in. Args: label: str The value for the category entry. Returns: An atom.data.Category or None if label is None. """ if label is None: return None return atom.data.Category( scheme=DATA_KIND_SCHEME, term='%s#%s' % (DOCUMENTS_NS, label), label=label) MakeKindCategory = make_kind_category def make_content_link_from_resource_id(resource_id): """Constructs export URL for a given resource. Args: resource_id: str The document/item's resource id. Example presentation: 'presentation%3A0A1234567890'. Raises: gdata.client.ValueError if the resource_id is not a valid format. """ match = RESOURCE_ID_PATTERN.match(resource_id) if match: label = match.group(1) doc_id = match.group(3) if label == DOCUMENT_LABEL: return '/feeds/download/documents/Export?docId=%s' % doc_id if label == PRESENTATION_LABEL: return '/feeds/download/presentations/Export?docId=%s' % doc_id if label == SPREADSHEET_LABEL: return ('https://spreadsheets.google.com/feeds/download/spreadsheets/' 'Export?key=%s' % doc_id) raise ValueError, ('Invalid resource id: %s, or manually creating the ' 'download url for this type of doc is not possible' % resource_id) MakeContentLinkFromResourceId = make_content_link_from_resource_id class ResourceId(atom.core.XmlElement): """The DocList gd:resourceId element.""" _qname = gdata.data.GDATA_TEMPLATE % 'resourceId' class LastModifiedBy(atom.data.Person): """The DocList gd:lastModifiedBy element.""" _qname = gdata.data.GDATA_TEMPLATE % 'lastModifiedBy' class LastViewed(atom.data.Person): """The DocList gd:lastViewed element.""" _qname = gdata.data.GDATA_TEMPLATE % 'lastViewed' class WritersCanInvite(atom.core.XmlElement): """The DocList docs:writersCanInvite element.""" _qname = DOCUMENTS_TEMPLATE % 'writersCanInvite' value = 'value' class QuotaBytesUsed(atom.core.XmlElement): """The DocList gd:quotaBytesUsed element.""" _qname = gdata.data.GDATA_TEMPLATE % 'quotaBytesUsed' class Publish(atom.core.XmlElement): """The DocList docs:publish element.""" _qname = DOCUMENTS_TEMPLATE % 'publish' value = 'value' class PublishAuto(atom.core.XmlElement): """The DocList docs:publishAuto element.""" _qname = DOCUMENTS_TEMPLATE % 'publishAuto' value = 'value' class PublishOutsideDomain(atom.core.XmlElement): """The DocList docs:publishOutsideDomain element.""" _qname = DOCUMENTS_TEMPLATE % 'publishOutsideDomain' value = 'value' class DocsEntry(gdata.data.GDEntry): """A DocList version of an Atom Entry.""" last_viewed = LastViewed last_modified_by = LastModifiedBy resource_id = ResourceId writers_can_invite = WritersCanInvite quota_bytes_used = QuotaBytesUsed feed_link = [gdata.data.FeedLink] def get_document_type(self): """Extracts the type of document this DocsEntry is. This method returns the type of document the DocsEntry represents. Possible values are document, presentation, spreadsheet, folder, or pdf. Returns: A string representing the type of document. """ if self.category: for category in self.category: if category.scheme == DATA_KIND_SCHEME: return category.label else: return None GetDocumentType = get_document_type def get_acl_feed_link(self): """Extracts the DocsEntry's ACL feed <gd:feedLink>. Returns: A gdata.data.FeedLink object. """ for feed_link in self.feed_link: if feed_link.rel == ACL_FEEDLINK_REL: return feed_link return None GetAclFeedLink = get_acl_feed_link def get_revisions_feed_link(self): """Extracts the DocsEntry's revisions feed <gd:feedLink>. Returns: A gdata.data.FeedLink object. """ for feed_link in self.feed_link: if feed_link.rel == REVISION_FEEDLINK_REL: return feed_link return None GetRevisionsFeedLink = get_revisions_feed_link def in_folders(self): """Returns the parents link(s) (folders) of this entry.""" links = [] for link in self.link: if link.rel == DOCS_PARENT_LINK_REL and link.href: links.append(link) return links InFolders = in_folders class Acl(gdata.acl.data.AclEntry): """A document ACL entry.""" class DocList(gdata.data.GDFeed): """The main DocList feed containing a list of Google Documents.""" entry = [DocsEntry] class AclFeed(gdata.acl.data.AclFeed): """A DocList ACL feed.""" entry = [Acl] class Revision(gdata.data.GDEntry): """A document Revision entry.""" publish = Publish publish_auto = PublishAuto publish_outside_domain = PublishOutsideDomain def find_publish_link(self): """Get the link that points to the published document on the web. Returns: A str for the URL in the link with a rel ending in #publish. """ return self.find_url(DOCS_PUBLISH_LINK_REL) FindPublishLink = find_publish_link def get_publish_link(self): """Get the link that points to the published document on the web. Returns: A gdata.data.Link for the link with a rel ending in #publish. """ return self.get_link(DOCS_PUBLISH_LINK_REL) GetPublishLink = get_publish_link class RevisionFeed(gdata.data.GDFeed): """A DocList Revision feed.""" entry = [Revision]
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains extensions to Atom objects used with Google Documents.""" __author__ = ('api.jfisher (Jeff Fisher), ' 'api.eric@google.com (Eric Bidelman)') import atom import gdata DOCUMENTS_NAMESPACE = 'http://schemas.google.com/docs/2007' class Scope(atom.AtomBase): """The DocList ACL scope element""" _tag = 'scope' _namespace = gdata.GACL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' _attributes['type'] = 'type' def __init__(self, value=None, type=None, extension_elements=None, extension_attributes=None, text=None): self.value = value self.type = type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Role(atom.AtomBase): """The DocList ACL role element""" _tag = 'role' _namespace = gdata.GACL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, extension_elements=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class FeedLink(atom.AtomBase): """The DocList gd:feedLink element""" _tag = 'feedLink' _namespace = gdata.GDATA_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['href'] = 'href' def __init__(self, href=None, rel=None, text=None, extension_elements=None, extension_attributes=None): self.href = href self.rel = rel atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class ResourceId(atom.AtomBase): """The DocList gd:resourceId element""" _tag = 'resourceId' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, extension_elements=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class LastModifiedBy(atom.Person): """The DocList gd:lastModifiedBy element""" _tag = 'lastModifiedBy' _namespace = gdata.GDATA_NAMESPACE class LastViewed(atom.Person): """The DocList gd:lastViewed element""" _tag = 'lastViewed' _namespace = gdata.GDATA_NAMESPACE class WritersCanInvite(atom.AtomBase): """The DocList docs:writersCanInvite element""" _tag = 'writersCanInvite' _namespace = DOCUMENTS_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' class DocumentListEntry(gdata.GDataEntry): """The Google Documents version of an Atom Entry""" _tag = gdata.GDataEntry._tag _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feedLink', FeedLink) _children['{%s}resourceId' % gdata.GDATA_NAMESPACE] = ('resourceId', ResourceId) _children['{%s}lastModifiedBy' % gdata.GDATA_NAMESPACE] = ('lastModifiedBy', LastModifiedBy) _children['{%s}lastViewed' % gdata.GDATA_NAMESPACE] = ('lastViewed', LastViewed) _children['{%s}writersCanInvite' % DOCUMENTS_NAMESPACE] = ( 'writersCanInvite', WritersCanInvite) def __init__(self, resourceId=None, feedLink=None, lastViewed=None, lastModifiedBy=None, writersCanInvite=None, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, text=None, extension_elements=None, extension_attributes=None): self.feedLink = feedLink self.lastViewed = lastViewed self.lastModifiedBy = lastModifiedBy self.resourceId = resourceId self.writersCanInvite = writersCanInvite gdata.GDataEntry.__init__( self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def GetAclLink(self): """Extracts the DocListEntry's <gd:feedLink>. Returns: A FeedLink object. """ return self.feedLink def GetDocumentType(self): """Extracts the type of document from the DocListEntry. This method returns the type of document the DocListEntry represents. Possible values are document, presentation, spreadsheet, folder, or pdf. Returns: A string representing the type of document. """ if self.category: for category in self.category: if category.scheme == gdata.GDATA_NAMESPACE + '#kind': return category.label else: return None def DocumentListEntryFromString(xml_string): """Converts an XML string into a DocumentListEntry object. Args: xml_string: string The XML describing a Document List feed entry. Returns: A DocumentListEntry object corresponding to the given XML. """ return atom.CreateClassFromXMLString(DocumentListEntry, xml_string) class DocumentListAclEntry(gdata.GDataEntry): """A DocList ACL Entry flavor of an Atom Entry""" _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}scope' % gdata.GACL_NAMESPACE] = ('scope', Scope) _children['{%s}role' % gdata.GACL_NAMESPACE] = ('role', Role) def __init__(self, category=None, atom_id=None, link=None, title=None, updated=None, scope=None, role=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=None, category=category, content=None, atom_id=atom_id, link=link, published=None, title=title, updated=updated, text=None) self.scope = scope self.role = role def DocumentListAclEntryFromString(xml_string): """Converts an XML string into a DocumentListAclEntry object. Args: xml_string: string The XML describing a Document List ACL feed entry. Returns: A DocumentListAclEntry object corresponding to the given XML. """ return atom.CreateClassFromXMLString(DocumentListAclEntry, xml_string) class DocumentListFeed(gdata.GDataFeed): """A feed containing a list of Google Documents Items""" _tag = gdata.GDataFeed._tag _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [DocumentListEntry]) def DocumentListFeedFromString(xml_string): """Converts an XML string into a DocumentListFeed object. Args: xml_string: string The XML describing a DocumentList feed. Returns: A DocumentListFeed object corresponding to the given XML. """ return atom.CreateClassFromXMLString(DocumentListFeed, xml_string) class DocumentListAclFeed(gdata.GDataFeed): """A DocList ACL feed flavor of a Atom feed""" _tag = gdata.GDataFeed._tag _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [DocumentListAclEntry]) def DocumentListAclFeedFromString(xml_string): """Converts an XML string into a DocumentListAclFeed object. Args: xml_string: string The XML describing a DocumentList feed. Returns: A DocumentListFeed object corresponding to the given XML. """ return atom.CreateClassFromXMLString(DocumentListAclFeed, xml_string)
Python
#!/usr/bin/env python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ContactsService extends the GDataService for Google Contacts operations. ContactsService: Provides methods to query feeds and manipulate items. Extends GDataService. DictionaryToParamList: Function which converts a dictionary into a list of URL arguments (represented as strings). This is a utility function used in CRUD operations. """ __author__ = 'dbrattli (Dag Brattli)' import gdata import gdata.calendar import gdata.service DEFAULT_BATCH_URL = ('http://www.google.com/m8/feeds/contacts/default/full' '/batch') DEFAULT_PROFILES_BATCH_URL = ('http://www.google.com' '/m8/feeds/profiles/default/full/batch') GDATA_VER_HEADER = 'GData-Version' class Error(Exception): pass class RequestError(Error): pass class ContactsService(gdata.service.GDataService): """Client for the Google Contacts service.""" def __init__(self, email=None, password=None, source=None, server='www.google.com', additional_headers=None, contact_list='default', **kwargs): """Creates a client for the Contacts service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'www.google.com'. contact_list: string (optional) The name of the default contact list to use when no URI is specified to the methods of the service. Default value: 'default' (the logged in user's contact list). **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ self.contact_list = contact_list gdata.service.GDataService.__init__( self, email=email, password=password, service='cp', source=source, server=server, additional_headers=additional_headers, **kwargs) def GetFeedUri(self, kind='contacts', contact_list=None, projection='full', scheme=None): """Builds a feed URI. Args: kind: The type of feed to return, typically 'groups' or 'contacts'. Default value: 'contacts'. contact_list: The contact list to return a feed for. Default value: self.contact_list. projection: The projection to apply to the feed contents, for example 'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'. scheme: The URL scheme such as 'http' or 'https', None to return a relative URI without hostname. Returns: A feed URI using the given kind, contact list, and projection. Example: '/m8/feeds/contacts/default/full'. """ contact_list = contact_list or self.contact_list if kind == 'profiles': contact_list = 'domain/%s' % contact_list prefix = scheme and '%s://%s' % (scheme, self.server) or '' return '%s/m8/feeds/%s/%s/%s' % (prefix, kind, contact_list, projection) def GetContactsFeed(self, uri=None): uri = uri or self.GetFeedUri() return self.Get(uri, converter=gdata.contacts.ContactsFeedFromString) def GetContact(self, uri): return self.Get(uri, converter=gdata.contacts.ContactEntryFromString) def CreateContact(self, new_contact, insert_uri=None, url_params=None, escape_params=True): """Adds an new contact to Google Contacts. Args: new_contact: atom.Entry or subclass A new contact which is to be added to Google Contacts. insert_uri: the URL to post new contacts to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the contact created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ insert_uri = insert_uri or self.GetFeedUri() return self.Post(new_contact, insert_uri, url_params=url_params, escape_params=escape_params, converter=gdata.contacts.ContactEntryFromString) def UpdateContact(self, edit_uri, updated_contact, url_params=None, escape_params=True): """Updates an existing contact. Args: edit_uri: string The edit link URI for the element being updated updated_contact: string, atom.Entry or subclass containing the Atom Entry which will replace the contact which is stored at the edit_url url_params: dict (optional) Additional URL parameters to be included in the update request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful update, a httplib.HTTPResponse containing the server's response to the PUT request. On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ return self.Put(updated_contact, self._CleanUri(edit_uri), url_params=url_params, escape_params=escape_params, converter=gdata.contacts.ContactEntryFromString) def DeleteContact(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): """Removes an contact with the specified ID from Google Contacts. Args: edit_uri: string The edit URL of the entry to be deleted. Example: '/m8/feeds/contacts/default/full/xxx/yyy' url_params: dict (optional) Additional URL parameters to be included in the deletion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful delete, a httplib.HTTPResponse containing the server's response to the DELETE request. On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ return self.Delete(self._CleanUri(edit_uri), url_params=url_params, escape_params=escape_params) def GetGroupsFeed(self, uri=None): uri = uri or self.GetFeedUri('groups') return self.Get(uri, converter=gdata.contacts.GroupsFeedFromString) def CreateGroup(self, new_group, insert_uri=None, url_params=None, escape_params=True): insert_uri = insert_uri or self.GetFeedUri('groups') return self.Post(new_group, insert_uri, url_params=url_params, escape_params=escape_params, converter=gdata.contacts.GroupEntryFromString) def UpdateGroup(self, edit_uri, updated_group, url_params=None, escape_params=True): return self.Put(updated_group, self._CleanUri(edit_uri), url_params=url_params, escape_params=escape_params, converter=gdata.contacts.GroupEntryFromString) def DeleteGroup(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): return self.Delete(self._CleanUri(edit_uri), url_params=url_params, escape_params=escape_params) def ChangePhoto(self, media, contact_entry_or_url, content_type=None, content_length=None): """Change the photo for the contact by uploading a new photo. Performs a PUT against the photo edit URL to send the binary data for the photo. Args: media: filename, file-like-object, or a gdata.MediaSource object to send. contact_entry_or_url: ContactEntry or str If it is a ContactEntry, this method will search for an edit photo link URL and perform a PUT to the URL. content_type: str (optional) the mime type for the photo data. This is necessary if media is a file or file name, but if media is a MediaSource object then the media object can contain the mime type. If media_type is set, it will override the mime type in the media object. content_length: int or str (optional) Specifying the content length is only required if media is a file-like object. If media is a filename, the length is determined using os.path.getsize. If media is a MediaSource object, it is assumed that it already contains the content length. """ if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry): url = contact_entry_or_url.GetPhotoEditLink().href else: url = contact_entry_or_url if isinstance(media, gdata.MediaSource): payload = media # If the media object is a file-like object, then use it as the file # handle in the in the MediaSource. elif hasattr(media, 'read'): payload = gdata.MediaSource(file_handle=media, content_type=content_type, content_length=content_length) # Assume that the media object is a file name. else: payload = gdata.MediaSource(content_type=content_type, content_length=content_length, file_path=media) return self.Put(payload, url) def GetPhoto(self, contact_entry_or_url): """Retrives the binary data for the contact's profile photo as a string. Args: contact_entry_or_url: a gdata.contacts.ContactEntry objecr or a string containing the photo link's URL. If the contact entry does not contain a photo link, the image will not be fetched and this method will return None. """ # TODO: add the ability to write out the binary image data to a file, # reading and writing a chunk at a time to avoid potentially using up # large amounts of memory. url = None if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry): photo_link = contact_entry_or_url.GetPhotoLink() if photo_link: url = photo_link.href else: url = contact_entry_or_url if url: return self.Get(url, converter=str) else: return None def DeletePhoto(self, contact_entry_or_url): url = None if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry): url = contact_entry_or_url.GetPhotoEditLink().href else: url = contact_entry_or_url if url: self.Delete(url) def GetProfilesFeed(self, uri=None): """Retrieves a feed containing all domain's profiles. Args: uri: string (optional) the URL to retrieve the profiles feed, for example /m8/feeds/profiles/default/full Returns: On success, a ProfilesFeed containing the profiles. On failure, raises a RequestError. """ uri = uri or self.GetFeedUri('profiles') return self.Get(uri, converter=gdata.contacts.ProfilesFeedFromString) def GetProfile(self, uri): """Retrieves a domain's profile for the user. Args: uri: string the URL to retrieve the profiles feed, for example /m8/feeds/profiles/default/full/username Returns: On success, a ProfileEntry containing the profile for the user. On failure, raises a RequestError """ return self.Get(uri, converter=gdata.contacts.ProfileEntryFromString) def UpdateProfile(self, edit_uri, updated_profile, url_params=None, escape_params=True): """Updates an existing profile. Args: edit_uri: string The edit link URI for the element being updated updated_profile: string atom.Entry or subclass containing the Atom Entry which will replace the profile which is stored at the edit_url. url_params: dict (optional) Additional URL parameters to be included in the update request. escape_params: boolean (optional) If true, the url_params will be escaped before they are included in the request. Returns: On successful update, a httplib.HTTPResponse containing the server's response to the PUT request. On failure, raises a RequestError. """ return self.Put(updated_profile, self._CleanUri(edit_uri), url_params=url_params, escape_params=escape_params, converter=gdata.contacts.ProfileEntryFromString) def ExecuteBatch(self, batch_feed, url, converter=gdata.contacts.ContactsFeedFromString): """Sends a batch request feed to the server. Args: batch_feed: gdata.contacts.ContactFeed A feed containing batch request entries. Each entry contains the operation to be performed on the data contained in the entry. For example an entry with an operation type of insert will be used as if the individual entry had been inserted. url: str The batch URL to which these operations should be applied. converter: Function (optional) The function used to convert the server's response to an object. The default value is ContactsFeedFromString. Returns: The results of the batch request's execution on the server. If the default converter is used, this is stored in a ContactsFeed. """ return self.Post(batch_feed, url, converter=converter) def ExecuteBatchProfiles(self, batch_feed, url, converter=gdata.contacts.ProfilesFeedFromString): """Sends a batch request feed to the server. Args: batch_feed: gdata.profiles.ProfilesFeed A feed containing batch request entries. Each entry contains the operation to be performed on the data contained in the entry. For example an entry with an operation type of insert will be used as if the individual entry had been inserted. url: string The batch URL to which these operations should be applied. converter: Function (optional) The function used to convert the server's response to an object. The default value is gdata.profiles.ProfilesFeedFromString. Returns: The results of the batch request's execution on the server. If the default converter is used, this is stored in a ProfilesFeed. """ return self.Post(batch_feed, url, converter=converter) def _CleanUri(self, uri): """Sanitizes a feed URI. Args: uri: The URI to sanitize, can be relative or absolute. Returns: The given URI without its http://server prefix, if any. Keeps the leading slash of the URI. """ url_prefix = 'http://%s' % self.server if uri.startswith(url_prefix): uri = uri[len(url_prefix):] return uri class ContactsQuery(gdata.service.Query): def __init__(self, feed=None, text_query=None, params=None, categories=None, group=None): self.feed = feed or '/m8/feeds/contacts/default/full' if group: self._SetGroup(group) gdata.service.Query.__init__(self, feed=self.feed, text_query=text_query, params=params, categories=categories) def _GetGroup(self): if 'group' in self: return self['group'] else: return None def _SetGroup(self, group_id): self['group'] = group_id group = property(_GetGroup, _SetGroup, doc='The group query parameter to find only contacts in this group') class GroupsQuery(gdata.service.Query): def __init__(self, feed=None, text_query=None, params=None, categories=None): self.feed = feed or '/m8/feeds/groups/default/full' gdata.service.Query.__init__(self, feed=self.feed, text_query=text_query, params=params, categories=categories) class ProfilesQuery(gdata.service.Query): """Constructs a query object for the profiles feed.""" def __init__(self, feed=None, text_query=None, params=None, categories=None): self.feed = feed or '/m8/feeds/profiles/default/full' gdata.service.Query.__init__(self, feed=self.feed, text_query=text_query, params=params, categories=categories)
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from types import ListType, DictionaryType """Contains a client to communicate with the Contacts servers. For documentation on the Contacts API, see: http://code.google.com/apis/contatcs/ """ __author__ = 'vinces1979@gmail.com (Vince Spicer)' import gdata.client import gdata.contacts.data import atom.data import atom.http_core import gdata.gauth DEFAULT_BATCH_URL = ('http://www.google.com/m8/feeds/contacts/default/full' '/batch') DEFAULT_PROFILES_BATCH_URL = ('http://www.google.com' '/m8/feeds/profiles/default/full/batch') class ContactsClient(gdata.client.GDClient): api_version = '3' auth_service = 'cp' server = "www.google.com" contact_list = "default" auth_scopes = gdata.gauth.AUTH_SCOPES['cp'] ssl = True def __init__(self, domain=None, auth_token=None, **kwargs): """Constructs a new client for the Email Settings API. Args: domain: string The Google Apps domain (if any). kwargs: The other parameters to pass to the gdata.client.GDClient constructor. """ gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs) self.domain = domain def get_feed_uri(self, kind='contacts', contact_list=None, projection='full', scheme="http"): """Builds a feed URI. Args: kind: The type of feed to return, typically 'groups' or 'contacts'. Default value: 'contacts'. contact_list: The contact list to return a feed for. Default value: self.contact_list. projection: The projection to apply to the feed contents, for example 'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'. scheme: The URL scheme such as 'http' or 'https', None to return a relative URI without hostname. Returns: A feed URI using the given kind, contact list, and projection. Example: '/m8/feeds/contacts/default/full'. """ contact_list = contact_list or self.contact_list if kind == 'profiles': contact_list = 'domain/%s' % self.domain prefix = scheme and '%s://%s' % (scheme, self.server) or '' return '%s/m8/feeds/%s/%s/%s' % (prefix, kind, contact_list, projection) GetFeedUri = get_feed_uri def get_contact(self, uri, desired_class=gdata.contacts.data.ContactEntry, auth_token=None, **kwargs): return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetContact = get_contact def create_contact(self, new_contact, insert_uri=None, auth_token=None, **kwargs): """Adds an new contact to Google Contacts. Args: new_contact: atom.Entry or subclass A new contact which is to be added to Google Contacts. insert_uri: the URL to post new contacts to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the contact created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ insert_uri = insert_uri or self.GetFeedUri() return self.Post(new_contact, insert_uri, auth_token=auth_token, **kwargs) CreateContact = create_contact def add_contact(self, new_contact, insert_uri=None, auth_token=None, billing_information=None, birthday=None, calendar_link=None, **kwargs): """Adds an new contact to Google Contacts. Args: new_contact: atom.Entry or subclass A new contact which is to be added to Google Contacts. insert_uri: the URL to post new contacts to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the contact created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ contact = gdata.contacts.data.ContactEntry() if billing_information is not None: if not isinstance(billing_information, gdata.contacts.data.BillingInformation): billing_information = gdata.contacts.data.BillingInformation(text=billing_information) contact.billing_information = billing_information if birthday is not None: if not isinstance(birthday, gdata.contacts.data.Birthday): birthday = gdata.contacts.data.Birthday(when=birthday) contact.birthday = birthday if calendar_link is not None: if type(calendar_link) is not ListType: calendar_link = [calendar_link] for link in calendar_link: if not isinstance(link, gdata.contacts.data.CalendarLink): if type(link) is not DictionaryType: raise TypeError, "calendar_link Requires dictionary not %s" % type(link) link = gdata.contacts.data.CalendarLink( rel=link.get("rel", None), label=link.get("label", None), primary=link.get("primary", None), href=link.get("href", None), ) contact.calendar_link.append(link) insert_uri = insert_uri or self.GetFeedUri() return self.Post(contact, insert_uri, auth_token=auth_token, **kwargs) AddContact = add_contact def get_contacts(self, desired_class=gdata.contacts.data.ContactsFeed, auth_token=None, **kwargs): """Obtains a feed with the contacts belonging to the current user. Args: auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.spreadsheets.data.SpreadsheetsFeed. """ return self.get_feed(self.GetFeedUri(), auth_token=auth_token, desired_class=desired_class, **kwargs) GetContacts = get_contacts def get_group(self, uri=None, desired_class=gdata.contacts.data.GroupEntry, auth_token=None, **kwargs): """ Get a single groups details Args: uri: the group uri or id """ return self.get_entry(uri, desired_class=desired_class, auth_token=auth_token, **kwargs) GetGroup = get_group def get_groups(self, uri=None, desired_class=gdata.contacts.data.GroupsFeed, auth_token=None, **kwargs): uri = uri or self.GetFeedUri('groups') return self.get_feed(uri, desired_class=desired_class, auth_token=auth_token, **kwargs) GetGroups = get_groups def create_group(self, new_group, insert_uri=None, url_params=None, desired_class=None): insert_uri = insert_uri or self.GetFeedUri('groups') return self.Post(new_group, insert_uri, url_params=url_params, desired_class=desired_class) CreateGroup = create_group def update_group(self, edit_uri, updated_group, url_params=None, escape_params=True, desired_class=None): return self.Put(updated_group, self._CleanUri(edit_uri), url_params=url_params, escape_params=escape_params, desired_class=desired_class) UpdateGroup = update_group def delete_group(self, group_object, auth_token=None, force=False, **kws): return self.Delete(group_object, auth_token=auth_token, force=force, **kws ) DeleteGroup = delete_group def change_photo(self, media, contact_entry_or_url, content_type=None, content_length=None): """Change the photo for the contact by uploading a new photo. Performs a PUT against the photo edit URL to send the binary data for the photo. Args: media: filename, file-like-object, or a gdata.MediaSource object to send. contact_entry_or_url: ContactEntry or str If it is a ContactEntry, this method will search for an edit photo link URL and perform a PUT to the URL. content_type: str (optional) the mime type for the photo data. This is necessary if media is a file or file name, but if media is a MediaSource object then the media object can contain the mime type. If media_type is set, it will override the mime type in the media object. content_length: int or str (optional) Specifying the content length is only required if media is a file-like object. If media is a filename, the length is determined using os.path.getsize. If media is a MediaSource object, it is assumed that it already contains the content length. """ if isinstance(contact_entry_or_url, gdata.contacts.data.ContactEntry): url = contact_entry_or_url.GetPhotoEditLink().href else: url = contact_entry_or_url if isinstance(media, gdata.MediaSource): payload = media # If the media object is a file-like object, then use it as the file # handle in the in the MediaSource. elif hasattr(media, 'read'): payload = gdata.MediaSource(file_handle=media, content_type=content_type, content_length=content_length) # Assume that the media object is a file name. else: payload = gdata.MediaSource(content_type=content_type, content_length=content_length, file_path=media) return self.Put(payload, url) ChangePhoto = change_photo def get_photo(self, contact_entry_or_url): """Retrives the binary data for the contact's profile photo as a string. Args: contact_entry_or_url: a gdata.contacts.ContactEntry objecr or a string containing the photo link's URL. If the contact entry does not contain a photo link, the image will not be fetched and this method will return None. """ # TODO: add the ability to write out the binary image data to a file, # reading and writing a chunk at a time to avoid potentially using up # large amounts of memory. url = None if isinstance(contact_entry_or_url, gdata.contacts.data.ContactEntry): photo_link = contact_entry_or_url.GetPhotoLink() if photo_link: url = photo_link.href else: url = contact_entry_or_url if url: return self.Get(url).read() else: return None GetPhoto = get_photo def delete_photo(self, contact_entry_or_url): url = None if isinstance(contact_entry_or_url, gdata.contacts.data.ContactEntry): url = contact_entry_or_url.GetPhotoEditLink().href else: url = contact_entry_or_url if url: self.Delete(url) DeletePhoto = delete_photo def get_profiles_feed(self, uri=None): """Retrieves a feed containing all domain's profiles. Args: uri: string (optional) the URL to retrieve the profiles feed, for example /m8/feeds/profiles/default/full Returns: On success, a ProfilesFeed containing the profiles. On failure, raises a RequestError. """ uri = uri or self.GetFeedUri('profiles') return self.Get(uri, desired_class=gdata.contacts.data.ProfilesFeed) GetProfilesFeed = get_profiles_feed def get_profile(self, uri): """Retrieves a domain's profile for the user. Args: uri: string the URL to retrieve the profiles feed, for example /m8/feeds/profiles/default/full/username Returns: On success, a ProfileEntry containing the profile for the user. On failure, raises a RequestError """ return self.Get(uri, desired_class=gdata.contacts.data.ProfileEntry) GetProfile = get_profile def update_profile(self, updated_profile, auth_token=None, force=False, **kwargs): """Updates an existing profile. Args: updated_profile: atom.Entry or subclass containing the Atom Entry which will replace the profile which is stored at the edit_url. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of ContactsClient. force: boolean stating whether an update should be forced. Defaults to False. Normally, if a change has been made since the passed in entry was obtained, the server will not overwrite the entry since the changes were based on an obsolete version of the entry. Setting force to True will cause the update to silently overwrite whatever version is present. url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful update, a httplib.HTTPResponse containing the server's response to the PUT request. On failure, raises a RequestError. """ return self.Update(updated_profile, auth_token=auth_token, force=force, **kwargs) UpdateProfile = update_profile def execute_batch(self, batch_feed, url=DEFAULT_BATCH_URL, desired_class=None): """Sends a batch request feed to the server. Args: batch_feed: gdata.contacts.ContactFeed A feed containing batch request entries. Each entry contains the operation to be performed on the data contained in the entry. For example an entry with an operation type of insert will be used as if the individual entry had been inserted. url: str The batch URL to which these operations should be applied. converter: Function (optional) The function used to convert the server's response to an object. Returns: The results of the batch request's execution on the server. If the default converter is used, this is stored in a ContactsFeed. """ return self.Post(batch_feed, url, desired_class=desired_class) ExecuteBatch = execute_batch def execute_batch_profiles(self, batch_feed, url, desired_class=gdata.contacts.data.ProfilesFeed): """Sends a batch request feed to the server. Args: batch_feed: gdata.profiles.ProfilesFeed A feed containing batch request entries. Each entry contains the operation to be performed on the data contained in the entry. For example an entry with an operation type of insert will be used as if the individual entry had been inserted. url: string The batch URL to which these operations should be applied. converter: Function (optional) The function used to convert the server's response to an object. The default value is gdata.profiles.ProfilesFeedFromString. Returns: The results of the batch request's execution on the server. If the default converter is used, this is stored in a ProfilesFeed. """ return self.Post(batch_feed, url, desired_class=desired_class) ExecuteBatchProfiles = execute_batch_profiles def _CleanUri(self, uri): """Sanitizes a feed URI. Args: uri: The URI to sanitize, can be relative or absolute. Returns: The given URI without its http://server prefix, if any. Keeps the leading slash of the URI. """ url_prefix = 'http://%s' % self.server if uri.startswith(url_prefix): uri = uri[len(url_prefix):] return uri class ContactsQuery(gdata.client.Query): """ Create a custom Contacts Query Full specs can be found at: U{Contacts query parameters reference <http://code.google.com/apis/contacts/docs/3.0/reference.html#Parameters>} """ def __init__(self, feed=None, group=None, orderby=None, showdeleted=None, sortorder=None, requirealldeleted=None, **kwargs): """ @param max_results: The maximum number of entries to return. If you want to receive all of the contacts, rather than only the default maximum, you can specify a very large number for max-results. @param start-index: The 1-based index of the first result to be retrieved. @param updated-min: The lower bound on entry update dates. @param group: Constrains the results to only the contacts belonging to the group specified. Value of this parameter specifies group ID @param orderby: Sorting criterion. The only supported value is lastmodified. @param showdeleted: Include deleted contacts in the returned contacts feed @pram sortorder: Sorting order direction. Can be either ascending or descending. @param requirealldeleted: Only relevant if showdeleted and updated-min are also provided. It dictates the behavior of the server in case it detects that placeholders of some entries deleted since the point in time specified as updated-min may have been lost. """ gdata.client.Query.__init__(self, **kwargs) self.group = group self.orderby = orderby self.sortorder = sortorder self.showdeleted = showdeleted def modify_request(self, http_request): if self.group: gdata.client._add_query_param('group', self.group, http_request) if self.orderby: gdata.client._add_query_param('orderby', self.orderby, http_request) if self.sortorder: gdata.client._add_query_param('sortorder', self.sortorder, http_request) if self.showdeleted: gdata.client._add_query_param('showdeleted', self.showdeleted, http_request) gdata.client.Query.modify_request(self, http_request) ModifyRequest = modify_request class ProfilesQuery(gdata.client.Query): def __init__(self, feed=None): self.feed = feed or 'http://www.google.com/m8/feeds/profiles/default/full'
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model classes for parsing and generating XML for the Contacts API.""" __author__ = 'vinces1979@gmail.com (Vince Spicer)' import atom.core import gdata import gdata.data PHOTO_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#photo' PHOTO_EDIT_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#edit-photo' EXTERNAL_ID_ORGANIZATION = 'organization' RELATION_MANAGER = 'manager' CONTACTS_NAMESPACE = 'http://schemas.google.com/contact/2008' CONTACTS_TEMPLATE = '{%s}%%s' % CONTACTS_NAMESPACE class BillingInformation(atom.core.XmlElement): """ gContact:billingInformation Specifies billing information of the entity represented by the contact. The element cannot be repeated. """ _qname = CONTACTS_TEMPLATE % 'billingInformation' class Birthday(atom.core.XmlElement): """ Stores birthday date of the person represented by the contact. The element cannot be repeated. """ _qname = CONTACTS_TEMPLATE % 'birthday' when = 'when' class CalendarLink(atom.core.XmlElement): """ Storage for URL of the contact's calendar. The element can be repeated. """ _qname = CONTACTS_TEMPLATE % 'calendarLink' rel = 'rel' label = 'label' primary = 'primary' href = 'href' class DirectoryServer(atom.core.XmlElement): """ A directory server associated with this contact. May not be repeated. """ _qname = CONTACTS_TEMPLATE % 'directoryServer' class Event(atom.core.XmlElement): """ These elements describe events associated with a contact. They may be repeated """ _qname = CONTACTS_TEMPLATE % 'event' label = 'label' rel = 'rel' when = gdata.data.When class ExternalId(atom.core.XmlElement): """ Describes an ID of the contact in an external system of some kind. This element may be repeated. """ _qname = CONTACTS_TEMPLATE % 'externalId' label = 'label' rel = 'rel' value = 'value' def ExternalIdFromString(xml_string): return atom.core.parse(ExternalId, xml_string) class Gender(atom.core.XmlElement): """ Specifies the gender of the person represented by the contact. The element cannot be repeated. """ _qname = CONTACTS_TEMPLATE % 'directoryServer' value = 'value' class Hobby(atom.core.XmlElement): """ Describes an ID of the contact in an external system of some kind. This element may be repeated. """ _qname = CONTACTS_TEMPLATE % 'hobby' class Initials(atom.core.XmlElement): """ Specifies the initials of the person represented by the contact. The element cannot be repeated. """ _qname = CONTACTS_TEMPLATE % 'initials' class Jot(atom.core.XmlElement): """ Storage for arbitrary pieces of information about the contact. Each jot has a type specified by the rel attribute and a text value. The element can be repeated. """ _qname = CONTACTS_TEMPLATE % 'jot' rel = 'rel' class Language(atom.core.XmlElement): """ Specifies the preferred languages of the contact. The element can be repeated. The language must be specified using one of two mutually exclusive methods: using the freeform @label attribute, or using the @code attribute, whose value must conform to the IETF BCP 47 specification. """ _qname = CONTACTS_TEMPLATE % 'language' code = 'code' label = 'label' class MaidenName(atom.core.XmlElement): """ Specifies maiden name of the person represented by the contact. The element cannot be repeated. """ _qname = CONTACTS_TEMPLATE % 'maidenName' class Mileage(atom.core.XmlElement): """ Specifies the mileage for the entity represented by the contact. Can be used for example to document distance needed for reimbursement purposes. The value is not interpreted. The element cannot be repeated. """ _qname = CONTACTS_TEMPLATE % 'mileage' class NickName(atom.core.XmlElement): """ Specifies the nickname of the person represented by the contact. The element cannot be repeated. """ _qname = CONTACTS_TEMPLATE % 'nickname' class Occupation(atom.core.XmlElement): """ Specifies the occupation/profession of the person specified by the contact. The element cannot be repeated. """ _qname = CONTACTS_TEMPLATE % 'occupation' class Priority(atom.core.XmlElement): """ Classifies importance of the contact into 3 categories: * Low * Normal * High The priority element cannot be repeated. """ _qname = CONTACTS_TEMPLATE % 'priority' class Relation(atom.core.XmlElement): """ This element describe another entity (usually a person) that is in a relation of some kind with the contact. """ _qname = CONTACTS_TEMPLATE % 'relation' rel = 'rel' label = 'label' class Sensitivity(atom.core.XmlElement): """ Classifies sensitivity of the contact into the following categories: * Confidential * Normal * Personal * Private The sensitivity element cannot be repeated. """ _qname = CONTACTS_TEMPLATE % 'sensitivity' rel = 'rel' class UserDefinedField(atom.core.XmlElement): """ Represents an arbitrary key-value pair attached to the contact. """ _qname = CONTACTS_TEMPLATE % 'userDefinedField' key = 'key' value = 'value' def UserDefinedFieldFromString(xml_string): return atom.core.parse(UserDefinedField, xml_string) class Website(atom.core.XmlElement): """ Describes websites associated with the contact, including links. May be repeated. """ _qname = CONTACTS_TEMPLATE % 'website' href = 'href' label = 'label' primary = 'primary' rel = 'rel' def WebsiteFromString(xml_string): return atom.core.parse(Website, xml_string) class HouseName(atom.core.XmlElement): """ Used in places where houses or buildings have names (and not necessarily numbers), eg. "The Pillars". """ _qname = CONTACTS_TEMPLATE % 'housename' class Street(atom.core.XmlElement): """ Can be street, avenue, road, etc. This element also includes the house number and room/apartment/flat/floor number. """ _qname = CONTACTS_TEMPLATE % 'street' class POBox(atom.core.XmlElement): """ Covers actual P.O. boxes, drawers, locked bags, etc. This is usually but not always mutually exclusive with street """ _qname = CONTACTS_TEMPLATE % 'pobox' class Neighborhood(atom.core.XmlElement): """ This is used to disambiguate a street address when a city contains more than one street with the same name, or to specify a small place whose mail is routed through a larger postal town. In China it could be a county or a minor city. """ _qname = CONTACTS_TEMPLATE % 'neighborhood' class City(atom.core.XmlElement): """ Can be city, village, town, borough, etc. This is the postal town and not necessarily the place of residence or place of business. """ _qname = CONTACTS_TEMPLATE % 'city' class SubRegion(atom.core.XmlElement): """ Handles administrative districts such as U.S. or U.K. counties that are not used for mail addressing purposes. Subregion is not intended for delivery addresses. """ _qname = CONTACTS_TEMPLATE % 'subregion' class Region(atom.core.XmlElement): """ A state, province, county (in Ireland), Land (in Germany), departement (in France), etc. """ _qname = CONTACTS_TEMPLATE % 'region' class PostalCode(atom.core.XmlElement): """ Postal code. Usually country-wide, but sometimes specific to the city (e.g. "2" in "Dublin 2, Ireland" addresses). """ _qname = CONTACTS_TEMPLATE % 'postcode' class Country(atom.core.XmlElement): """ The name or code of the country. """ _qname = CONTACTS_TEMPLATE % 'country' class PersonEntry(gdata.data.BatchEntry): """Represents a google contact""" billing_information = BillingInformation birthday = Birthday calendar_link = [CalendarLink] directory_server = DirectoryServer event = [Event] external_id = [ExternalId] gender = Gender hobby = [Hobby] initals = Initials jot = [Jot] language= [Language] maiden_name = MaidenName mileage = Mileage nickname = NickName occupation = Occupation priority = Priority relation = [Relation] sensitivity = Sensitivity user_defined_field = [UserDefinedField] website = [Website] name = gdata.data.Name phone_number = [gdata.data.PhoneNumber] organization = gdata.data.Organization postal_address = [gdata.data.PostalAddress] email = [gdata.data.Email] im = [gdata.data.Im] structured_postal_address = [gdata.data.StructuredPostalAddress] extended_property = [gdata.data.ExtendedProperty] class Deleted(atom.core.XmlElement): """If present, indicates that this contact has been deleted.""" _qname = gdata.GDATA_TEMPLATE % 'deleted' class GroupMembershipInfo(atom.core.XmlElement): """ Identifies the group to which the contact belongs or belonged. The group is referenced by its id. """ _qname = CONTACTS_TEMPLATE % 'groupMembershipInfo' href = 'href' deleted = 'deleted' class ContactEntry(PersonEntry): """A Google Contacts flavor of an Atom Entry.""" deleted = Deleted group_membership_info = [GroupMembershipInfo] organization = gdata.data.Organization def GetPhotoLink(self): for a_link in self.link: if a_link.rel == PHOTO_LINK_REL: return a_link return None def GetPhotoEditLink(self): for a_link in self.link: if a_link.rel == PHOTO_EDIT_LINK_REL: return a_link return None class ContactsFeed(gdata.data.BatchFeed): """A collection of Contacts.""" entry = [ContactEntry] class SystemGroup(atom.core.XmlElement): """The contacts systemGroup element. When used within a contact group entry, indicates that the group in question is one of the predefined system groups.""" _qname = CONTACTS_TEMPLATE % 'systemGroup' id = 'id' class GroupEntry(gdata.data.BatchEntry): """Represents a contact group.""" extended_property = [gdata.data.ExtendedProperty] system_group = SystemGroup class GroupsFeed(gdata.data.BatchFeed): """A Google contact groups feed flavor of an Atom Feed.""" entry = [GroupEntry] class ProfileEntry(PersonEntry): """A Google Profiles flavor of an Atom Entry.""" def ProfileEntryFromString(xml_string): """Converts an XML string into a ProfileEntry object. Args: xml_string: string The XML describing a Profile entry. Returns: A ProfileEntry object corresponding to the given XML. """ return atom.core.parse(ProfileEntry, xml_string) class ProfilesFeed(gdata.data.BatchFeed): """A Google Profiles feed flavor of an Atom Feed.""" _qname = atom.data.ATOM_TEMPLATE % 'feed' entry = [ProfileEntry] def ProfilesFeedFromString(xml_string): """Converts an XML string into a ProfilesFeed object. Args: xml_string: string The XML describing a Profiles feed. Returns: A ProfilesFeed object corresponding to the given XML. """ return atom.core.parse(ProfilesFeed, xml_string)
Python
#!/usr/bin/env python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains extensions to ElementWrapper objects used with Google Contacts.""" __author__ = 'dbrattli (Dag Brattli)' import atom import gdata ## Constants from http://code.google.com/apis/gdata/elements.html ## REL_HOME = 'http://schemas.google.com/g/2005#home' REL_WORK = 'http://schemas.google.com/g/2005#work' REL_OTHER = 'http://schemas.google.com/g/2005#other' # AOL Instant Messenger protocol IM_AIM = 'http://schemas.google.com/g/2005#AIM' IM_MSN = 'http://schemas.google.com/g/2005#MSN' # MSN Messenger protocol IM_YAHOO = 'http://schemas.google.com/g/2005#YAHOO' # Yahoo Messenger protocol IM_SKYPE = 'http://schemas.google.com/g/2005#SKYPE' # Skype protocol IM_QQ = 'http://schemas.google.com/g/2005#QQ' # QQ protocol # Google Talk protocol IM_GOOGLE_TALK = 'http://schemas.google.com/g/2005#GOOGLE_TALK' IM_ICQ = 'http://schemas.google.com/g/2005#ICQ' # ICQ protocol IM_JABBER = 'http://schemas.google.com/g/2005#JABBER' # Jabber protocol IM_NETMEETING = 'http://schemas.google.com/g/2005#netmeeting' # NetMeeting PHOTO_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#photo' PHOTO_EDIT_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#edit-photo' # Different phone types, for more info see: # http://code.google.com/apis/gdata/docs/2.0/elements.html#gdPhoneNumber PHONE_CAR = 'http://schemas.google.com/g/2005#car' PHONE_FAX = 'http://schemas.google.com/g/2005#fax' PHONE_GENERAL = 'http://schemas.google.com/g/2005#general' PHONE_HOME = REL_HOME PHONE_HOME_FAX = 'http://schemas.google.com/g/2005#home_fax' PHONE_INTERNAL = 'http://schemas.google.com/g/2005#internal-extension' PHONE_MOBILE = 'http://schemas.google.com/g/2005#mobile' PHONE_OTHER = REL_OTHER PHONE_PAGER = 'http://schemas.google.com/g/2005#pager' PHONE_SATELLITE = 'http://schemas.google.com/g/2005#satellite' PHONE_VOIP = 'http://schemas.google.com/g/2005#voip' PHONE_WORK = REL_WORK PHONE_WORK_FAX = 'http://schemas.google.com/g/2005#work_fax' PHONE_WORK_MOBILE = 'http://schemas.google.com/g/2005#work_mobile' PHONE_WORK_PAGER = 'http://schemas.google.com/g/2005#work_pager' PHONE_MAIN = 'http://schemas.google.com/g/2005#main' PHONE_ASSISTANT = 'http://schemas.google.com/g/2005#assistant' PHONE_CALLBACK = 'http://schemas.google.com/g/2005#callback' PHONE_COMPANY_MAIN = 'http://schemas.google.com/g/2005#company_main' PHONE_ISDN = 'http://schemas.google.com/g/2005#isdn' PHONE_OTHER_FAX = 'http://schemas.google.com/g/2005#other_fax' PHONE_RADIO = 'http://schemas.google.com/g/2005#radio' PHONE_TELEX = 'http://schemas.google.com/g/2005#telex' PHONE_TTY_TDD = 'http://schemas.google.com/g/2005#tty_tdd' EXTERNAL_ID_ORGANIZATION = 'organization' RELATION_MANAGER = 'manager' CONTACTS_NAMESPACE = 'http://schemas.google.com/contact/2008' class GDataBase(atom.AtomBase): """The Google Contacts intermediate class from atom.AtomBase.""" _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class ContactsBase(GDataBase): """The Google Contacts intermediate class for Contacts namespace.""" _namespace = CONTACTS_NAMESPACE class OrgName(GDataBase): """The Google Contacts OrgName element.""" _tag = 'orgName' class OrgTitle(GDataBase): """The Google Contacts OrgTitle element.""" _tag = 'orgTitle' class OrgDepartment(GDataBase): """The Google Contacts OrgDepartment element.""" _tag = 'orgDepartment' class OrgJobDescription(GDataBase): """The Google Contacts OrgJobDescription element.""" _tag = 'orgJobDescription' class Where(GDataBase): """The Google Contacts Where element.""" _tag = 'where' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['label'] = 'label' _attributes['valueString'] = 'value_string' def __init__(self, value_string=None, rel=None, label=None, text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.rel = rel self.label = label self.value_string = value_string class When(GDataBase): """The Google Contacts When element.""" _tag = 'when' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['startTime'] = 'start_time' _attributes['endTime'] = 'end_time' _attributes['label'] = 'label' def __init__(self, start_time=None, end_time=None, label=None, text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.start_time = start_time self.end_time = end_time self.label = label class Organization(GDataBase): """The Google Contacts Organization element.""" _tag = 'organization' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['label'] = 'label' _attributes['rel'] = 'rel' _attributes['primary'] = 'primary' _children['{%s}orgName' % GDataBase._namespace] = ( 'org_name', OrgName) _children['{%s}orgTitle' % GDataBase._namespace] = ( 'org_title', OrgTitle) _children['{%s}orgDepartment' % GDataBase._namespace] = ( 'org_department', OrgDepartment) _children['{%s}orgJobDescription' % GDataBase._namespace] = ( 'org_job_description', OrgJobDescription) #_children['{%s}where' % GDataBase._namespace] = ('where', Where) def __init__(self, label=None, rel=None, primary='false', org_name=None, org_title=None, org_department=None, org_job_description=None, where=None, text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.label = label self.rel = rel or REL_OTHER self.primary = primary self.org_name = org_name self.org_title = org_title self.org_department = org_department self.org_job_description = org_job_description self.where = where class PostalAddress(GDataBase): """The Google Contacts PostalAddress element.""" _tag = 'postalAddress' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['primary'] = 'primary' def __init__(self, primary=None, rel=None, text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.rel = rel or REL_OTHER self.primary = primary class FormattedAddress(GDataBase): """The Google Contacts FormattedAddress element.""" _tag = 'formattedAddress' class StructuredPostalAddress(GDataBase): """The Google Contacts StructuredPostalAddress element.""" _tag = 'structuredPostalAddress' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['primary'] = 'primary' _children['{%s}formattedAddress' % GDataBase._namespace] = ( 'formatted_address', FormattedAddress) def __init__(self, rel=None, primary=None, formatted_address=None, text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.rel = rel or REL_OTHER self.primary = primary self.formatted_address = formatted_address class IM(GDataBase): """The Google Contacts IM element.""" _tag = 'im' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['address'] = 'address' _attributes['primary'] = 'primary' _attributes['protocol'] = 'protocol' _attributes['label'] = 'label' _attributes['rel'] = 'rel' def __init__(self, primary='false', rel=None, address=None, protocol=None, label=None, text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.protocol = protocol self.address = address self.primary = primary self.rel = rel or REL_OTHER self.label = label class Email(GDataBase): """The Google Contacts Email element.""" _tag = 'email' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['address'] = 'address' _attributes['primary'] = 'primary' _attributes['rel'] = 'rel' _attributes['label'] = 'label' def __init__(self, label=None, rel=None, address=None, primary='false', text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.label = label self.rel = rel or REL_OTHER self.address = address self.primary = primary class PhoneNumber(GDataBase): """The Google Contacts PhoneNumber element.""" _tag = 'phoneNumber' _children = GDataBase._children.copy() _attributes = GDataBase._attributes.copy() _attributes['label'] = 'label' _attributes['rel'] = 'rel' _attributes['uri'] = 'uri' _attributes['primary'] = 'primary' def __init__(self, label=None, rel=None, uri=None, primary='false', text=None, extension_elements=None, extension_attributes=None): GDataBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.label = label self.rel = rel or REL_OTHER self.uri = uri self.primary = primary class Nickname(ContactsBase): """The Google Contacts Nickname element.""" _tag = 'nickname' class Occupation(ContactsBase): """The Google Contacts Occupation element.""" _tag = 'occupation' class Gender(ContactsBase): """The Google Contacts Gender element.""" _tag = 'gender' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.value = value class Birthday(ContactsBase): """The Google Contacts Birthday element.""" _tag = 'birthday' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['when'] = 'when' def __init__(self, when=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.when = when class Relation(ContactsBase): """The Google Contacts Relation element.""" _tag = 'relation' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['label'] = 'label' _attributes['rel'] = 'rel' def __init__(self, label=None, rel=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.label = label self.rel = rel def RelationFromString(xml_string): return atom.CreateClassFromXMLString(Relation, xml_string) class UserDefinedField(ContactsBase): """The Google Contacts UserDefinedField element.""" _tag = 'userDefinedField' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['key'] = 'key' _attributes['value'] = 'value' def __init__(self, key=None, value=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.key = key self.value = value def UserDefinedFieldFromString(xml_string): return atom.CreateClassFromXMLString(UserDefinedField, xml_string) class Website(ContactsBase): """The Google Contacts Website element.""" _tag = 'website' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['href'] = 'href' _attributes['label'] = 'label' _attributes['primary'] = 'primary' _attributes['rel'] = 'rel' def __init__(self, href=None, label=None, primary='false', rel=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.href = href self.label = label self.primary = primary self.rel = rel def WebsiteFromString(xml_string): return atom.CreateClassFromXMLString(Website, xml_string) class ExternalId(ContactsBase): """The Google Contacts ExternalId element.""" _tag = 'externalId' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['label'] = 'label' _attributes['rel'] = 'rel' _attributes['value'] = 'value' def __init__(self, label=None, rel=None, value=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.label = label self.rel = rel self.value = value def ExternalIdFromString(xml_string): return atom.CreateClassFromXMLString(ExternalId, xml_string) class Event(ContactsBase): """The Google Contacts Event element.""" _tag = 'event' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['label'] = 'label' _attributes['rel'] = 'rel' _children['{%s}when' % ContactsBase._namespace] = ('when', When) def __init__(self, label=None, rel=None, when=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.label = label self.rel = rel self.when = when def EventFromString(xml_string): return atom.CreateClassFromXMLString(Event, xml_string) class Deleted(GDataBase): """The Google Contacts Deleted element.""" _tag = 'deleted' class GroupMembershipInfo(ContactsBase): """The Google Contacts GroupMembershipInfo element.""" _tag = 'groupMembershipInfo' _children = ContactsBase._children.copy() _attributes = ContactsBase._attributes.copy() _attributes['deleted'] = 'deleted' _attributes['href'] = 'href' def __init__(self, deleted=None, href=None, text=None, extension_elements=None, extension_attributes=None): ContactsBase.__init__(self, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.deleted = deleted self.href = href class PersonEntry(gdata.BatchEntry): """Base class for ContactEntry and ProfileEntry.""" _children = gdata.BatchEntry._children.copy() _children['{%s}organization' % gdata.GDATA_NAMESPACE] = ( 'organization', [Organization]) _children['{%s}phoneNumber' % gdata.GDATA_NAMESPACE] = ( 'phone_number', [PhoneNumber]) _children['{%s}nickname' % CONTACTS_NAMESPACE] = ('nickname', Nickname) _children['{%s}occupation' % CONTACTS_NAMESPACE] = ('occupation', Occupation) _children['{%s}gender' % CONTACTS_NAMESPACE] = ('gender', Gender) _children['{%s}birthday' % CONTACTS_NAMESPACE] = ('birthday', Birthday) _children['{%s}postalAddress' % gdata.GDATA_NAMESPACE] = ('postal_address', [PostalAddress]) _children['{%s}structuredPostalAddress' % gdata.GDATA_NAMESPACE] = ( 'structured_postal_address', [StructuredPostalAddress]) _children['{%s}email' % gdata.GDATA_NAMESPACE] = ('email', [Email]) _children['{%s}im' % gdata.GDATA_NAMESPACE] = ('im', [IM]) _children['{%s}relation' % CONTACTS_NAMESPACE] = ('relation', [Relation]) _children['{%s}userDefinedField' % CONTACTS_NAMESPACE] = ( 'user_defined_field', [UserDefinedField]) _children['{%s}website' % CONTACTS_NAMESPACE] = ('website', [Website]) _children['{%s}externalId' % CONTACTS_NAMESPACE] = ( 'external_id', [ExternalId]) _children['{%s}event' % CONTACTS_NAMESPACE] = ('event', [Event]) # The following line should be removed once the Python support # for GData 2.0 is mature. _attributes = gdata.BatchEntry._attributes.copy() _attributes['{%s}etag' % gdata.GDATA_NAMESPACE] = 'etag' def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, organization=None, phone_number=None, nickname=None, occupation=None, gender=None, birthday=None, postal_address=None, structured_postal_address=None, email=None, im=None, relation=None, user_defined_field=None, website=None, external_id=None, event=None, batch_operation=None, batch_id=None, batch_status=None, text=None, extension_elements=None, extension_attributes=None, etag=None): gdata.BatchEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, batch_operation=batch_operation, batch_id=batch_id, batch_status=batch_status, title=title, updated=updated) self.organization = organization or [] self.phone_number = phone_number or [] self.nickname = nickname self.occupation = occupation self.gender = gender self.birthday = birthday self.postal_address = postal_address or [] self.structured_postal_address = structured_postal_address or [] self.email = email or [] self.im = im or [] self.relation = relation or [] self.user_defined_field = user_defined_field or [] self.website = website or [] self.external_id = external_id or [] self.event = event or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} # The following line should be removed once the Python support # for GData 2.0 is mature. self.etag = etag class ContactEntry(PersonEntry): """A Google Contact flavor of an Atom Entry.""" _children = PersonEntry._children.copy() _children['{%s}deleted' % gdata.GDATA_NAMESPACE] = ('deleted', Deleted) _children['{%s}groupMembershipInfo' % CONTACTS_NAMESPACE] = ( 'group_membership_info', [GroupMembershipInfo]) _children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = ( 'extended_property', [gdata.ExtendedProperty]) # Overwrite the organization rule in PersonEntry so that a ContactEntry # may only contain one <gd:organization> element. _children['{%s}organization' % gdata.GDATA_NAMESPACE] = ( 'organization', Organization) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, organization=None, phone_number=None, nickname=None, occupation=None, gender=None, birthday=None, postal_address=None, structured_postal_address=None, email=None, im=None, relation=None, user_defined_field=None, website=None, external_id=None, event=None, batch_operation=None, batch_id=None, batch_status=None, text=None, extension_elements=None, extension_attributes=None, etag=None, deleted=None, extended_property=None, group_membership_info=None): PersonEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, organization=organization, phone_number=phone_number, nickname=nickname, occupation=occupation, gender=gender, birthday=birthday, postal_address=postal_address, structured_postal_address=structured_postal_address, email=email, im=im, relation=relation, user_defined_field=user_defined_field, website=website, external_id=external_id, event=event, batch_operation=batch_operation, batch_id=batch_id, batch_status=batch_status, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes, etag=etag) self.deleted = deleted self.extended_property = extended_property or [] self.group_membership_info = group_membership_info or [] def GetPhotoLink(self): for a_link in self.link: if a_link.rel == PHOTO_LINK_REL: return a_link return None def GetPhotoEditLink(self): for a_link in self.link: if a_link.rel == PHOTO_EDIT_LINK_REL: return a_link return None def ContactEntryFromString(xml_string): return atom.CreateClassFromXMLString(ContactEntry, xml_string) class ContactsFeed(gdata.BatchFeed, gdata.LinkFinder): """A Google Contacts feed flavor of an Atom Feed.""" _children = gdata.BatchFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [ContactEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.BatchFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def ContactsFeedFromString(xml_string): return atom.CreateClassFromXMLString(ContactsFeed, xml_string) class GroupEntry(gdata.BatchEntry): """Represents a contact group.""" _children = gdata.BatchEntry._children.copy() _children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = ( 'extended_property', [gdata.ExtendedProperty]) def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, control=None, title=None, updated=None, extended_property=None, batch_operation=None, batch_id=None, batch_status=None, extension_elements=None, extension_attributes=None, text=None): gdata.BatchEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, batch_operation=batch_operation, batch_id=batch_id, batch_status=batch_status, title=title, updated=updated) self.extended_property = extended_property or [] def GroupEntryFromString(xml_string): return atom.CreateClassFromXMLString(GroupEntry, xml_string) class GroupsFeed(gdata.BatchFeed): """A Google contact groups feed flavor of an Atom Feed.""" _children = gdata.BatchFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GroupEntry]) def GroupsFeedFromString(xml_string): return atom.CreateClassFromXMLString(GroupsFeed, xml_string) class ProfileEntry(PersonEntry): """A Google Profiles flavor of an Atom Entry.""" def ProfileEntryFromString(xml_string): """Converts an XML string into a ProfileEntry object. Args: xml_string: string The XML describing a Profile entry. Returns: A ProfileEntry object corresponding to the given XML. """ return atom.CreateClassFromXMLString(ProfileEntry, xml_string) class ProfilesFeed(gdata.BatchFeed, gdata.LinkFinder): """A Google Profiles feed flavor of an Atom Feed.""" _children = gdata.BatchFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [ProfileEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.BatchFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def ProfilesFeedFromString(xml_string): """Converts an XML string into a ProfilesFeed object. Args: xml_string: string The XML describing a Profiles feed. Returns: A ProfilesFeed object corresponding to the given XML. """ return atom.CreateClassFromXMLString(ProfilesFeed, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """CalendarService extends the GDataService to streamline Google Calendar operations. CalendarService: Provides methods to query feeds and manipulate items. Extends GDataService. DictionaryToParamList: Function which converts a dictionary into a list of URL arguments (represented as strings). This is a utility function used in CRUD operations. """ __author__ = 'api.vli (Vivian Li)' import urllib import gdata import atom.service import gdata.service import gdata.calendar import atom DEFAULT_BATCH_URL = ('http://www.google.com/calendar/feeds/default/private' '/full/batch') class Error(Exception): pass class RequestError(Error): pass class CalendarService(gdata.service.GDataService): """Client for the Google Calendar service.""" def __init__(self, email=None, password=None, source=None, server='www.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Calendar service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'www.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='cl', source=source, server=server, additional_headers=additional_headers, **kwargs) def GetCalendarEventFeed(self, uri='/calendar/feeds/default/private/full'): return self.Get(uri, converter=gdata.calendar.CalendarEventFeedFromString) def GetCalendarEventEntry(self, uri): return self.Get(uri, converter=gdata.calendar.CalendarEventEntryFromString) def GetCalendarListFeed(self, uri='/calendar/feeds/default/allcalendars/full'): return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString) def GetAllCalendarsFeed(self, uri='/calendar/feeds/default/allcalendars/full'): return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString) def GetOwnCalendarsFeed(self, uri='/calendar/feeds/default/owncalendars/full'): return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString) def GetCalendarListEntry(self, uri): return self.Get(uri, converter=gdata.calendar.CalendarListEntryFromString) def GetCalendarAclFeed(self, uri='/calendar/feeds/default/acl/full'): return self.Get(uri, converter=gdata.calendar.CalendarAclFeedFromString) def GetCalendarAclEntry(self, uri): return self.Get(uri, converter=gdata.calendar.CalendarAclEntryFromString) def GetCalendarEventCommentFeed(self, uri): return self.Get(uri, converter=gdata.calendar.CalendarEventCommentFeedFromString) def GetCalendarEventCommentEntry(self, uri): return self.Get(uri, converter=gdata.calendar.CalendarEventCommentEntryFromString) def Query(self, uri, converter=None): """Performs a query and returns a resulting feed or entry. Args: feed: string The feed which is to be queried Returns: On success, a GDataFeed or Entry depending on which is sent from the server. On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ if converter: result = self.Get(uri, converter=converter) else: result = self.Get(uri) return result def CalendarQuery(self, query): if isinstance(query, CalendarEventQuery): return self.Query(query.ToUri(), converter=gdata.calendar.CalendarEventFeedFromString) elif isinstance(query, CalendarListQuery): return self.Query(query.ToUri(), converter=gdata.calendar.CalendarListFeedFromString) elif isinstance(query, CalendarEventCommentQuery): return self.Query(query.ToUri(), converter=gdata.calendar.CalendarEventCommentFeedFromString) else: return self.Query(query.ToUri()) def InsertEvent(self, new_event, insert_uri, url_params=None, escape_params=True): """Adds an event to Google Calendar. Args: new_event: atom.Entry or subclass A new event which is to be added to Google Calendar. insert_uri: the URL to post new events to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the event created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ return self.Post(new_event, insert_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarEventEntryFromString) def InsertCalendarSubscription(self, calendar, url_params=None, escape_params=True): """Subscribes the authenticated user to the provided calendar. Args: calendar: The calendar to which the user should be subscribed. url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the subscription created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ insert_uri = '/calendar/feeds/default/allcalendars/full' return self.Post(calendar, insert_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarListEntryFromString) def InsertCalendar(self, new_calendar, url_params=None, escape_params=True): """Creates a new calendar. Args: new_calendar: The calendar to be created url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the calendar created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ insert_uri = '/calendar/feeds/default/owncalendars/full' response = self.Post(new_calendar, insert_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarListEntryFromString) return response def UpdateCalendar(self, calendar, url_params=None, escape_params=True): """Updates a calendar. Args: calendar: The calendar which should be updated url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the calendar created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ update_uri = calendar.GetEditLink().href response = self.Put(data=calendar, uri=update_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarListEntryFromString) return response def InsertAclEntry(self, new_entry, insert_uri, url_params=None, escape_params=True): """Adds an ACL entry (rule) to Google Calendar. Args: new_entry: atom.Entry or subclass A new ACL entry which is to be added to Google Calendar. insert_uri: the URL to post new entries to the ACL feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the ACL entry created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ return self.Post(new_entry, insert_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarAclEntryFromString) def InsertEventComment(self, new_entry, insert_uri, url_params=None, escape_params=True): """Adds an entry to Google Calendar. Args: new_entry: atom.Entry or subclass A new entry which is to be added to Google Calendar. insert_uri: the URL to post new entrys to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the comment created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ return self.Post(new_entry, insert_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarEventCommentEntryFromString) def _RemoveStandardUrlPrefix(self, url): url_prefix = 'http://%s/' % self.server if url.startswith(url_prefix): return url[len(url_prefix) - 1:] return url def DeleteEvent(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): """Removes an event with the specified ID from Google Calendar. Args: edit_uri: string The edit URL of the entry to be deleted. Example: 'http://www.google.com/calendar/feeds/default/private/full/abx' url_params: dict (optional) Additional URL parameters to be included in the deletion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful delete, a httplib.HTTPResponse containing the server's response to the DELETE request. On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ edit_uri = self._RemoveStandardUrlPrefix(edit_uri) return self.Delete('%s' % edit_uri, url_params=url_params, escape_params=escape_params) def DeleteAclEntry(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): """Removes an ACL entry at the given edit_uri from Google Calendar. Args: edit_uri: string The edit URL of the entry to be deleted. Example: 'http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default' url_params: dict (optional) Additional URL parameters to be included in the deletion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful delete, a httplib.HTTPResponse containing the server's response to the DELETE request. On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ edit_uri = self._RemoveStandardUrlPrefix(edit_uri) return self.Delete('%s' % edit_uri, url_params=url_params, escape_params=escape_params) def DeleteCalendarEntry(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): """Removes a calendar entry at the given edit_uri from Google Calendar. Args: edit_uri: string The edit URL of the entry to be deleted. Example: 'http://www.google.com/calendar/feeds/default/allcalendars/abcdef@group.calendar.google.com' url_params: dict (optional) Additional URL parameters to be included in the deletion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful delete, True is returned On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ return self.Delete(edit_uri, url_params=url_params, escape_params=escape_params) def UpdateEvent(self, edit_uri, updated_event, url_params=None, escape_params=True): """Updates an existing event. Args: edit_uri: string The edit link URI for the element being updated updated_event: string, atom.Entry, or subclass containing the Atom Entry which will replace the event which is stored at the edit_url url_params: dict (optional) Additional URL parameters to be included in the update request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful update, a httplib.HTTPResponse containing the server's response to the PUT request. On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ edit_uri = self._RemoveStandardUrlPrefix(edit_uri) return self.Put(updated_event, '%s' % edit_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarEventEntryFromString) def UpdateAclEntry(self, edit_uri, updated_rule, url_params=None, escape_params=True): """Updates an existing ACL rule. Args: edit_uri: string The edit link URI for the element being updated updated_rule: string, atom.Entry, or subclass containing the Atom Entry which will replace the event which is stored at the edit_url url_params: dict (optional) Additional URL parameters to be included in the update request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful update, a httplib.HTTPResponse containing the server's response to the PUT request. On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ edit_uri = self._RemoveStandardUrlPrefix(edit_uri) return self.Put(updated_rule, '%s' % edit_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarAclEntryFromString) def ExecuteBatch(self, batch_feed, url, converter=gdata.calendar.CalendarEventFeedFromString): """Sends a batch request feed to the server. The batch request needs to be sent to the batch URL for a particular calendar. You can find the URL by calling GetBatchLink().href on the CalendarEventFeed. Args: batch_feed: gdata.calendar.CalendarEventFeed A feed containing batch request entries. Each entry contains the operation to be performed on the data contained in the entry. For example an entry with an operation type of insert will be used as if the individual entry had been inserted. url: str The batch URL for the Calendar to which these operations should be applied. converter: Function (optional) The function used to convert the server's response to an object. The default value is CalendarEventFeedFromString. Returns: The results of the batch request's execution on the server. If the default converter is used, this is stored in a CalendarEventFeed. """ return self.Post(batch_feed, url, converter=converter) class CalendarEventQuery(gdata.service.Query): def __init__(self, user='default', visibility='private', projection='full', text_query=None, params=None, categories=None): gdata.service.Query.__init__(self, feed='http://www.google.com/calendar/feeds/%s/%s/%s' % ( urllib.quote(user), urllib.quote(visibility), urllib.quote(projection)), text_query=text_query, params=params, categories=categories) def _GetStartMin(self): if 'start-min' in self.keys(): return self['start-min'] else: return None def _SetStartMin(self, val): self['start-min'] = val start_min = property(_GetStartMin, _SetStartMin, doc="""The start-min query parameter""") def _GetStartMax(self): if 'start-max' in self.keys(): return self['start-max'] else: return None def _SetStartMax(self, val): self['start-max'] = val start_max = property(_GetStartMax, _SetStartMax, doc="""The start-max query parameter""") def _GetOrderBy(self): if 'orderby' in self.keys(): return self['orderby'] else: return None def _SetOrderBy(self, val): if val is not 'lastmodified' and val is not 'starttime': raise Error, "Order By must be either 'lastmodified' or 'starttime'" self['orderby'] = val orderby = property(_GetOrderBy, _SetOrderBy, doc="""The orderby query parameter""") def _GetSortOrder(self): if 'sortorder' in self.keys(): return self['sortorder'] else: return None def _SetSortOrder(self, val): if (val is not 'ascending' and val is not 'descending' and val is not 'a' and val is not 'd' and val is not 'ascend' and val is not 'descend'): raise Error, "Sort order must be either ascending, ascend, " + ( "a or descending, descend, or d") self['sortorder'] = val sortorder = property(_GetSortOrder, _SetSortOrder, doc="""The sortorder query parameter""") def _GetSingleEvents(self): if 'singleevents' in self.keys(): return self['singleevents'] else: return None def _SetSingleEvents(self, val): self['singleevents'] = val singleevents = property(_GetSingleEvents, _SetSingleEvents, doc="""The singleevents query parameter""") def _GetFutureEvents(self): if 'futureevents' in self.keys(): return self['futureevents'] else: return None def _SetFutureEvents(self, val): self['futureevents'] = val futureevents = property(_GetFutureEvents, _SetFutureEvents, doc="""The futureevents query parameter""") def _GetRecurrenceExpansionStart(self): if 'recurrence-expansion-start' in self.keys(): return self['recurrence-expansion-start'] else: return None def _SetRecurrenceExpansionStart(self, val): self['recurrence-expansion-start'] = val recurrence_expansion_start = property(_GetRecurrenceExpansionStart, _SetRecurrenceExpansionStart, doc="""The recurrence-expansion-start query parameter""") def _GetRecurrenceExpansionEnd(self): if 'recurrence-expansion-end' in self.keys(): return self['recurrence-expansion-end'] else: return None def _SetRecurrenceExpansionEnd(self, val): self['recurrence-expansion-end'] = val recurrence_expansion_end = property(_GetRecurrenceExpansionEnd, _SetRecurrenceExpansionEnd, doc="""The recurrence-expansion-end query parameter""") def _SetTimezone(self, val): self['ctz'] = val def _GetTimezone(self): if 'ctz' in self.keys(): return self['ctz'] else: return None ctz = property(_GetTimezone, _SetTimezone, doc="""The ctz query parameter which sets report time on the server.""") class CalendarListQuery(gdata.service.Query): """Queries the Google Calendar meta feed""" def __init__(self, userId=None, text_query=None, params=None, categories=None): if userId is None: userId = 'default' gdata.service.Query.__init__(self, feed='http://www.google.com/calendar/feeds/' +userId, text_query=text_query, params=params, categories=categories) class CalendarEventCommentQuery(gdata.service.Query): """Queries the Google Calendar event comments feed""" def __init__(self, feed=None): gdata.service.Query.__init__(self, feed=feed)
Python
#!/usr/bin/python # # Copyright (C) 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """CalendarClient extends the GDataService to streamline Google Calendar operations. CalendarService: Provides methods to query feeds and manipulate items. Extends GDataService. DictionaryToParamList: Function which converts a dictionary into a list of URL arguments (represented as strings). This is a utility function used in CRUD operations. """ __author__ = 'alainv (Alain Vongsouvanh)' import urllib import gdata.client import gdata.calendar.data import atom.data import atom.http_core import gdata.gauth DEFAULT_BATCH_URL = ('https://www.google.com/calendar/feeds/default/private' '/full/batch') class CalendarClient(gdata.client.GDClient): """Client for the Google Calendar service.""" api_version = '2' auth_service = 'cl' server = "www.google.com" contact_list = "default" auth_scopes = gdata.gauth.AUTH_SCOPES['cl'] def __init__(self, domain=None, auth_token=None, **kwargs): """Constructs a new client for the Calendar API. Args: domain: string The Google Apps domain (if any). kwargs: The other parameters to pass to the gdata.client.GDClient constructor. """ gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs) self.domain = domain def get_calendar_feed_uri(self, feed='', projection='full', scheme="https"): """Builds a feed URI. Args: projection: The projection to apply to the feed contents, for example 'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'. scheme: The URL scheme such as 'http' or 'https', None to return a relative URI without hostname. Returns: A feed URI using the given scheme and projection. Example: '/calendar/feeds/default/owncalendars/full'. """ prefix = scheme and '%s://%s' % (scheme, self.server) or '' suffix = feed and '/%s/%s' % (feed, projection) or '' return '%s/calendar/feeds/default%s' % (prefix, suffix) GetCalendarFeedUri = get_calendar_feed_uri def get_calendar_event_feed_uri(self, calendar='default', visibility='private', projection='full', scheme="https"): """Builds a feed URI. Args: projection: The projection to apply to the feed contents, for example 'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'. scheme: The URL scheme such as 'http' or 'https', None to return a relative URI without hostname. Returns: A feed URI using the given scheme and projection. Example: '/calendar/feeds/default/private/full'. """ prefix = scheme and '%s://%s' % (scheme, self.server) or '' return '%s/calendar/feeds/%s/%s/%s' % (prefix, calendar, visibility, projection) GetCalendarEventFeedUri = get_calendar_event_feed_uri def get_calendars_feed(self, uri, desired_class=gdata.calendar.data.CalendarFeed, auth_token=None, **kwargs): """Obtains a calendar feed. Args: uri: The uri of the calendar feed to request. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarFeed. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.get_feed(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetCalendarsFeed = get_calendars_feed def get_own_calendars_feed(self, desired_class=gdata.calendar.data.CalendarFeed, auth_token=None, **kwargs): """Obtains a feed containing the calendars owned by the current user. Args: desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarFeed. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.GetCalendarsFeed(uri=self.GetCalendarFeedUri(feed='owncalendars'), desired_class=desired_class, auth_token=auth_token, **kwargs) GetOwnCalendarsFeed = get_own_calendars_feed def get_all_calendars_feed(self, desired_class=gdata.calendar.data.CalendarFeed, auth_token=None, **kwargs): """Obtains a feed containing all the ccalendars the current user has access to. Args: desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarFeed. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.GetCalendarsFeed(uri=self.GetCalendarFeedUri(feed='allcalendars'), desired_class=desired_class, auth_token=auth_token, **kwargs) GetAllCalendarsFeed = get_all_calendars_feed def get_calendar_entry(self, uri, desired_class=gdata.calendar.data.CalendarEntry, auth_token=None, **kwargs): """Obtains a single calendar entry. Args: uri: The uri of the desired calendar entry. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarEntry. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetCalendarEntry = get_calendar_entry def get_calendar_event_feed(self, uri=None, desired_class=gdata.calendar.data.CalendarEventFeed, auth_token=None, **kwargs): """Obtains a feed of events for the desired calendar. Args: uri: The uri of the desired calendar entry. Defaults to https://www.google.com/calendar/feeds/default/private/full. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarEventFeed. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ uri = uri or self.GetCalendarEventFeedUri() return self.get_feed(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetCalendarEventFeed = get_calendar_event_feed def get_event_entry(self, uri, desired_class=gdata.calendar.data.CalendarEventEntry, auth_token=None, **kwargs): """Obtains a single event entry. Args: uri: The uri of the desired calendar event entry. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarEventEntry. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetEventEntry = get_event_entry def get_calendar_acl_feed(self, uri='https://www.google.com/calendar/feeds/default/acl/full', desired_class=gdata.calendar.data.CalendarAclFeed, auth_token=None, **kwargs): """Obtains an Access Control List feed. Args: uri: The uri of the desired Acl feed. Defaults to https://www.google.com/calendar/feeds/default/acl/full. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarAclFeed. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.get_feed(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetCalendarAclFeed = get_calendar_acl_feed def get_calendar_acl_entry(self, uri, desired_class=gdata.calendar.data.CalendarAclEntry, auth_token=None, **kwargs): """Obtains a single Access Control List entry. Args: uri: The uri of the desired Acl feed. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarAclEntry. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetCalendarAclEntry = get_calendar_acl_entry def insert_calendar(self, new_calendar, insert_uri=None, auth_token=None, **kwargs): """Adds an new calendar to Google Calendar. Args: new_calendar: atom.Entry or subclass A new calendar which is to be added to Google Calendar. insert_uri: the URL to post new contacts to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the contact created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ insert_uri = insert_uri or self.GetCalendarFeedUri(feed='owncalendars') return self.Post(new_calendar, insert_uri, auth_token=auth_token, **kwargs) InsertCalendar = insert_calendar def insert_calendar_subscription(self, calendar, insert_uri=None, auth_token=None, **kwargs): """Subscribes the authenticated user to the provided calendar. Args: calendar: The calendar to which the user should be subscribed. url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the subscription created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ insert_uri = insert_uri or self.GetCalendarFeedUri(feed='allcalendars') return self.Post(calendar, insert_uri, auth_token=auth_token, **kwargs) InsertCalendarSubscription = insert_calendar_subscription def insert_event(self, new_event, insert_uri=None, auth_token=None, **kwargs): """Adds an new event to Google Calendar. Args: new_event: atom.Entry or subclass A new event which is to be added to Google Calendar. insert_uri: the URL to post new contacts to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the contact created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ insert_uri = insert_uri or self.GetCalendarEventFeedUri() return self.Post(new_event, insert_uri, auth_token=auth_token, **kwargs) InsertEvent = insert_event def insert_acl_entry(self, new_acl_entry, insert_uri = 'https://www.google.com/calendar/feeds/default/acl/full', auth_token=None, **kwargs): """Adds an new Acl entry to Google Calendar. Args: new_acl_event: atom.Entry or subclass A new acl which is to be added to Google Calendar. insert_uri: the URL to post new contacts to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the contact created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ return self.Post(new_acl_entry, insert_uri, auth_token=auth_token, **kwargs) InsertAclEntry = insert_acl_entry def execute_batch(self, batch_feed, url, desired_class=None): """Sends a batch request feed to the server. Args: batch_feed: gdata.contacts.CalendarEventFeed A feed containing batch request entries. Each entry contains the operation to be performed on the data contained in the entry. For example an entry with an operation type of insert will be used as if the individual entry had been inserted. url: str The batch URL to which these operations should be applied. converter: Function (optional) The function used to convert the server's response to an object. Returns: The results of the batch request's execution on the server. If the default converter is used, this is stored in a ContactsFeed. """ return self.Post(batch_feed, url, desired_class=desired_class) ExecuteBatch = execute_batch def update(self, entry, auth_token=None, **kwargs): """Edits the entry on the server by sending the XML for this entry. Performs a PUT and converts the response to a new entry object with a matching class to the entry passed in. Args: entry: auth_token: Returns: A new Entry object of a matching type to the entry which was passed in. """ return gdata.client.GDClient.Update(self, entry, auth_token=auth_token, force=True, **kwargs) Update = update class CalendarEventQuery(gdata.client.Query): """ Create a custom Calendar Query Full specs can be found at: U{Calendar query parameters reference <http://code.google.com/apis/calendar/data/2.0/reference.html#Parameters>} """ def __init__(self, feed=None, ctz=None, fields=None, futureevents=None, max_attendees=None, orderby=None, recurrence_expansion_start=None, recurrence_expansion_end=None, singleevents=None, showdeleted=None, showhidden=None, sortorder=None, start_min=None, start_max=None, updated_min=None, **kwargs): """ @param max_results: The maximum number of entries to return. If you want to receive all of the contacts, rather than only the default maximum, you can specify a very large number for max-results. @param start-index: The 1-based index of the first result to be retrieved. @param updated-min: The lower bound on entry update dates. @param group: Constrains the results to only the contacts belonging to the group specified. Value of this parameter specifies group ID @param orderby: Sorting criterion. The only supported value is lastmodified. @param showdeleted: Include deleted contacts in the returned contacts feed @pram sortorder: Sorting order direction. Can be either ascending or descending. @param requirealldeleted: Only relevant if showdeleted and updated-min are also provided. It dictates the behavior of the server in case it detects that placeholders of some entries deleted since the point in time specified as updated-min may have been lost. """ gdata.client.Query.__init__(self, **kwargs) self.ctz = ctz self.fields = fields self.futureevents = futureevents self.max_attendees = max_attendees self.orderby = orderby self.recurrence_expansion_start = recurrence_expansion_start self.recurrence_expansion_end = recurrence_expansion_end self.singleevents = singleevents self.showdeleted = showdeleted self.showhidden = showhidden self.sortorder = sortorder self.start_min = start_min self.start_max = start_max self.updated_min = updated_min def modify_request(self, http_request): if self.ctz: gdata.client._add_query_param('ctz', self.ctz, http_request) if self.fields: gdata.client._add_query_param('fields', self.fields, http_request) if self.futureevents: gdata.client._add_query_param('futureevents', self.futureevents, http_request) if self.max_attendees: gdata.client._add_query_param('max-attendees', self.max_attendees, http_request) if self.orderby: gdata.client._add_query_param('orderby', self.orderby, http_request) if self.recurrence_expansion_start: gdata.client._add_query_param('recurrence-expansion-start', self.recurrence_expansion_start, http_request) if self.recurrence_expansion_end: gdata.client._add_query_param('recurrence-expansion-end', self.recurrence_expansion_end, http_request) if self.singleevents: gdata.client._add_query_param('singleevents', self.singleevents, http_request) if self.showdeleted: gdata.client._add_query_param('showdeleted', self.showdeleted, http_request) if self.showhidden: gdata.client._add_query_param('showhidden', self.showhidden, http_request) if self.sortorder: gdata.client._add_query_param('sortorder', self.sortorder, http_request) if self.start_min: gdata.client._add_query_param('start-min', self.start_min, http_request) if self.start_max: gdata.client._add_query_param('start-max', self.start_max, http_request) if self.updated_min: gdata.client._add_query_param('updated-min', self.updated_min, http_request) gdata.client.Query.modify_request(self, http_request) ModifyRequest = modify_request
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the data classes of the Google Calendar Data API""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import atom.data import gdata.acl.data import gdata.data import gdata.geo.data import gdata.opensearch.data GCAL_NAMESPACE = 'http://schemas.google.com/gCal/2005' GCAL_TEMPLATE = '{http://schemas.google.com/gCal/2005/}%s' WEB_CONTENT_LINK_REL = '%s/%s' % (GCAL_NAMESPACE, 'webContent') class AccessLevelProperty(atom.core.XmlElement): """Describes how much a given user may do with an event or calendar""" _qname = GCAL_TEMPLATE % 'accesslevel' value = 'value' class AllowGSync2Property(atom.core.XmlElement): """Whether the user is permitted to run Google Apps Sync""" _qname = GCAL_TEMPLATE % 'allowGSync2' value = 'value' class AllowGSyncProperty(atom.core.XmlElement): """Whether the user is permitted to run Google Apps Sync""" _qname = GCAL_TEMPLATE % 'allowGSync' value = 'value' class AnyoneCanAddSelfProperty(atom.core.XmlElement): """Whether anyone can add self as attendee""" _qname = GCAL_TEMPLATE % 'anyoneCanAddSelf' value = 'value' class CalendarAclRole(gdata.acl.data.AclRole): """Describes the Calendar roles of an entry in the Calendar access control list""" _qname = gdata.acl.data.GACL_TEMPLATE % 'role' class CalendarCommentEntry(gdata.data.GDEntry): """Describes an entry in a feed of a Calendar event's comments""" class CalendarCommentFeed(gdata.data.GDFeed): """Describes feed of a Calendar event's comments""" entry = [CalendarCommentEntry] class CalendarComments(gdata.data.Comments): """Describes a container of a feed link for Calendar comment entries""" _qname = gdata.data.GD_TEMPLATE % 'comments' class CalendarExtendedProperty(gdata.data.ExtendedProperty): """Defines a value for the realm attribute that is used only in the calendar API""" _qname = gdata.data.GD_TEMPLATE % 'extendedProperty' class CalendarWhere(gdata.data.Where): """Extends the base Where class with Calendar extensions""" _qname = gdata.data.GD_TEMPLATE % 'where' class ColorProperty(atom.core.XmlElement): """Describes the color of a calendar""" _qname = GCAL_TEMPLATE % 'color' value = 'value' class GuestsCanInviteOthersProperty(atom.core.XmlElement): """Whether guests can invite others to the event""" _qname = GCAL_TEMPLATE % 'guestsCanInviteOthers' value = 'value' class GuestsCanModifyProperty(atom.core.XmlElement): """Whether guests can modify event""" _qname = GCAL_TEMPLATE % 'guestsCanModify' value = 'value' class GuestsCanSeeGuestsProperty(atom.core.XmlElement): """Whether guests can see other attendees""" _qname = GCAL_TEMPLATE % 'guestsCanSeeGuests' value = 'value' class HiddenProperty(atom.core.XmlElement): """Describes whether a calendar is hidden""" _qname = GCAL_TEMPLATE % 'hidden' value = 'value' class IcalUIDProperty(atom.core.XmlElement): """Describes the UID in the ical export of the event""" _qname = GCAL_TEMPLATE % 'uid' value = 'value' class OverrideNameProperty(atom.core.XmlElement): """Describes the override name property of a calendar""" _qname = GCAL_TEMPLATE % 'overridename' value = 'value' class PrivateCopyProperty(atom.core.XmlElement): """Indicates whether this is a private copy of the event, changes to which should not be sent to other calendars""" _qname = GCAL_TEMPLATE % 'privateCopy' value = 'value' class QuickAddProperty(atom.core.XmlElement): """Describes whether gd:content is for quick-add processing""" _qname = GCAL_TEMPLATE % 'quickadd' value = 'value' class ResourceProperty(atom.core.XmlElement): """Describes whether gd:who is a resource such as a conference room""" _qname = GCAL_TEMPLATE % 'resource' value = 'value' id = 'id' class EventWho(gdata.data.Who): """Extends the base Who class with Calendar extensions""" _qname = gdata.data.GD_TEMPLATE % 'who' resource = ResourceProperty class SelectedProperty(atom.core.XmlElement): """Describes whether a calendar is selected""" _qname = GCAL_TEMPLATE % 'selected' value = 'value' class SendAclNotificationsProperty(atom.core.XmlElement): """Describes whether to send ACL notifications to grantees""" _qname = GCAL_TEMPLATE % 'sendAclNotifications' value = 'value' class CalendarAclEntry(gdata.acl.data.AclEntry): """Describes an entry in a feed of a Calendar access control list (ACL)""" send_acl_notifications = SendAclNotificationsProperty class CalendarAclFeed(gdata.data.GDFeed): """Describes a Calendar access contorl list (ACL) feed""" entry = [CalendarAclEntry] class SendEventNotificationsProperty(atom.core.XmlElement): """Describes whether to send event notifications to other participants of the event""" _qname = GCAL_TEMPLATE % 'sendEventNotifications' value = 'value' class SequenceNumberProperty(atom.core.XmlElement): """Describes sequence number of an event""" _qname = GCAL_TEMPLATE % 'sequence' value = 'value' class CalendarRecurrenceExceptionEntry(gdata.data.GDEntry): """Describes an entry used by a Calendar recurrence exception entry link""" uid = IcalUIDProperty sequence = SequenceNumberProperty class CalendarRecurrenceException(gdata.data.RecurrenceException): """Describes an exception to a recurring Calendar event""" _qname = gdata.data.GD_TEMPLATE % 'recurrenceException' class SettingsProperty(atom.core.XmlElement): """User preference name-value pair""" _qname = GCAL_TEMPLATE % 'settingsProperty' name = 'name' value = 'value' class SettingsEntry(gdata.data.GDEntry): """Describes a Calendar Settings property entry""" settings_property = SettingsProperty class CalendarSettingsFeed(gdata.data.GDFeed): """Personal settings for Calendar application""" entry = [SettingsEntry] class SuppressReplyNotificationsProperty(atom.core.XmlElement): """Lists notification methods to be suppressed for this reply""" _qname = GCAL_TEMPLATE % 'suppressReplyNotifications' methods = 'methods' class SyncEventProperty(atom.core.XmlElement): """Describes whether this is a sync scenario where the Ical UID and Sequence number are honored during inserts and updates""" _qname = GCAL_TEMPLATE % 'syncEvent' value = 'value' class When(gdata.data.When): """Extends the gd:when element to add reminders""" reminder = [gdata.data.Reminder] class CalendarEventEntry(gdata.data.BatchEntry): """Describes a Calendar event entry""" quick_add = QuickAddProperty send_event_notifications = SendEventNotificationsProperty sync_event = SyncEventProperty anyone_can_add_self = AnyoneCanAddSelfProperty extended_property = [CalendarExtendedProperty] sequence = SequenceNumberProperty guests_can_invite_others = GuestsCanInviteOthersProperty guests_can_modify = GuestsCanModifyProperty guests_can_see_guests = GuestsCanSeeGuestsProperty georss_where = gdata.geo.data.GeoRssWhere private_copy = PrivateCopyProperty suppress_reply_notifications = SuppressReplyNotificationsProperty uid = IcalUIDProperty where = [gdata.data.Where] when = [When] who = [gdata.data.Who] transparency = gdata.data.Transparency comments = gdata.data.Comments event_status = gdata.data.EventStatus visibility = gdata.data.Visibility recurrence = gdata.data.Recurrence recurrence_exception = [gdata.data.RecurrenceException] original_event = gdata.data.OriginalEvent reminder = [gdata.data.Reminder] class TimeZoneProperty(atom.core.XmlElement): """Describes the time zone of a calendar""" _qname = GCAL_TEMPLATE % 'timezone' value = 'value' class TimesCleanedProperty(atom.core.XmlElement): """Describes how many times calendar was cleaned via Manage Calendars""" _qname = GCAL_TEMPLATE % 'timesCleaned' value = 'value' class CalendarEntry(gdata.data.GDEntry): """Describes a Calendar entry in the feed of a user's calendars""" timezone = TimeZoneProperty overridename = OverrideNameProperty hidden = HiddenProperty selected = SelectedProperty times_cleaned = TimesCleanedProperty color = ColorProperty where = [CalendarWhere] accesslevel = AccessLevelProperty class CalendarEventFeed(gdata.data.BatchFeed): """Describes a Calendar event feed""" allow_g_sync2 = AllowGSync2Property timezone = TimeZoneProperty entry = [CalendarEventEntry] times_cleaned = TimesCleanedProperty allow_g_sync = AllowGSyncProperty class CalendarFeed(gdata.data.GDFeed): """Describes a feed of Calendars""" entry = [CalendarEntry] class WebContentGadgetPref(atom.core.XmlElement): """Describes a single web content gadget preference""" _qname = GCAL_TEMPLATE % 'webContentGadgetPref' name = 'name' value = 'value' class WebContent(atom.core.XmlElement): """Describes a "web content" extension""" _qname = GCAL_TEMPLATE % 'webContent' height = 'height' width = 'width' web_content_gadget_pref = [WebContentGadgetPref] url = 'url' display = 'display' class WebContentLink(atom.data.Link): """Describes a "web content" link""" def __init__(self, title=None, href=None, link_type=None, web_content=None): atom.data.Link.__init__(self, rel=WEB_CONTENT_LINK_REL, title=title, href=href, link_type=link_type) web_content = WebContent
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains extensions to ElementWrapper objects used with Google Calendar.""" __author__ = 'api.vli (Vivian Li), api.rboyd (Ryan Boyd)' try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata # XML namespaces which are often used in Google Calendar entities. GCAL_NAMESPACE = 'http://schemas.google.com/gCal/2005' GCAL_TEMPLATE = '{http://schemas.google.com/gCal/2005}%s' WEB_CONTENT_LINK_REL = '%s/%s' % (GCAL_NAMESPACE, 'webContent') GACL_NAMESPACE = gdata.GACL_NAMESPACE GACL_TEMPLATE = gdata.GACL_TEMPLATE class ValueAttributeContainer(atom.AtomBase): """A parent class for all Calendar classes which have a value attribute. Children include Color, AccessLevel, Hidden """ _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, extension_elements=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Color(ValueAttributeContainer): """The Google Calendar color element""" _tag = 'color' _namespace = GCAL_NAMESPACE _children = ValueAttributeContainer._children.copy() _attributes = ValueAttributeContainer._attributes.copy() class AccessLevel(ValueAttributeContainer): """The Google Calendar accesslevel element""" _tag = 'accesslevel' _namespace = GCAL_NAMESPACE _children = ValueAttributeContainer._children.copy() _attributes = ValueAttributeContainer._attributes.copy() class Hidden(ValueAttributeContainer): """The Google Calendar hidden element""" _tag = 'hidden' _namespace = GCAL_NAMESPACE _children = ValueAttributeContainer._children.copy() _attributes = ValueAttributeContainer._attributes.copy() class Selected(ValueAttributeContainer): """The Google Calendar selected element""" _tag = 'selected' _namespace = GCAL_NAMESPACE _children = ValueAttributeContainer._children.copy() _attributes = ValueAttributeContainer._attributes.copy() class Timezone(ValueAttributeContainer): """The Google Calendar timezone element""" _tag = 'timezone' _namespace = GCAL_NAMESPACE _children = ValueAttributeContainer._children.copy() _attributes = ValueAttributeContainer._attributes.copy() class Where(atom.AtomBase): """The Google Calendar Where element""" _tag = 'where' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['valueString'] = 'value_string' def __init__(self, value_string=None, extension_elements=None, extension_attributes=None, text=None): self.value_string = value_string self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class CalendarListEntry(gdata.GDataEntry, gdata.LinkFinder): """A Google Calendar meta Entry flavor of an Atom Entry """ _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}color' % GCAL_NAMESPACE] = ('color', Color) _children['{%s}accesslevel' % GCAL_NAMESPACE] = ('access_level', AccessLevel) _children['{%s}hidden' % GCAL_NAMESPACE] = ('hidden', Hidden) _children['{%s}selected' % GCAL_NAMESPACE] = ('selected', Selected) _children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone) _children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', Where) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, color=None, access_level=None, hidden=None, timezone=None, selected=None, where=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=None) self.color = color self.access_level = access_level self.hidden = hidden self.selected = selected self.timezone = timezone self.where = where class CalendarListFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Calendar meta feed flavor of an Atom Feed""" _tag = gdata.GDataFeed._tag _namespace = gdata.GDataFeed._namespace _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarListEntry]) class Scope(atom.AtomBase): """The Google ACL scope element""" _tag = 'scope' _namespace = GACL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' _attributes['type'] = 'type' def __init__(self, extension_elements=None, value=None, scope_type=None, extension_attributes=None, text=None): self.value = value self.type = scope_type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Role(ValueAttributeContainer): """The Google Calendar timezone element""" _tag = 'role' _namespace = GACL_NAMESPACE _children = ValueAttributeContainer._children.copy() _attributes = ValueAttributeContainer._attributes.copy() class CalendarAclEntry(gdata.GDataEntry, gdata.LinkFinder): """A Google Calendar ACL Entry flavor of an Atom Entry """ _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}scope' % GACL_NAMESPACE] = ('scope', Scope) _children['{%s}role' % GACL_NAMESPACE] = ('role', Role) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, scope=None, role=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=None) self.scope = scope self.role = role class CalendarAclFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Calendar ACL feed flavor of an Atom Feed""" _tag = gdata.GDataFeed._tag _namespace = gdata.GDataFeed._namespace _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarAclEntry]) class CalendarEventCommentEntry(gdata.GDataEntry, gdata.LinkFinder): """A Google Calendar event comments entry flavor of an Atom Entry""" _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() class CalendarEventCommentFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Calendar event comments feed flavor of an Atom Feed""" _tag = gdata.GDataFeed._tag _namespace = gdata.GDataFeed._namespace _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarEventCommentEntry]) class ExtendedProperty(gdata.ExtendedProperty): """A transparent subclass of gdata.ExtendedProperty added to this module for backwards compatibility.""" class Reminder(atom.AtomBase): """The Google Calendar reminder element""" _tag = 'reminder' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['absoluteTime'] = 'absolute_time' _attributes['days'] = 'days' _attributes['hours'] = 'hours' _attributes['minutes'] = 'minutes' _attributes['method'] = 'method' def __init__(self, absolute_time=None, days=None, hours=None, minutes=None, method=None, extension_elements=None, extension_attributes=None, text=None): self.absolute_time = absolute_time if days is not None: self.days = str(days) else: self.days = None if hours is not None: self.hours = str(hours) else: self.hours = None if minutes is not None: self.minutes = str(minutes) else: self.minutes = None self.method = method self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class When(atom.AtomBase): """The Google Calendar When element""" _tag = 'when' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}reminder' % gdata.GDATA_NAMESPACE] = ('reminder', [Reminder]) _attributes['startTime'] = 'start_time' _attributes['endTime'] = 'end_time' def __init__(self, start_time=None, end_time=None, reminder=None, extension_elements=None, extension_attributes=None, text=None): self.start_time = start_time self.end_time = end_time self.reminder = reminder or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Recurrence(atom.AtomBase): """The Google Calendar Recurrence element""" _tag = 'recurrence' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() class UriEnumElement(atom.AtomBase): _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, tag, enum_map, attrib_name='value', extension_elements=None, extension_attributes=None, text=None): self.tag=tag self.enum_map=enum_map self.attrib_name=attrib_name self.value=None self.text=text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def findKey(self, value): res=[item[0] for item in self.enum_map.items() if item[1] == value] if res is None or len(res) == 0: return None return res[0] def _ConvertElementAttributeToMember(self, attribute, value): # Special logic to use the enum_map to set the value of the object's value member. if attribute == self.attrib_name and value != '': self.value = self.enum_map[value] return # Find the attribute in this class's list of attributes. if self.__class__._attributes.has_key(attribute): # Find the member of this class which corresponds to the XML attribute # (lookup in current_class._attributes) and set this member to the # desired value (using self.__dict__). setattr(self, self.__class__._attributes[attribute], value) else: # The current class doesn't map this attribute, so try to parent class. atom.ExtensionContainer._ConvertElementAttributeToMember(self, attribute, value) def _AddMembersToElementTree(self, tree): # Convert the members of this class which are XML child nodes. # This uses the class's _children dictionary to find the members which # should become XML child nodes. member_node_names = [values[0] for tag, values in self.__class__._children.iteritems()] for member_name in member_node_names: member = getattr(self, member_name) if member is None: pass elif isinstance(member, list): for instance in member: instance._BecomeChildElement(tree) else: member._BecomeChildElement(tree) # Special logic to set the desired XML attribute. key = self.findKey(self.value) if key is not None: tree.attrib[self.attrib_name]=key # Convert the members of this class which are XML attributes. for xml_attribute, member_name in self.__class__._attributes.iteritems(): member = getattr(self, member_name) if member is not None: tree.attrib[xml_attribute] = member # Lastly, call the parent's _AddMembersToElementTree to get any # extension elements. atom.ExtensionContainer._AddMembersToElementTree(self, tree) class AttendeeStatus(UriEnumElement): """The Google Calendar attendeeStatus element""" _tag = 'attendeeStatus' _namespace = gdata.GDATA_NAMESPACE _children = UriEnumElement._children.copy() _attributes = UriEnumElement._attributes.copy() attendee_enum = { 'http://schemas.google.com/g/2005#event.accepted' : 'ACCEPTED', 'http://schemas.google.com/g/2005#event.declined' : 'DECLINED', 'http://schemas.google.com/g/2005#event.invited' : 'INVITED', 'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'} def __init__(self, extension_elements=None, extension_attributes=None, text=None): UriEnumElement.__init__(self, 'attendeeStatus', AttendeeStatus.attendee_enum, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class AttendeeType(UriEnumElement): """The Google Calendar attendeeType element""" _tag = 'attendeeType' _namespace = gdata.GDATA_NAMESPACE _children = UriEnumElement._children.copy() _attributes = UriEnumElement._attributes.copy() attendee_type_enum = { 'http://schemas.google.com/g/2005#event.optional' : 'OPTIONAL', 'http://schemas.google.com/g/2005#event.required' : 'REQUIRED' } def __init__(self, extension_elements=None, extension_attributes=None, text=None): UriEnumElement.__init__(self, 'attendeeType', AttendeeType.attendee_type_enum, extension_elements=extension_elements, extension_attributes=extension_attributes,text=text) class Visibility(UriEnumElement): """The Google Calendar Visibility element""" _tag = 'visibility' _namespace = gdata.GDATA_NAMESPACE _children = UriEnumElement._children.copy() _attributes = UriEnumElement._attributes.copy() visibility_enum = { 'http://schemas.google.com/g/2005#event.confidential' : 'CONFIDENTIAL', 'http://schemas.google.com/g/2005#event.default' : 'DEFAULT', 'http://schemas.google.com/g/2005#event.private' : 'PRIVATE', 'http://schemas.google.com/g/2005#event.public' : 'PUBLIC' } def __init__(self, extension_elements=None, extension_attributes=None, text=None): UriEnumElement.__init__(self, 'visibility', Visibility.visibility_enum, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Transparency(UriEnumElement): """The Google Calendar Transparency element""" _tag = 'transparency' _namespace = gdata.GDATA_NAMESPACE _children = UriEnumElement._children.copy() _attributes = UriEnumElement._attributes.copy() transparency_enum = { 'http://schemas.google.com/g/2005#event.opaque' : 'OPAQUE', 'http://schemas.google.com/g/2005#event.transparent' : 'TRANSPARENT' } def __init__(self, extension_elements=None, extension_attributes=None, text=None): UriEnumElement.__init__(self, tag='transparency', enum_map=Transparency.transparency_enum, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Comments(atom.AtomBase): """The Google Calendar comments element""" _tag = 'comments' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', gdata.FeedLink) _attributes['rel'] = 'rel' def __init__(self, rel=None, feed_link=None, extension_elements=None, extension_attributes=None, text=None): self.rel = rel self.feed_link = feed_link self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class EventStatus(UriEnumElement): """The Google Calendar eventStatus element""" _tag = 'eventStatus' _namespace = gdata.GDATA_NAMESPACE _children = UriEnumElement._children.copy() _attributes = UriEnumElement._attributes.copy() status_enum = { 'http://schemas.google.com/g/2005#event.canceled' : 'CANCELED', 'http://schemas.google.com/g/2005#event.confirmed' : 'CONFIRMED', 'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'} def __init__(self, extension_elements=None, extension_attributes=None, text=None): UriEnumElement.__init__(self, tag='eventStatus', enum_map=EventStatus.status_enum, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Who(UriEnumElement): """The Google Calendar Who element""" _tag = 'who' _namespace = gdata.GDATA_NAMESPACE _children = UriEnumElement._children.copy() _attributes = UriEnumElement._attributes.copy() _children['{%s}attendeeStatus' % gdata.GDATA_NAMESPACE] = ( 'attendee_status', AttendeeStatus) _children['{%s}attendeeType' % gdata.GDATA_NAMESPACE] = ('attendee_type', AttendeeType) _attributes['valueString'] = 'name' _attributes['email'] = 'email' relEnum = { 'http://schemas.google.com/g/2005#event.attendee' : 'ATTENDEE', 'http://schemas.google.com/g/2005#event.organizer' : 'ORGANIZER', 'http://schemas.google.com/g/2005#event.performer' : 'PERFORMER', 'http://schemas.google.com/g/2005#event.speaker' : 'SPEAKER', 'http://schemas.google.com/g/2005#message.bcc' : 'BCC', 'http://schemas.google.com/g/2005#message.cc' : 'CC', 'http://schemas.google.com/g/2005#message.from' : 'FROM', 'http://schemas.google.com/g/2005#message.reply-to' : 'REPLY_TO', 'http://schemas.google.com/g/2005#message.to' : 'TO' } def __init__(self, name=None, email=None, attendee_status=None, attendee_type=None, rel=None, extension_elements=None, extension_attributes=None, text=None): UriEnumElement.__init__(self, 'who', Who.relEnum, attrib_name='rel', extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.name = name self.email = email self.attendee_status = attendee_status self.attendee_type = attendee_type self.rel = rel class OriginalEvent(atom.AtomBase): """The Google Calendar OriginalEvent element""" _tag = 'originalEvent' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() # TODO: The when tag used to map to a EntryLink, make sure it should really be a When. _children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', When) _attributes['id'] = 'id' _attributes['href'] = 'href' def __init__(self, id=None, href=None, when=None, extension_elements=None, extension_attributes=None, text=None): self.id = id self.href = href self.when = when self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def GetCalendarEventEntryClass(): return CalendarEventEntry # This class is not completely defined here, because of a circular reference # in which CalendarEventEntryLink and CalendarEventEntry refer to one another. class CalendarEventEntryLink(gdata.EntryLink): """An entryLink which contains a calendar event entry Within an event's recurranceExceptions, an entry link points to a calendar event entry. This class exists to capture the calendar specific extensions in the entry. """ _tag = 'entryLink' _namespace = gdata.GDATA_NAMESPACE _children = gdata.EntryLink._children.copy() _attributes = gdata.EntryLink._attributes.copy() # The CalendarEventEntryLink should like CalendarEventEntry as a child but # that class hasn't been defined yet, so we will wait until after defining # CalendarEventEntry to list it in _children. class RecurrenceException(atom.AtomBase): """The Google Calendar RecurrenceException element""" _tag = 'recurrenceException' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}entryLink' % gdata.GDATA_NAMESPACE] = ('entry_link', CalendarEventEntryLink) _children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event', OriginalEvent) _attributes['specialized'] = 'specialized' def __init__(self, specialized=None, entry_link=None, original_event=None, extension_elements=None, extension_attributes=None, text=None): self.specialized = specialized self.entry_link = entry_link self.original_event = original_event self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class SendEventNotifications(atom.AtomBase): """The Google Calendar sendEventNotifications element""" _tag = 'sendEventNotifications' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, extension_elements=None, value=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class QuickAdd(atom.AtomBase): """The Google Calendar quickadd element""" _tag = 'quickadd' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, extension_elements=None, value=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def _TransferToElementTree(self, element_tree): if self.value: element_tree.attrib['value'] = self.value element_tree.tag = GCAL_TEMPLATE % 'quickadd' atom.AtomBase._TransferToElementTree(self, element_tree) return element_tree def _TakeAttributeFromElementTree(self, attribute, element_tree): if attribute == 'value': self.value = element_tree.attrib[attribute] del element_tree.attrib[attribute] else: atom.AtomBase._TakeAttributeFromElementTree(self, attribute, element_tree) class SyncEvent(atom.AtomBase): _tag = 'syncEvent' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value='false', extension_elements=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class UID(atom.AtomBase): _tag = 'uid' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, extension_elements=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Sequence(atom.AtomBase): _tag = 'sequence' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, extension_elements=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class WebContentGadgetPref(atom.AtomBase): _tag = 'webContentGadgetPref' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' _attributes['value'] = 'value' """The Google Calendar Web Content Gadget Preferences element""" def __init__(self, name=None, value=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class WebContent(atom.AtomBase): _tag = 'webContent' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}webContentGadgetPref' % GCAL_NAMESPACE] = ('gadget_pref', [WebContentGadgetPref]) _attributes['url'] = 'url' _attributes['width'] = 'width' _attributes['height'] = 'height' def __init__(self, url=None, width=None, height=None, text=None, gadget_pref=None, extension_elements=None, extension_attributes=None): self.url = url self.width = width self.height = height self.text = text self.gadget_pref = gadget_pref or [] self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class WebContentLink(atom.Link): _tag = 'link' _namespace = atom.ATOM_NAMESPACE _children = atom.Link._children.copy() _attributes = atom.Link._attributes.copy() _children['{%s}webContent' % GCAL_NAMESPACE] = ('web_content', WebContent) def __init__(self, title=None, href=None, link_type=None, web_content=None): atom.Link.__init__(self, rel=WEB_CONTENT_LINK_REL, title=title, href=href, link_type=link_type) self.web_content = web_content class GuestsCanInviteOthers(atom.AtomBase): """Indicates whether event attendees may invite others to the event. This element may only be changed by the organizer of the event. If not included as part of the event entry, this element will default to true during a POST request, and will inherit its previous value during a PUT request. """ _tag = 'guestsCanInviteOthers' _namespace = GCAL_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value='true', *args, **kwargs): atom.AtomBase.__init__(self, *args, **kwargs) self.value = value class GuestsCanSeeGuests(atom.AtomBase): """Indicates whether attendees can see other people invited to the event. The organizer always sees all attendees. Guests always see themselves. This property affects what attendees see in the event's guest list via both the Calendar UI and API feeds. This element may only be changed by the organizer of the event. If not included as part of the event entry, this element will default to true during a POST request, and will inherit its previous value during a PUT request. """ _tag = 'guestsCanSeeGuests' _namespace = GCAL_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value='true', *args, **kwargs): atom.AtomBase.__init__(self, *args, **kwargs) self.value = value class GuestsCanModify(atom.AtomBase): """Indicates whether event attendees may modify the original event. If yes, changes are visible to organizer and other attendees. Otherwise, any changes made by attendees will be restricted to that attendee's calendar. This element may only be changed by the organizer of the event, and may be set to 'true' only if both gCal:guestsCanInviteOthers and gCal:guestsCanSeeGuests are set to true in the same PUT/POST request. Otherwise, request fails with HTTP error code 400 (Bad Request). If not included as part of the event entry, this element will default to false during a POST request, and will inherit its previous value during a PUT request.""" _tag = 'guestsCanModify' _namespace = GCAL_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value='false', *args, **kwargs): atom.AtomBase.__init__(self, *args, **kwargs) self.value = value class CalendarEventEntry(gdata.BatchEntry): """A Google Calendar flavor of an Atom Entry """ _tag = gdata.BatchEntry._tag _namespace = gdata.BatchEntry._namespace _children = gdata.BatchEntry._children.copy() _attributes = gdata.BatchEntry._attributes.copy() # This class also contains WebContentLinks but converting those members # is handled in a special version of _ConvertElementTreeToMember. _children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', [Where]) _children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', [When]) _children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', [Who]) _children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = ( 'extended_property', [ExtendedProperty]) _children['{%s}visibility' % gdata.GDATA_NAMESPACE] = ('visibility', Visibility) _children['{%s}transparency' % gdata.GDATA_NAMESPACE] = ('transparency', Transparency) _children['{%s}eventStatus' % gdata.GDATA_NAMESPACE] = ('event_status', EventStatus) _children['{%s}recurrence' % gdata.GDATA_NAMESPACE] = ('recurrence', Recurrence) _children['{%s}recurrenceException' % gdata.GDATA_NAMESPACE] = ( 'recurrence_exception', [RecurrenceException]) _children['{%s}sendEventNotifications' % GCAL_NAMESPACE] = ( 'send_event_notifications', SendEventNotifications) _children['{%s}quickadd' % GCAL_NAMESPACE] = ('quick_add', QuickAdd) _children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments) _children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event', OriginalEvent) _children['{%s}sequence' % GCAL_NAMESPACE] = ('sequence', Sequence) _children['{%s}reminder' % gdata.GDATA_NAMESPACE] = ('reminder', [Reminder]) _children['{%s}syncEvent' % GCAL_NAMESPACE] = ('sync_event', SyncEvent) _children['{%s}uid' % GCAL_NAMESPACE] = ('uid', UID) _children['{%s}guestsCanInviteOthers' % GCAL_NAMESPACE] = ( 'guests_can_invite_others', GuestsCanInviteOthers) _children['{%s}guestsCanModify' % GCAL_NAMESPACE] = ( 'guests_can_modify', GuestsCanModify) _children['{%s}guestsCanSeeGuests' % GCAL_NAMESPACE] = ( 'guests_can_see_guests', GuestsCanSeeGuests) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, transparency=None, comments=None, event_status=None, send_event_notifications=None, visibility=None, recurrence=None, recurrence_exception=None, where=None, when=None, who=None, quick_add=None, extended_property=None, original_event=None, batch_operation=None, batch_id=None, batch_status=None, sequence=None, reminder=None, sync_event=None, uid=None, guests_can_invite_others=None, guests_can_modify=None, guests_can_see_guests=None, extension_elements=None, extension_attributes=None, text=None): gdata.BatchEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, batch_operation=batch_operation, batch_id=batch_id, batch_status=batch_status, title=title, updated=updated) self.transparency = transparency self.comments = comments self.event_status = event_status self.send_event_notifications = send_event_notifications self.visibility = visibility self.recurrence = recurrence self.recurrence_exception = recurrence_exception or [] self.where = where or [] self.when = when or [] self.who = who or [] self.quick_add = quick_add self.extended_property = extended_property or [] self.original_event = original_event self.sequence = sequence self.reminder = reminder or [] self.sync_event = sync_event self.uid = uid self.text = text self.guests_can_invite_others = guests_can_invite_others self.guests_can_modify = guests_can_modify self.guests_can_see_guests = guests_can_see_guests self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} # We needed to add special logic to _ConvertElementTreeToMember because we # want to make links with a rel of WEB_CONTENT_LINK_REL into a # WebContentLink def _ConvertElementTreeToMember(self, child_tree): # Special logic to handle Web Content links if (child_tree.tag == '{%s}link' % atom.ATOM_NAMESPACE and child_tree.attrib['rel'] == WEB_CONTENT_LINK_REL): if self.link is None: self.link = [] self.link.append(atom._CreateClassFromElementTree(WebContentLink, child_tree)) return # Find the element's tag in this class's list of child members if self.__class__._children.has_key(child_tree.tag): member_name = self.__class__._children[child_tree.tag][0] member_class = self.__class__._children[child_tree.tag][1] # If the class member is supposed to contain a list, make sure the # matching member is set to a list, then append the new member # instance to the list. if isinstance(member_class, list): if getattr(self, member_name) is None: setattr(self, member_name, []) getattr(self, member_name).append(atom._CreateClassFromElementTree( member_class[0], child_tree)) else: setattr(self, member_name, atom._CreateClassFromElementTree(member_class, child_tree)) else: atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree) def GetWebContentLink(self): """Finds the first link with rel set to WEB_CONTENT_REL Returns: A gdata.calendar.WebContentLink or none if none of the links had rel equal to WEB_CONTENT_REL """ for a_link in self.link: if a_link.rel == WEB_CONTENT_LINK_REL: return a_link return None def CalendarEventEntryFromString(xml_string): return atom.CreateClassFromXMLString(CalendarEventEntry, xml_string) def CalendarEventCommentEntryFromString(xml_string): return atom.CreateClassFromXMLString(CalendarEventCommentEntry, xml_string) CalendarEventEntryLink._children = {'{%s}entry' % atom.ATOM_NAMESPACE: ('entry', CalendarEventEntry)} def CalendarEventEntryLinkFromString(xml_string): return atom.CreateClassFromXMLString(CalendarEventEntryLink, xml_string) class CalendarEventFeed(gdata.BatchFeed, gdata.LinkFinder): """A Google Calendar event feed flavor of an Atom Feed""" _tag = gdata.BatchFeed._tag _namespace = gdata.BatchFeed._namespace _children = gdata.BatchFeed._children.copy() _attributes = gdata.BatchFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarEventEntry]) _children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, interrupted=None, timezone=None, extension_elements=None, extension_attributes=None, text=None): gdata.BatchFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, interrupted=interrupted, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.timezone = timezone def CalendarListEntryFromString(xml_string): return atom.CreateClassFromXMLString(CalendarListEntry, xml_string) def CalendarAclEntryFromString(xml_string): return atom.CreateClassFromXMLString(CalendarAclEntry, xml_string) def CalendarListFeedFromString(xml_string): return atom.CreateClassFromXMLString(CalendarListFeed, xml_string) def CalendarAclFeedFromString(xml_string): return atom.CreateClassFromXMLString(CalendarAclFeed, xml_string) def CalendarEventFeedFromString(xml_string): return atom.CreateClassFromXMLString(CalendarEventFeed, xml_string) def CalendarEventCommentFeedFromString(xml_string): return atom.CreateClassFromXMLString(CalendarEventCommentFeed, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the data classes of the Yahoo! Media RSS Extension""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core MEDIA_TEMPLATE = '{http://search.yahoo.com/mrss//}%s' class MediaCategory(atom.core.XmlElement): """Describes a media category.""" _qname = MEDIA_TEMPLATE % 'category' scheme = 'scheme' label = 'label' class MediaCopyright(atom.core.XmlElement): """Describes a media copyright.""" _qname = MEDIA_TEMPLATE % 'copyright' url = 'url' class MediaCredit(atom.core.XmlElement): """Describes a media credit.""" _qname = MEDIA_TEMPLATE % 'credit' role = 'role' scheme = 'scheme' class MediaDescription(atom.core.XmlElement): """Describes a media description.""" _qname = MEDIA_TEMPLATE % 'description' type = 'type' class MediaHash(atom.core.XmlElement): """Describes a media hash.""" _qname = MEDIA_TEMPLATE % 'hash' algo = 'algo' class MediaKeywords(atom.core.XmlElement): """Describes a media keywords.""" _qname = MEDIA_TEMPLATE % 'keywords' class MediaPlayer(atom.core.XmlElement): """Describes a media player.""" _qname = MEDIA_TEMPLATE % 'player' height = 'height' width = 'width' url = 'url' class MediaRating(atom.core.XmlElement): """Describes a media rating.""" _qname = MEDIA_TEMPLATE % 'rating' scheme = 'scheme' class MediaRestriction(atom.core.XmlElement): """Describes a media restriction.""" _qname = MEDIA_TEMPLATE % 'restriction' relationship = 'relationship' type = 'type' class MediaText(atom.core.XmlElement): """Describes a media text.""" _qname = MEDIA_TEMPLATE % 'text' end = 'end' lang = 'lang' type = 'type' start = 'start' class MediaThumbnail(atom.core.XmlElement): """Describes a media thumbnail.""" _qname = MEDIA_TEMPLATE % 'thumbnail' time = 'time' url = 'url' width = 'width' height = 'height' class MediaTitle(atom.core.XmlElement): """Describes a media title.""" _qname = MEDIA_TEMPLATE % 'title' type = 'type' class MediaContent(atom.core.XmlElement): """Describes a media content.""" _qname = MEDIA_TEMPLATE % 'content' bitrate = 'bitrate' is_default = 'isDefault' medium = 'medium' height = 'height' credit = [MediaCredit] language = 'language' hash = MediaHash width = 'width' player = MediaPlayer url = 'url' file_size = 'fileSize' channels = 'channels' expression = 'expression' text = [MediaText] samplingrate = 'samplingrate' title = MediaTitle category = [MediaCategory] rating = [MediaRating] type = 'type' description = MediaDescription framerate = 'framerate' thumbnail = [MediaThumbnail] duration = 'duration' copyright = MediaCopyright keywords = MediaKeywords restriction = [MediaRestriction] class MediaGroup(atom.core.XmlElement): """Describes a media group.""" _qname = MEDIA_TEMPLATE % 'group' credit = [MediaCredit] content = [MediaContent] copyright = MediaCopyright description = MediaDescription category = [MediaCategory] player = MediaPlayer rating = [MediaRating] hash = MediaHash title = MediaTitle keywords = MediaKeywords restriction = [MediaRestriction] thumbnail = [MediaThumbnail] text = [MediaText]
Python
# -*-*- encoding: utf-8 -*-*- # # This is gdata.photos.media, implementing parts of the MediaRSS spec in gdata structures # # $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # Portions copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Essential attributes of photos in Google Photos/Picasa Web Albums are expressed using elements from the `media' namespace, defined in the MediaRSS specification[1]. Due to copyright issues, the elements herein are documented sparingly, please consult with the Google Photos API Reference Guide[2], alternatively the official MediaRSS specification[1] for details. (If there is a version conflict between the two sources, stick to the Google Photos API). [1]: http://search.yahoo.com/mrss (version 1.1.1) [2]: http://code.google.com/apis/picasaweb/reference.html#media_reference Keep in mind that Google Photos only uses a subset of the MediaRSS elements (and some of the attributes are trimmed down, too): media:content media:credit media:description media:group media:keywords media:thumbnail media:title """ __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: api chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' import atom import gdata MEDIA_NAMESPACE = 'http://search.yahoo.com/mrss/' YOUTUBE_NAMESPACE = 'http://gdata.youtube.com/schemas/2007' class MediaBaseElement(atom.AtomBase): """Base class for elements in the MEDIA_NAMESPACE. To add new elements, you only need to add the element tag name to self._tag """ _tag = '' _namespace = MEDIA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Content(MediaBaseElement): """(attribute container) This element describes the original content, e.g. an image or a video. There may be multiple Content elements in a media:Group. For example, a video may have a <media:content medium="image"> element that specifies a JPEG representation of the video, and a <media:content medium="video"> element that specifies the URL of the video itself. Attributes: url: non-ambigous reference to online object width: width of the object frame, in pixels height: width of the object frame, in pixels medium: one of `image' or `video', allowing the api user to quickly determine the object's type type: Internet media Type[1] (a.k.a. mime type) of the object -- a more verbose way of determining the media type. To set the type member in the contructor, use the content_type parameter. (optional) fileSize: the size of the object, in bytes [1]: http://en.wikipedia.org/wiki/Internet_media_type """ _tag = 'content' _attributes = atom.AtomBase._attributes.copy() _attributes['url'] = 'url' _attributes['width'] = 'width' _attributes['height'] = 'height' _attributes['medium'] = 'medium' _attributes['type'] = 'type' _attributes['fileSize'] = 'fileSize' def __init__(self, url=None, width=None, height=None, medium=None, content_type=None, fileSize=None, format=None, extension_elements=None, extension_attributes=None, text=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.url = url self.width = width self.height = height self.medium = medium self.type = content_type self.fileSize = fileSize def ContentFromString(xml_string): return atom.CreateClassFromXMLString(Content, xml_string) class Credit(MediaBaseElement): """(string) Contains the nickname of the user who created the content, e.g. `Liz Bennet'. This is a user-specified value that should be used when referring to the user by name. Note that none of the attributes from the MediaRSS spec are supported. """ _tag = 'credit' def CreditFromString(xml_string): return atom.CreateClassFromXMLString(Credit, xml_string) class Description(MediaBaseElement): """(string) A description of the media object. Either plain unicode text, or entity-encoded html (look at the `type' attribute). E.g `A set of photographs I took while vacationing in Italy.' For `api' projections, the description is in plain text; for `base' projections, the description is in HTML. Attributes: type: either `text' or `html'. To set the type member in the contructor, use the description_type parameter. """ _tag = 'description' _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' def __init__(self, description_type=None, extension_elements=None, extension_attributes=None, text=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.type = description_type def DescriptionFromString(xml_string): return atom.CreateClassFromXMLString(Description, xml_string) class Keywords(MediaBaseElement): """(string) Lists the tags associated with the entry, e.g `italy, vacation, sunset'. Contains a comma-separated list of tags that have been added to the photo, or all tags that have been added to photos in the album. """ _tag = 'keywords' def KeywordsFromString(xml_string): return atom.CreateClassFromXMLString(Keywords, xml_string) class Thumbnail(MediaBaseElement): """(attributes) Contains the URL of a thumbnail of a photo or album cover. There can be multiple <media:thumbnail> elements for a given <media:group>; for example, a given item may have multiple thumbnails at different sizes. Photos generally have two thumbnails at different sizes; albums generally have one cropped thumbnail. If the thumbsize parameter is set to the initial query, this element points to thumbnails of the requested sizes; otherwise the thumbnails are the default thumbnail size. This element must not be confused with the <gphoto:thumbnail> element. Attributes: url: The URL of the thumbnail image. height: The height of the thumbnail image, in pixels. width: The width of the thumbnail image, in pixels. """ _tag = 'thumbnail' _attributes = atom.AtomBase._attributes.copy() _attributes['url'] = 'url' _attributes['width'] = 'width' _attributes['height'] = 'height' def __init__(self, url=None, width=None, height=None, extension_attributes=None, text=None, extension_elements=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.url = url self.width = width self.height = height def ThumbnailFromString(xml_string): return atom.CreateClassFromXMLString(Thumbnail, xml_string) class Title(MediaBaseElement): """(string) Contains the title of the entry's media content, in plain text. Attributes: type: Always set to plain. To set the type member in the constructor, use the title_type parameter. """ _tag = 'title' _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' def __init__(self, title_type=None, extension_attributes=None, text=None, extension_elements=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.type = title_type def TitleFromString(xml_string): return atom.CreateClassFromXMLString(Title, xml_string) class Player(MediaBaseElement): """(string) Contains the embeddable player URL for the entry's media content if the media is a video. Attributes: url: Always set to plain """ _tag = 'player' _attributes = atom.AtomBase._attributes.copy() _attributes['url'] = 'url' def __init__(self, player_url=None, extension_attributes=None, extension_elements=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes) self.url= player_url class Private(atom.AtomBase): """The YouTube Private element""" _tag = 'private' _namespace = YOUTUBE_NAMESPACE class Duration(atom.AtomBase): """The YouTube Duration element""" _tag = 'duration' _namespace = YOUTUBE_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['seconds'] = 'seconds' class Category(MediaBaseElement): """The mediagroup:category element""" _tag = 'category' _attributes = atom.AtomBase._attributes.copy() _attributes['term'] = 'term' _attributes['scheme'] = 'scheme' _attributes['label'] = 'label' def __init__(self, term=None, scheme=None, label=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Category Args: term: str scheme: str label: str text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.term = term self.scheme = scheme self.label = label self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Group(MediaBaseElement): """Container element for all media elements. The <media:group> element can appear as a child of an album, photo or video entry.""" _tag = 'group' _children = atom.AtomBase._children.copy() _children['{%s}content' % MEDIA_NAMESPACE] = ('content', [Content,]) _children['{%s}credit' % MEDIA_NAMESPACE] = ('credit', Credit) _children['{%s}description' % MEDIA_NAMESPACE] = ('description', Description) _children['{%s}keywords' % MEDIA_NAMESPACE] = ('keywords', Keywords) _children['{%s}thumbnail' % MEDIA_NAMESPACE] = ('thumbnail', [Thumbnail,]) _children['{%s}title' % MEDIA_NAMESPACE] = ('title', Title) _children['{%s}category' % MEDIA_NAMESPACE] = ('category', [Category,]) _children['{%s}duration' % YOUTUBE_NAMESPACE] = ('duration', Duration) _children['{%s}private' % YOUTUBE_NAMESPACE] = ('private', Private) _children['{%s}player' % MEDIA_NAMESPACE] = ('player', Player) def __init__(self, content=None, credit=None, description=None, keywords=None, thumbnail=None, title=None, duration=None, private=None, category=None, player=None, extension_elements=None, extension_attributes=None, text=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.content=content self.credit=credit self.description=description self.keywords=keywords self.thumbnail=thumbnail or [] self.title=title self.duration=duration self.private=private self.category=category or [] self.player=player def GroupFromString(xml_string): return atom.CreateClassFromXMLString(Group, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the data classes of the Geography Extension""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core GEORSS_TEMPLATE = '{http://www.georss.org/georss/}%s' GML_TEMPLATE = '{http://www.opengis.net/gml/}%s' GEO_TEMPLATE = '{http://www.w3.org/2003/01/geo/wgs84_pos#/}%s' class GeoLat(atom.core.XmlElement): """Describes a W3C latitude.""" _qname = GEO_TEMPLATE % 'lat' class GeoLong(atom.core.XmlElement): """Describes a W3C longitude.""" _qname = GEO_TEMPLATE % 'long' class GeoRssBox(atom.core.XmlElement): """Describes a geographical region.""" _qname = GEORSS_TEMPLATE % 'box' class GeoRssPoint(atom.core.XmlElement): """Describes a geographical location.""" _qname = GEORSS_TEMPLATE % 'point' class GmlLowerCorner(atom.core.XmlElement): """Describes a lower corner of a region.""" _qname = GML_TEMPLATE % 'lowerCorner' class GmlPos(atom.core.XmlElement): """Describes a latitude and longitude.""" _qname = GML_TEMPLATE % 'pos' class GmlPoint(atom.core.XmlElement): """Describes a particular geographical point.""" _qname = GML_TEMPLATE % 'Point' pos = GmlPos class GmlUpperCorner(atom.core.XmlElement): """Describes an upper corner of a region.""" _qname = GML_TEMPLATE % 'upperCorner' class GmlEnvelope(atom.core.XmlElement): """Describes a Gml geographical region.""" _qname = GML_TEMPLATE % 'Envelope' lower_corner = GmlLowerCorner upper_corner = GmlUpperCorner class GeoRssWhere(atom.core.XmlElement): """Describes a geographical location or region.""" _qname = GEORSS_TEMPLATE % 'where' Point = GmlPoint Envelope = GmlEnvelope class W3CPoint(atom.core.XmlElement): """Describes a W3C geographical location.""" _qname = GEO_TEMPLATE % 'Point' long = GeoLong lat = GeoLat
Python
# -*-*- encoding: utf-8 -*-*- # # This is gdata.photos.geo, implementing geological positioning in gdata structures # # $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # Portions copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Picasa Web Albums uses the georss and gml namespaces for elements defined in the GeoRSS and Geography Markup Language specifications. Specifically, Picasa Web Albums uses the following elements: georss:where gml:Point gml:pos http://code.google.com/apis/picasaweb/reference.html#georss_reference Picasa Web Albums also accepts geographic-location data in two other formats: W3C format and plain-GeoRSS (without GML) format. """ # #Over the wire, the Picasa Web Albums only accepts and sends the #elements mentioned above, but this module will let you seamlessly convert #between the different formats (TODO 2007-10-18 hg) __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: api chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' import atom import gdata GEO_NAMESPACE = 'http://www.w3.org/2003/01/geo/wgs84_pos#' GML_NAMESPACE = 'http://www.opengis.net/gml' GEORSS_NAMESPACE = 'http://www.georss.org/georss' class GeoBaseElement(atom.AtomBase): """Base class for elements. To add new elements, you only need to add the element tag name to self._tag and the namespace to self._namespace """ _tag = '' _namespace = GML_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Pos(GeoBaseElement): """(string) Specifies a latitude and longitude, separated by a space, e.g. `35.669998 139.770004'""" _tag = 'pos' def PosFromString(xml_string): return atom.CreateClassFromXMLString(Pos, xml_string) class Point(GeoBaseElement): """(container) Specifies a particular geographical point, by means of a <gml:pos> element.""" _tag = 'Point' _children = atom.AtomBase._children.copy() _children['{%s}pos' % GML_NAMESPACE] = ('pos', Pos) def __init__(self, pos=None, extension_elements=None, extension_attributes=None, text=None): GeoBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) if pos is None: pos = Pos() self.pos=pos def PointFromString(xml_string): return atom.CreateClassFromXMLString(Point, xml_string) class Where(GeoBaseElement): """(container) Specifies a geographical location or region. A container element, containing a single <gml:Point> element. (Not to be confused with <gd:where>.) Note that the (only) child attribute, .Point, is title-cased. This reflects the names of elements in the xml stream (principle of least surprise). As a convenience, you can get a tuple of (lat, lon) with Where.location(), and set the same data with Where.setLocation( (lat, lon) ). Similarly, there are methods to set and get only latitude and longitude. """ _tag = 'where' _namespace = GEORSS_NAMESPACE _children = atom.AtomBase._children.copy() _children['{%s}Point' % GML_NAMESPACE] = ('Point', Point) def __init__(self, point=None, extension_elements=None, extension_attributes=None, text=None): GeoBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) if point is None: point = Point() self.Point=point def location(self): "(float, float) Return Where.Point.pos.text as a (lat,lon) tuple" try: return tuple([float(z) for z in self.Point.pos.text.split(' ')]) except AttributeError: return tuple() def set_location(self, latlon): """(bool) Set Where.Point.pos.text from a (lat,lon) tuple. Arguments: lat (float): The latitude in degrees, from -90.0 to 90.0 lon (float): The longitude in degrees, from -180.0 to 180.0 Returns True on success. """ assert(isinstance(latlon[0], float)) assert(isinstance(latlon[1], float)) try: self.Point.pos.text = "%s %s" % (latlon[0], latlon[1]) return True except AttributeError: return False def latitude(self): "(float) Get the latitude value of the geo-tag. See also .location()" lat, lon = self.location() return lat def longitude(self): "(float) Get the longtitude value of the geo-tag. See also .location()" lat, lon = self.location() return lon longtitude = longitude def set_latitude(self, lat): """(bool) Set the latitude value of the geo-tag. Args: lat (float): The new latitude value See also .set_location() """ _lat, lon = self.location() return self.set_location(lat, lon) def set_longitude(self, lon): """(bool) Set the longtitude value of the geo-tag. Args: lat (float): The new latitude value See also .set_location() """ lat, _lon = self.location() return self.set_location(lat, lon) set_longtitude = set_longitude def WhereFromString(xml_string): return atom.CreateClassFromXMLString(Where, xml_string)
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """LicensingClient simplifies Google Apps Marketplace Licensing API calls. LicensingClient extends gdata.client.GDClient to ease interaction with the Google Apps Marketplace Licensing API. These interactions include the ability to retrieve License informations for an application in the Google Apps Marketplace. """ __author__ = 'Alexandre Vivien <alex@simplecode.fr>' import gdata.marketplace.data import gdata.client import urllib # Feed URI template. This must end with a / # The strings in this template are eventually replaced with the API version # and Google Apps domain name, respectively. LICENSE_ROOT_URL = 'http://feedserver-enterprise.googleusercontent.com' LICENSE_FEED_TEMPLATE = '%s/license?bq=' % LICENSE_ROOT_URL LICENSE_NOTIFICATIONS_FEED_TEMPLATE = '%s/licensenotification?bq=' % LICENSE_ROOT_URL class LicensingClient(gdata.client.GDClient): """Client extension for the Google Apps Marketplace Licensing API service. Attributes: host: string The hostname for the Google Apps Marketplace Licensing API service. api_version: string The version of the Google Apps Marketplace Licensing API. """ api_version = '1.0' auth_service = 'apps' auth_scopes = gdata.gauth.AUTH_SCOPES['apps'] ssl = False def __init__(self, domain, auth_token=None, **kwargs): """Constructs a new client for the Google Apps Marketplace Licensing API. Args: domain: string The Google Apps domain with the application installed. auth_token: (optional) gdata.gauth.OAuthToken which authorizes this client to retrieve the License information. kwargs: The other parameters to pass to the gdata.client.GDClient constructor. """ gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs) self.domain = domain def make_license_feed_uri(self, app_id=None, params=None): """Creates a license feed URI for the Google Apps Marketplace Licensing API. Using this client's Google Apps domain, create a license feed URI for a particular application in this domain. If params are provided, append them as GET params. Args: app_id: string The ID of the application for which to make a license feed URI. params: dict (optional) key -> value params to append as GET vars to the URI. Example: params={'start': 'my-resource-id'} Returns: A string giving the URI for the application's license for this client's Google Apps domain. """ parameters = '[appid=%s][domain=%s]' % (app_id, self.domain) uri = LICENSE_FEED_TEMPLATE + urllib.quote_plus(parameters) if params: uri += '&' + urllib.urlencode(params) return uri MakeLicenseFeedUri = make_license_feed_uri def make_license_notifications_feed_uri(self, app_id=None, startdatetime=None, max_results=None, params=None): """Creates a license notifications feed URI for the Google Apps Marketplace Licensing API. Using this client's Google Apps domain, create a license notifications feed URI for a particular application. If params are provided, append them as GET params. Args: app_id: string The ID of the application for which to make a license feed URI. startdatetime: Start date to retrieve the License notifications. max_results: Number of results per page. Maximum is 100. params: dict (optional) key -> value params to append as GET vars to the URI. Example: params={'start': 'my-resource-id'} Returns: A string giving the URI for the application's license notifications for this client's Google Apps domain. """ parameters = '[appid=%s]' % (app_id) if startdatetime: parameters += '[startdatetime=%s]' % startdatetime else: parameters += '[startdatetime=1970-01-01T00:00:00Z]' if max_results: parameters += '[max-results=%s]' % max_results else: parameters += '[max-results=100]' uri = LICENSE_NOTIFICATIONS_FEED_TEMPLATE + urllib.quote_plus(parameters) if params: uri += '&' + urllib.urlencode(params) return uri MakeLicenseNotificationsFeedUri = make_license_notifications_feed_uri def get_license(self, uri=None, app_id=None, **kwargs): """Fetches the application's license by application ID. Args: uri: string The base URI of the feed from which to fetch the license. app_id: string The string ID of the application for which to fetch the license. kwargs: The other parameters to pass to gdata.client.GDClient.get_entry(). Returns: A License feed object representing the license with the given base URI and application ID. """ if uri is None: uri = self.MakeLicenseFeedUri(app_id) return self.get_feed(uri, desired_class=gdata.marketplace.data.LicenseFeed, **kwargs) GetLicense = get_license def get_license_notifications(self, uri=None, app_id=None, startdatetime=None, max_results=None, **kwargs): """Fetches the application's license notifications by application ID. Args: uri: string The base URI of the feed from which to fetch the license. app_id: string The string ID of the application for which to fetch the license. startdatetime: Start date to retrieve the License notifications. max_results: Number of results per page. Maximum is 100. kwargs: The other parameters to pass to gdata.client.GDClient.get_entry(). Returns: A License feed object representing the license notifications with the given base URI and application ID. """ if uri is None: uri = self.MakeLicenseNotificationsFeedUri(app_id, startdatetime, max_results) return self.get_feed(uri, desired_class=gdata.marketplace.data.LicenseFeed, **kwargs) GetLicenseNotifications = get_license_notifications
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model for parsing and generating XML for the Google Apps Marketplace Licensing API.""" __author__ = 'Alexandre Vivien <alex@simplecode.fr>' import atom.core import gdata import gdata.data LICENSES_NAMESPACE = 'http://www.w3.org/2005/Atom' LICENSES_TEMPLATE = '{%s}%%s' % LICENSES_NAMESPACE class Enabled(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'enabled' class Id(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'id' class CustomerId(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'customerid' class DomainName(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'domainname' class InstallerEmail(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'installeremail' class TosAcceptanceTime(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'tosacceptancetime' class LastChangeTime(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'lastchangetime' class ProductConfigId(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'productconfigid' class State(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'state' class Entity(atom.core.XmlElement): """ The entity representing the License. """ _qname = LICENSES_TEMPLATE % 'entity' enabled = Enabled id = Id customer_id = CustomerId domain_name = DomainName installer_email = InstallerEmail tos_acceptance_time = TosAcceptanceTime last_change_time = LastChangeTime product_config_id = ProductConfigId state = State class Content(atom.data.Content): entity = Entity class LicenseEntry(gdata.data.GDEntry): """ Represents a LicenseEntry object. """ content = Content class LicenseFeed(gdata.data.GDFeed): """ Represents a feed of LicenseEntry objects. """ # Override entry so that this feed knows how to type its list of entries. entry = [LicenseEntry]
Python
#!/usr/bin/env python # -*-*- encoding: utf-8 -*-*- # # This is the service file for the Google Photo python client. # It is used for higher level operations. # # $Id: service.py 144 2007-10-25 21:03:34Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Google PhotoService provides a human-friendly interface to Google Photo (a.k.a Picasa Web) services[1]. It extends gdata.service.GDataService and as such hides all the nasty details about authenticating, parsing and communicating with Google Photos. [1]: http://code.google.com/apis/picasaweb/gdata.html Example: import gdata.photos, gdata.photos.service pws = gdata.photos.service.PhotosService() pws.ClientLogin(username, password) #Get all albums albums = pws.GetUserFeed().entry # Get all photos in second album photos = pws.GetFeed(albums[1].GetPhotosUri()).entry # Get all tags for photos in second album and print them tags = pws.GetFeed(albums[1].GetTagsUri()).entry print [ tag.summary.text for tag in tags ] # Get all comments for the first photos in list and print them comments = pws.GetCommentFeed(photos[0].GetCommentsUri()).entry print [ c.summary.text for c in comments ] # Get a photo to work with photo = photos[0] # Update metadata # Attributes from the <gphoto:*> namespace photo.summary.text = u'A nice view from my veranda' photo.title.text = u'Verandaview.jpg' # Attributes from the <media:*> namespace photo.media.keywords.text = u'Home, Long-exposure, Sunset' # Comma-separated # Adding attributes to media object # Rotate 90 degrees clockwise photo.rotation = gdata.photos.Rotation(text='90') # Submit modified photo object photo = pws.UpdatePhotoMetadata(photo) # Make sure you only modify the newly returned object, else you'll get # versioning errors. See Optimistic-concurrency # Add comment to a picture comment = pws.InsertComment(photo, u'I wish the water always was this warm') # Remove comment because it was silly print "*blush*" pws.Delete(comment.GetEditLink().href) """ __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' __version__ = '$Revision: 176 $'[11:-2] import sys, os.path, StringIO import time import gdata.service import gdata import atom.service import atom import gdata.photos SUPPORTED_UPLOAD_TYPES = ('bmp', 'jpeg', 'jpg', 'gif', 'png') UNKOWN_ERROR=1000 GPHOTOS_BAD_REQUEST=400 GPHOTOS_CONFLICT=409 GPHOTOS_INTERNAL_SERVER_ERROR=500 GPHOTOS_INVALID_ARGUMENT=601 GPHOTOS_INVALID_CONTENT_TYPE=602 GPHOTOS_NOT_AN_IMAGE=603 GPHOTOS_INVALID_KIND=604 class GooglePhotosException(Exception): def __init__(self, response): self.error_code = response['status'] self.reason = response['reason'].strip() if '<html>' in str(response['body']): #general html message, discard it response['body'] = "" self.body = response['body'].strip() self.message = "(%(status)s) %(body)s -- %(reason)s" % response #return explicit error codes error_map = { '(12) Not an image':GPHOTOS_NOT_AN_IMAGE, 'kind: That is not one of the acceptable values': GPHOTOS_INVALID_KIND, } for msg, code in error_map.iteritems(): if self.body == msg: self.error_code = code break self.args = [self.error_code, self.reason, self.body] class PhotosService(gdata.service.GDataService): ssl = True userUri = '/data/feed/api/user/%s' def __init__(self, email=None, password=None, source=None, server='picasaweb.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Photos service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'picasaweb.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ self.email = email self.client = source gdata.service.GDataService.__init__( self, email=email, password=password, service='lh2', source=source, server=server, additional_headers=additional_headers, **kwargs) def GetFeed(self, uri, limit=None, start_index=None): """Get a feed. The results are ordered by the values of their `updated' elements, with the most recently updated entry appearing first in the feed. Arguments: uri: the uri to fetch limit (optional): the maximum number of entries to return. Defaults to what the server returns. Returns: one of gdata.photos.AlbumFeed, gdata.photos.UserFeed, gdata.photos.PhotoFeed, gdata.photos.CommentFeed, gdata.photos.TagFeed, depending on the results of the query. Raises: GooglePhotosException See: http://code.google.com/apis/picasaweb/gdata.html#Get_Album_Feed_Manual """ if limit is not None: uri += '&max-results=%s' % limit if start_index is not None: uri += '&start-index=%s' % start_index try: return self.Get(uri, converter=gdata.photos.AnyFeedFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def GetEntry(self, uri, limit=None, start_index=None): """Get an Entry. Arguments: uri: the uri to the entry limit (optional): the maximum number of entries to return. Defaults to what the server returns. Returns: one of gdata.photos.AlbumEntry, gdata.photos.UserEntry, gdata.photos.PhotoEntry, gdata.photos.CommentEntry, gdata.photos.TagEntry, depending on the results of the query. Raises: GooglePhotosException """ if limit is not None: uri += '&max-results=%s' % limit if start_index is not None: uri += '&start-index=%s' % start_index try: return self.Get(uri, converter=gdata.photos.AnyEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def GetUserFeed(self, kind='album', user='default', limit=None): """Get user-based feed, containing albums, photos, comments or tags; defaults to albums. The entries are ordered by the values of their `updated' elements, with the most recently updated entry appearing first in the feed. Arguments: kind: the kind of entries to get, either `album', `photo', `comment' or `tag', or a python list of these. Defaults to `album'. user (optional): whose albums we're querying. Defaults to current user. limit (optional): the maximum number of entries to return. Defaults to everything the server returns. Returns: gdata.photos.UserFeed, containing appropriate Entry elements See: http://code.google.com/apis/picasaweb/gdata.html#Get_Album_Feed_Manual http://googledataapis.blogspot.com/2007/07/picasa-web-albums-adds-new-api-features.html """ if isinstance(kind, (list, tuple) ): kind = ",".join(kind) uri = '/data/feed/api/user/%s?kind=%s' % (user, kind) return self.GetFeed(uri, limit=limit) def GetTaggedPhotos(self, tag, user='default', limit=None): """Get all photos belonging to a specific user, tagged by the given keyword Arguments: tag: The tag you're looking for, e.g. `dog' user (optional): Whose images/videos you want to search, defaults to current user limit (optional): the maximum number of entries to return. Defaults to everything the server returns. Returns: gdata.photos.UserFeed containing PhotoEntry elements """ # Lower-casing because of # http://code.google.com/p/gdata-issues/issues/detail?id=194 uri = '/data/feed/api/user/%s?kind=photo&tag=%s' % (user, tag.lower()) return self.GetFeed(uri, limit) def SearchUserPhotos(self, query, user='default', limit=100): """Search through all photos for a specific user and return a feed. This will look for matches in file names and image tags (a.k.a. keywords) Arguments: query: The string you're looking for, e.g. `vacation' user (optional): The username of whose photos you want to search, defaults to current user. limit (optional): Don't return more than `limit' hits, defaults to 100 Only public photos are searched, unless you are authenticated and searching through your own photos. Returns: gdata.photos.UserFeed with PhotoEntry elements """ uri = '/data/feed/api/user/%s?kind=photo&q=%s' % (user, query) return self.GetFeed(uri, limit=limit) def SearchCommunityPhotos(self, query, limit=100): """Search through all public photos and return a feed. This will look for matches in file names and image tags (a.k.a. keywords) Arguments: query: The string you're looking for, e.g. `vacation' limit (optional): Don't return more than `limit' hits, defaults to 100 Returns: gdata.GDataFeed with PhotoEntry elements """ uri='/data/feed/api/all?q=%s' % query return self.GetFeed(uri, limit=limit) def GetContacts(self, user='default', limit=None): """Retrieve a feed that contains a list of your contacts Arguments: user: Username of the user whose contacts you want Returns gdata.photos.UserFeed, with UserEntry entries See: http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38 """ uri = '/data/feed/api/user/%s/contacts?kind=user' % user return self.GetFeed(uri, limit=limit) def SearchContactsPhotos(self, user='default', search=None, limit=None): """Search over your contacts' photos and return a feed Arguments: user: Username of the user whose contacts you want search (optional): What to search for (photo title, description and keywords) Returns gdata.photos.UserFeed, with PhotoEntry elements See: http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38 """ uri = '/data/feed/api/user/%s/contacts?kind=photo&q=%s' % (user, search) return self.GetFeed(uri, limit=limit) def InsertAlbum(self, title, summary, location=None, access='public', commenting_enabled='true', timestamp=None): """Add an album. Needs authentication, see self.ClientLogin() Arguments: title: Album title summary: Album summary / description access (optional): `private' or `public'. Public albums are searchable by everyone on the internet. Defaults to `public' commenting_enabled (optional): `true' or `false'. Defaults to `true'. timestamp (optional): A date and time for the album, in milliseconds since Unix epoch[1] UTC. Defaults to now. Returns: The newly created gdata.photos.AlbumEntry See: http://code.google.com/apis/picasaweb/gdata.html#Add_Album_Manual_Installed [1]: http://en.wikipedia.org/wiki/Unix_epoch """ album = gdata.photos.AlbumEntry() album.title = atom.Title(text=title, title_type='text') album.summary = atom.Summary(text=summary, summary_type='text') if location is not None: album.location = gdata.photos.Location(text=location) album.access = gdata.photos.Access(text=access) if commenting_enabled in ('true', 'false'): album.commentingEnabled = gdata.photos.CommentingEnabled(text=commenting_enabled) if timestamp is None: timestamp = '%i' % int(time.time() * 1000) album.timestamp = gdata.photos.Timestamp(text=timestamp) try: return self.Post(album, uri=self.userUri % self.email, converter=gdata.photos.AlbumEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertPhoto(self, album_or_uri, photo, filename_or_handle, content_type='image/jpeg'): """Add a PhotoEntry Needs authentication, see self.ClientLogin() Arguments: album_or_uri: AlbumFeed or uri of the album where the photo should go photo: PhotoEntry to add filename_or_handle: A file-like object or file name where the image/video will be read from content_type (optional): Internet media type (a.k.a. mime type) of media object. Currently Google Photos supports these types: o image/bmp o image/gif o image/jpeg o image/png Images will be converted to jpeg on upload. Defaults to `image/jpeg' """ try: assert(isinstance(photo, gdata.photos.PhotoEntry)) except AssertionError: raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT, 'body':'`photo` must be a gdata.photos.PhotoEntry instance', 'reason':'Found %s, not PhotoEntry' % type(photo) }) try: majtype, mintype = content_type.split('/') assert(mintype in SUPPORTED_UPLOAD_TYPES) except (ValueError, AssertionError): raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE, 'body':'This is not a valid content type: %s' % content_type, 'reason':'Accepted content types: %s' % \ ['image/'+t for t in SUPPORTED_UPLOAD_TYPES] }) if isinstance(filename_or_handle, (str, unicode)) and \ os.path.exists(filename_or_handle): # it's a file name mediasource = gdata.MediaSource() mediasource.setFile(filename_or_handle, content_type) elif hasattr(filename_or_handle, 'read'):# it's a file-like resource if hasattr(filename_or_handle, 'seek'): filename_or_handle.seek(0) # rewind pointer to the start of the file # gdata.MediaSource needs the content length, so read the whole image file_handle = StringIO.StringIO(filename_or_handle.read()) name = 'image' if hasattr(filename_or_handle, 'name'): name = filename_or_handle.name mediasource = gdata.MediaSource(file_handle, content_type, content_length=file_handle.len, file_name=name) else: #filename_or_handle is not valid raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT, 'body':'`filename_or_handle` must be a path name or a file-like object', 'reason':'Found %s, not path name or object with a .read() method' % \ filename_or_handle }) if isinstance(album_or_uri, (str, unicode)): # it's a uri feed_uri = album_or_uri elif hasattr(album_or_uri, 'GetFeedLink'): # it's a AlbumFeed object feed_uri = album_or_uri.GetFeedLink().href try: return self.Post(photo, uri=feed_uri, media_source=mediasource, converter=gdata.photos.PhotoEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertPhotoSimple(self, album_or_uri, title, summary, filename_or_handle, content_type='image/jpeg', keywords=None): """Add a photo without constructing a PhotoEntry. Needs authentication, see self.ClientLogin() Arguments: album_or_uri: AlbumFeed or uri of the album where the photo should go title: Photo title summary: Photo summary / description filename_or_handle: A file-like object or file name where the image/video will be read from content_type (optional): Internet media type (a.k.a. mime type) of media object. Currently Google Photos supports these types: o image/bmp o image/gif o image/jpeg o image/png Images will be converted to jpeg on upload. Defaults to `image/jpeg' keywords (optional): a 1) comma separated string or 2) a python list() of keywords (a.k.a. tags) to add to the image. E.g. 1) `dog, vacation, happy' 2) ['dog', 'happy', 'vacation'] Returns: The newly created gdata.photos.PhotoEntry or GooglePhotosException on errors See: http://code.google.com/apis/picasaweb/gdata.html#Add_Album_Manual_Installed [1]: http://en.wikipedia.org/wiki/Unix_epoch """ metadata = gdata.photos.PhotoEntry() metadata.title=atom.Title(text=title) metadata.summary = atom.Summary(text=summary, summary_type='text') if keywords is not None: if isinstance(keywords, list): keywords = ','.join(keywords) metadata.media.keywords = gdata.media.Keywords(text=keywords) return self.InsertPhoto(album_or_uri, metadata, filename_or_handle, content_type) def UpdatePhotoMetadata(self, photo): """Update a photo's metadata. Needs authentication, see self.ClientLogin() You can update any or all of the following metadata properties: * <title> * <media:description> * <gphoto:checksum> * <gphoto:client> * <gphoto:rotation> * <gphoto:timestamp> * <gphoto:commentingEnabled> Arguments: photo: a gdata.photos.PhotoEntry object with updated elements Returns: The modified gdata.photos.PhotoEntry Example: p = GetFeed(uri).entry[0] p.title.text = u'My new text' p.commentingEnabled.text = 'false' p = UpdatePhotoMetadata(p) It is important that you don't keep the old object around, once it has been updated. See http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency """ try: return self.Put(data=photo, uri=photo.GetEditLink().href, converter=gdata.photos.PhotoEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def UpdatePhotoBlob(self, photo_or_uri, filename_or_handle, content_type = 'image/jpeg'): """Update a photo's binary data. Needs authentication, see self.ClientLogin() Arguments: photo_or_uri: a gdata.photos.PhotoEntry that will be updated, or a `edit-media' uri pointing to it filename_or_handle: A file-like object or file name where the image/video will be read from content_type (optional): Internet media type (a.k.a. mime type) of media object. Currently Google Photos supports these types: o image/bmp o image/gif o image/jpeg o image/png Images will be converted to jpeg on upload. Defaults to `image/jpeg' Returns: The modified gdata.photos.PhotoEntry Example: p = GetFeed(PhotoUri) p = UpdatePhotoBlob(p, '/tmp/newPic.jpg') It is important that you don't keep the old object around, once it has been updated. See http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency """ try: majtype, mintype = content_type.split('/') assert(mintype in SUPPORTED_UPLOAD_TYPES) except (ValueError, AssertionError): raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE, 'body':'This is not a valid content type: %s' % content_type, 'reason':'Accepted content types: %s' % \ ['image/'+t for t in SUPPORTED_UPLOAD_TYPES] }) if isinstance(filename_or_handle, (str, unicode)) and \ os.path.exists(filename_or_handle): # it's a file name photoblob = gdata.MediaSource() photoblob.setFile(filename_or_handle, content_type) elif hasattr(filename_or_handle, 'read'):# it's a file-like resource if hasattr(filename_or_handle, 'seek'): filename_or_handle.seek(0) # rewind pointer to the start of the file # gdata.MediaSource needs the content length, so read the whole image file_handle = StringIO.StringIO(filename_or_handle.read()) name = 'image' if hasattr(filename_or_handle, 'name'): name = filename_or_handle.name mediasource = gdata.MediaSource(file_handle, content_type, content_length=file_handle.len, file_name=name) else: #filename_or_handle is not valid raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT, 'body':'`filename_or_handle` must be a path name or a file-like object', 'reason':'Found %s, not path name or an object with .read() method' % \ type(filename_or_handle) }) if isinstance(photo_or_uri, (str, unicode)): entry_uri = photo_or_uri # it's a uri elif hasattr(photo_or_uri, 'GetEditMediaLink'): entry_uri = photo_or_uri.GetEditMediaLink().href try: return self.Put(photoblob, entry_uri, converter=gdata.photos.PhotoEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertTag(self, photo_or_uri, tag): """Add a tag (a.k.a. keyword) to a photo. Needs authentication, see self.ClientLogin() Arguments: photo_or_uri: a gdata.photos.PhotoEntry that will be tagged, or a `post' uri pointing to it (string) tag: The tag/keyword Returns: The new gdata.photos.TagEntry Example: p = GetFeed(PhotoUri) tag = InsertTag(p, 'Beautiful sunsets') """ tag = gdata.photos.TagEntry(title=atom.Title(text=tag)) if isinstance(photo_or_uri, (str, unicode)): post_uri = photo_or_uri # it's a uri elif hasattr(photo_or_uri, 'GetEditMediaLink'): post_uri = photo_or_uri.GetPostLink().href try: return self.Post(data=tag, uri=post_uri, converter=gdata.photos.TagEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertComment(self, photo_or_uri, comment): """Add a comment to a photo. Needs authentication, see self.ClientLogin() Arguments: photo_or_uri: a gdata.photos.PhotoEntry that is about to be commented , or a `post' uri pointing to it (string) comment: The actual comment Returns: The new gdata.photos.CommentEntry Example: p = GetFeed(PhotoUri) tag = InsertComment(p, 'OOOH! I would have loved to be there. Who's that in the back?') """ comment = gdata.photos.CommentEntry(content=atom.Content(text=comment)) if isinstance(photo_or_uri, (str, unicode)): post_uri = photo_or_uri # it's a uri elif hasattr(photo_or_uri, 'GetEditMediaLink'): post_uri = photo_or_uri.GetPostLink().href try: return self.Post(data=comment, uri=post_uri, converter=gdata.photos.CommentEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def Delete(self, object_or_uri, *args, **kwargs): """Delete an object. Re-implementing the GDataService.Delete method, to add some convenience. Arguments: object_or_uri: Any object that has a GetEditLink() method that returns a link, or a uri to that object. Returns: ? or GooglePhotosException on errors """ try: uri = object_or_uri.GetEditLink().href except AttributeError: uri = object_or_uri try: return gdata.service.GDataService.Delete(self, uri, *args, **kwargs) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def GetSmallestThumbnail(media_thumbnail_list): """Helper function to get the smallest thumbnail of a list of gdata.media.Thumbnail. Returns gdata.media.Thumbnail """ r = {} for thumb in media_thumbnail_list: r[int(thumb.width)*int(thumb.height)] = thumb keys = r.keys() keys.sort() return r[keys[0]] def ConvertAtomTimestampToEpoch(timestamp): """Helper function to convert a timestamp string, for instance from atom:updated or atom:published, to milliseconds since Unix epoch (a.k.a. POSIX time). `2007-07-22T00:45:10.000Z' -> """ return time.mktime(time.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.000Z')) ## TODO: Timezone aware
Python
# -*-*- encoding: utf-8 -*-*- # # This is the base file for the PicasaWeb python client. # It is used for lower level operations. # # $Id: __init__.py 148 2007-10-28 15:09:19Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # Portions (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module provides a pythonic, gdata-centric interface to Google Photos (a.k.a. Picasa Web Services. It is modelled after the gdata/* interfaces from the gdata-python-client project[1] by Google. You'll find the user-friendly api in photos.service. Please see the documentation or live help() system for available methods. [1]: http://gdata-python-client.googlecode.com/ """ __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' __version__ = '$Revision: 164 $'[11:-2] import re try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata # importing google photo submodules import gdata.media as Media, gdata.exif as Exif, gdata.geo as Geo # XML namespaces which are often used in Google Photo elements PHOTOS_NAMESPACE = 'http://schemas.google.com/photos/2007' MEDIA_NAMESPACE = 'http://search.yahoo.com/mrss/' EXIF_NAMESPACE = 'http://schemas.google.com/photos/exif/2007' OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/' GEO_NAMESPACE = 'http://www.w3.org/2003/01/geo/wgs84_pos#' GML_NAMESPACE = 'http://www.opengis.net/gml' GEORSS_NAMESPACE = 'http://www.georss.org/georss' PHEED_NAMESPACE = 'http://www.pheed.com/pheed/' BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch' class PhotosBaseElement(atom.AtomBase): """Base class for elements in the PHOTO_NAMESPACE. To add new elements, you only need to add the element tag name to self._tag """ _tag = '' _namespace = PHOTOS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} #def __str__(self): #return str(self.text) #def __unicode__(self): #return unicode(self.text) def __int__(self): return int(self.text) def bool(self): return self.text == 'true' class GPhotosBaseFeed(gdata.GDataFeed, gdata.LinkFinder): "Base class for all Feeds in gdata.photos" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _attributes = gdata.GDataFeed._attributes.copy() _children = gdata.GDataFeed._children.copy() # We deal with Entry elements ourselves del _children['{%s}entry' % atom.ATOM_NAMESPACE] def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def kind(self): "(string) Returns the kind" try: return self.category[0].term.split('#')[1] except IndexError: return None def _feedUri(self, kind): "Convenience method to return a uri to a feed of a special kind" assert(kind in ('album', 'tag', 'photo', 'comment', 'user')) here_href = self.GetSelfLink().href if 'kind=%s' % kind in here_href: return here_href if not 'kind=' in here_href: sep = '?' if '?' in here_href: sep = '&' return here_href + "%skind=%s" % (sep, kind) rx = re.match('.*(kind=)(album|tag|photo|comment)', here_href) return here_href[:rx.end(1)] + kind + here_href[rx.end(2):] def _ConvertElementTreeToMember(self, child_tree): """Re-implementing the method from AtomBase, since we deal with Entry elements specially""" category = child_tree.find('{%s}category' % atom.ATOM_NAMESPACE) if category is None: return atom.AtomBase._ConvertElementTreeToMember(self, child_tree) namespace, kind = category.get('term').split('#') if namespace != PHOTOS_NAMESPACE: return atom.AtomBase._ConvertElementTreeToMember(self, child_tree) ## TODO: is it safe to use getattr on gdata.photos? entry_class = getattr(gdata.photos, '%sEntry' % kind.title()) if not hasattr(self, 'entry') or self.entry is None: self.entry = [] self.entry.append(atom._CreateClassFromElementTree( entry_class, child_tree)) class GPhotosBaseEntry(gdata.GDataEntry, gdata.LinkFinder): "Base class for all Entry elements in gdata.photos" _tag = 'entry' _kind = '' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.category.append( atom.Category(scheme='http://schemas.google.com/g/2005#kind', term = 'http://schemas.google.com/photos/2007#%s' % self._kind)) def kind(self): "(string) Returns the kind" try: return self.category[0].term.split('#')[1] except IndexError: return None def _feedUri(self, kind): "Convenience method to get the uri to this entry's feed of the some kind" try: href = self.GetFeedLink().href except AttributeError: return None sep = '?' if '?' in href: sep = '&' return '%s%skind=%s' % (href, sep, kind) class PhotosBaseEntry(GPhotosBaseEntry): pass class PhotosBaseFeed(GPhotosBaseFeed): pass class GPhotosBaseData(object): pass class Access(PhotosBaseElement): """The Google Photo `Access' element. The album's access level. Valid values are `public' or `private'. In documentation, access level is also referred to as `visibility.'""" _tag = 'access' def AccessFromString(xml_string): return atom.CreateClassFromXMLString(Access, xml_string) class Albumid(PhotosBaseElement): "The Google Photo `Albumid' element" _tag = 'albumid' def AlbumidFromString(xml_string): return atom.CreateClassFromXMLString(Albumid, xml_string) class BytesUsed(PhotosBaseElement): "The Google Photo `BytesUsed' element" _tag = 'bytesUsed' def BytesUsedFromString(xml_string): return atom.CreateClassFromXMLString(BytesUsed, xml_string) class Client(PhotosBaseElement): "The Google Photo `Client' element" _tag = 'client' def ClientFromString(xml_string): return atom.CreateClassFromXMLString(Client, xml_string) class Checksum(PhotosBaseElement): "The Google Photo `Checksum' element" _tag = 'checksum' def ChecksumFromString(xml_string): return atom.CreateClassFromXMLString(Checksum, xml_string) class CommentCount(PhotosBaseElement): "The Google Photo `CommentCount' element" _tag = 'commentCount' def CommentCountFromString(xml_string): return atom.CreateClassFromXMLString(CommentCount, xml_string) class CommentingEnabled(PhotosBaseElement): "The Google Photo `CommentingEnabled' element" _tag = 'commentingEnabled' def CommentingEnabledFromString(xml_string): return atom.CreateClassFromXMLString(CommentingEnabled, xml_string) class Height(PhotosBaseElement): "The Google Photo `Height' element" _tag = 'height' def HeightFromString(xml_string): return atom.CreateClassFromXMLString(Height, xml_string) class Id(PhotosBaseElement): "The Google Photo `Id' element" _tag = 'id' def IdFromString(xml_string): return atom.CreateClassFromXMLString(Id, xml_string) class Location(PhotosBaseElement): "The Google Photo `Location' element" _tag = 'location' def LocationFromString(xml_string): return atom.CreateClassFromXMLString(Location, xml_string) class MaxPhotosPerAlbum(PhotosBaseElement): "The Google Photo `MaxPhotosPerAlbum' element" _tag = 'maxPhotosPerAlbum' def MaxPhotosPerAlbumFromString(xml_string): return atom.CreateClassFromXMLString(MaxPhotosPerAlbum, xml_string) class Name(PhotosBaseElement): "The Google Photo `Name' element" _tag = 'name' def NameFromString(xml_string): return atom.CreateClassFromXMLString(Name, xml_string) class Nickname(PhotosBaseElement): "The Google Photo `Nickname' element" _tag = 'nickname' def NicknameFromString(xml_string): return atom.CreateClassFromXMLString(Nickname, xml_string) class Numphotos(PhotosBaseElement): "The Google Photo `Numphotos' element" _tag = 'numphotos' def NumphotosFromString(xml_string): return atom.CreateClassFromXMLString(Numphotos, xml_string) class Numphotosremaining(PhotosBaseElement): "The Google Photo `Numphotosremaining' element" _tag = 'numphotosremaining' def NumphotosremainingFromString(xml_string): return atom.CreateClassFromXMLString(Numphotosremaining, xml_string) class Position(PhotosBaseElement): "The Google Photo `Position' element" _tag = 'position' def PositionFromString(xml_string): return atom.CreateClassFromXMLString(Position, xml_string) class Photoid(PhotosBaseElement): "The Google Photo `Photoid' element" _tag = 'photoid' def PhotoidFromString(xml_string): return atom.CreateClassFromXMLString(Photoid, xml_string) class Quotacurrent(PhotosBaseElement): "The Google Photo `Quotacurrent' element" _tag = 'quotacurrent' def QuotacurrentFromString(xml_string): return atom.CreateClassFromXMLString(Quotacurrent, xml_string) class Quotalimit(PhotosBaseElement): "The Google Photo `Quotalimit' element" _tag = 'quotalimit' def QuotalimitFromString(xml_string): return atom.CreateClassFromXMLString(Quotalimit, xml_string) class Rotation(PhotosBaseElement): "The Google Photo `Rotation' element" _tag = 'rotation' def RotationFromString(xml_string): return atom.CreateClassFromXMLString(Rotation, xml_string) class Size(PhotosBaseElement): "The Google Photo `Size' element" _tag = 'size' def SizeFromString(xml_string): return atom.CreateClassFromXMLString(Size, xml_string) class Snippet(PhotosBaseElement): """The Google Photo `snippet' element. When searching, the snippet element will contain a string with the word you're looking for, highlighted in html markup E.g. when your query is `hafjell', this element may contain: `... here at <b>Hafjell</b>.' You'll find this element in searches -- that is, feeds that combine the `kind=photo' and `q=yoursearch' parameters in the request. See also gphoto:truncated and gphoto:snippettype. """ _tag = 'snippet' def SnippetFromString(xml_string): return atom.CreateClassFromXMLString(Snippet, xml_string) class Snippettype(PhotosBaseElement): """The Google Photo `Snippettype' element When searching, this element will tell you the type of element that matches. You'll find this element in searches -- that is, feeds that combine the `kind=photo' and `q=yoursearch' parameters in the request. See also gphoto:snippet and gphoto:truncated. Possible values and their interpretation: o ALBUM_TITLE - The album title matches o PHOTO_TAGS - The match is a tag/keyword o PHOTO_DESCRIPTION - The match is in the photo's description If you discover a value not listed here, please submit a patch to update this docstring. """ _tag = 'snippettype' def SnippettypeFromString(xml_string): return atom.CreateClassFromXMLString(Snippettype, xml_string) class Thumbnail(PhotosBaseElement): """The Google Photo `Thumbnail' element Used to display user's photo thumbnail (hackergotchi). (Not to be confused with the <media:thumbnail> element, which gives you small versions of the photo object.)""" _tag = 'thumbnail' def ThumbnailFromString(xml_string): return atom.CreateClassFromXMLString(Thumbnail, xml_string) class Timestamp(PhotosBaseElement): """The Google Photo `Timestamp' element Represented as the number of milliseconds since January 1st, 1970. Take a look at the convenience methods .isoformat() and .datetime(): photo_epoch = Time.text # 1180294337000 photo_isostring = Time.isoformat() # '2007-05-27T19:32:17.000Z' Alternatively: photo_datetime = Time.datetime() # (requires python >= 2.3) """ _tag = 'timestamp' def isoformat(self): """(string) Return the timestamp as a ISO 8601 formatted string, e.g. '2007-05-27T19:32:17.000Z' """ import time epoch = float(self.text)/1000 return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(epoch)) def datetime(self): """(datetime.datetime) Return the timestamp as a datetime.datetime object Requires python 2.3 """ import datetime epoch = float(self.text)/1000 return datetime.datetime.fromtimestamp(epoch) def TimestampFromString(xml_string): return atom.CreateClassFromXMLString(Timestamp, xml_string) class Truncated(PhotosBaseElement): """The Google Photo `Truncated' element You'll find this element in searches -- that is, feeds that combine the `kind=photo' and `q=yoursearch' parameters in the request. See also gphoto:snippet and gphoto:snippettype. Possible values and their interpretation: 0 -- unknown """ _tag = 'Truncated' def TruncatedFromString(xml_string): return atom.CreateClassFromXMLString(Truncated, xml_string) class User(PhotosBaseElement): "The Google Photo `User' element" _tag = 'user' def UserFromString(xml_string): return atom.CreateClassFromXMLString(User, xml_string) class Version(PhotosBaseElement): "The Google Photo `Version' element" _tag = 'version' def VersionFromString(xml_string): return atom.CreateClassFromXMLString(Version, xml_string) class Width(PhotosBaseElement): "The Google Photo `Width' element" _tag = 'width' def WidthFromString(xml_string): return atom.CreateClassFromXMLString(Width, xml_string) class Weight(PhotosBaseElement): """The Google Photo `Weight' element. The weight of the tag is the number of times the tag appears in the collection of tags currently being viewed. The default weight is 1, in which case this tags is omitted.""" _tag = 'weight' def WeightFromString(xml_string): return atom.CreateClassFromXMLString(Weight, xml_string) class CommentAuthor(atom.Author): """The Atom `Author' element in CommentEntry entries is augmented to contain elements from the PHOTOS_NAMESPACE http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38 """ _children = atom.Author._children.copy() _children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User) _children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname) _children['{%s}thumbnail' % PHOTOS_NAMESPACE] = ('thumbnail', Thumbnail) def CommentAuthorFromString(xml_string): return atom.CreateClassFromXMLString(CommentAuthor, xml_string) ########################## ################################ class AlbumData(object): _children = {} _children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id) _children['{%s}name' % PHOTOS_NAMESPACE] = ('name', Name) _children['{%s}location' % PHOTOS_NAMESPACE] = ('location', Location) _children['{%s}access' % PHOTOS_NAMESPACE] = ('access', Access) _children['{%s}bytesUsed' % PHOTOS_NAMESPACE] = ('bytesUsed', BytesUsed) _children['{%s}timestamp' % PHOTOS_NAMESPACE] = ('timestamp', Timestamp) _children['{%s}numphotos' % PHOTOS_NAMESPACE] = ('numphotos', Numphotos) _children['{%s}numphotosremaining' % PHOTOS_NAMESPACE] = \ ('numphotosremaining', Numphotosremaining) _children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User) _children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname) _children['{%s}commentingEnabled' % PHOTOS_NAMESPACE] = \ ('commentingEnabled', CommentingEnabled) _children['{%s}commentCount' % PHOTOS_NAMESPACE] = \ ('commentCount', CommentCount) ## NOTE: storing media:group as self.media, to create a self-explaining api gphoto_id = None name = None location = None access = None bytesUsed = None timestamp = None numphotos = None numphotosremaining = None user = None nickname = None commentingEnabled = None commentCount = None class AlbumEntry(GPhotosBaseEntry, AlbumData): """All metadata for a Google Photos Album Take a look at AlbumData for metadata accessible as attributes to this object. Notes: To avoid name clashes, and to create a more sensible api, some objects have names that differ from the original elements: o media:group -> self.media, o geo:where -> self.geo, o photo:id -> self.gphoto_id """ _kind = 'album' _children = GPhotosBaseEntry._children.copy() _children.update(AlbumData._children.copy()) # child tags only for Album entries, not feeds _children['{%s}where' % GEORSS_NAMESPACE] = ('geo', Geo.Where) _children['{%s}group' % MEDIA_NAMESPACE] = ('media', Media.Group) media = Media.Group() geo = Geo.Where() def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, #GPHOTO NAMESPACE: gphoto_id=None, name=None, location=None, access=None, timestamp=None, numphotos=None, user=None, nickname=None, commentingEnabled=None, commentCount=None, thumbnail=None, # MEDIA NAMESPACE: media=None, # GEORSS NAMESPACE: geo=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): GPhotosBaseEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) ## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id self.gphoto_id = gphoto_id self.name = name self.location = location self.access = access self.timestamp = timestamp self.numphotos = numphotos self.user = user self.nickname = nickname self.commentingEnabled = commentingEnabled self.commentCount = commentCount self.thumbnail = thumbnail self.extended_property = extended_property or [] self.text = text ## NOTE: storing media:group as self.media, and geo:where as geo, ## to create a self-explaining api self.media = media or Media.Group() self.geo = geo or Geo.Where() def GetAlbumId(self): "Return the id of this album" return self.GetFeedLink().href.split('/')[-1] def GetPhotosUri(self): "(string) Return the uri to this albums feed of the PhotoEntry kind" return self._feedUri('photo') def GetCommentsUri(self): "(string) Return the uri to this albums feed of the CommentEntry kind" return self._feedUri('comment') def GetTagsUri(self): "(string) Return the uri to this albums feed of the TagEntry kind" return self._feedUri('tag') def AlbumEntryFromString(xml_string): return atom.CreateClassFromXMLString(AlbumEntry, xml_string) class AlbumFeed(GPhotosBaseFeed, AlbumData): """All metadata for a Google Photos Album, including its sub-elements This feed represents an album as the container for other objects. A Album feed contains entries of PhotoEntry, CommentEntry or TagEntry, depending on the `kind' parameter in the original query. Take a look at AlbumData for accessible attributes. """ _children = GPhotosBaseFeed._children.copy() _children.update(AlbumData._children.copy()) def GetPhotosUri(self): "(string) Return the uri to the same feed, but of the PhotoEntry kind" return self._feedUri('photo') def GetTagsUri(self): "(string) Return the uri to the same feed, but of the TagEntry kind" return self._feedUri('tag') def GetCommentsUri(self): "(string) Return the uri to the same feed, but of the CommentEntry kind" return self._feedUri('comment') def AlbumFeedFromString(xml_string): return atom.CreateClassFromXMLString(AlbumFeed, xml_string) class PhotoData(object): _children = {} ## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id _children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id) _children['{%s}albumid' % PHOTOS_NAMESPACE] = ('albumid', Albumid) _children['{%s}checksum' % PHOTOS_NAMESPACE] = ('checksum', Checksum) _children['{%s}client' % PHOTOS_NAMESPACE] = ('client', Client) _children['{%s}height' % PHOTOS_NAMESPACE] = ('height', Height) _children['{%s}position' % PHOTOS_NAMESPACE] = ('position', Position) _children['{%s}rotation' % PHOTOS_NAMESPACE] = ('rotation', Rotation) _children['{%s}size' % PHOTOS_NAMESPACE] = ('size', Size) _children['{%s}timestamp' % PHOTOS_NAMESPACE] = ('timestamp', Timestamp) _children['{%s}version' % PHOTOS_NAMESPACE] = ('version', Version) _children['{%s}width' % PHOTOS_NAMESPACE] = ('width', Width) _children['{%s}commentingEnabled' % PHOTOS_NAMESPACE] = \ ('commentingEnabled', CommentingEnabled) _children['{%s}commentCount' % PHOTOS_NAMESPACE] = \ ('commentCount', CommentCount) ## NOTE: storing media:group as self.media, exif:tags as self.exif, and ## geo:where as self.geo, to create a self-explaining api _children['{%s}tags' % EXIF_NAMESPACE] = ('exif', Exif.Tags) _children['{%s}where' % GEORSS_NAMESPACE] = ('geo', Geo.Where) _children['{%s}group' % MEDIA_NAMESPACE] = ('media', Media.Group) # These elements show up in search feeds _children['{%s}snippet' % PHOTOS_NAMESPACE] = ('snippet', Snippet) _children['{%s}snippettype' % PHOTOS_NAMESPACE] = ('snippettype', Snippettype) _children['{%s}truncated' % PHOTOS_NAMESPACE] = ('truncated', Truncated) gphoto_id = None albumid = None checksum = None client = None height = None position = None rotation = None size = None timestamp = None version = None width = None commentingEnabled = None commentCount = None snippet=None snippettype=None truncated=None media = Media.Group() geo = Geo.Where() tags = Exif.Tags() class PhotoEntry(GPhotosBaseEntry, PhotoData): """All metadata for a Google Photos Photo Take a look at PhotoData for metadata accessible as attributes to this object. Notes: To avoid name clashes, and to create a more sensible api, some objects have names that differ from the original elements: o media:group -> self.media, o exif:tags -> self.exif, o geo:where -> self.geo, o photo:id -> self.gphoto_id """ _kind = 'photo' _children = GPhotosBaseEntry._children.copy() _children.update(PhotoData._children.copy()) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, text=None, # GPHOTO NAMESPACE: gphoto_id=None, albumid=None, checksum=None, client=None, height=None, position=None, rotation=None, size=None, timestamp=None, version=None, width=None, commentCount=None, commentingEnabled=None, # MEDIARSS NAMESPACE: media=None, # EXIF_NAMESPACE: exif=None, # GEORSS NAMESPACE: geo=None, extension_elements=None, extension_attributes=None): GPhotosBaseEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) ## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id self.gphoto_id = gphoto_id self.albumid = albumid self.checksum = checksum self.client = client self.height = height self.position = position self.rotation = rotation self.size = size self.timestamp = timestamp self.version = version self.width = width self.commentingEnabled = commentingEnabled self.commentCount = commentCount ## NOTE: storing media:group as self.media, to create a self-explaining api self.media = media or Media.Group() self.exif = exif or Exif.Tags() self.geo = geo or Geo.Where() def GetPostLink(self): "Return the uri to this photo's `POST' link (use it for updates of the object)" return self.GetFeedLink() def GetCommentsUri(self): "Return the uri to this photo's feed of CommentEntry comments" return self._feedUri('comment') def GetTagsUri(self): "Return the uri to this photo's feed of TagEntry tags" return self._feedUri('tag') def GetAlbumUri(self): """Return the uri to the AlbumEntry containing this photo""" href = self.GetSelfLink().href return href[:href.find('/photoid')] def PhotoEntryFromString(xml_string): return atom.CreateClassFromXMLString(PhotoEntry, xml_string) class PhotoFeed(GPhotosBaseFeed, PhotoData): """All metadata for a Google Photos Photo, including its sub-elements This feed represents a photo as the container for other objects. A Photo feed contains entries of CommentEntry or TagEntry, depending on the `kind' parameter in the original query. Take a look at PhotoData for metadata accessible as attributes to this object. """ _children = GPhotosBaseFeed._children.copy() _children.update(PhotoData._children.copy()) def GetTagsUri(self): "(string) Return the uri to the same feed, but of the TagEntry kind" return self._feedUri('tag') def GetCommentsUri(self): "(string) Return the uri to the same feed, but of the CommentEntry kind" return self._feedUri('comment') def PhotoFeedFromString(xml_string): return atom.CreateClassFromXMLString(PhotoFeed, xml_string) class TagData(GPhotosBaseData): _children = {} _children['{%s}weight' % PHOTOS_NAMESPACE] = ('weight', Weight) weight=None class TagEntry(GPhotosBaseEntry, TagData): """All metadata for a Google Photos Tag The actual tag is stored in the .title.text attribute """ _kind = 'tag' _children = GPhotosBaseEntry._children.copy() _children.update(TagData._children.copy()) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, # GPHOTO NAMESPACE: weight=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): GPhotosBaseEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.weight = weight def GetAlbumUri(self): """Return the uri to the AlbumEntry containing this tag""" href = self.GetSelfLink().href pos = href.find('/photoid') if pos == -1: return None return href[:pos] def GetPhotoUri(self): """Return the uri to the PhotoEntry containing this tag""" href = self.GetSelfLink().href pos = href.find('/tag') if pos == -1: return None return href[:pos] def TagEntryFromString(xml_string): return atom.CreateClassFromXMLString(TagEntry, xml_string) class TagFeed(GPhotosBaseFeed, TagData): """All metadata for a Google Photos Tag, including its sub-elements""" _children = GPhotosBaseFeed._children.copy() _children.update(TagData._children.copy()) def TagFeedFromString(xml_string): return atom.CreateClassFromXMLString(TagFeed, xml_string) class CommentData(GPhotosBaseData): _children = {} ## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id _children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id) _children['{%s}albumid' % PHOTOS_NAMESPACE] = ('albumid', Albumid) _children['{%s}photoid' % PHOTOS_NAMESPACE] = ('photoid', Photoid) _children['{%s}author' % atom.ATOM_NAMESPACE] = ('author', [CommentAuthor,]) gphoto_id=None albumid=None photoid=None author=None class CommentEntry(GPhotosBaseEntry, CommentData): """All metadata for a Google Photos Comment The comment is stored in the .content.text attribute, with a content type in .content.type. """ _kind = 'comment' _children = GPhotosBaseEntry._children.copy() _children.update(CommentData._children.copy()) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, # GPHOTO NAMESPACE: gphoto_id=None, albumid=None, photoid=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): GPhotosBaseEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.gphoto_id = gphoto_id self.albumid = albumid self.photoid = photoid def GetCommentId(self): """Return the globally unique id of this comment""" return self.GetSelfLink().href.split('/')[-1] def GetAlbumUri(self): """Return the uri to the AlbumEntry containing this comment""" href = self.GetSelfLink().href return href[:href.find('/photoid')] def GetPhotoUri(self): """Return the uri to the PhotoEntry containing this comment""" href = self.GetSelfLink().href return href[:href.find('/commentid')] def CommentEntryFromString(xml_string): return atom.CreateClassFromXMLString(CommentEntry, xml_string) class CommentFeed(GPhotosBaseFeed, CommentData): """All metadata for a Google Photos Comment, including its sub-elements""" _children = GPhotosBaseFeed._children.copy() _children.update(CommentData._children.copy()) def CommentFeedFromString(xml_string): return atom.CreateClassFromXMLString(CommentFeed, xml_string) class UserData(GPhotosBaseData): _children = {} _children['{%s}maxPhotosPerAlbum' % PHOTOS_NAMESPACE] = ('maxPhotosPerAlbum', MaxPhotosPerAlbum) _children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname) _children['{%s}quotalimit' % PHOTOS_NAMESPACE] = ('quotalimit', Quotalimit) _children['{%s}quotacurrent' % PHOTOS_NAMESPACE] = ('quotacurrent', Quotacurrent) _children['{%s}thumbnail' % PHOTOS_NAMESPACE] = ('thumbnail', Thumbnail) _children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User) _children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id) maxPhotosPerAlbum=None nickname=None quotalimit=None quotacurrent=None thumbnail=None user=None gphoto_id=None class UserEntry(GPhotosBaseEntry, UserData): """All metadata for a Google Photos User This entry represents an album owner and all appropriate metadata. Take a look at at the attributes of the UserData for metadata available. """ _children = GPhotosBaseEntry._children.copy() _children.update(UserData._children.copy()) _kind = 'user' def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, # GPHOTO NAMESPACE: gphoto_id=None, maxPhotosPerAlbum=None, nickname=None, quotalimit=None, quotacurrent=None, thumbnail=None, user=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): GPhotosBaseEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.gphoto_id=gphoto_id self.maxPhotosPerAlbum=maxPhotosPerAlbum self.nickname=nickname self.quotalimit=quotalimit self.quotacurrent=quotacurrent self.thumbnail=thumbnail self.user=user def GetAlbumsUri(self): "(string) Return the uri to this user's feed of the AlbumEntry kind" return self._feedUri('album') def GetPhotosUri(self): "(string) Return the uri to this user's feed of the PhotoEntry kind" return self._feedUri('photo') def GetCommentsUri(self): "(string) Return the uri to this user's feed of the CommentEntry kind" return self._feedUri('comment') def GetTagsUri(self): "(string) Return the uri to this user's feed of the TagEntry kind" return self._feedUri('tag') def UserEntryFromString(xml_string): return atom.CreateClassFromXMLString(UserEntry, xml_string) class UserFeed(GPhotosBaseFeed, UserData): """Feed for a User in the google photos api. This feed represents a user as the container for other objects. A User feed contains entries of AlbumEntry, PhotoEntry, CommentEntry, UserEntry or TagEntry, depending on the `kind' parameter in the original query. The user feed itself also contains all of the metadata available as part of a UserData object.""" _children = GPhotosBaseFeed._children.copy() _children.update(UserData._children.copy()) def GetAlbumsUri(self): """Get the uri to this feed, but with entries of the AlbumEntry kind.""" return self._feedUri('album') def GetTagsUri(self): """Get the uri to this feed, but with entries of the TagEntry kind.""" return self._feedUri('tag') def GetPhotosUri(self): """Get the uri to this feed, but with entries of the PhotosEntry kind.""" return self._feedUri('photo') def GetCommentsUri(self): """Get the uri to this feed, but with entries of the CommentsEntry kind.""" return self._feedUri('comment') def UserFeedFromString(xml_string): return atom.CreateClassFromXMLString(UserFeed, xml_string) def AnyFeedFromString(xml_string): """Creates an instance of the appropriate feed class from the xml string contents. Args: xml_string: str A string which contains valid XML. The root element of the XML string should match the tag and namespace of the desired class. Returns: An instance of the target class with members assigned according to the contents of the XML - or a basic gdata.GDataFeed instance if it is impossible to determine the appropriate class (look for extra elements in GDataFeed's .FindExtensions() and extension_elements[] ). """ tree = ElementTree.fromstring(xml_string) category = tree.find('{%s}category' % atom.ATOM_NAMESPACE) if category is None: # TODO: is this the best way to handle this? return atom._CreateClassFromElementTree(GPhotosBaseFeed, tree) namespace, kind = category.get('term').split('#') if namespace != PHOTOS_NAMESPACE: # TODO: is this the best way to handle this? return atom._CreateClassFromElementTree(GPhotosBaseFeed, tree) ## TODO: is getattr safe this way? feed_class = getattr(gdata.photos, '%sFeed' % kind.title()) return atom._CreateClassFromElementTree(feed_class, tree) def AnyEntryFromString(xml_string): """Creates an instance of the appropriate entry class from the xml string contents. Args: xml_string: str A string which contains valid XML. The root element of the XML string should match the tag and namespace of the desired class. Returns: An instance of the target class with members assigned according to the contents of the XML - or a basic gdata.GDataEndry instance if it is impossible to determine the appropriate class (look for extra elements in GDataEntry's .FindExtensions() and extension_elements[] ). """ tree = ElementTree.fromstring(xml_string) category = tree.find('{%s}category' % atom.ATOM_NAMESPACE) if category is None: # TODO: is this the best way to handle this? return atom._CreateClassFromElementTree(GPhotosBaseEntry, tree) namespace, kind = category.get('term').split('#') if namespace != PHOTOS_NAMESPACE: # TODO: is this the best way to handle this? return atom._CreateClassFromElementTree(GPhotosBaseEntry, tree) ## TODO: is getattr safe this way? feed_class = getattr(gdata.photos, '%sEntry' % kind.title()) return atom._CreateClassFromElementTree(feed_class, tree)
Python
#!/usr/bin/env python # # Copyright (C) 2008, 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. """Provides a client to interact with Google Data API servers. This module is used for version 2 of the Google Data APIs. The primary class in this module is GDClient. GDClient: handles auth and CRUD operations when communicating with servers. GDataClient: deprecated client for version one services. Will be removed. """ __author__ = 'j.s@google.com (Jeff Scudder)' import re import atom.client import atom.core import atom.http_core import gdata.gauth import gdata.data class Error(Exception): pass class RequestError(Error): status = None reason = None body = None headers = None class RedirectError(RequestError): pass class CaptchaChallenge(RequestError): captcha_url = None captcha_token = None class ClientLoginTokenMissing(Error): pass class MissingOAuthParameters(Error): pass class ClientLoginFailed(RequestError): pass class UnableToUpgradeToken(RequestError): pass class Unauthorized(Error): pass class BadAuthenticationServiceURL(RedirectError): pass class BadAuthentication(RequestError): pass class NotModified(RequestError): pass class NotImplemented(RequestError): pass def error_from_response(message, http_response, error_class, response_body=None): """Creates a new exception and sets the HTTP information in the error. Args: message: str human readable message to be displayed if the exception is not caught. http_response: The response from the server, contains error information. error_class: The exception to be instantiated and populated with information from the http_response response_body: str (optional) specify if the response has already been read from the http_response object. """ if response_body is None: body = http_response.read() else: body = response_body error = error_class('%s: %i, %s' % (message, http_response.status, body)) error.status = http_response.status error.reason = http_response.reason error.body = body error.headers = atom.http_core.get_headers(http_response) return error def get_xml_version(version): """Determines which XML schema to use based on the client API version. Args: version: string which is converted to an int. The version string is in the form 'Major.Minor.x.y.z' and only the major version number is considered. If None is provided assume version 1. """ if version is None: return 1 return int(version.split('.')[0]) class GDClient(atom.client.AtomPubClient): """Communicates with Google Data servers to perform CRUD operations. This class is currently experimental and may change in backwards incompatible ways. This class exists to simplify the following three areas involved in using the Google Data APIs. CRUD Operations: The client provides a generic 'request' method for making HTTP requests. There are a number of convenience methods which are built on top of request, which include get_feed, get_entry, get_next, post, update, and delete. These methods contact the Google Data servers. Auth: Reading user-specific private data requires authorization from the user as do any changes to user data. An auth_token object can be passed into any of the HTTP requests to set the Authorization header in the request. You may also want to set the auth_token member to a an object which can use modify_request to set the Authorization header in the HTTP request. If you are authenticating using the email address and password, you can use the client_login method to obtain an auth token and set the auth_token member. If you are using browser redirects, specifically AuthSub, you will want to use gdata.gauth.AuthSubToken.from_url to obtain the token after the redirect, and you will probably want to updgrade this since use token to a multiple use (session) token using the upgrade_token method. API Versions: This client is multi-version capable and can be used with Google Data API version 1 and version 2. The version should be specified by setting the api_version member to a string, either '1' or '2'. """ # The gsessionid is used by Google Calendar to prevent redirects. __gsessionid = None api_version = None # Name of the Google Data service when making a ClientLogin request. auth_service = None # URL prefixes which should be requested for AuthSub and OAuth. auth_scopes = None def request(self, method=None, uri=None, auth_token=None, http_request=None, converter=None, desired_class=None, redirects_remaining=4, **kwargs): """Make an HTTP request to the server. See also documentation for atom.client.AtomPubClient.request. If a 302 redirect is sent from the server to the client, this client assumes that the redirect is in the form used by the Google Calendar API. The same request URI and method will be used as in the original request, but a gsessionid URL parameter will be added to the request URI with the value provided in the server's 302 redirect response. If the 302 redirect is not in the format specified by the Google Calendar API, a RedirectError will be raised containing the body of the server's response. The method calls the client's modify_request method to make any changes required by the client before the request is made. For example, a version 2 client could add a GData-Version: 2 header to the request in its modify_request method. Args: method: str The HTTP verb for this request, usually 'GET', 'POST', 'PUT', or 'DELETE' uri: atom.http_core.Uri, str, or unicode The URL being requested. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. http_request: (optional) atom.http_core.HttpRequest converter: function which takes the body of the response as it's only argument and returns the desired object. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (converter=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. redirects_remaining: (optional) int, if this number is 0 and the server sends a 302 redirect, the request method will raise an exception. This parameter is used in recursive request calls to avoid an infinite loop. Any additional arguments are passed through to atom.client.AtomPubClient.request. Returns: An HTTP response object (see atom.http_core.HttpResponse for a description of the object's interface) if no converter was specified and no desired_class was specified. If a converter function was provided, the results of calling the converter are returned. If no converter was specified but a desired_class was provided, the response body will be converted to the class using atom.core.parse. """ if isinstance(uri, (str, unicode)): uri = atom.http_core.Uri.parse_uri(uri) # Add the gsession ID to the URL to prevent further redirects. # TODO: If different sessions are using the same client, there will be a # multitude of redirects and session ID shuffling. # If the gsession ID is in the URL, adopt it as the standard location. if uri is not None and uri.query is not None and 'gsessionid' in uri.query: self.__gsessionid = uri.query['gsessionid'] # The gsession ID could also be in the HTTP request. elif (http_request is not None and http_request.uri is not None and http_request.uri.query is not None and 'gsessionid' in http_request.uri.query): self.__gsessionid = http_request.uri.query['gsessionid'] # If the gsession ID is stored in the client, and was not present in the # URI then add it to the URI. elif self.__gsessionid is not None: uri.query['gsessionid'] = self.__gsessionid # The AtomPubClient should call this class' modify_request before # performing the HTTP request. #http_request = self.modify_request(http_request) response = atom.client.AtomPubClient.request(self, method=method, uri=uri, auth_token=auth_token, http_request=http_request, **kwargs) # On success, convert the response body using the desired converter # function if present. if response is None: return None if response.status == 200 or response.status == 201: if converter is not None: return converter(response) elif desired_class is not None: if self.api_version is not None: return atom.core.parse(response.read(), desired_class, version=get_xml_version(self.api_version)) else: # No API version was specified, so allow parse to # use the default version. return atom.core.parse(response.read(), desired_class) else: return response # TODO: move the redirect logic into the Google Calendar client once it # exists since the redirects are only used in the calendar API. elif response.status == 302: if redirects_remaining > 0: location = (response.getheader('Location') or response.getheader('location')) if location is not None: m = re.compile('[\?\&]gsessionid=(\w*)').search(location) if m is not None: self.__gsessionid = m.group(1) # Make a recursive call with the gsession ID in the URI to follow # the redirect. return self.request(method=method, uri=uri, auth_token=auth_token, http_request=http_request, converter=converter, desired_class=desired_class, redirects_remaining=redirects_remaining-1, **kwargs) else: raise error_from_response('302 received without Location header', response, RedirectError) else: raise error_from_response('Too many redirects from server', response, RedirectError) elif response.status == 401: raise error_from_response('Unauthorized - Server responded with', response, Unauthorized) elif response.status == 304: raise error_from_response('Entry Not Modified - Server responded with', response, NotModified) elif response.status == 501: raise error_from_response( 'This API operation is not implemented. - Server responded with', response, NotImplemented) # If the server's response was not a 200, 201, 302, 304, 401, or 501, raise # an exception. else: raise error_from_response('Server responded with', response, RequestError) Request = request def request_client_login_token( self, email, password, source, service=None, account_type='HOSTED_OR_GOOGLE', auth_url=atom.http_core.Uri.parse_uri( 'https://www.google.com/accounts/ClientLogin'), captcha_token=None, captcha_response=None): service = service or self.auth_service # Set the target URL. http_request = atom.http_core.HttpRequest(uri=auth_url, method='POST') http_request.add_body_part( gdata.gauth.generate_client_login_request_body(email=email, password=password, service=service, source=source, account_type=account_type, captcha_token=captcha_token, captcha_response=captcha_response), 'application/x-www-form-urlencoded') # Use the underlying http_client to make the request. response = self.http_client.request(http_request) response_body = response.read() if response.status == 200: token_string = gdata.gauth.get_client_login_token_string(response_body) if token_string is not None: return gdata.gauth.ClientLoginToken(token_string) else: raise ClientLoginTokenMissing( 'Recieved a 200 response to client login request,' ' but no token was present. %s' % (response_body,)) elif response.status == 403: captcha_challenge = gdata.gauth.get_captcha_challenge(response_body) if captcha_challenge: challenge = CaptchaChallenge('CAPTCHA required') challenge.captcha_url = captcha_challenge['url'] challenge.captcha_token = captcha_challenge['token'] raise challenge elif response_body.splitlines()[0] == 'Error=BadAuthentication': raise BadAuthentication('Incorrect username or password') else: raise error_from_response('Server responded with a 403 code', response, RequestError, response_body) elif response.status == 302: # Google tries to redirect all bad URLs back to # http://www.google.<locale>. If a redirect # attempt is made, assume the user has supplied an incorrect # authentication URL raise error_from_response('Server responded with a redirect', response, BadAuthenticationServiceURL, response_body) else: raise error_from_response('Server responded to ClientLogin request', response, ClientLoginFailed, response_body) RequestClientLoginToken = request_client_login_token def client_login(self, email, password, source, service=None, account_type='HOSTED_OR_GOOGLE', auth_url=atom.http_core.Uri.parse_uri( 'https://www.google.com/accounts/ClientLogin'), captcha_token=None, captcha_response=None): """Performs an auth request using the user's email address and password. In order to modify user specific data and read user private data, your application must be authorized by the user. One way to demonstrage authorization is by including a Client Login token in the Authorization HTTP header of all requests. This method requests the Client Login token by sending the user's email address, password, the name of the application, and the service code for the service which will be accessed by the application. If the username and password are correct, the server will respond with the client login code and a new ClientLoginToken object will be set in the client's auth_token member. With the auth_token set, future requests from this client will include the Client Login token. For a list of service names, see http://code.google.com/apis/gdata/faq.html#clientlogin For more information on Client Login, see: http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html Args: email: str The user's email address or username. password: str The password for the user's account. source: str The name of your application. This can be anything you like but should should give some indication of which app is making the request. service: str The service code for the service you would like to access. For example, 'cp' for contacts, 'cl' for calendar. For a full list see http://code.google.com/apis/gdata/faq.html#clientlogin If you are using a subclass of the gdata.client.GDClient, the service will usually be filled in for you so you do not need to specify it. For example see BloggerClient, SpreadsheetsClient, etc. account_type: str (optional) The type of account which is being authenticated. This can be either 'GOOGLE' for a Google Account, 'HOSTED' for a Google Apps Account, or the default 'HOSTED_OR_GOOGLE' which will select the Google Apps Account if the same email address is used for both a Google Account and a Google Apps Account. auth_url: str (optional) The URL to which the login request should be sent. captcha_token: str (optional) If a previous login attempt was reponded to with a CAPTCHA challenge, this is the token which identifies the challenge (from the CAPTCHA's URL). captcha_response: str (optional) If a previous login attempt was reponded to with a CAPTCHA challenge, this is the response text which was contained in the challenge. Returns: None Raises: A RequestError or one of its suclasses: BadAuthentication, BadAuthenticationServiceURL, ClientLoginFailed, ClientLoginTokenMissing, or CaptchaChallenge """ service = service or self.auth_service self.auth_token = self.request_client_login_token(email, password, source, service=service, account_type=account_type, auth_url=auth_url, captcha_token=captcha_token, captcha_response=captcha_response) ClientLogin = client_login def upgrade_token(self, token=None, url=atom.http_core.Uri.parse_uri( 'https://www.google.com/accounts/AuthSubSessionToken')): """Asks the Google auth server for a multi-use AuthSub token. For details on AuthSub, see: http://code.google.com/apis/accounts/docs/AuthSub.html Args: token: gdata.gauth.AuthSubToken or gdata.gauth.SecureAuthSubToken (optional) If no token is passed in, the client's auth_token member is used to request the new token. The token object will be modified to contain the new session token string. url: str or atom.http_core.Uri (optional) The URL to which the token upgrade request should be sent. Defaults to: https://www.google.com/accounts/AuthSubSessionToken Returns: The upgraded gdata.gauth.AuthSubToken object. """ # Default to using the auth_token member if no token is provided. if token is None: token = self.auth_token # We cannot upgrade a None token. if token is None: raise UnableToUpgradeToken('No token was provided.') if not isinstance(token, gdata.gauth.AuthSubToken): raise UnableToUpgradeToken( 'Cannot upgrade the token because it is not an AuthSubToken object.') http_request = atom.http_core.HttpRequest(uri=url, method='GET') token.modify_request(http_request) # Use the lower level HttpClient to make the request. response = self.http_client.request(http_request) if response.status == 200: token._upgrade_token(response.read()) return token else: raise UnableToUpgradeToken( 'Server responded to token upgrade request with %s: %s' % ( response.status, response.read())) UpgradeToken = upgrade_token def revoke_token(self, token=None, url=atom.http_core.Uri.parse_uri( 'https://www.google.com/accounts/AuthSubRevokeToken')): """Requests that the token be invalidated. This method can be used for both AuthSub and OAuth tokens (to invalidate a ClientLogin token, the user must change their password). Returns: True if the server responded with a 200. Raises: A RequestError if the server responds with a non-200 status. """ # Default to using the auth_token member if no token is provided. if token is None: token = self.auth_token http_request = atom.http_core.HttpRequest(uri=url, method='GET') token.modify_request(http_request) response = self.http_client.request(http_request) if response.status != 200: raise error_from_response('Server sent non-200 to revoke token', response, RequestError, response.read()) return True RevokeToken = revoke_token def get_oauth_token(self, scopes, next, consumer_key, consumer_secret=None, rsa_private_key=None, url=gdata.gauth.REQUEST_TOKEN_URL): """Obtains an OAuth request token to allow the user to authorize this app. Once this client has a request token, the user can authorize the request token by visiting the authorization URL in their browser. After being redirected back to this app at the 'next' URL, this app can then exchange the authorized request token for an access token. For more information see the documentation on Google Accounts with OAuth: http://code.google.com/apis/accounts/docs/OAuth.html#AuthProcess Args: scopes: list of strings or atom.http_core.Uri objects which specify the URL prefixes which this app will be accessing. For example, to access the Google Calendar API, you would want to use scopes: ['https://www.google.com/calendar/feeds/', 'http://www.google.com/calendar/feeds/'] next: str or atom.http_core.Uri object, The URL which the user's browser should be sent to after they authorize access to their data. This should be a URL in your application which will read the token information from the URL and upgrade the request token to an access token. consumer_key: str This is the identifier for this application which you should have received when you registered your application with Google to use OAuth. consumer_secret: str (optional) The shared secret between your app and Google which provides evidence that this request is coming from you application and not another app. If present, this libraries assumes you want to use an HMAC signature to verify requests. Keep this data a secret. rsa_private_key: str (optional) The RSA private key which is used to generate a digital signature which is checked by Google's server. If present, this library assumes that you want to use an RSA signature to verify requests. Keep this data a secret. url: The URL to which a request for a token should be made. The default is Google's OAuth request token provider. """ http_request = None if rsa_private_key is not None: http_request = gdata.gauth.generate_request_for_request_token( consumer_key, gdata.gauth.RSA_SHA1, scopes, rsa_key=rsa_private_key, auth_server_url=url, next=next) elif consumer_secret is not None: http_request = gdata.gauth.generate_request_for_request_token( consumer_key, gdata.gauth.HMAC_SHA1, scopes, consumer_secret=consumer_secret, auth_server_url=url, next=next) else: raise MissingOAuthParameters( 'To request an OAuth token, you must provide your consumer secret' ' or your private RSA key.') response = self.http_client.request(http_request) response_body = response.read() if response.status != 200: raise error_from_response('Unable to obtain OAuth request token', response, RequestError, response_body) if rsa_private_key is not None: return gdata.gauth.rsa_token_from_body(response_body, consumer_key, rsa_private_key, gdata.gauth.REQUEST_TOKEN) elif consumer_secret is not None: return gdata.gauth.hmac_token_from_body(response_body, consumer_key, consumer_secret, gdata.gauth.REQUEST_TOKEN) GetOAuthToken = get_oauth_token def get_access_token(self, request_token, url=gdata.gauth.ACCESS_TOKEN_URL): """Exchanges an authorized OAuth request token for an access token. Contacts the Google OAuth server to upgrade a previously authorized request token. Once the request token is upgraded to an access token, the access token may be used to access the user's data. For more details, see the Google Accounts OAuth documentation: http://code.google.com/apis/accounts/docs/OAuth.html#AccessToken Args: request_token: An OAuth token which has been authorized by the user. url: (optional) The URL to which the upgrade request should be sent. Defaults to: https://www.google.com/accounts/OAuthAuthorizeToken """ http_request = gdata.gauth.generate_request_for_access_token( request_token, auth_server_url=url) response = self.http_client.request(http_request) response_body = response.read() if response.status != 200: raise error_from_response( 'Unable to upgrade OAuth request token to access token', response, RequestError, response_body) return gdata.gauth.upgrade_to_access_token(request_token, response_body) GetAccessToken = get_access_token def modify_request(self, http_request): """Adds or changes request before making the HTTP request. This client will add the API version if it is specified. Subclasses may override this method to add their own request modifications before the request is made. """ http_request = atom.client.AtomPubClient.modify_request(self, http_request) if self.api_version is not None: http_request.headers['GData-Version'] = self.api_version return http_request ModifyRequest = modify_request def get_feed(self, uri, auth_token=None, converter=None, desired_class=gdata.data.GDFeed, **kwargs): return self.request(method='GET', uri=uri, auth_token=auth_token, converter=converter, desired_class=desired_class, **kwargs) GetFeed = get_feed def get_entry(self, uri, auth_token=None, converter=None, desired_class=gdata.data.GDEntry, etag=None, **kwargs): http_request = atom.http_core.HttpRequest() # Conditional retrieval if etag is not None: http_request.headers['If-None-Match'] = etag return self.request(method='GET', uri=uri, auth_token=auth_token, http_request=http_request, converter=converter, desired_class=desired_class, **kwargs) GetEntry = get_entry def get_next(self, feed, auth_token=None, converter=None, desired_class=None, **kwargs): """Fetches the next set of results from the feed. When requesting a feed, the number of entries returned is capped at a service specific default limit (often 25 entries). You can specify your own entry-count cap using the max-results URL query parameter. If there are more results than could fit under max-results, the feed will contain a next link. This method performs a GET against this next results URL. Returns: A new feed object containing the next set of entries in this feed. """ if converter is None and desired_class is None: desired_class = feed.__class__ return self.get_feed(feed.find_next_link(), auth_token=auth_token, converter=converter, desired_class=desired_class, **kwargs) GetNext = get_next # TODO: add a refresh method to re-fetch the entry/feed from the server # if it has been updated. def post(self, entry, uri, auth_token=None, converter=None, desired_class=None, **kwargs): if converter is None and desired_class is None: desired_class = entry.__class__ http_request = atom.http_core.HttpRequest() http_request.add_body_part( entry.to_string(get_xml_version(self.api_version)), 'application/atom+xml') return self.request(method='POST', uri=uri, auth_token=auth_token, http_request=http_request, converter=converter, desired_class=desired_class, **kwargs) Post = post def update(self, entry, auth_token=None, force=False, uri=None, **kwargs): """Edits the entry on the server by sending the XML for this entry. Performs a PUT and converts the response to a new entry object with a matching class to the entry passed in. Args: entry: auth_token: force: boolean stating whether an update should be forced. Defaults to False. Normally, if a change has been made since the passed in entry was obtained, the server will not overwrite the entry since the changes were based on an obsolete version of the entry. Setting force to True will cause the update to silently overwrite whatever version is present. uri: The uri to put to. If provided, this uri is PUT to rather than the inferred uri from the entry's edit link. Returns: A new Entry object of a matching type to the entry which was passed in. """ http_request = atom.http_core.HttpRequest() http_request.add_body_part( entry.to_string(get_xml_version(self.api_version)), 'application/atom+xml') # Include the ETag in the request if present. if force: http_request.headers['If-Match'] = '*' elif hasattr(entry, 'etag') and entry.etag: http_request.headers['If-Match'] = entry.etag if uri is None: uri = entry.find_edit_link() return self.request(method='PUT', uri=uri, auth_token=auth_token, http_request=http_request, desired_class=entry.__class__, **kwargs) Update = update def delete(self, entry_or_uri, auth_token=None, force=False, **kwargs): http_request = atom.http_core.HttpRequest() # Include the ETag in the request if present. if force: http_request.headers['If-Match'] = '*' elif hasattr(entry_or_uri, 'etag') and entry_or_uri.etag: http_request.headers['If-Match'] = entry_or_uri.etag # If the user passes in a URL, just delete directly, may not work as # the service might require an ETag. if isinstance(entry_or_uri, (str, unicode, atom.http_core.Uri)): return self.request(method='DELETE', uri=entry_or_uri, http_request=http_request, auth_token=auth_token, **kwargs) return self.request(method='DELETE', uri=entry_or_uri.find_edit_link(), http_request=http_request, auth_token=auth_token, **kwargs) Delete = delete #TODO: implement batch requests. #def batch(feed, uri, auth_token=None, converter=None, **kwargs): # pass # TODO: add a refresh method to request a conditional update to an entry # or feed. def _add_query_param(param_string, value, http_request): if value: http_request.uri.query[param_string] = value class Query(object): def __init__(self, text_query=None, categories=None, author=None, alt=None, updated_min=None, updated_max=None, pretty_print=False, published_min=None, published_max=None, start_index=None, max_results=None, strict=False): """Constructs a Google Data Query to filter feed contents serverside. Args: text_query: Full text search str (optional) categories: list of strings (optional). Each string is a required category. To include an 'or' query, put a | in the string between terms. For example, to find everything in the Fitz category and the Laurie or Jane category (Fitz and (Laurie or Jane)) you would set categories to ['Fitz', 'Laurie|Jane']. author: str (optional) The service returns entries where the author name and/or email address match your query string. alt: str (optional) for the Alternative representation type you'd like the feed in. If you don't specify an alt parameter, the service returns an Atom feed. This is equivalent to alt='atom'. alt='rss' returns an RSS 2.0 result feed. alt='json' returns a JSON representation of the feed. alt='json-in-script' Requests a response that wraps JSON in a script tag. alt='atom-in-script' Requests an Atom response that wraps an XML string in a script tag. alt='rss-in-script' Requests an RSS response that wraps an XML string in a script tag. updated_min: str (optional), RFC 3339 timestamp format, lower bounds. For example: 2005-08-09T10:57:00-08:00 updated_max: str (optional) updated time must be earlier than timestamp. pretty_print: boolean (optional) If True the server's XML response will be indented to make it more human readable. Defaults to False. published_min: str (optional), Similar to updated_min but for published time. published_max: str (optional), Similar to updated_max but for published time. start_index: int or str (optional) 1-based index of the first result to be retrieved. Note that this isn't a general cursoring mechanism. If you first send a query with ?start-index=1&max-results=10 and then send another query with ?start-index=11&max-results=10, the service cannot guarantee that the results are equivalent to ?start-index=1&max-results=20, because insertions and deletions could have taken place in between the two queries. max_results: int or str (optional) Maximum number of results to be retrieved. Each service has a default max (usually 25) which can vary from service to service. There is also a service-specific limit to the max_results you can fetch in a request. strict: boolean (optional) If True, the server will return an error if the server does not recognize any of the parameters in the request URL. Defaults to False. """ self.text_query = text_query self.categories = categories or [] self.author = author self.alt = alt self.updated_min = updated_min self.updated_max = updated_max self.pretty_print = pretty_print self.published_min = published_min self.published_max = published_max self.start_index = start_index self.max_results = max_results self.strict = strict def modify_request(self, http_request): _add_query_param('q', self.text_query, http_request) if self.categories: http_request.uri.query['category'] = ','.join(self.categories) _add_query_param('author', self.author, http_request) _add_query_param('alt', self.alt, http_request) _add_query_param('updated-min', self.updated_min, http_request) _add_query_param('updated-max', self.updated_max, http_request) if self.pretty_print: http_request.uri.query['prettyprint'] = 'true' _add_query_param('published-min', self.published_min, http_request) _add_query_param('published-max', self.published_max, http_request) if self.start_index is not None: http_request.uri.query['start-index'] = str(self.start_index) if self.max_results is not None: http_request.uri.query['max-results'] = str(self.max_results) if self.strict: http_request.uri.query['strict'] = 'true' ModifyRequest = modify_request class GDQuery(atom.http_core.Uri): def _get_text_query(self): return self.query['q'] def _set_text_query(self, value): self.query['q'] = value text_query = property(_get_text_query, _set_text_query, doc='The q parameter for searching for an exact text match on content') class ResumableUploader(object): """Resumable upload helper for the Google Data protocol.""" DEFAULT_CHUNK_SIZE = 5242880 # 5MB def __init__(self, client, file_handle, content_type, total_file_size, chunk_size=None, desired_class=None): """Starts a resumable upload to a service that supports the protocol. Args: client: gdata.client.GDClient A Google Data API service. file_handle: object A file-like object containing the file to upload. content_type: str The mimetype of the file to upload. total_file_size: int The file's total size in bytes. chunk_size: int The size of each upload chunk. If None, the DEFAULT_CHUNK_SIZE will be used. desired_class: object (optional) The type of gdata.data.GDEntry to parse the completed entry as. This should be specific to the API. """ self.client = client self.file_handle = file_handle self.content_type = content_type self.total_file_size = total_file_size self.chunk_size = chunk_size or self.DEFAULT_CHUNK_SIZE self.desired_class = desired_class or gdata.data.GDEntry self.upload_uri = None # Send the entire file if the chunk size is less than fize's total size. if self.total_file_size <= self.chunk_size: self.chunk_size = total_file_size def _init_session(self, resumable_media_link, entry=None, headers=None, auth_token=None): """Starts a new resumable upload to a service that supports the protocol. The method makes a request to initiate a new upload session. The unique upload uri returned by the server (and set in this method) should be used to send upload chunks to the server. Args: resumable_media_link: str The full URL for the #resumable-create-media or #resumable-edit-media link for starting a resumable upload request or updating media using a resumable PUT. entry: A (optional) gdata.data.GDEntry containging metadata to create the upload from. headers: dict (optional) Additional headers to send in the initial request to create the resumable upload request. These headers will override any default headers sent in the request. For example: headers={'Slug': 'MyTitle'}. auth_token: (optional) An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Returns: The final Atom entry as created on the server. The entry will be parsed accoring to the class specified in self.desired_class. Raises: RequestError if the unique upload uri is not set or the server returns something other than an HTTP 308 when the upload is incomplete. """ http_request = atom.http_core.HttpRequest() # Send empty POST if Atom XML wasn't specified. if entry is None: http_request.add_body_part('', self.content_type, size=0) else: http_request.add_body_part(str(entry), 'application/atom+xml', size=len(str(entry))) http_request.headers['X-Upload-Content-Type'] = self.content_type http_request.headers['X-Upload-Content-Length'] = self.total_file_size if headers is not None: http_request.headers.update(headers) response = self.client.request(method='POST', uri=resumable_media_link, auth_token=auth_token, http_request=http_request) self.upload_uri = (response.getheader('location') or response.getheader('Location')) _InitSession = _init_session def upload_chunk(self, start_byte, content_bytes): """Uploads a byte range (chunk) to the resumable upload server. Args: start_byte: int The byte offset of the total file where the byte range passed in lives. content_bytes: str The file contents of this chunk. Returns: The final Atom entry created on the server. The entry object's type will be the class specified in self.desired_class. Raises: RequestError if the unique upload uri is not set or the server returns something other than an HTTP 308 when the upload is incomplete. """ if self.upload_uri is None: raise RequestError('Resumable upload request not initialized.') # Adjustment if last byte range is less than defined chunk size. chunk_size = self.chunk_size if len(content_bytes) <= chunk_size: chunk_size = len(content_bytes) http_request = atom.http_core.HttpRequest() http_request.add_body_part(content_bytes, self.content_type, size=len(content_bytes)) http_request.headers['Content-Range'] = ('bytes %s-%s/%s' % (start_byte, start_byte + chunk_size - 1, self.total_file_size)) try: response = self.client.request(method='POST', uri=self.upload_uri, http_request=http_request, desired_class=self.desired_class) return response except RequestError, error: if error.status == 308: return None else: raise error UploadChunk = upload_chunk def upload_file(self, resumable_media_link, entry=None, headers=None, auth_token=None): """Uploads an entire file in chunks using the resumable upload protocol. If you are interested in pausing an upload or controlling the chunking yourself, use the upload_chunk() method instead. Args: resumable_media_link: str The full URL for the #resumable-create-media for starting a resumable upload request. entry: A (optional) gdata.data.GDEntry containging metadata to create the upload from. headers: dict Additional headers to send in the initial request to create the resumable upload request. These headers will override any default headers sent in the request. For example: headers={'Slug': 'MyTitle'}. auth_token: (optional) An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Returns: The final Atom entry created on the server. The entry object's type will be the class specified in self.desired_class. Raises: RequestError if anything other than a HTTP 308 is returned when the request raises an exception. """ self._init_session(resumable_media_link, headers=headers, auth_token=auth_token, entry=entry) start_byte = 0 entry = None while not entry: entry = self.upload_chunk( start_byte, self.file_handle.read(self.chunk_size)) start_byte += self.chunk_size return entry UploadFile = upload_file def update_file(self, entry_or_resumable_edit_link, headers=None, force=False, auth_token=None): """Updates the contents of an existing file using the resumable protocol. If you are interested in pausing an upload or controlling the chunking yourself, use the upload_chunk() method instead. Args: entry_or_resumable_edit_link: object or string A gdata.data.GDEntry for the entry/file to update or the full uri of the link with rel #resumable-edit-media. headers: dict Additional headers to send in the initial request to create the resumable upload request. These headers will override any default headers sent in the request. For example: headers={'Slug': 'MyTitle'}. force boolean (optional) True to force an update and set the If-Match header to '*'. If False and entry_or_resumable_edit_link is a gdata.data.GDEntry object, its etag value is used. Otherwise this parameter should be set to True to force the update. auth_token: (optional) An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Returns: The final Atom entry created on the server. The entry object's type will be the class specified in self.desired_class. Raises: RequestError if anything other than a HTTP 308 is returned when the request raises an exception. """ # Need to override the POST request for a resumable update (required). customer_headers = {'X-HTTP-Method-Override': 'PUT'} if headers is not None: customer_headers.update(headers) if isinstance(entry_or_resumable_edit_link, gdata.data.GDEntry): resumable_edit_link = entry_or_resumable_edit_link.find_url( 'http://schemas.google.com/g/2005#resumable-edit-media') customer_headers['If-Match'] = entry_or_resumable_edit_link.etag else: resumable_edit_link = entry_or_resumable_edit_link if force: customer_headers['If-Match'] = '*' return self.upload_file(resumable_edit_link, headers=customer_headers, auth_token=auth_token) UpdateFile = update_file def query_upload_status(self, uri=None): """Queries the current status of a resumable upload request. Args: uri: str (optional) A resumable upload uri to query and override the one that is set in this object. Returns: An integer representing the file position (byte) to resume the upload from or True if the upload is complete. Raises: RequestError if anything other than a HTTP 308 is returned when the request raises an exception. """ # Override object's unique upload uri. if uri is None: uri = self.upload_uri http_request = atom.http_core.HttpRequest() http_request.headers['Content-Length'] = '0' http_request.headers['Content-Range'] = 'bytes */%s' % self.total_file_size try: response = self.client.request( method='POST', uri=uri, http_request=http_request) if response.status == 201: return True else: raise error_from_response( '%s returned by server' % response.status, response, RequestError) except RequestError, error: if error.status == 308: for pair in error.headers: if pair[0].capitalize() == 'Range': return int(pair[1].split('-')[1]) + 1 else: raise error QueryUploadStatus = query_upload_status
Python
#!/usr/bin/python # # Copyright (C) 2009 Tan Swee Heng # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Classes to interact with the Google Finance server.""" __author__ = 'thesweeheng@gmail.com' import gdata.service import gdata.finance import atom class PortfolioQuery(gdata.service.Query): """A query object for the list of a user's portfolios.""" def returns(self): return self.get('returns', False) def set_returns(self, value): if value is 'true' or value is True: self['returns'] = 'true' returns = property(returns, set_returns, doc="The returns query parameter") def positions(self): return self.get('positions', False) def set_positions(self, value): if value is 'true' or value is True: self['positions'] = 'true' positions = property(positions, set_positions, doc="The positions query parameter") class PositionQuery(gdata.service.Query): """A query object for the list of a user's positions in a portfolio.""" def returns(self): return self.get('returns', False) def set_returns(self, value): if value is 'true' or value is True: self['returns'] = 'true' returns = property(returns, set_returns, doc="The returns query parameter") def transactions(self): return self.get('transactions', False) def set_transactions(self, value): if value is 'true' or value is True: self['transactions'] = 'true' transactions = property(transactions, set_transactions, doc="The transactions query parameter") class FinanceService(gdata.service.GDataService): def __init__(self, email=None, password=None, source=None, server='finance.google.com', **kwargs): """Creates a client for the Finance service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'finance.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__(self, email=email, password=password, service='finance', server=server, **kwargs) def GetPortfolioFeed(self, query=None): uri = '/finance/feeds/default/portfolios' if query: uri = PortfolioQuery(feed=uri, params=query).ToUri() return self.Get(uri, converter=gdata.finance.PortfolioFeedFromString) def GetPositionFeed(self, portfolio_entry=None, portfolio_id=None, query=None): """ Args: portfolio_entry: PortfolioEntry (optional; see Notes) portfolio_id: string (optional; see Notes) This may be obtained from a PortfolioEntry's portfolio_id attribute. query: PortfolioQuery (optional) Notes: Either a PortfolioEntry OR a portfolio ID must be provided. """ if portfolio_entry: uri = portfolio_entry.GetSelfLink().href + '/positions' elif portfolio_id: uri = '/finance/feeds/default/portfolios/%s/positions' % portfolio_id if query: uri = PositionQuery(feed=uri, params=query).ToUri() return self.Get(uri, converter=gdata.finance.PositionFeedFromString) def GetTransactionFeed(self, position_entry=None, portfolio_id=None, ticker_id=None): """ Args: position_entry: PositionEntry (optional; see Notes) portfolio_id: string (optional; see Notes) This may be obtained from a PortfolioEntry's portfolio_id attribute. ticker_id: string (optional; see Notes) This may be obtained from a PositionEntry's ticker_id attribute. Alternatively it can be constructed using the security's exchange and symbol, e.g. 'NASDAQ:GOOG' Notes: Either a PositionEntry OR (a portfolio ID AND ticker ID) must be provided. """ if position_entry: uri = position_entry.GetSelfLink().href + '/transactions' elif portfolio_id and ticker_id: uri = '/finance/feeds/default/portfolios/%s/positions/%s/transactions' \ % (portfolio_id, ticker_id) return self.Get(uri, converter=gdata.finance.TransactionFeedFromString) def GetPortfolio(self, portfolio_id=None, query=None): uri = '/finance/feeds/default/portfolios/%s' % portfolio_id if query: uri = PortfolioQuery(feed=uri, params=query).ToUri() return self.Get(uri, converter=gdata.finance.PortfolioEntryFromString) def AddPortfolio(self, portfolio_entry=None): uri = '/finance/feeds/default/portfolios' return self.Post(portfolio_entry, uri, converter=gdata.finance.PortfolioEntryFromString) def UpdatePortfolio(self, portfolio_entry=None): uri = portfolio_entry.GetEditLink().href return self.Put(portfolio_entry, uri, converter=gdata.finance.PortfolioEntryFromString) def DeletePortfolio(self, portfolio_entry=None): uri = portfolio_entry.GetEditLink().href return self.Delete(uri) def GetPosition(self, portfolio_id=None, ticker_id=None, query=None): uri = '/finance/feeds/default/portfolios/%s/positions/%s' \ % (portfolio_id, ticker_id) if query: uri = PositionQuery(feed=uri, params=query).ToUri() return self.Get(uri, converter=gdata.finance.PositionEntryFromString) def DeletePosition(self, position_entry=None, portfolio_id=None, ticker_id=None, transaction_feed=None): """A position is deleted by deleting all its transactions. Args: position_entry: PositionEntry (optional; see Notes) portfolio_id: string (optional; see Notes) This may be obtained from a PortfolioEntry's portfolio_id attribute. ticker_id: string (optional; see Notes) This may be obtained from a PositionEntry's ticker_id attribute. Alternatively it can be constructed using the security's exchange and symbol, e.g. 'NASDAQ:GOOG' transaction_feed: TransactionFeed (optional; see Notes) Notes: Either a PositionEntry OR (a portfolio ID AND ticker ID) OR a TransactionFeed must be provided. """ if transaction_feed: feed = transaction_feed else: if position_entry: feed = self.GetTransactionFeed(position_entry=position_entry) elif portfolio_id and ticker_id: feed = self.GetTransactionFeed( portfolio_id=portfolio_id, ticker_id=ticker_id) for txn in feed.entry: self.DeleteTransaction(txn) return True def GetTransaction(self, portfolio_id=None, ticker_id=None, transaction_id=None): uri = '/finance/feeds/default/portfolios/%s/positions/%s/transactions/%s' \ % (portfolio_id, ticker_id, transaction_id) return self.Get(uri, converter=gdata.finance.TransactionEntryFromString) def AddTransaction(self, transaction_entry=None, transaction_feed = None, position_entry=None, portfolio_id=None, ticker_id=None): """ Args: transaction_entry: TransactionEntry (required) transaction_feed: TransactionFeed (optional; see Notes) position_entry: PositionEntry (optional; see Notes) portfolio_id: string (optional; see Notes) This may be obtained from a PortfolioEntry's portfolio_id attribute. ticker_id: string (optional; see Notes) This may be obtained from a PositionEntry's ticker_id attribute. Alternatively it can be constructed using the security's exchange and symbol, e.g. 'NASDAQ:GOOG' Notes: Either a TransactionFeed OR a PositionEntry OR (a portfolio ID AND ticker ID) must be provided. """ if transaction_feed: uri = transaction_feed.GetPostLink().href elif position_entry: uri = position_entry.GetSelfLink().href + '/transactions' elif portfolio_id and ticker_id: uri = '/finance/feeds/default/portfolios/%s/positions/%s/transactions' \ % (portfolio_id, ticker_id) return self.Post(transaction_entry, uri, converter=gdata.finance.TransactionEntryFromString) def UpdateTransaction(self, transaction_entry=None): uri = transaction_entry.GetEditLink().href return self.Put(transaction_entry, uri, converter=gdata.finance.TransactionEntryFromString) def DeleteTransaction(self, transaction_entry=None): uri = transaction_entry.GetEditLink().href return self.Delete(uri)
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the data classes of the Google Finance Portfolio Data API""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import atom.data import gdata.data import gdata.opensearch.data GF_TEMPLATE = '{http://schemas.google.com/finance/2007/}%s' class Commission(atom.core.XmlElement): """Commission for the transaction""" _qname = GF_TEMPLATE % 'commission' money = [gdata.data.Money] class CostBasis(atom.core.XmlElement): """Cost basis for the portfolio or position""" _qname = GF_TEMPLATE % 'costBasis' money = [gdata.data.Money] class DaysGain(atom.core.XmlElement): """Today's gain for the portfolio or position""" _qname = GF_TEMPLATE % 'daysGain' money = [gdata.data.Money] class Gain(atom.core.XmlElement): """Total gain for the portfolio or position""" _qname = GF_TEMPLATE % 'gain' money = [gdata.data.Money] class MarketValue(atom.core.XmlElement): """Market value for the portfolio or position""" _qname = GF_TEMPLATE % 'marketValue' money = [gdata.data.Money] class PortfolioData(atom.core.XmlElement): """Data for the portfolio""" _qname = GF_TEMPLATE % 'portfolioData' return_overall = 'returnOverall' currency_code = 'currencyCode' return3y = 'return3y' return4w = 'return4w' market_value = MarketValue return_y_t_d = 'returnYTD' cost_basis = CostBasis gain_percentage = 'gainPercentage' days_gain = DaysGain return3m = 'return3m' return5y = 'return5y' return1w = 'return1w' gain = Gain return1y = 'return1y' class PortfolioEntry(gdata.data.GDEntry): """Describes an entry in a feed of Finance portfolios""" portfolio_data = PortfolioData class PortfolioFeed(gdata.data.GDFeed): """Describes a Finance portfolio feed""" entry = [PortfolioEntry] class PositionData(atom.core.XmlElement): """Data for the position""" _qname = GF_TEMPLATE % 'positionData' return_y_t_d = 'returnYTD' return5y = 'return5y' return_overall = 'returnOverall' cost_basis = CostBasis return3y = 'return3y' return1y = 'return1y' return4w = 'return4w' shares = 'shares' days_gain = DaysGain gain_percentage = 'gainPercentage' market_value = MarketValue gain = Gain return3m = 'return3m' return1w = 'return1w' class Price(atom.core.XmlElement): """Price of the transaction""" _qname = GF_TEMPLATE % 'price' money = [gdata.data.Money] class Symbol(atom.core.XmlElement): """Stock symbol for the company""" _qname = GF_TEMPLATE % 'symbol' symbol = 'symbol' exchange = 'exchange' full_name = 'fullName' class PositionEntry(gdata.data.GDEntry): """Describes an entry in a feed of Finance positions""" symbol = Symbol position_data = PositionData class PositionFeed(gdata.data.GDFeed): """Describes a Finance position feed""" entry = [PositionEntry] class TransactionData(atom.core.XmlElement): """Data for the transction""" _qname = GF_TEMPLATE % 'transactionData' shares = 'shares' notes = 'notes' date = 'date' type = 'type' commission = Commission price = Price class TransactionEntry(gdata.data.GDEntry): """Describes an entry in a feed of Finance transactions""" transaction_data = TransactionData class TransactionFeed(gdata.data.GDFeed): """Describes a Finance transaction feed""" entry = [TransactionEntry]
Python
#!/usr/bin/python # # Copyright (C) 2009 Tan Swee Heng # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains extensions to Atom objects used with Google Finance.""" __author__ = 'thesweeheng@gmail.com' import atom import gdata GD_NAMESPACE = 'http://schemas.google.com/g/2005' GF_NAMESPACE = 'http://schemas.google.com/finance/2007' class Money(atom.AtomBase): """The <gd:money> element.""" _tag = 'money' _namespace = GD_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['amount'] = 'amount' _attributes['currencyCode'] = 'currency_code' def __init__(self, amount=None, currency_code=None, **kwargs): self.amount = amount self.currency_code = currency_code atom.AtomBase.__init__(self, **kwargs) def __str__(self): return "%s %s" % (self.amount, self.currency_code) def MoneyFromString(xml_string): return atom.CreateClassFromXMLString(Money, xml_string) class _Monies(atom.AtomBase): """An element containing multiple <gd:money> in multiple currencies.""" _namespace = GF_NAMESPACE _children = atom.AtomBase._children.copy() _children['{%s}money' % GD_NAMESPACE] = ('money', [Money]) def __init__(self, money=None, **kwargs): self.money = money or [] atom.AtomBase.__init__(self, **kwargs) def __str__(self): return " / ".join(["%s" % i for i in self.money]) class CostBasis(_Monies): """The <gf:costBasis> element.""" _tag = 'costBasis' def CostBasisFromString(xml_string): return atom.CreateClassFromXMLString(CostBasis, xml_string) class DaysGain(_Monies): """The <gf:daysGain> element.""" _tag = 'daysGain' def DaysGainFromString(xml_string): return atom.CreateClassFromXMLString(DaysGain, xml_string) class Gain(_Monies): """The <gf:gain> element.""" _tag = 'gain' def GainFromString(xml_string): return atom.CreateClassFromXMLString(Gain, xml_string) class MarketValue(_Monies): """The <gf:marketValue> element.""" _tag = 'gain' _tag = 'marketValue' def MarketValueFromString(xml_string): return atom.CreateClassFromXMLString(MarketValue, xml_string) class Commission(_Monies): """The <gf:commission> element.""" _tag = 'commission' def CommissionFromString(xml_string): return atom.CreateClassFromXMLString(Commission, xml_string) class Price(_Monies): """The <gf:price> element.""" _tag = 'price' def PriceFromString(xml_string): return atom.CreateClassFromXMLString(Price, xml_string) class Symbol(atom.AtomBase): """The <gf:symbol> element.""" _tag = 'symbol' _namespace = GF_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['fullName'] = 'full_name' _attributes['exchange'] = 'exchange' _attributes['symbol'] = 'symbol' def __init__(self, full_name=None, exchange=None, symbol=None, **kwargs): self.full_name = full_name self.exchange = exchange self.symbol = symbol atom.AtomBase.__init__(self, **kwargs) def __str__(self): return "%s:%s (%s)" % (self.exchange, self.symbol, self.full_name) def SymbolFromString(xml_string): return atom.CreateClassFromXMLString(Symbol, xml_string) class TransactionData(atom.AtomBase): """The <gf:transactionData> element.""" _tag = 'transactionData' _namespace = GF_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' _attributes['date'] = 'date' _attributes['shares'] = 'shares' _attributes['notes'] = 'notes' _children = atom.AtomBase._children.copy() _children['{%s}commission' % GF_NAMESPACE] = ('commission', Commission) _children['{%s}price' % GF_NAMESPACE] = ('price', Price) def __init__(self, type=None, date=None, shares=None, notes=None, commission=None, price=None, **kwargs): self.type = type self.date = date self.shares = shares self.notes = notes self.commission = commission self.price = price atom.AtomBase.__init__(self, **kwargs) def TransactionDataFromString(xml_string): return atom.CreateClassFromXMLString(TransactionData, xml_string) class TransactionEntry(gdata.GDataEntry): """An entry of the transaction feed. A TransactionEntry contains TransactionData such as the transaction type (Buy, Sell, Sell Short, or Buy to Cover), the number of units, the date, the price, any commission, and any notes. """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _children['{%s}transactionData' % GF_NAMESPACE] = ( 'transaction_data', TransactionData) def __init__(self, transaction_data=None, **kwargs): self.transaction_data = transaction_data gdata.GDataEntry.__init__(self, **kwargs) def transaction_id(self): return self.id.text.split("/")[-1] transaction_id = property(transaction_id, doc='The transaction ID.') def TransactionEntryFromString(xml_string): return atom.CreateClassFromXMLString(TransactionEntry, xml_string) class TransactionFeed(gdata.GDataFeed): """A feed that lists all of the transactions that have been recorded for a particular position. A transaction is a collection of information about an instance of buying or selling a particular security. The TransactionFeed lists all of the transactions that have been recorded for a particular position as a list of TransactionEntries. """ _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [TransactionEntry]) def TransactionFeedFromString(xml_string): return atom.CreateClassFromXMLString(TransactionFeed, xml_string) class TransactionFeedLink(atom.AtomBase): """Link to TransactionFeed embedded in PositionEntry. If a PositionFeed is queried with transactions='true', TransactionFeeds are inlined in the returned PositionEntries. These TransactionFeeds are accessible via TransactionFeedLink's feed attribute. """ _tag = 'feedLink' _namespace = GD_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['href'] = 'href' _children = atom.AtomBase._children.copy() _children['{%s}feed' % atom.ATOM_NAMESPACE] = ( 'feed', TransactionFeed) def __init__(self, href=None, feed=None, **kwargs): self.href = href self.feed = feed atom.AtomBase.__init__(self, **kwargs) class PositionData(atom.AtomBase): """The <gf:positionData> element.""" _tag = 'positionData' _namespace = GF_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['gainPercentage'] = 'gain_percentage' _attributes['return1w'] = 'return1w' _attributes['return4w'] = 'return4w' _attributes['return3m'] = 'return3m' _attributes['returnYTD'] = 'returnYTD' _attributes['return1y'] = 'return1y' _attributes['return3y'] = 'return3y' _attributes['return5y'] = 'return5y' _attributes['returnOverall'] = 'return_overall' _attributes['shares'] = 'shares' _children = atom.AtomBase._children.copy() _children['{%s}costBasis' % GF_NAMESPACE] = ('cost_basis', CostBasis) _children['{%s}daysGain' % GF_NAMESPACE] = ('days_gain', DaysGain) _children['{%s}gain' % GF_NAMESPACE] = ('gain', Gain) _children['{%s}marketValue' % GF_NAMESPACE] = ('market_value', MarketValue) def __init__(self, gain_percentage=None, return1w=None, return4w=None, return3m=None, returnYTD=None, return1y=None, return3y=None, return5y=None, return_overall=None, shares=None, cost_basis=None, days_gain=None, gain=None, market_value=None, **kwargs): self.gain_percentage = gain_percentage self.return1w = return1w self.return4w = return4w self.return3m = return3m self.returnYTD = returnYTD self.return1y = return1y self.return3y = return3y self.return5y = return5y self.return_overall = return_overall self.shares = shares self.cost_basis = cost_basis self.days_gain = days_gain self.gain = gain self.market_value = market_value atom.AtomBase.__init__(self, **kwargs) def PositionDataFromString(xml_string): return atom.CreateClassFromXMLString(PositionData, xml_string) class PositionEntry(gdata.GDataEntry): """An entry of the position feed. A PositionEntry contains the ticker exchange and Symbol for a stock, mutual fund, or other security, along with PositionData such as the number of units of that security that the user holds, and performance statistics. """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _children['{%s}positionData' % GF_NAMESPACE] = ( 'position_data', PositionData) _children['{%s}symbol' % GF_NAMESPACE] = ('symbol', Symbol) _children['{%s}feedLink' % GD_NAMESPACE] = ( 'feed_link', TransactionFeedLink) def __init__(self, position_data=None, symbol=None, feed_link=None, **kwargs): self.position_data = position_data self.symbol = symbol self.feed_link = feed_link gdata.GDataEntry.__init__(self, **kwargs) def position_title(self): return self.title.text position_title = property(position_title, doc='The position title as a string (i.e. position.title.text).') def ticker_id(self): return self.id.text.split("/")[-1] ticker_id = property(ticker_id, doc='The position TICKER ID.') def transactions(self): if self.feed_link.feed: return self.feed_link.feed.entry else: return None transactions = property(transactions, doc=""" Inlined TransactionEntries are returned if PositionFeed is queried with transactions='true'.""") def PositionEntryFromString(xml_string): return atom.CreateClassFromXMLString(PositionEntry, xml_string) class PositionFeed(gdata.GDataFeed): """A feed that lists all of the positions in a particular portfolio. A position is a collection of information about a security that the user holds. The PositionFeed lists all of the positions in a particular portfolio as a list of PositionEntries. """ _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [PositionEntry]) def PositionFeedFromString(xml_string): return atom.CreateClassFromXMLString(PositionFeed, xml_string) class PositionFeedLink(atom.AtomBase): """Link to PositionFeed embedded in PortfolioEntry. If a PortfolioFeed is queried with positions='true', the PositionFeeds are inlined in the returned PortfolioEntries. These PositionFeeds are accessible via PositionFeedLink's feed attribute. """ _tag = 'feedLink' _namespace = GD_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['href'] = 'href' _children = atom.AtomBase._children.copy() _children['{%s}feed' % atom.ATOM_NAMESPACE] = ( 'feed', PositionFeed) def __init__(self, href=None, feed=None, **kwargs): self.href = href self.feed = feed atom.AtomBase.__init__(self, **kwargs) class PortfolioData(atom.AtomBase): """The <gf:portfolioData> element.""" _tag = 'portfolioData' _namespace = GF_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['currencyCode'] = 'currency_code' _attributes['gainPercentage'] = 'gain_percentage' _attributes['return1w'] = 'return1w' _attributes['return4w'] = 'return4w' _attributes['return3m'] = 'return3m' _attributes['returnYTD'] = 'returnYTD' _attributes['return1y'] = 'return1y' _attributes['return3y'] = 'return3y' _attributes['return5y'] = 'return5y' _attributes['returnOverall'] = 'return_overall' _children = atom.AtomBase._children.copy() _children['{%s}costBasis' % GF_NAMESPACE] = ('cost_basis', CostBasis) _children['{%s}daysGain' % GF_NAMESPACE] = ('days_gain', DaysGain) _children['{%s}gain' % GF_NAMESPACE] = ('gain', Gain) _children['{%s}marketValue' % GF_NAMESPACE] = ('market_value', MarketValue) def __init__(self, currency_code=None, gain_percentage=None, return1w=None, return4w=None, return3m=None, returnYTD=None, return1y=None, return3y=None, return5y=None, return_overall=None, cost_basis=None, days_gain=None, gain=None, market_value=None, **kwargs): self.currency_code = currency_code self.gain_percentage = gain_percentage self.return1w = return1w self.return4w = return4w self.return3m = return3m self.returnYTD = returnYTD self.return1y = return1y self.return3y = return3y self.return5y = return5y self.return_overall = return_overall self.cost_basis = cost_basis self.days_gain = days_gain self.gain = gain self.market_value = market_value atom.AtomBase.__init__(self, **kwargs) def PortfolioDataFromString(xml_string): return atom.CreateClassFromXMLString(PortfolioData, xml_string) class PortfolioEntry(gdata.GDataEntry): """An entry of the PortfolioFeed. A PortfolioEntry contains the portfolio's title along with PortfolioData such as currency, total market value, and overall performance statistics. """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _children['{%s}portfolioData' % GF_NAMESPACE] = ( 'portfolio_data', PortfolioData) _children['{%s}feedLink' % GD_NAMESPACE] = ( 'feed_link', PositionFeedLink) def __init__(self, portfolio_data=None, feed_link=None, **kwargs): self.portfolio_data = portfolio_data self.feed_link = feed_link gdata.GDataEntry.__init__(self, **kwargs) def portfolio_title(self): return self.title.text def set_portfolio_title(self, portfolio_title): self.title = atom.Title(text=portfolio_title, title_type='text') portfolio_title = property(portfolio_title, set_portfolio_title, doc='The portfolio title as a string (i.e. portfolio.title.text).') def portfolio_id(self): return self.id.text.split("/")[-1] portfolio_id = property(portfolio_id, doc='The portfolio ID. Do not confuse with portfolio.id.') def positions(self): if self.feed_link.feed: return self.feed_link.feed.entry else: return None positions = property(positions, doc=""" Inlined PositionEntries are returned if PortfolioFeed was queried with positions='true'.""") def PortfolioEntryFromString(xml_string): return atom.CreateClassFromXMLString(PortfolioEntry, xml_string) class PortfolioFeed(gdata.GDataFeed): """A feed that lists all of the user's portfolios. A portfolio is a collection of positions that the user holds in various securities, plus metadata. The PortfolioFeed lists all of the user's portfolios as a list of PortfolioEntries. """ _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [PortfolioEntry]) def PortfolioFeedFromString(xml_string): return atom.CreateClassFromXMLString(PortfolioFeed, xml_string)
Python
# -*- coding: utf-8 -*- # # Copyright (c) 2007 Benoit Chesneau <benoitc@metavers.net> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """CodesearchService extends GDataService to streamline Google Codesearch operations""" __author__ = 'Benoit Chesneau' import atom import gdata.service import gdata.codesearch class CodesearchService(gdata.service.GDataService): """Client extension for Google codesearch service""" ssl = True def __init__(self, email=None, password=None, source=None, server='www.google.com', additional_headers=None, **kwargs): """Creates a client for the Google codesearch service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'www.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='codesearch', source=source, server=server, additional_headers=additional_headers, **kwargs) def Query(self, uri, converter=gdata.codesearch.CodesearchFeedFromString): """Queries the Codesearch feed and returns the resulting feed of entries. Args: uri: string The full URI to be queried. This can contain query parameters, a hostname, or simply the relative path to a Document List feed. The DocumentQuery object is useful when constructing query parameters. converter: func (optional) A function which will be executed on the retrieved item, generally to render it into a Python object. By default the CodesearchFeedFromString function is used to return a CodesearchFeed object. This is because most feed queries will result in a feed and not a single entry. Returns : A CodesearchFeed objects representing the feed returned by the server """ return self.Get(uri, converter=converter) def GetSnippetsFeed(self, text_query=None): """Retrieve Codesearch feed for a keyword Args: text_query : string (optional) The contents of the q query parameter. This string is URL escaped upon conversion to a URI. Returns: A CodesearchFeed objects representing the feed returned by the server """ query=gdata.codesearch.service.CodesearchQuery(text_query=text_query) feed = self.Query(query.ToUri()) return feed class CodesearchQuery(gdata.service.Query): """Object used to construct the query to the Google Codesearch feed. here only as a shorcut""" def __init__(self, feed='/codesearch/feeds/search', text_query=None, params=None, categories=None): """Constructor for Codesearch Query. Args: feed: string (optional) The path for the feed. (e.g. '/codesearch/feeds/search') text_query: string (optional) The contents of the q query parameter. This string is URL escaped upon conversion to a URI. params: dict (optional) Parameter value string pairs which become URL params when translated to a URI. These parameters are added to the query's items. categories: list (optional) List of category strings which should be included as query categories. See gdata.service.Query for additional documentation. Yelds: A CodesearchQuery object to construct a URI based on Codesearch feed """ gdata.service.Query.__init__(self, feed, text_query, params, categories)
Python
# -*- coding: utf-8 -*- # # Copyright (c) 2007 Benoit Chesneau <benoitc@metavers.net> # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Contains extensions to Atom objects used by Google Codesearch""" __author__ = 'Benoit Chesneau' import atom import gdata CODESEARCH_NAMESPACE='http://schemas.google.com/codesearch/2006' CODESEARCH_TEMPLATE='{http://shema.google.com/codesearch/2006}%s' class Match(atom.AtomBase): """ The Google Codesearch match element """ _tag = 'match' _namespace = CODESEARCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['lineNumber'] = 'line_number' _attributes['type'] = 'type' def __init__(self, line_number=None, type=None, extension_elements=None, extension_attributes=None, text=None): self.text = text self.type = type self.line_number = line_number self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class File(atom.AtomBase): """ The Google Codesearch file element""" _tag = 'file' _namespace = CODESEARCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.text = text self.name = name self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Package(atom.AtomBase): """ The Google Codesearch package element""" _tag = 'package' _namespace = CODESEARCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' _attributes['uri'] = 'uri' def __init__(self, name=None, uri=None, extension_elements=None, extension_attributes=None, text=None): self.text = text self.name = name self.uri = uri self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class CodesearchEntry(gdata.GDataEntry): """ Google codesearch atom entry""" _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}file' % CODESEARCH_NAMESPACE] = ('file', File) _children['{%s}package' % CODESEARCH_NAMESPACE] = ('package', Package) _children['{%s}match' % CODESEARCH_NAMESPACE] = ('match', [Match]) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, match=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=None) self.match = match or [] def CodesearchEntryFromString(xml_string): """Converts an XML string into a CodesearchEntry object. Args: xml_string: string The XML describing a Codesearch feed entry. Returns: A CodesearchEntry object corresponding to the given XML. """ return atom.CreateClassFromXMLString(CodesearchEntry, xml_string) class CodesearchFeed(gdata.GDataFeed): """feed containing list of Google codesearch Items""" _tag = gdata.GDataFeed._tag _namespace = gdata.GDataFeed._namespace _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CodesearchEntry]) def CodesearchFeedFromString(xml_string): """Converts an XML string into a CodesearchFeed object. Args: xml_string: string The XML describing a Codesearch feed. Returns: A CodeseartchFeed object corresponding to the given XML. """ return atom.CreateClassFromXMLString(CodesearchFeed, xml_string)
Python
#!/usr/bin/python """ requires tlslite - http://trevp.net/tlslite/ """ import binascii from gdata.tlslite.utils import keyfactory from gdata.tlslite.utils import cryptomath # XXX andy: ugly local import due to module name, oauth.oauth import gdata.oauth as oauth class OAuthSignatureMethod_RSA_SHA1(oauth.OAuthSignatureMethod): def get_name(self): return "RSA-SHA1" def _fetch_public_cert(self, oauth_request): # not implemented yet, ideas are: # (1) do a lookup in a table of trusted certs keyed off of consumer # (2) fetch via http using a url provided by the requester # (3) some sort of specific discovery code based on request # # either way should return a string representation of the certificate raise NotImplementedError def _fetch_private_cert(self, oauth_request): # not implemented yet, ideas are: # (1) do a lookup in a table of trusted certs keyed off of consumer # # either way should return a string representation of the certificate raise NotImplementedError def build_signature_base_string(self, oauth_request, consumer, token): sig = ( oauth.escape(oauth_request.get_normalized_http_method()), oauth.escape(oauth_request.get_normalized_http_url()), oauth.escape(oauth_request.get_normalized_parameters()), ) key = '' raw = '&'.join(sig) return key, raw def build_signature(self, oauth_request, consumer, token): key, base_string = self.build_signature_base_string(oauth_request, consumer, token) # Fetch the private key cert based on the request cert = self._fetch_private_cert(oauth_request) # Pull the private key from the certificate privatekey = keyfactory.parsePrivateKey(cert) # Convert base_string to bytes #base_string_bytes = cryptomath.createByteArraySequence(base_string) # Sign using the key signed = privatekey.hashAndSign(base_string) return binascii.b2a_base64(signed)[:-1] def check_signature(self, oauth_request, consumer, token, signature): decoded_sig = base64.b64decode(signature); key, base_string = self.build_signature_base_string(oauth_request, consumer, token) # Fetch the public key cert based on the request cert = self._fetch_public_cert(oauth_request) # Pull the public key from the certificate publickey = keyfactory.parsePEMKey(cert, public=True) # Check the signature ok = publickey.hashAndVerify(decoded_sig, base_string) return ok class TestOAuthSignatureMethod_RSA_SHA1(OAuthSignatureMethod_RSA_SHA1): def _fetch_public_cert(self, oauth_request): cert = """ -----BEGIN CERTIFICATE----- MIIBpjCCAQ+gAwIBAgIBATANBgkqhkiG9w0BAQUFADAZMRcwFQYDVQQDDA5UZXN0 IFByaW5jaXBhbDAeFw03MDAxMDEwODAwMDBaFw0zODEyMzEwODAwMDBaMBkxFzAV BgNVBAMMDlRlc3QgUHJpbmNpcGFsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQC0YjCwIfYoprq/FQO6lb3asXrxLlJFuCvtinTF5p0GxvQGu5O3gYytUvtC2JlY zypSRjVxwxrsuRcP3e641SdASwfrmzyvIgP08N4S0IFzEURkV1wp/IpH7kH41Etb mUmrXSwfNZsnQRE5SYSOhh+LcK2wyQkdgcMv11l4KoBkcwIDAQABMA0GCSqGSIb3 DQEBBQUAA4GBAGZLPEuJ5SiJ2ryq+CmEGOXfvlTtEL2nuGtr9PewxkgnOjZpUy+d 4TvuXJbNQc8f4AMWL/tO9w0Fk80rWKp9ea8/df4qMq5qlFWlx6yOLQxumNOmECKb WpkUQDIDJEoFUzKMVuJf4KO/FJ345+BNLGgbJ6WujreoM1X/gYfdnJ/J -----END CERTIFICATE----- """ return cert def _fetch_private_cert(self, oauth_request): cert = """ -----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALRiMLAh9iimur8V A7qVvdqxevEuUkW4K+2KdMXmnQbG9Aa7k7eBjK1S+0LYmVjPKlJGNXHDGuy5Fw/d 7rjVJ0BLB+ubPK8iA/Tw3hLQgXMRRGRXXCn8ikfuQfjUS1uZSatdLB81mydBETlJ hI6GH4twrbDJCR2Bwy/XWXgqgGRzAgMBAAECgYBYWVtleUzavkbrPjy0T5FMou8H X9u2AC2ry8vD/l7cqedtwMPp9k7TubgNFo+NGvKsl2ynyprOZR1xjQ7WgrgVB+mm uScOM/5HVceFuGRDhYTCObE+y1kxRloNYXnx3ei1zbeYLPCHdhxRYW7T0qcynNmw rn05/KO2RLjgQNalsQJBANeA3Q4Nugqy4QBUCEC09SqylT2K9FrrItqL2QKc9v0Z zO2uwllCbg0dwpVuYPYXYvikNHHg+aCWF+VXsb9rpPsCQQDWR9TT4ORdzoj+Nccn qkMsDmzt0EfNaAOwHOmVJ2RVBspPcxt5iN4HI7HNeG6U5YsFBb+/GZbgfBT3kpNG WPTpAkBI+gFhjfJvRw38n3g/+UeAkwMI2TJQS4n8+hid0uus3/zOjDySH3XHCUno cn1xOJAyZODBo47E+67R4jV1/gzbAkEAklJaspRPXP877NssM5nAZMU0/O/NGCZ+ 3jPgDUno6WbJn5cqm8MqWhW1xGkImgRk+fkDBquiq4gPiT898jusgQJAd5Zrr6Q8 AO/0isr/3aa6O6NLQxISLKcPDk2NOccAfS/xOtfOz4sJYM3+Bs4Io9+dZGSDCA54 Lw03eHTNQghS0A== -----END PRIVATE KEY----- """ return cert
Python
import cgi import urllib import time import random import urlparse import hmac import binascii VERSION = '1.0' # Hi Blaine! HTTP_METHOD = 'GET' SIGNATURE_METHOD = 'PLAINTEXT' # Generic exception class class OAuthError(RuntimeError): def __init__(self, message='OAuth error occured.'): self.message = message # optional WWW-Authenticate header (401 error) def build_authenticate_header(realm=''): return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} # url escape def escape(s): # escape '/' too return urllib.quote(s, safe='~') # util function: current timestamp # seconds since epoch (UTC) def generate_timestamp(): return int(time.time()) # util function: nonce # pseudorandom number def generate_nonce(length=8): return ''.join([str(random.randint(0, 9)) for i in range(length)]) # OAuthConsumer is a data type that represents the identity of the Consumer # via its shared secret with the Service Provider. class OAuthConsumer(object): key = None secret = None def __init__(self, key, secret): self.key = key self.secret = secret # OAuthToken is a data type that represents an End User via either an access # or request token. class OAuthToken(object): # access tokens and request tokens key = None secret = None ''' key = the token secret = the token secret ''' def __init__(self, key, secret): self.key = key self.secret = secret def to_string(self): return urllib.urlencode({'oauth_token': self.key, 'oauth_token_secret': self.secret}) # return a token from something like: # oauth_token_secret=digg&oauth_token=digg def from_string(s): params = cgi.parse_qs(s, keep_blank_values=False) key = params['oauth_token'][0] secret = params['oauth_token_secret'][0] return OAuthToken(key, secret) from_string = staticmethod(from_string) def __str__(self): return self.to_string() # OAuthRequest represents the request and can be serialized class OAuthRequest(object): ''' OAuth parameters: - oauth_consumer_key - oauth_token - oauth_signature_method - oauth_signature - oauth_timestamp - oauth_nonce - oauth_version ... any additional parameters, as defined by the Service Provider. ''' parameters = None # oauth parameters http_method = HTTP_METHOD http_url = None version = VERSION def __init__(self, http_method=HTTP_METHOD, http_url=None, parameters=None): self.http_method = http_method self.http_url = http_url self.parameters = parameters or {} def set_parameter(self, parameter, value): self.parameters[parameter] = value def get_parameter(self, parameter): try: return self.parameters[parameter] except: raise OAuthError('Parameter not found: %s' % parameter) def _get_timestamp_nonce(self): return self.get_parameter('oauth_timestamp'), self.get_parameter('oauth_nonce') # get any non-oauth parameters def get_nonoauth_parameters(self): parameters = {} for k, v in self.parameters.iteritems(): # ignore oauth parameters if k.find('oauth_') < 0: parameters[k] = v return parameters # serialize as a header for an HTTPAuth request def to_header(self, realm=''): auth_header = 'OAuth realm="%s"' % realm # add the oauth parameters if self.parameters: for k, v in self.parameters.iteritems(): if k[:6] == 'oauth_': auth_header += ', %s="%s"' % (k, escape(str(v))) return {'Authorization': auth_header} # serialize as post data for a POST request def to_postdata(self): return '&'.join(['%s=%s' % (escape(str(k)), escape(str(v))) for k, v in self.parameters.iteritems()]) # serialize as a url for a GET request def to_url(self): return '%s?%s' % (self.get_normalized_http_url(), self.to_postdata()) # return a string that consists of all the parameters that need to be signed def get_normalized_parameters(self): params = self.parameters try: # exclude the signature if it exists del params['oauth_signature'] except: pass key_values = params.items() # sort lexicographically, first after key, then after value key_values.sort() # combine key value pairs in string and escape return '&'.join(['%s=%s' % (escape(str(k)), escape(str(v))) for k, v in key_values]) # just uppercases the http method def get_normalized_http_method(self): return self.http_method.upper() # parses the url and rebuilds it to be scheme://host/path def get_normalized_http_url(self): parts = urlparse.urlparse(self.http_url) host = parts[1].lower() if host.endswith(':80') or host.endswith(':443'): host = host.split(':')[0] url_string = '%s://%s%s' % (parts[0], host, parts[2]) # scheme, netloc, path return url_string # set the signature parameter to the result of build_signature def sign_request(self, signature_method, consumer, token): # set the signature method self.set_parameter('oauth_signature_method', signature_method.get_name()) # set the signature self.set_parameter('oauth_signature', self.build_signature(signature_method, consumer, token)) def build_signature(self, signature_method, consumer, token): # call the build signature method within the signature method return signature_method.build_signature(self, consumer, token) def from_request(http_method, http_url, headers=None, parameters=None, query_string=None): # combine multiple parameter sources if parameters is None: parameters = {} # headers if headers and 'Authorization' in headers: auth_header = headers['Authorization'] # check that the authorization header is OAuth if auth_header.index('OAuth') > -1: try: # get the parameters from the header header_params = OAuthRequest._split_header(auth_header) parameters.update(header_params) except: raise OAuthError('Unable to parse OAuth parameters from Authorization header.') # GET or POST query string if query_string: query_params = OAuthRequest._split_url_string(query_string) parameters.update(query_params) # URL parameters param_str = urlparse.urlparse(http_url)[4] # query url_params = OAuthRequest._split_url_string(param_str) parameters.update(url_params) if parameters: return OAuthRequest(http_method, http_url, parameters) return None from_request = staticmethod(from_request) def from_consumer_and_token(oauth_consumer, token=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} defaults = { 'oauth_consumer_key': oauth_consumer.key, 'oauth_timestamp': generate_timestamp(), 'oauth_nonce': generate_nonce(), 'oauth_version': OAuthRequest.version, } defaults.update(parameters) parameters = defaults if token: parameters['oauth_token'] = token.key return OAuthRequest(http_method, http_url, parameters) from_consumer_and_token = staticmethod(from_consumer_and_token) def from_token_and_callback(token, callback=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} parameters['oauth_token'] = token.key if callback: parameters['oauth_callback'] = callback return OAuthRequest(http_method, http_url, parameters) from_token_and_callback = staticmethod(from_token_and_callback) # util function: turn Authorization: header into parameters, has to do some unescaping def _split_header(header): params = {} parts = header[6:].split(',') for param in parts: # ignore realm parameter if param.find('realm') > -1: continue # remove whitespace param = param.strip() # split key-value param_parts = param.split('=', 1) # remove quotes and unescape the value params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"')) return params _split_header = staticmethod(_split_header) # util function: turn url string into parameters, has to do some unescaping # even empty values should be included def _split_url_string(param_str): parameters = cgi.parse_qs(param_str, keep_blank_values=True) for k, v in parameters.iteritems(): parameters[k] = urllib.unquote(v[0]) return parameters _split_url_string = staticmethod(_split_url_string) # OAuthServer is a worker to check a requests validity against a data store class OAuthServer(object): timestamp_threshold = 300 # in seconds, five minutes version = VERSION signature_methods = None data_store = None def __init__(self, data_store=None, signature_methods=None): self.data_store = data_store self.signature_methods = signature_methods or {} def set_data_store(self, oauth_data_store): self.data_store = oauth_data_store def get_data_store(self): return self.data_store def add_signature_method(self, signature_method): self.signature_methods[signature_method.get_name()] = signature_method return self.signature_methods # process a request_token request # returns the request token on success def fetch_request_token(self, oauth_request): try: # get the request token for authorization token = self._get_token(oauth_request, 'request') except OAuthError: # no token required for the initial token request version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) self._check_signature(oauth_request, consumer, None) # fetch a new token token = self.data_store.fetch_request_token(consumer) return token # process an access_token request # returns the access token on success def fetch_access_token(self, oauth_request): version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) # get the request token token = self._get_token(oauth_request, 'request') self._check_signature(oauth_request, consumer, token) new_token = self.data_store.fetch_access_token(consumer, token) return new_token # verify an api call, checks all the parameters def verify_request(self, oauth_request): # -> consumer and token version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) # get the access token token = self._get_token(oauth_request, 'access') self._check_signature(oauth_request, consumer, token) parameters = oauth_request.get_nonoauth_parameters() return consumer, token, parameters # authorize a request token def authorize_token(self, token, user): return self.data_store.authorize_request_token(token, user) # get the callback url def get_callback(self, oauth_request): return oauth_request.get_parameter('oauth_callback') # optional support for the authenticate header def build_authenticate_header(self, realm=''): return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} # verify the correct version request for this server def _get_version(self, oauth_request): try: version = oauth_request.get_parameter('oauth_version') except: version = VERSION if version and version != self.version: raise OAuthError('OAuth version %s not supported.' % str(version)) return version # figure out the signature with some defaults def _get_signature_method(self, oauth_request): try: signature_method = oauth_request.get_parameter('oauth_signature_method') except: signature_method = SIGNATURE_METHOD try: # get the signature method object signature_method = self.signature_methods[signature_method] except: signature_method_names = ', '.join(self.signature_methods.keys()) raise OAuthError('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names)) return signature_method def _get_consumer(self, oauth_request): consumer_key = oauth_request.get_parameter('oauth_consumer_key') if not consumer_key: raise OAuthError('Invalid consumer key.') consumer = self.data_store.lookup_consumer(consumer_key) if not consumer: raise OAuthError('Invalid consumer.') return consumer # try to find the token for the provided request token key def _get_token(self, oauth_request, token_type='access'): token_field = oauth_request.get_parameter('oauth_token') consumer = self._get_consumer(oauth_request) token = self.data_store.lookup_token(consumer, token_type, token_field) if not token: raise OAuthError('Invalid %s token: %s' % (token_type, token_field)) return token def _check_signature(self, oauth_request, consumer, token): timestamp, nonce = oauth_request._get_timestamp_nonce() self._check_timestamp(timestamp) self._check_nonce(consumer, token, nonce) signature_method = self._get_signature_method(oauth_request) try: signature = oauth_request.get_parameter('oauth_signature') except: raise OAuthError('Missing signature.') # validate the signature valid_sig = signature_method.check_signature(oauth_request, consumer, token, signature) if not valid_sig: key, base = signature_method.build_signature_base_string(oauth_request, consumer, token) raise OAuthError('Invalid signature. Expected signature base string: %s' % base) built = signature_method.build_signature(oauth_request, consumer, token) def _check_timestamp(self, timestamp): # verify that timestamp is recentish timestamp = int(timestamp) now = int(time.time()) lapsed = now - timestamp if lapsed > self.timestamp_threshold: raise OAuthError('Expired timestamp: given %d and now %s has a greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold)) def _check_nonce(self, consumer, token, nonce): # verify that the nonce is uniqueish nonce = self.data_store.lookup_nonce(consumer, token, nonce) if nonce: raise OAuthError('Nonce already used: %s' % str(nonce)) # OAuthClient is a worker to attempt to execute a request class OAuthClient(object): consumer = None token = None def __init__(self, oauth_consumer, oauth_token): self.consumer = oauth_consumer self.token = oauth_token def get_consumer(self): return self.consumer def get_token(self): return self.token def fetch_request_token(self, oauth_request): # -> OAuthToken raise NotImplementedError def fetch_access_token(self, oauth_request): # -> OAuthToken raise NotImplementedError def access_resource(self, oauth_request): # -> some protected resource raise NotImplementedError # OAuthDataStore is a database abstraction used to lookup consumers and tokens class OAuthDataStore(object): def lookup_consumer(self, key): # -> OAuthConsumer raise NotImplementedError def lookup_token(self, oauth_consumer, token_type, token_token): # -> OAuthToken raise NotImplementedError def lookup_nonce(self, oauth_consumer, oauth_token, nonce, timestamp): # -> OAuthToken raise NotImplementedError def fetch_request_token(self, oauth_consumer): # -> OAuthToken raise NotImplementedError def fetch_access_token(self, oauth_consumer, oauth_token): # -> OAuthToken raise NotImplementedError def authorize_request_token(self, oauth_token, user): # -> OAuthToken raise NotImplementedError # OAuthSignatureMethod is a strategy class that implements a signature method class OAuthSignatureMethod(object): def get_name(self): # -> str raise NotImplementedError def build_signature_base_string(self, oauth_request, oauth_consumer, oauth_token): # -> str key, str raw raise NotImplementedError def build_signature(self, oauth_request, oauth_consumer, oauth_token): # -> str raise NotImplementedError def check_signature(self, oauth_request, consumer, token, signature): built = self.build_signature(oauth_request, consumer, token) return built == signature class OAuthSignatureMethod_HMAC_SHA1(OAuthSignatureMethod): def get_name(self): return 'HMAC-SHA1' def build_signature_base_string(self, oauth_request, consumer, token): sig = ( escape(oauth_request.get_normalized_http_method()), escape(oauth_request.get_normalized_http_url()), escape(oauth_request.get_normalized_parameters()), ) key = '%s&' % escape(consumer.secret) if token: key += escape(token.secret) raw = '&'.join(sig) return key, raw def build_signature(self, oauth_request, consumer, token): # build the base signature string key, raw = self.build_signature_base_string(oauth_request, consumer, token) # hmac object try: import hashlib # 2.5 hashed = hmac.new(key, raw, hashlib.sha1) except: import sha # deprecated hashed = hmac.new(key, raw, sha) # calculate the digest base 64 return binascii.b2a_base64(hashed.digest())[:-1] class OAuthSignatureMethod_PLAINTEXT(OAuthSignatureMethod): def get_name(self): return 'PLAINTEXT' def build_signature_base_string(self, oauth_request, consumer, token): # concatenate the consumer key and secret sig = escape(consumer.secret) + '&' if token: sig = sig + escape(token.secret) return sig def build_signature(self, oauth_request, consumer, token): return self.build_signature_base_string(oauth_request, consumer, token)
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """GBaseService extends the GDataService to streamline Google Base operations. GBaseService: Provides methods to query feeds and manipulate items. Extends GDataService. DictionaryToParamList: Function which converts a dictionary into a list of URL arguments (represented as strings). This is a utility function used in CRUD operations. """ __author__ = 'api.jscudder (Jeffrey Scudder)' import urllib import gdata import atom.service import gdata.service import gdata.base import atom # URL to which all batch requests are sent. BASE_BATCH_URL = 'http://www.google.com/base/feeds/items/batch' class Error(Exception): pass class RequestError(Error): pass class GBaseService(gdata.service.GDataService): """Client for the Google Base service.""" def __init__(self, email=None, password=None, source=None, server='base.google.com', api_key=None, additional_headers=None, handler=None, **kwargs): """Creates a client for the Google Base service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'base.google.com'. api_key: string (optional) The Google Base API key to use. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='gbase', source=source, server=server, additional_headers=additional_headers, handler=handler, **kwargs) self.api_key = api_key def _SetAPIKey(self, api_key): if not isinstance(self.additional_headers, dict): self.additional_headers = {} self.additional_headers['X-Google-Key'] = api_key def __SetAPIKey(self, api_key): self._SetAPIKey(api_key) def _GetAPIKey(self): if 'X-Google-Key' not in self.additional_headers: return None else: return self.additional_headers['X-Google-Key'] def __GetAPIKey(self): return self._GetAPIKey() api_key = property(__GetAPIKey, __SetAPIKey, doc="""Get or set the API key to be included in all requests.""") def Query(self, uri, converter=None): """Performs a style query and returns a resulting feed or entry. Args: uri: string The full URI which be queried. Examples include '/base/feeds/snippets?bq=digital+camera', 'http://www.google.com/base/feeds/snippets?bq=digital+camera' '/base/feeds/items' I recommend creating a URI using a query class. converter: func (optional) A function which will be executed on the server's response. Examples include GBaseItemFromString, etc. Returns: If converter was specified, returns the results of calling converter on the server's response. If converter was not specified, and the result was an Atom Entry, returns a GBaseItem, by default, the method returns the result of calling gdata.service's Get method. """ result = self.Get(uri, converter=converter) if converter: return result elif isinstance(result, atom.Entry): return gdata.base.GBaseItemFromString(result.ToString()) return result def QuerySnippetsFeed(self, uri): return self.Get(uri, converter=gdata.base.GBaseSnippetFeedFromString) def QueryItemsFeed(self, uri): return self.Get(uri, converter=gdata.base.GBaseItemFeedFromString) def QueryAttributesFeed(self, uri): return self.Get(uri, converter=gdata.base.GBaseAttributesFeedFromString) def QueryItemTypesFeed(self, uri): return self.Get(uri, converter=gdata.base.GBaseItemTypesFeedFromString) def QueryLocalesFeed(self, uri): return self.Get(uri, converter=gdata.base.GBaseLocalesFeedFromString) def GetItem(self, uri): return self.Get(uri, converter=gdata.base.GBaseItemFromString) def GetSnippet(self, uri): return self.Get(uri, converter=gdata.base.GBaseSnippetFromString) def GetAttribute(self, uri): return self.Get(uri, converter=gdata.base.GBaseAttributeEntryFromString) def GetItemType(self, uri): return self.Get(uri, converter=gdata.base.GBaseItemTypeEntryFromString) def GetLocale(self, uri): return self.Get(uri, converter=gdata.base.GDataEntryFromString) def InsertItem(self, new_item, url_params=None, escape_params=True, converter=None): """Adds an item to Google Base. Args: new_item: atom.Entry or subclass A new item which is to be added to Google Base. url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. converter: func (optional) Function which is executed on the server's response before it is returned. Usually this is a function like GBaseItemFromString which will parse the response and turn it into an object. Returns: If converter is defined, the results of running converter on the server's response. Otherwise, it will be a GBaseItem. """ response = self.Post(new_item, '/base/feeds/items', url_params=url_params, escape_params=escape_params, converter=converter) if not converter and isinstance(response, atom.Entry): return gdata.base.GBaseItemFromString(response.ToString()) return response def DeleteItem(self, item_id, url_params=None, escape_params=True): """Removes an item with the specified ID from Google Base. Args: item_id: string The ID of the item to be deleted. Example: 'http://www.google.com/base/feeds/items/13185446517496042648' url_params: dict (optional) Additional URL parameters to be included in the deletion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: True if the delete succeeded. """ return self.Delete('%s' % (item_id[len('http://www.google.com'):],), url_params=url_params, escape_params=escape_params) def UpdateItem(self, item_id, updated_item, url_params=None, escape_params=True, converter=gdata.base.GBaseItemFromString): """Updates an existing item. Args: item_id: string The ID of the item to be updated. Example: 'http://www.google.com/base/feeds/items/13185446517496042648' updated_item: atom.Entry, subclass, or string, containing the Atom Entry which will replace the base item which is stored at the item_id. url_params: dict (optional) Additional URL parameters to be included in the update request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. converter: func (optional) Function which is executed on the server's response before it is returned. Usually this is a function like GBaseItemFromString which will parse the response and turn it into an object. Returns: If converter is defined, the results of running converter on the server's response. Otherwise, it will be a GBaseItem. """ response = self.Put(updated_item, item_id, url_params=url_params, escape_params=escape_params, converter=converter) if not converter and isinstance(response, atom.Entry): return gdata.base.GBaseItemFromString(response.ToString()) return response def ExecuteBatch(self, batch_feed, converter=gdata.base.GBaseItemFeedFromString): """Sends a batch request feed to the server. Args: batch_feed: gdata.BatchFeed A feed containing BatchEntry elements which contain the desired CRUD operation and any necessary entry data. converter: Function (optional) Function to be executed on the server's response. This function should take one string as a parameter. The default value is GBaseItemFeedFromString which will turn the result into a gdata.base.GBaseItem object. Returns: A gdata.BatchFeed containing the results. """ return self.Post(batch_feed, BASE_BATCH_URL, converter=converter) class BaseQuery(gdata.service.Query): def _GetBaseQuery(self): return self['bq'] def _SetBaseQuery(self, base_query): self['bq'] = base_query bq = property(_GetBaseQuery, _SetBaseQuery, doc="""The bq query parameter""")
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains extensions to Atom objects used with Google Base.""" __author__ = 'api.jscudder (Jeffrey Scudder)' try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata # XML namespaces which are often used in Google Base entities. GBASE_NAMESPACE = 'http://base.google.com/ns/1.0' GBASE_TEMPLATE = '{http://base.google.com/ns/1.0}%s' GMETA_NAMESPACE = 'http://base.google.com/ns-metadata/1.0' GMETA_TEMPLATE = '{http://base.google.com/ns-metadata/1.0}%s' class ItemAttributeContainer(atom.AtomBase): """Provides methods for finding Google Base Item attributes. Google Base item attributes are child nodes in the gbase namespace. Google Base allows you to define your own item attributes and this class provides methods to interact with the custom attributes. """ def GetItemAttributes(self, name): """Returns a list of all item attributes which have the desired name. Args: name: str The tag of the desired base attributes. For example, calling this method with 'rating' would return a list of ItemAttributes represented by a 'g:rating' tag. Returns: A list of matching ItemAttribute objects. """ result = [] for attrib in self.item_attributes: if attrib.name == name: result.append(attrib) return result def FindItemAttribute(self, name): """Get the contents of the first Base item attribute which matches name. This method is deprecated, please use GetItemAttributes instead. Args: name: str The tag of the desired base attribute. For example, calling this method with name = 'rating' would search for a tag rating in the GBase namespace in the item attributes. Returns: The text contents of the item attribute, or none if the attribute was not found. """ for attrib in self.item_attributes: if attrib.name == name: return attrib.text return None def AddItemAttribute(self, name, value, value_type=None, access=None): """Adds a new item attribute tag containing the value. Creates a new extension element in the GBase namespace to represent a Google Base item attribute. Args: name: str The tag name for the new attribute. This must be a valid xml tag name. The tag will be placed in the GBase namespace. value: str Contents for the item attribute value_type: str (optional) The type of data in the vlaue, Examples: text float access: str (optional) Used to hide attributes. The attribute is not exposed in the snippets feed if access is set to 'private'. """ new_attribute = ItemAttribute(name, text=value, text_type=value_type, access=access) self.item_attributes.append(new_attribute) return new_attribute def SetItemAttribute(self, name, value): """Changes an existing item attribute's value.""" for attrib in self.item_attributes: if attrib.name == name: attrib.text = value return def RemoveItemAttribute(self, name): """Deletes the first extension element which matches name. Deletes the first extension element which matches name. """ for i in xrange(len(self.item_attributes)): if self.item_attributes[i].name == name: del self.item_attributes[i] return # We need to overwrite _ConvertElementTreeToMember to add special logic to # convert custom attributes to members def _ConvertElementTreeToMember(self, child_tree): # Find the element's tag in this class's list of child members if self.__class__._children.has_key(child_tree.tag): member_name = self.__class__._children[child_tree.tag][0] member_class = self.__class__._children[child_tree.tag][1] # If the class member is supposed to contain a list, make sure the # matching member is set to a list, then append the new member # instance to the list. if isinstance(member_class, list): if getattr(self, member_name) is None: setattr(self, member_name, []) getattr(self, member_name).append(atom._CreateClassFromElementTree( member_class[0], child_tree)) else: setattr(self, member_name, atom._CreateClassFromElementTree(member_class, child_tree)) elif child_tree.tag.find('{%s}' % GBASE_NAMESPACE) == 0: # If this is in the gbase namespace, make it into an extension element. name = child_tree.tag[child_tree.tag.index('}')+1:] value = child_tree.text if child_tree.attrib.has_key('type'): value_type = child_tree.attrib['type'] else: value_type = None attrib=self.AddItemAttribute(name, value, value_type) for sub in child_tree.getchildren(): sub_name = sub.tag[sub.tag.index('}')+1:] sub_value=sub.text if sub.attrib.has_key('type'): sub_type = sub.attrib['type'] else: sub_type=None attrib.AddItemAttribute(sub_name, sub_value, sub_type) else: atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree) # We need to overwtite _AddMembersToElementTree to add special logic to # convert custom members to XML nodes. def _AddMembersToElementTree(self, tree): # Convert the members of this class which are XML child nodes. # This uses the class's _children dictionary to find the members which # should become XML child nodes. member_node_names = [values[0] for tag, values in self.__class__._children.iteritems()] for member_name in member_node_names: member = getattr(self, member_name) if member is None: pass elif isinstance(member, list): for instance in member: instance._BecomeChildElement(tree) else: member._BecomeChildElement(tree) # Convert the members of this class which are XML attributes. for xml_attribute, member_name in self.__class__._attributes.iteritems(): member = getattr(self, member_name) if member is not None: tree.attrib[xml_attribute] = member # Convert all special custom item attributes to nodes for attribute in self.item_attributes: attribute._BecomeChildElement(tree) # Lastly, call the ExtensionContainers's _AddMembersToElementTree to # convert any extension attributes. atom.ExtensionContainer._AddMembersToElementTree(self, tree) class ItemAttribute(ItemAttributeContainer): """An optional or user defined attribute for a GBase item. Google Base allows items to have custom attribute child nodes. These nodes have contents and a type attribute which tells Google Base whether the contents are text, a float value with units, etc. The Atom text class has the same structure, so this class inherits from Text. """ _namespace = GBASE_NAMESPACE _children = atom.Text._children.copy() _attributes = atom.Text._attributes.copy() _attributes['access'] = 'access' def __init__(self, name, text_type=None, access=None, text=None, extension_elements=None, extension_attributes=None, item_attributes=None): """Constructor for a GBase item attribute Args: name: str The name of the attribute. Examples include price, color, make, model, pages, salary, etc. text_type: str (optional) The type associated with the text contents access: str (optional) If the access attribute is set to 'private', the attribute will not be included in the item's description in the snippets feed text: str (optional) The text data in the this element extension_elements: list (optional) A list of ExtensionElement instances extension_attributes: dict (optional) A dictionary of attribute value string pairs """ self.name = name self.type = text_type self.access = access self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.item_attributes = item_attributes or [] def _BecomeChildElement(self, tree): new_child = ElementTree.Element('') tree.append(new_child) new_child.tag = '{%s}%s' % (self.__class__._namespace, self.name) self._AddMembersToElementTree(new_child) def _ToElementTree(self): new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace, self.name)) self._AddMembersToElementTree(new_tree) return new_tree def ItemAttributeFromString(xml_string): element_tree = ElementTree.fromstring(xml_string) return _ItemAttributeFromElementTree(element_tree) def _ItemAttributeFromElementTree(element_tree): if element_tree.tag.find(GBASE_TEMPLATE % '') == 0: to_return = ItemAttribute('') to_return._HarvestElementTree(element_tree) to_return.name = element_tree.tag[element_tree.tag.index('}')+1:] if to_return.name and to_return.name != '': return to_return return None class Label(atom.AtomBase): """The Google Base label element""" _tag = 'label' _namespace = GBASE_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def LabelFromString(xml_string): return atom.CreateClassFromXMLString(Label, xml_string) class Thumbnail(atom.AtomBase): """The Google Base thumbnail element""" _tag = 'thumbnail' _namespace = GMETA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['width'] = 'width' _attributes['height'] = 'height' def __init__(self, width=None, height=None, text=None, extension_elements=None, extension_attributes=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.width = width self.height = height def ThumbnailFromString(xml_string): return atom.CreateClassFromXMLString(Thumbnail, xml_string) class ImageLink(atom.Text): """The Google Base image_link element""" _tag = 'image_link' _namespace = GBASE_NAMESPACE _children = atom.Text._children.copy() _attributes = atom.Text._attributes.copy() _children['{%s}thumbnail' % GMETA_NAMESPACE] = ('thumbnail', [Thumbnail]) def __init__(self, thumbnail=None, text=None, extension_elements=None, text_type=None, extension_attributes=None): self.thumbnail = thumbnail or [] self.text = text self.type = text_type self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def ImageLinkFromString(xml_string): return atom.CreateClassFromXMLString(ImageLink, xml_string) class ItemType(atom.Text): """The Google Base item_type element""" _tag = 'item_type' _namespace = GBASE_NAMESPACE _children = atom.Text._children.copy() _attributes = atom.Text._attributes.copy() def __init__(self, text=None, extension_elements=None, text_type=None, extension_attributes=None): self.text = text self.type = text_type self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def ItemTypeFromString(xml_string): return atom.CreateClassFromXMLString(ItemType, xml_string) class MetaItemType(ItemType): """The Google Base item_type element""" _tag = 'item_type' _namespace = GMETA_NAMESPACE _children = ItemType._children.copy() _attributes = ItemType._attributes.copy() def MetaItemTypeFromString(xml_string): return atom.CreateClassFromXMLString(MetaItemType, xml_string) class Value(atom.AtomBase): """Metadata about common values for a given attribute A value is a child of an attribute which comes from the attributes feed. The value's text is a commonly used value paired with an attribute name and the value's count tells how often this value appears for the given attribute in the search results. """ _tag = 'value' _namespace = GMETA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['count'] = 'count' def __init__(self, count=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Attribute metadata element Args: count: str (optional) The number of times the value in text is given for the parent attribute. text: str (optional) The value which appears in the search results. extension_elements: list (optional) A list of ExtensionElement instances extension_attributes: dict (optional) A dictionary of attribute value string pairs """ self.count = count self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def ValueFromString(xml_string): return atom.CreateClassFromXMLString(Value, xml_string) class Bucket(atom.AtomBase): """Metadata about common values for a given attribute A bucket is a child of an attribute which comes from the attributes feed. The bucket's text is a commonly used value paired with an attribute name and the bucket's count tells how often this attribute's value falls within the bucket's range in the search results. """ _tag = 'bucket' _namespace = GMETA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['count'] = 'count' _attributes['low'] = 'low' _attributes['high'] = 'high' def __init__(self, count=None, text=None, low=None, high=None, extension_elements=None, extension_attributes=None): """Constructor for Bucket metadata element Args: count: str (optional) The number of times the value in text is given for the parent attribute. text: str (optional) The bucket's string representation. low: str (optional) The low end of the bucket. high: str (optional) The high end of the bucket. extension_elements: list (optional) A list of ExtensionElement instances extension_attributes: dict (optional) A dictionary of attribute value string pairs """ self.count = count self.text = text self.low = low self.high = high self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def BucketFromString(xml_string): return atom.CreateClassFromXMLString(Bucket, xml_string) class Attribute(atom.Text): """Metadata about an attribute from the attributes feed An entry from the attributes feed contains a list of attributes. Each attribute describes the attribute's type and count of the items which use the attribute. """ _tag = 'attribute' _namespace = GMETA_NAMESPACE _children = atom.Text._children.copy() _attributes = atom.Text._attributes.copy() _children['{%s}value' % GMETA_NAMESPACE] = ('value', [Value]) _children['{%s}bucket' % GMETA_NAMESPACE] = ('bucket', [Bucket]) _attributes['count'] = 'count' _attributes['name'] = 'name' def __init__(self, name=None, attribute_type=None, count=None, value=None, bucket=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Attribute metadata element Args: name: str (optional) The name of the attribute attribute_type: str (optional) The type for the attribute. Examples: test, float, etc. count: str (optional) The number of times this attribute appears in the query results. value: list (optional) The values which are often used for this attirbute. bucket: list (optional) The buckets for this attribute. text: str (optional) The text contents of the XML for this attribute. extension_elements: list (optional) A list of ExtensionElement instances extension_attributes: dict (optional) A dictionary of attribute value string pairs """ self.name = name self.type = attribute_type self.count = count self.value = value or [] self.bucket = bucket or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def AttributeFromString(xml_string): return atom.CreateClassFromXMLString(Attribute, xml_string) class Attributes(atom.AtomBase): """A collection of Google Base metadata attributes""" _tag = 'attributes' _namespace = GMETA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute]) def __init__(self, attribute=None, extension_elements=None, extension_attributes=None, text=None): self.attribute = attribute or [] self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text class GBaseItem(ItemAttributeContainer, gdata.BatchEntry): """An Google Base flavor of an Atom Entry. Google Base items have required attributes, recommended attributes, and user defined attributes. The required attributes are stored in this class as members, and other attributes are stored as extension elements. You can access the recommended and user defined attributes by using AddItemAttribute, SetItemAttribute, FindItemAttribute, and RemoveItemAttribute. The Base Item """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.BatchEntry._children.copy() _attributes = gdata.BatchEntry._attributes.copy() _children['{%s}label' % GBASE_NAMESPACE] = ('label', [Label]) _children['{%s}item_type' % GBASE_NAMESPACE] = ('item_type', ItemType) def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, title=None, updated=None, control=None, label=None, item_type=None, item_attributes=None, batch_operation=None, batch_id=None, batch_status=None, text=None, extension_elements=None, extension_attributes=None): self.author = author or [] self.category = category or [] self.content = content self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.published = published self.rights = rights self.source = source self.summary = summary self.title = title self.updated = updated self.control = control self.label = label or [] self.item_type = item_type self.item_attributes = item_attributes or [] self.batch_operation = batch_operation self.batch_id = batch_id self.batch_status = batch_status self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def GBaseItemFromString(xml_string): return atom.CreateClassFromXMLString(GBaseItem, xml_string) class GBaseSnippet(GBaseItem): _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = GBaseItem._children.copy() _attributes = GBaseItem._attributes.copy() def GBaseSnippetFromString(xml_string): return atom.CreateClassFromXMLString(GBaseSnippet, xml_string) class GBaseAttributeEntry(gdata.GDataEntry): """An Atom Entry from the attributes feed""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute]) def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, title=None, updated=None, label=None, attribute=None, control=None, text=None, extension_elements=None, extension_attributes=None): self.author = author or [] self.category = category or [] self.content = content self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.published = published self.rights = rights self.source = source self.summary = summary self.control = control self.title = title self.updated = updated self.label = label or [] self.attribute = attribute or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def GBaseAttributeEntryFromString(xml_string): return atom.CreateClassFromXMLString(GBaseAttributeEntry, xml_string) class GBaseItemTypeEntry(gdata.GDataEntry): """An Atom entry from the item types feed These entries contain a list of attributes which are stored in one XML node called attributes. This class simplifies the data structure by treating attributes as a list of attribute instances. Note that the item_type for an item type entry is in the Google Base meta namespace as opposed to item_types encountered in other feeds. """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}attributes' % GMETA_NAMESPACE] = ('attributes', Attributes) _children['{%s}attribute' % GMETA_NAMESPACE] = ('attribute', [Attribute]) _children['{%s}item_type' % GMETA_NAMESPACE] = ('item_type', MetaItemType) def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, title=None, updated=None, label=None, item_type=None, control=None, attribute=None, attributes=None, text=None, extension_elements=None, extension_attributes=None): self.author = author or [] self.category = category or [] self.content = content self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.published = published self.rights = rights self.source = source self.summary = summary self.title = title self.updated = updated self.control = control self.label = label or [] self.item_type = item_type self.attributes = attributes self.attribute = attribute or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def GBaseItemTypeEntryFromString(xml_string): return atom.CreateClassFromXMLString(GBaseItemTypeEntry, xml_string) class GBaseItemFeed(gdata.BatchFeed): """A feed containing Google Base Items""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.BatchFeed._children.copy() _attributes = gdata.BatchFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseItem]) def GBaseItemFeedFromString(xml_string): return atom.CreateClassFromXMLString(GBaseItemFeed, xml_string) class GBaseSnippetFeed(gdata.GDataFeed): """A feed containing Google Base Snippets""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseSnippet]) def GBaseSnippetFeedFromString(xml_string): return atom.CreateClassFromXMLString(GBaseSnippetFeed, xml_string) class GBaseAttributesFeed(gdata.GDataFeed): """A feed containing Google Base Attributes A query sent to the attributes feed will return a feed of attributes which are present in the items that match the query. """ _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseAttributeEntry]) def GBaseAttributesFeedFromString(xml_string): return atom.CreateClassFromXMLString(GBaseAttributesFeed, xml_string) class GBaseLocalesFeed(gdata.GDataFeed): """The locales feed from Google Base. This read-only feed defines the permitted locales for Google Base. The locale value identifies the language, currency, and date formats used in a feed. """ _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() def GBaseLocalesFeedFromString(xml_string): return atom.CreateClassFromXMLString(GBaseLocalesFeed, xml_string) class GBaseItemTypesFeed(gdata.GDataFeed): """A feed from the Google Base item types feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GBaseItemTypeEntry]) def GBaseItemTypesFeedFromString(xml_string): return atom.CreateClassFromXMLString(GBaseItemTypesFeed, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the data classes of the OpenSearch Extension""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core OPENSEARCH_TEMPLATE_V1 = '{http://a9.com/-/spec/opensearchrss/1.0//}%s' OPENSEARCH_TEMPLATE_V2 = '{http://a9.com/-/spec/opensearch/1.1//}%s' class ItemsPerPage(atom.core.XmlElement): """Describes the number of items that will be returned per page for paged feeds""" _qname = (OPENSEARCH_TEMPLATE_V1 % 'itemsPerPage', OPENSEARCH_TEMPLATE_V2 % 'itemsPerPage') class StartIndex(atom.core.XmlElement): """Describes the starting index of the contained entries for paged feeds""" _qname = (OPENSEARCH_TEMPLATE_V1 % 'startIndex', OPENSEARCH_TEMPLATE_V2 % 'startIndex') class TotalResults(atom.core.XmlElement): """Describes the total number of results associated with this feed""" _qname = (OPENSEARCH_TEMPLATE_V1 % 'totalResults', OPENSEARCH_TEMPLATE_V2 % 'totalResults')
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. """Provides classes and constants for the XML in the Google Data namespace. Documentation for the raw XML which these classes represent can be found here: http://code.google.com/apis/gdata/docs/2.0/elements.html """ __author__ = 'j.s@google.com (Jeff Scudder)' import os import atom.core import atom.data GDATA_TEMPLATE = '{http://schemas.google.com/g/2005}%s' GD_TEMPLATE = GDATA_TEMPLATE OPENSEARCH_TEMPLATE_V1 = '{http://a9.com/-/spec/opensearchrss/1.0/}%s' OPENSEARCH_TEMPLATE_V2 = '{http://a9.com/-/spec/opensearch/1.1/}%s' BATCH_TEMPLATE = '{http://schemas.google.com/gdata/batch}%s' # Labels used in batch request entries to specify the desired CRUD operation. BATCH_INSERT = 'insert' BATCH_UPDATE = 'update' BATCH_DELETE = 'delete' BATCH_QUERY = 'query' EVENT_LOCATION = 'http://schemas.google.com/g/2005#event' ALTERNATE_LOCATION = 'http://schemas.google.com/g/2005#event.alternate' PARKING_LOCATION = 'http://schemas.google.com/g/2005#event.parking' CANCELED_EVENT = 'http://schemas.google.com/g/2005#event.canceled' CONFIRMED_EVENT = 'http://schemas.google.com/g/2005#event.confirmed' TENTATIVE_EVENT = 'http://schemas.google.com/g/2005#event.tentative' CONFIDENTIAL_EVENT = 'http://schemas.google.com/g/2005#event.confidential' DEFAULT_EVENT = 'http://schemas.google.com/g/2005#event.default' PRIVATE_EVENT = 'http://schemas.google.com/g/2005#event.private' PUBLIC_EVENT = 'http://schemas.google.com/g/2005#event.public' OPAQUE_EVENT = 'http://schemas.google.com/g/2005#event.opaque' TRANSPARENT_EVENT = 'http://schemas.google.com/g/2005#event.transparent' CHAT_MESSAGE = 'http://schemas.google.com/g/2005#message.chat' INBOX_MESSAGE = 'http://schemas.google.com/g/2005#message.inbox' SENT_MESSAGE = 'http://schemas.google.com/g/2005#message.sent' SPAM_MESSAGE = 'http://schemas.google.com/g/2005#message.spam' STARRED_MESSAGE = 'http://schemas.google.com/g/2005#message.starred' UNREAD_MESSAGE = 'http://schemas.google.com/g/2005#message.unread' BCC_RECIPIENT = 'http://schemas.google.com/g/2005#message.bcc' CC_RECIPIENT = 'http://schemas.google.com/g/2005#message.cc' SENDER = 'http://schemas.google.com/g/2005#message.from' REPLY_TO = 'http://schemas.google.com/g/2005#message.reply-to' TO_RECIPIENT = 'http://schemas.google.com/g/2005#message.to' ASSISTANT_REL = 'http://schemas.google.com/g/2005#assistant' CALLBACK_REL = 'http://schemas.google.com/g/2005#callback' CAR_REL = 'http://schemas.google.com/g/2005#car' COMPANY_MAIN_REL = 'http://schemas.google.com/g/2005#company_main' FAX_REL = 'http://schemas.google.com/g/2005#fax' HOME_REL = 'http://schemas.google.com/g/2005#home' HOME_FAX_REL = 'http://schemas.google.com/g/2005#home_fax' ISDN_REL = 'http://schemas.google.com/g/2005#isdn' MAIN_REL = 'http://schemas.google.com/g/2005#main' MOBILE_REL = 'http://schemas.google.com/g/2005#mobile' OTHER_REL = 'http://schemas.google.com/g/2005#other' OTHER_FAX_REL = 'http://schemas.google.com/g/2005#other_fax' PAGER_REL = 'http://schemas.google.com/g/2005#pager' RADIO_REL = 'http://schemas.google.com/g/2005#radio' TELEX_REL = 'http://schemas.google.com/g/2005#telex' TTL_TDD_REL = 'http://schemas.google.com/g/2005#tty_tdd' WORK_REL = 'http://schemas.google.com/g/2005#work' WORK_FAX_REL = 'http://schemas.google.com/g/2005#work_fax' WORK_MOBILE_REL = 'http://schemas.google.com/g/2005#work_mobile' WORK_PAGER_REL = 'http://schemas.google.com/g/2005#work_pager' NETMEETING_REL = 'http://schemas.google.com/g/2005#netmeeting' OVERALL_REL = 'http://schemas.google.com/g/2005#overall' PRICE_REL = 'http://schemas.google.com/g/2005#price' QUALITY_REL = 'http://schemas.google.com/g/2005#quality' EVENT_REL = 'http://schemas.google.com/g/2005#event' EVENT_ALTERNATE_REL = 'http://schemas.google.com/g/2005#event.alternate' EVENT_PARKING_REL = 'http://schemas.google.com/g/2005#event.parking' AIM_PROTOCOL = 'http://schemas.google.com/g/2005#AIM' MSN_PROTOCOL = 'http://schemas.google.com/g/2005#MSN' YAHOO_MESSENGER_PROTOCOL = 'http://schemas.google.com/g/2005#YAHOO' SKYPE_PROTOCOL = 'http://schemas.google.com/g/2005#SKYPE' QQ_PROTOCOL = 'http://schemas.google.com/g/2005#QQ' GOOGLE_TALK_PROTOCOL = 'http://schemas.google.com/g/2005#GOOGLE_TALK' ICQ_PROTOCOL = 'http://schemas.google.com/g/2005#ICQ' JABBER_PROTOCOL = 'http://schemas.google.com/g/2005#JABBER' REGULAR_COMMENTS = 'http://schemas.google.com/g/2005#regular' REVIEW_COMMENTS = 'http://schemas.google.com/g/2005#reviews' MAIL_BOTH = 'http://schemas.google.com/g/2005#both' MAIL_LETTERS = 'http://schemas.google.com/g/2005#letters' MAIL_PARCELS = 'http://schemas.google.com/g/2005#parcels' MAIL_NEITHER = 'http://schemas.google.com/g/2005#neither' GENERAL_ADDRESS = 'http://schemas.google.com/g/2005#general' LOCAL_ADDRESS = 'http://schemas.google.com/g/2005#local' OPTIONAL_ATENDEE = 'http://schemas.google.com/g/2005#event.optional' REQUIRED_ATENDEE = 'http://schemas.google.com/g/2005#event.required' ATTENDEE_ACCEPTED = 'http://schemas.google.com/g/2005#event.accepted' ATTENDEE_DECLINED = 'http://schemas.google.com/g/2005#event.declined' ATTENDEE_INVITED = 'http://schemas.google.com/g/2005#event.invited' ATTENDEE_TENTATIVE = 'http://schemas.google.com/g/2005#event.tentative' FULL_PROJECTION = 'full' VALUES_PROJECTION = 'values' BASIC_PROJECTION = 'basic' PRIVATE_VISIBILITY = 'private' PUBLIC_VISIBILITY = 'public' OPAQUE_TRANSPARENCY = 'http://schemas.google.com/g/2005#event.opaque' TRANSPARENT_TRANSPARENCY = 'http://schemas.google.com/g/2005#event.transparent' CONFIDENTIAL_EVENT_VISIBILITY = 'http://schemas.google.com/g/2005#event.confidential' DEFAULT_EVENT_VISIBILITY = 'http://schemas.google.com/g/2005#event.default' PRIVATE_EVENT_VISIBILITY = 'http://schemas.google.com/g/2005#event.private' PUBLIC_EVENT_VISIBILITY = 'http://schemas.google.com/g/2005#event.public' CANCELED_EVENT_STATUS = 'http://schemas.google.com/g/2005#event.canceled' CONFIRMED_EVENT_STATUS = 'http://schemas.google.com/g/2005#event.confirmed' TENTATIVE_EVENT_STATUS = 'http://schemas.google.com/g/2005#event.tentative' ACL_REL = 'http://schemas.google.com/acl/2007#accessControlList' class Error(Exception): pass class MissingRequiredParameters(Error): pass class LinkFinder(atom.data.LinkFinder): """Mixin used in Feed and Entry classes to simplify link lookups by type. Provides lookup methods for edit, edit-media, post, ACL and other special links which are common across Google Data APIs. """ def find_html_link(self): """Finds the first link with rel of alternate and type of text/html.""" for link in self.link: if link.rel == 'alternate' and link.type == 'text/html': return link.href return None FindHtmlLink = find_html_link def get_html_link(self): for a_link in self.link: if a_link.rel == 'alternate' and a_link.type == 'text/html': return a_link return None GetHtmlLink = get_html_link def find_post_link(self): """Get the URL to which new entries should be POSTed. The POST target URL is used to insert new entries. Returns: A str for the URL in the link with a rel matching the POST type. """ return self.find_url('http://schemas.google.com/g/2005#post') FindPostLink = find_post_link def get_post_link(self): return self.get_link('http://schemas.google.com/g/2005#post') GetPostLink = get_post_link def find_acl_link(self): acl_link = self.get_acl_link() if acl_link: return acl_link.href return None FindAclLink = find_acl_link def get_acl_link(self): """Searches for a link or feed_link (if present) with the rel for ACL.""" acl_link = self.get_link(ACL_REL) if acl_link: return acl_link elif hasattr(self, 'feed_link'): for a_feed_link in self.feed_link: if a_feed_link.rel == ACL_REL: return a_feed_link return None GetAclLink = get_acl_link def find_feed_link(self): return self.find_url('http://schemas.google.com/g/2005#feed') FindFeedLink = find_feed_link def get_feed_link(self): return self.get_link('http://schemas.google.com/g/2005#feed') GetFeedLink = get_feed_link def find_previous_link(self): return self.find_url('previous') FindPreviousLink = find_previous_link def get_previous_link(self): return self.get_link('previous') GetPreviousLink = get_previous_link class TotalResults(atom.core.XmlElement): """opensearch:TotalResults for a GData feed.""" _qname = (OPENSEARCH_TEMPLATE_V1 % 'totalResults', OPENSEARCH_TEMPLATE_V2 % 'totalResults') class StartIndex(atom.core.XmlElement): """The opensearch:startIndex element in GData feed.""" _qname = (OPENSEARCH_TEMPLATE_V1 % 'startIndex', OPENSEARCH_TEMPLATE_V2 % 'startIndex') class ItemsPerPage(atom.core.XmlElement): """The opensearch:itemsPerPage element in GData feed.""" _qname = (OPENSEARCH_TEMPLATE_V1 % 'itemsPerPage', OPENSEARCH_TEMPLATE_V2 % 'itemsPerPage') class ExtendedProperty(atom.core.XmlElement): """The Google Data extendedProperty element. Used to store arbitrary key-value information specific to your application. The value can either be a text string stored as an XML attribute (.value), or an XML node (XmlBlob) as a child element. This element is used in the Google Calendar data API and the Google Contacts data API. """ _qname = GDATA_TEMPLATE % 'extendedProperty' name = 'name' value = 'value' def get_xml_blob(self): """Returns the XML blob as an atom.core.XmlElement. Returns: An XmlElement representing the blob's XML, or None if no blob was set. """ if self._other_elements: return self._other_elements[0] else: return None GetXmlBlob = get_xml_blob def set_xml_blob(self, blob): """Sets the contents of the extendedProperty to XML as a child node. Since the extendedProperty is only allowed one child element as an XML blob, setting the XML blob will erase any preexisting member elements in this object. Args: blob: str or atom.core.XmlElement representing the XML blob stored in the extendedProperty. """ # Erase any existing extension_elements, clears the child nodes from the # extendedProperty. if isinstance(blob, atom.core.XmlElement): self._other_elements = [blob] else: self._other_elements = [atom.core.parse(str(blob))] SetXmlBlob = set_xml_blob class GDEntry(atom.data.Entry, LinkFinder): """Extends Atom Entry to provide data processing""" etag = '{http://schemas.google.com/g/2005}etag' def get_id(self): if self.id is not None and self.id.text is not None: return self.id.text.strip() return None GetId = get_id def is_media(self): if self.find_edit_media_link(): return True return False IsMedia = is_media def find_media_link(self): """Returns the URL to the media content, if the entry is a media entry. Otherwise returns None. """ if self.is_media(): return self.content.src return None FindMediaLink = find_media_link class GDFeed(atom.data.Feed, LinkFinder): """A Feed from a GData service.""" etag = '{http://schemas.google.com/g/2005}etag' total_results = TotalResults start_index = StartIndex items_per_page = ItemsPerPage entry = [GDEntry] def get_id(self): if self.id is not None and self.id.text is not None: return self.id.text.strip() return None GetId = get_id def get_generator(self): if self.generator and self.generator.text: return self.generator.text.strip() return None class BatchId(atom.core.XmlElement): """Identifies a single operation in a batch request.""" _qname = BATCH_TEMPLATE % 'id' class BatchOperation(atom.core.XmlElement): """The CRUD operation which this batch entry represents.""" _qname = BATCH_TEMPLATE % 'operation' type = 'type' class BatchStatus(atom.core.XmlElement): """The batch:status element present in a batch response entry. A status element contains the code (HTTP response code) and reason as elements. In a single request these fields would be part of the HTTP response, but in a batch request each Entry operation has a corresponding Entry in the response feed which includes status information. See http://code.google.com/apis/gdata/batch.html#Handling_Errors """ _qname = BATCH_TEMPLATE % 'status' code = 'code' reason = 'reason' content_type = 'content-type' class BatchEntry(GDEntry): """An atom:entry for use in batch requests. The BatchEntry contains additional members to specify the operation to be performed on this entry and a batch ID so that the server can reference individual operations in the response feed. For more information, see: http://code.google.com/apis/gdata/batch.html """ batch_operation = BatchOperation batch_id = BatchId batch_status = BatchStatus class BatchInterrupted(atom.core.XmlElement): """The batch:interrupted element sent if batch request was interrupted. Only appears in a feed if some of the batch entries could not be processed. See: http://code.google.com/apis/gdata/batch.html#Handling_Errors """ _qname = BATCH_TEMPLATE % 'interrupted' reason = 'reason' success = 'success' failures = 'failures' parsed = 'parsed' class BatchFeed(GDFeed): """A feed containing a list of batch request entries.""" interrupted = BatchInterrupted entry = [BatchEntry] def add_batch_entry(self, entry=None, id_url_string=None, batch_id_string=None, operation_string=None): """Logic for populating members of a BatchEntry and adding to the feed. If the entry is not a BatchEntry, it is converted to a BatchEntry so that the batch specific members will be present. The id_url_string can be used in place of an entry if the batch operation applies to a URL. For example query and delete operations require just the URL of an entry, no body is sent in the HTTP request. If an id_url_string is sent instead of an entry, a BatchEntry is created and added to the feed. This method also assigns the desired batch id to the entry so that it can be referenced in the server's response. If the batch_id_string is None, this method will assign a batch_id to be the index at which this entry will be in the feed's entry list. Args: entry: BatchEntry, atom.data.Entry, or another Entry flavor (optional) The entry which will be sent to the server as part of the batch request. The item must have a valid atom id so that the server knows which entry this request references. id_url_string: str (optional) The URL of the entry to be acted on. You can find this URL in the text member of the atom id for an entry. If an entry is not sent, this id will be used to construct a new BatchEntry which will be added to the request feed. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. Note that batch_ids should either always be specified or never, mixing could potentially result in duplicate batch ids. operation_string: str (optional) The desired batch operation which will set the batch_operation.type member of the entry. Options are 'insert', 'update', 'delete', and 'query' Raises: MissingRequiredParameters: Raised if neither an id_ url_string nor an entry are provided in the request. Returns: The added entry. """ if entry is None and id_url_string is None: raise MissingRequiredParameters('supply either an entry or URL string') if entry is None and id_url_string is not None: entry = BatchEntry(id=atom.data.Id(text=id_url_string)) if batch_id_string is not None: entry.batch_id = BatchId(text=batch_id_string) elif entry.batch_id is None or entry.batch_id.text is None: entry.batch_id = BatchId(text=str(len(self.entry))) if operation_string is not None: entry.batch_operation = BatchOperation(type=operation_string) self.entry.append(entry) return entry AddBatchEntry = add_batch_entry def add_insert(self, entry, batch_id_string=None): """Add an insert request to the operations in this batch request feed. If the entry doesn't yet have an operation or a batch id, these will be set to the insert operation and a batch_id specified as a parameter. Args: entry: BatchEntry The entry which will be sent in the batch feed as an insert request. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. Note that batch_ids should either always be specified or never, mixing could potentially result in duplicate batch ids. """ self.add_batch_entry(entry=entry, batch_id_string=batch_id_string, operation_string=BATCH_INSERT) AddInsert = add_insert def add_update(self, entry, batch_id_string=None): """Add an update request to the list of batch operations in this feed. Sets the operation type of the entry to insert if it is not already set and assigns the desired batch id to the entry so that it can be referenced in the server's response. Args: entry: BatchEntry The entry which will be sent to the server as an update (HTTP PUT) request. The item must have a valid atom id so that the server knows which entry to replace. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. See also comments for AddInsert. """ self.add_batch_entry(entry=entry, batch_id_string=batch_id_string, operation_string=BATCH_UPDATE) AddUpdate = add_update def add_delete(self, url_string=None, entry=None, batch_id_string=None): """Adds a delete request to the batch request feed. This method takes either the url_string which is the atom id of the item to be deleted, or the entry itself. The atom id of the entry must be present so that the server knows which entry should be deleted. Args: url_string: str (optional) The URL of the entry to be deleted. You can find this URL in the text member of the atom id for an entry. entry: BatchEntry (optional) The entry to be deleted. batch_id_string: str (optional) Raises: MissingRequiredParameters: Raised if neither a url_string nor an entry are provided in the request. """ self.add_batch_entry(entry=entry, id_url_string=url_string, batch_id_string=batch_id_string, operation_string=BATCH_DELETE) AddDelete = add_delete def add_query(self, url_string=None, entry=None, batch_id_string=None): """Adds a query request to the batch request feed. This method takes either the url_string which is the query URL whose results will be added to the result feed. The query URL will be encapsulated in a BatchEntry, and you may pass in the BatchEntry with a query URL instead of sending a url_string. Args: url_string: str (optional) entry: BatchEntry (optional) batch_id_string: str (optional) Raises: MissingRequiredParameters """ self.add_batch_entry(entry=entry, id_url_string=url_string, batch_id_string=batch_id_string, operation_string=BATCH_QUERY) AddQuery = add_query def find_batch_link(self): return self.find_url('http://schemas.google.com/g/2005#batch') FindBatchLink = find_batch_link class EntryLink(atom.core.XmlElement): """The gd:entryLink element. Represents a logically nested entry. For example, a <gd:who> representing a contact might have a nested entry from a contact feed. """ _qname = GDATA_TEMPLATE % 'entryLink' entry = GDEntry rel = 'rel' read_only = 'readOnly' href = 'href' class FeedLink(atom.core.XmlElement): """The gd:feedLink element. Represents a logically nested feed. For example, a calendar feed might have a nested feed representing all comments on entries. """ _qname = GDATA_TEMPLATE % 'feedLink' feed = GDFeed rel = 'rel' read_only = 'readOnly' count_hint = 'countHint' href = 'href' class AdditionalName(atom.core.XmlElement): """The gd:additionalName element. Specifies additional (eg. middle) name of the person. Contains an attribute for the phonetic representaton of the name. """ _qname = GDATA_TEMPLATE % 'additionalName' yomi = 'yomi' class Comments(atom.core.XmlElement): """The gd:comments element. Contains a comments feed for the enclosing entry (such as a calendar event). """ _qname = GDATA_TEMPLATE % 'comments' rel = 'rel' feed_link = FeedLink class Country(atom.core.XmlElement): """The gd:country element. Country name along with optional country code. The country code is given in accordance with ISO 3166-1 alpha-2: http://www.iso.org/iso/iso-3166-1_decoding_table """ _qname = GDATA_TEMPLATE % 'country' code = 'code' class EmailImParent(atom.core.XmlElement): address = 'address' label = 'label' rel = 'rel' primary = 'primary' class Email(EmailImParent): """The gd:email element. An email address associated with the containing entity (which is usually an entity representing a person or a location). """ _qname = GDATA_TEMPLATE % 'email' display_name = 'displayName' class FamilyName(atom.core.XmlElement): """The gd:familyName element. Specifies family name of the person, eg. "Smith". """ _qname = GDATA_TEMPLATE % 'familyName' yomi = 'yomi' class Im(EmailImParent): """The gd:im element. An instant messaging address associated with the containing entity. """ _qname = GDATA_TEMPLATE % 'im' protocol = 'protocol' class GivenName(atom.core.XmlElement): """The gd:givenName element. Specifies given name of the person, eg. "John". """ _qname = GDATA_TEMPLATE % 'givenName' yomi = 'yomi' class NamePrefix(atom.core.XmlElement): """The gd:namePrefix element. Honorific prefix, eg. 'Mr' or 'Mrs'. """ _qname = GDATA_TEMPLATE % 'namePrefix' class NameSuffix(atom.core.XmlElement): """The gd:nameSuffix element. Honorific suffix, eg. 'san' or 'III'. """ _qname = GDATA_TEMPLATE % 'nameSuffix' class FullName(atom.core.XmlElement): """The gd:fullName element. Unstructured representation of the name. """ _qname = GDATA_TEMPLATE % 'fullName' class Name(atom.core.XmlElement): """The gd:name element. Allows storing person's name in a structured way. Consists of given name, additional name, family name, prefix, suffix and full name. """ _qname = GDATA_TEMPLATE % 'name' given_name = GivenName additional_name = AdditionalName family_name = FamilyName name_prefix = NamePrefix name_suffix = NameSuffix full_name = FullName class OrgDepartment(atom.core.XmlElement): """The gd:orgDepartment element. Describes a department within an organization. Must appear within a gd:organization element. """ _qname = GDATA_TEMPLATE % 'orgDepartment' class OrgJobDescription(atom.core.XmlElement): """The gd:orgJobDescription element. Describes a job within an organization. Must appear within a gd:organization element. """ _qname = GDATA_TEMPLATE % 'orgJobDescription' class OrgName(atom.core.XmlElement): """The gd:orgName element. The name of the organization. Must appear within a gd:organization element. Contains a Yomigana attribute (Japanese reading aid) for the organization name. """ _qname = GDATA_TEMPLATE % 'orgName' yomi = 'yomi' class OrgSymbol(atom.core.XmlElement): """The gd:orgSymbol element. Provides a symbol of an organization. Must appear within a gd:organization element. """ _qname = GDATA_TEMPLATE % 'orgSymbol' class OrgTitle(atom.core.XmlElement): """The gd:orgTitle element. The title of a person within an organization. Must appear within a gd:organization element. """ _qname = GDATA_TEMPLATE % 'orgTitle' class Organization(atom.core.XmlElement): """The gd:organization element. An organization, typically associated with a contact. """ _qname = GDATA_TEMPLATE % 'organization' label = 'label' primary = 'primary' rel = 'rel' department = OrgDepartment job_description = OrgJobDescription name = OrgName symbol = OrgSymbol title = OrgTitle class When(atom.core.XmlElement): """The gd:when element. Represents a period of time or an instant. """ _qname = GDATA_TEMPLATE % 'when' end = 'endTime' start = 'startTime' value = 'valueString' class OriginalEvent(atom.core.XmlElement): """The gd:originalEvent element. Equivalent to the Recurrence ID property specified in section 4.8.4.4 of RFC 2445. Appears in every instance of a recurring event, to identify the original event. Contains a <gd:when> element specifying the original start time of the instance that has become an exception. """ _qname = GDATA_TEMPLATE % 'originalEvent' id = 'id' href = 'href' when = When class PhoneNumber(atom.core.XmlElement): """The gd:phoneNumber element. A phone number associated with the containing entity (which is usually an entity representing a person or a location). """ _qname = GDATA_TEMPLATE % 'phoneNumber' label = 'label' rel = 'rel' uri = 'uri' primary = 'primary' class PostalAddress(atom.core.XmlElement): """The gd:postalAddress element.""" _qname = GDATA_TEMPLATE % 'postalAddress' label = 'label' rel = 'rel' uri = 'uri' primary = 'primary' class Rating(atom.core.XmlElement): """The gd:rating element. Represents a numeric rating of the enclosing entity, such as a comment. Each rating supplies its own scale, although it may be normalized by a service; for example, some services might convert all ratings to a scale from 1 to 5. """ _qname = GDATA_TEMPLATE % 'rating' average = 'average' max = 'max' min = 'min' num_raters = 'numRaters' rel = 'rel' value = 'value' class Recurrence(atom.core.XmlElement): """The gd:recurrence element. Represents the dates and times when a recurring event takes place. The string that defines the recurrence consists of a set of properties, each of which is defined in the iCalendar standard (RFC 2445). Specifically, the string usually begins with a DTSTART property that indicates the starting time of the first instance of the event, and often a DTEND property or a DURATION property to indicate when the first instance ends. Next come RRULE, RDATE, EXRULE, and/or EXDATE properties, which collectively define a recurring event and its exceptions (but see below). (See section 4.8.5 of RFC 2445 for more information about these recurrence component properties.) Last comes a VTIMEZONE component, providing detailed timezone rules for any timezone ID mentioned in the preceding properties. Google services like Google Calendar don't generally generate EXRULE and EXDATE properties to represent exceptions to recurring events; instead, they generate <gd:recurrenceException> elements. However, Google services may include EXRULE and/or EXDATE properties anyway; for example, users can import events and exceptions into Calendar, and if those imported events contain EXRULE or EXDATE properties, then Calendar will provide those properties when it sends a <gd:recurrence> element. Note the the use of <gd:recurrenceException> means that you can't be sure just from examining a <gd:recurrence> element whether there are any exceptions to the recurrence description. To ensure that you find all exceptions, look for <gd:recurrenceException> elements in the feed, and use their <gd:originalEvent> elements to match them up with <gd:recurrence> elements. """ _qname = GDATA_TEMPLATE % 'recurrence' class RecurrenceException(atom.core.XmlElement): """The gd:recurrenceException element. Represents an event that's an exception to a recurring event-that is, an instance of a recurring event in which one or more aspects of the recurring event (such as attendance list, time, or location) have been changed. Contains a <gd:originalEvent> element that specifies the original recurring event that this event is an exception to. When you change an instance of a recurring event, that instance becomes an exception. Depending on what change you made to it, the exception behaves in either of two different ways when the original recurring event is changed: - If you add, change, or remove comments, attendees, or attendee responses, then the exception remains tied to the original event, and changes to the original event also change the exception. - If you make any other changes to the exception (such as changing the time or location) then the instance becomes "specialized," which means that it's no longer as tightly tied to the original event. If you change the original event, specialized exceptions don't change. But see below. For example, say you have a meeting every Tuesday and Thursday at 2:00 p.m. If you change the attendance list for this Thursday's meeting (but not for the regularly scheduled meeting), then it becomes an exception. If you change the time for this Thursday's meeting (but not for the regularly scheduled meeting), then it becomes specialized. Regardless of whether an exception is specialized or not, if you do something that deletes the instance that the exception was derived from, then the exception is deleted. Note that changing the day or time of a recurring event deletes all instances, and creates new ones. For example, after you've specialized this Thursday's meeting, say you change the recurring meeting to happen on Monday, Wednesday, and Friday. That change deletes all of the recurring instances of the Tuesday/Thursday meeting, including the specialized one. If a particular instance of a recurring event is deleted, then that instance appears as a <gd:recurrenceException> containing a <gd:entryLink> that has its <gd:eventStatus> set to "http://schemas.google.com/g/2005#event.canceled". (For more information about canceled events, see RFC 2445.) """ _qname = GDATA_TEMPLATE % 'recurrenceException' specialized = 'specialized' entry_link = EntryLink original_event = OriginalEvent class Reminder(atom.core.XmlElement): """The gd:reminder element. A time interval, indicating how long before the containing entity's start time or due time attribute a reminder should be issued. Alternatively, may specify an absolute time at which a reminder should be issued. Also specifies a notification method, indicating what medium the system should use to remind the user. """ _qname = GDATA_TEMPLATE % 'reminder' absolute_time = 'absoluteTime' method = 'method' days = 'days' hours = 'hours' minutes = 'minutes' class Transparency(atom.core.XmlElement): """The gd:transparency element: Extensible enum corresponding to the TRANSP property defined in RFC 244. """ _qname = GDATA_TEMPLATE % 'transparency' value = 'value' class Agent(atom.core.XmlElement): """The gd:agent element. The agent who actually receives the mail. Used in work addresses. Also for 'in care of' or 'c/o'. """ _qname = GDATA_TEMPLATE % 'agent' class HouseName(atom.core.XmlElement): """The gd:housename element. Used in places where houses or buildings have names (and not necessarily numbers), eg. "The Pillars". """ _qname = GDATA_TEMPLATE % 'housename' class Street(atom.core.XmlElement): """The gd:street element. Can be street, avenue, road, etc. This element also includes the house number and room/apartment/flat/floor number. """ _qname = GDATA_TEMPLATE % 'street' class PoBox(atom.core.XmlElement): """The gd:pobox element. Covers actual P.O. boxes, drawers, locked bags, etc. This is usually but not always mutually exclusive with street. """ _qname = GDATA_TEMPLATE % 'pobox' class Neighborhood(atom.core.XmlElement): """The gd:neighborhood element. This is used to disambiguate a street address when a city contains more than one street with the same name, or to specify a small place whose mail is routed through a larger postal town. In China it could be a county or a minor city. """ _qname = GDATA_TEMPLATE % 'neighborhood' class City(atom.core.XmlElement): """The gd:city element. Can be city, village, town, borough, etc. This is the postal town and not necessarily the place of residence or place of business. """ _qname = GDATA_TEMPLATE % 'city' class Subregion(atom.core.XmlElement): """The gd:subregion element. Handles administrative districts such as U.S. or U.K. counties that are not used for mail addressing purposes. Subregion is not intended for delivery addresses. """ _qname = GDATA_TEMPLATE % 'subregion' class Region(atom.core.XmlElement): """The gd:region element. A state, province, county (in Ireland), Land (in Germany), departement (in France), etc. """ _qname = GDATA_TEMPLATE % 'region' class Postcode(atom.core.XmlElement): """The gd:postcode element. Postal code. Usually country-wide, but sometimes specific to the city (e.g. "2" in "Dublin 2, Ireland" addresses). """ _qname = GDATA_TEMPLATE % 'postcode' class Country(atom.core.XmlElement): """The gd:country element. The name or code of the country. """ _qname = GDATA_TEMPLATE % 'country' class FormattedAddress(atom.core.XmlElement): """The gd:formattedAddress element. The full, unstructured postal address. """ _qname = GDATA_TEMPLATE % 'formattedAddress' class StructuredPostalAddress(atom.core.XmlElement): """The gd:structuredPostalAddress element. Postal address split into components. It allows to store the address in locale independent format. The fields can be interpreted and used to generate formatted, locale dependent address. The following elements reperesent parts of the address: agent, house name, street, P.O. box, neighborhood, city, subregion, region, postal code, country. The subregion element is not used for postal addresses, it is provided for extended uses of addresses only. In order to store postal address in an unstructured form formatted address field is provided. """ _qname = GDATA_TEMPLATE % 'structuredPostalAddress' rel = 'rel' mail_class = 'mailClass' usage = 'usage' label = 'label' primary = 'primary' agent = Agent house_name = HouseName street = Street po_box = PoBox neighborhood = Neighborhood city = City subregion = Subregion region = Region postcode = Postcode country = Country formatted_address = FormattedAddress class Where(atom.core.XmlElement): """The gd:where element. A place (such as an event location) associated with the containing entity. The type of the association is determined by the rel attribute; the details of the location are contained in an embedded or linked-to Contact entry. A <gd:where> element is more general than a <gd:geoPt> element. The former identifies a place using a text description and/or a Contact entry, while the latter identifies a place using a specific geographic location. """ _qname = GDATA_TEMPLATE % 'where' label = 'label' rel = 'rel' value = 'valueString' entry_link = EntryLink class AttendeeType(atom.core.XmlElement): """The gd:attendeeType element.""" _qname = GDATA_TEMPLATE % 'attendeeType' value = 'value' class AttendeeStatus(atom.core.XmlElement): """The gd:attendeeStatus element.""" _qname = GDATA_TEMPLATE % 'attendeeStatus' value = 'value' class EventStatus(atom.core.XmlElement): """The gd:eventStatus element.""" _qname = GDATA_TEMPLATE % 'eventStatus' value = 'value' class Visibility(atom.core.XmlElement): """The gd:visibility element.""" _qname = GDATA_TEMPLATE % 'visibility' value = 'value' class Who(atom.core.XmlElement): """The gd:who element. A person associated with the containing entity. The type of the association is determined by the rel attribute; the details about the person are contained in an embedded or linked-to Contact entry. The <gd:who> element can be used to specify email senders and recipients, calendar event organizers, and so on. """ _qname = GDATA_TEMPLATE % 'who' email = 'email' rel = 'rel' value = 'valueString' attendee_status = AttendeeStatus attendee_type = AttendeeType entry_link = EntryLink class Deleted(atom.core.XmlElement): """gd:deleted when present, indicates the containing entry is deleted.""" _qname = GD_TEMPLATE % 'deleted' class Money(atom.core.XmlElement): """Describes money""" _qname = GD_TEMPLATE % 'money' amount = 'amount' currency_code = 'currencyCode' class MediaSource(object): """GData Entries can refer to media sources, so this class provides a place to store references to these objects along with some metadata. """ def __init__(self, file_handle=None, content_type=None, content_length=None, file_path=None, file_name=None): """Creates an object of type MediaSource. Args: file_handle: A file handle pointing to the file to be encapsulated in the MediaSource. content_type: string The MIME type of the file. Required if a file_handle is given. content_length: int The size of the file. Required if a file_handle is given. file_path: string (optional) A full path name to the file. Used in place of a file_handle. file_name: string The name of the file without any path information. Required if a file_handle is given. """ self.file_handle = file_handle self.content_type = content_type self.content_length = content_length self.file_name = file_name if (file_handle is None and content_type is not None and file_path is not None): self.set_file_handle(file_path, content_type) def set_file_handle(self, file_name, content_type): """A helper function which can create a file handle from a given filename and set the content type and length all at once. Args: file_name: string The path and file name to the file containing the media content_type: string A MIME type representing the type of the media """ self.file_handle = open(file_name, 'rb') self.content_type = content_type self.content_length = os.path.getsize(file_name) self.file_name = os.path.basename(file_name) SetFileHandle = set_file_handle def modify_request(self, http_request): http_request.add_body_part(self.file_handle, self.content_type, self.content_length) return http_request ModifyRequest = modify_request
Python
#!/usr/bin/env python # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. """Provides a base class to represent property elements in feeds. This module is used for version 2 of the Google Data APIs. The primary class in this module is AppsProperty. """ __author__ = 'Vic Fryzel <vicfryzel@google.com>' import atom.core import gdata.apps class AppsProperty(atom.core.XmlElement): """Represents an <apps:property> element in a feed.""" _qname = gdata.apps.APPS_TEMPLATE % 'property' name = 'name' value = 'value'
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains classes representing Google Data elements. Extends Atom classes to add Google Data specific elements. """ __author__ = 'j.s@google.com (Jeffrey Scudder)' import os import atom try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree # XML namespaces which are often used in GData entities. GDATA_NAMESPACE = 'http://schemas.google.com/g/2005' GDATA_TEMPLATE = '{http://schemas.google.com/g/2005}%s' OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/' OPENSEARCH_TEMPLATE = '{http://a9.com/-/spec/opensearchrss/1.0/}%s' BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch' GACL_NAMESPACE = 'http://schemas.google.com/acl/2007' GACL_TEMPLATE = '{http://schemas.google.com/acl/2007}%s' # Labels used in batch request entries to specify the desired CRUD operation. BATCH_INSERT = 'insert' BATCH_UPDATE = 'update' BATCH_DELETE = 'delete' BATCH_QUERY = 'query' class Error(Exception): pass class MissingRequiredParameters(Error): pass class MediaSource(object): """GData Entries can refer to media sources, so this class provides a place to store references to these objects along with some metadata. """ def __init__(self, file_handle=None, content_type=None, content_length=None, file_path=None, file_name=None): """Creates an object of type MediaSource. Args: file_handle: A file handle pointing to the file to be encapsulated in the MediaSource content_type: string The MIME type of the file. Required if a file_handle is given. content_length: int The size of the file. Required if a file_handle is given. file_path: string (optional) A full path name to the file. Used in place of a file_handle. file_name: string The name of the file without any path information. Required if a file_handle is given. """ self.file_handle = file_handle self.content_type = content_type self.content_length = content_length self.file_name = file_name if (file_handle is None and content_type is not None and file_path is not None): self.setFile(file_path, content_type) def setFile(self, file_name, content_type): """A helper function which can create a file handle from a given filename and set the content type and length all at once. Args: file_name: string The path and file name to the file containing the media content_type: string A MIME type representing the type of the media """ self.file_handle = open(file_name, 'rb') self.content_type = content_type self.content_length = os.path.getsize(file_name) self.file_name = os.path.basename(file_name) class LinkFinder(atom.LinkFinder): """An "interface" providing methods to find link elements GData Entry elements often contain multiple links which differ in the rel attribute or content type. Often, developers are interested in a specific type of link so this class provides methods to find specific classes of links. This class is used as a mixin in GData entries. """ def GetSelfLink(self): """Find the first link with rel set to 'self' Returns: An atom.Link or none if none of the links had rel equal to 'self' """ for a_link in self.link: if a_link.rel == 'self': return a_link return None def GetEditLink(self): for a_link in self.link: if a_link.rel == 'edit': return a_link return None def GetEditMediaLink(self): """The Picasa API mistakenly returns media-edit rather than edit-media, but this may change soon. """ for a_link in self.link: if a_link.rel == 'edit-media': return a_link if a_link.rel == 'media-edit': return a_link return None def GetHtmlLink(self): """Find the first link with rel of alternate and type of text/html Returns: An atom.Link or None if no links matched """ for a_link in self.link: if a_link.rel == 'alternate' and a_link.type == 'text/html': return a_link return None def GetPostLink(self): """Get a link containing the POST target URL. The POST target URL is used to insert new entries. Returns: A link object with a rel matching the POST type. """ for a_link in self.link: if a_link.rel == 'http://schemas.google.com/g/2005#post': return a_link return None def GetAclLink(self): for a_link in self.link: if a_link.rel == 'http://schemas.google.com/acl/2007#accessControlList': return a_link return None def GetFeedLink(self): for a_link in self.link: if a_link.rel == 'http://schemas.google.com/g/2005#feed': return a_link return None def GetNextLink(self): for a_link in self.link: if a_link.rel == 'next': return a_link return None def GetPrevLink(self): for a_link in self.link: if a_link.rel == 'previous': return a_link return None class TotalResults(atom.AtomBase): """opensearch:TotalResults for a GData feed""" _tag = 'totalResults' _namespace = OPENSEARCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def TotalResultsFromString(xml_string): return atom.CreateClassFromXMLString(TotalResults, xml_string) class StartIndex(atom.AtomBase): """The opensearch:startIndex element in GData feed""" _tag = 'startIndex' _namespace = OPENSEARCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def StartIndexFromString(xml_string): return atom.CreateClassFromXMLString(StartIndex, xml_string) class ItemsPerPage(atom.AtomBase): """The opensearch:itemsPerPage element in GData feed""" _tag = 'itemsPerPage' _namespace = OPENSEARCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def ItemsPerPageFromString(xml_string): return atom.CreateClassFromXMLString(ItemsPerPage, xml_string) class ExtendedProperty(atom.AtomBase): """The Google Data extendedProperty element. Used to store arbitrary key-value information specific to your application. The value can either be a text string stored as an XML attribute (.value), or an XML node (XmlBlob) as a child element. This element is used in the Google Calendar data API and the Google Contacts data API. """ _tag = 'extendedProperty' _namespace = GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' _attributes['value'] = 'value' def __init__(self, name=None, value=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def GetXmlBlobExtensionElement(self): """Returns the XML blob as an atom.ExtensionElement. Returns: An atom.ExtensionElement representing the blob's XML, or None if no blob was set. """ if len(self.extension_elements) < 1: return None else: return self.extension_elements[0] def GetXmlBlobString(self): """Returns the XML blob as a string. Returns: A string containing the blob's XML, or None if no blob was set. """ blob = self.GetXmlBlobExtensionElement() if blob: return blob.ToString() return None def SetXmlBlob(self, blob): """Sets the contents of the extendedProperty to XML as a child node. Since the extendedProperty is only allowed one child element as an XML blob, setting the XML blob will erase any preexisting extension elements in this object. Args: blob: str, ElementTree Element or atom.ExtensionElement representing the XML blob stored in the extendedProperty. """ # Erase any existing extension_elements, clears the child nodes from the # extendedProperty. self.extension_elements = [] if isinstance(blob, atom.ExtensionElement): self.extension_elements.append(blob) elif ElementTree.iselement(blob): self.extension_elements.append(atom._ExtensionElementFromElementTree( blob)) else: self.extension_elements.append(atom.ExtensionElementFromString(blob)) def ExtendedPropertyFromString(xml_string): return atom.CreateClassFromXMLString(ExtendedProperty, xml_string) class GDataEntry(atom.Entry, LinkFinder): """Extends Atom Entry to provide data processing""" _tag = atom.Entry._tag _namespace = atom.Entry._namespace _children = atom.Entry._children.copy() _attributes = atom.Entry._attributes.copy() def __GetId(self): return self.__id # This method was created to strip the unwanted whitespace from the id's # text node. def __SetId(self, id): self.__id = id if id is not None and id.text is not None: self.__id.text = id.text.strip() id = property(__GetId, __SetId) def IsMedia(self): """Determines whether or not an entry is a GData Media entry. """ if (self.GetEditMediaLink()): return True else: return False def GetMediaURL(self): """Returns the URL to the media content, if the entry is a media entry. Otherwise returns None. """ if not self.IsMedia(): return None else: return self.content.src def GDataEntryFromString(xml_string): """Creates a new GDataEntry instance given a string of XML.""" return atom.CreateClassFromXMLString(GDataEntry, xml_string) class GDataFeed(atom.Feed, LinkFinder): """A Feed from a GData service""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = atom.Feed._children.copy() _attributes = atom.Feed._attributes.copy() _children['{%s}totalResults' % OPENSEARCH_NAMESPACE] = ('total_results', TotalResults) _children['{%s}startIndex' % OPENSEARCH_NAMESPACE] = ('start_index', StartIndex) _children['{%s}itemsPerPage' % OPENSEARCH_NAMESPACE] = ('items_per_page', ItemsPerPage) # Add a conversion rule for atom:entry to make it into a GData # Entry. _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GDataEntry]) def __GetId(self): return self.__id def __SetId(self, id): self.__id = id if id is not None and id.text is not None: self.__id.text = id.text.strip() id = property(__GetId, __SetId) def __GetGenerator(self): return self.__generator def __SetGenerator(self, generator): self.__generator = generator if generator is not None: self.__generator.text = generator.text.strip() generator = property(__GetGenerator, __SetGenerator) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): """Constructor for Source Args: author: list (optional) A list of Author instances which belong to this class. category: list (optional) A list of Category instances contributor: list (optional) A list on Contributor instances generator: Generator (optional) icon: Icon (optional) id: Id (optional) The entry's Id element link: list (optional) A list of Link instances logo: Logo (optional) rights: Rights (optional) The entry's Rights element subtitle: Subtitle (optional) The entry's subtitle element title: Title (optional) the entry's title element updated: Updated (optional) the entry's updated element entry: list (optional) A list of the Entry instances contained in the feed. text: String (optional) The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) extension_elements: list (optional) A list of ExtensionElement instances which are children of this element. extension_attributes: dict (optional) A dictionary of strings which are the values for additional XML attributes of this element. """ self.author = author or [] self.category = category or [] self.contributor = contributor or [] self.generator = generator self.icon = icon self.id = atom_id self.link = link or [] self.logo = logo self.rights = rights self.subtitle = subtitle self.title = title self.updated = updated self.entry = entry or [] self.total_results = total_results self.start_index = start_index self.items_per_page = items_per_page self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def GDataFeedFromString(xml_string): return atom.CreateClassFromXMLString(GDataFeed, xml_string) class BatchId(atom.AtomBase): _tag = 'id' _namespace = BATCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def BatchIdFromString(xml_string): return atom.CreateClassFromXMLString(BatchId, xml_string) class BatchOperation(atom.AtomBase): _tag = 'operation' _namespace = BATCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' def __init__(self, op_type=None, extension_elements=None, extension_attributes=None, text=None): self.type = op_type atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def BatchOperationFromString(xml_string): return atom.CreateClassFromXMLString(BatchOperation, xml_string) class BatchStatus(atom.AtomBase): """The batch:status element present in a batch response entry. A status element contains the code (HTTP response code) and reason as elements. In a single request these fields would be part of the HTTP response, but in a batch request each Entry operation has a corresponding Entry in the response feed which includes status information. See http://code.google.com/apis/gdata/batch.html#Handling_Errors """ _tag = 'status' _namespace = BATCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['code'] = 'code' _attributes['reason'] = 'reason' _attributes['content-type'] = 'content_type' def __init__(self, code=None, reason=None, content_type=None, extension_elements=None, extension_attributes=None, text=None): self.code = code self.reason = reason self.content_type = content_type atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def BatchStatusFromString(xml_string): return atom.CreateClassFromXMLString(BatchStatus, xml_string) class BatchEntry(GDataEntry): """An atom:entry for use in batch requests. The BatchEntry contains additional members to specify the operation to be performed on this entry and a batch ID so that the server can reference individual operations in the response feed. For more information, see: http://code.google.com/apis/gdata/batch.html """ _tag = GDataEntry._tag _namespace = GDataEntry._namespace _children = GDataEntry._children.copy() _children['{%s}operation' % BATCH_NAMESPACE] = ('batch_operation', BatchOperation) _children['{%s}id' % BATCH_NAMESPACE] = ('batch_id', BatchId) _children['{%s}status' % BATCH_NAMESPACE] = ('batch_status', BatchStatus) _attributes = GDataEntry._attributes.copy() def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, control=None, title=None, updated=None, batch_operation=None, batch_id=None, batch_status=None, extension_elements=None, extension_attributes=None, text=None): self.batch_operation = batch_operation self.batch_id = batch_id self.batch_status = batch_status GDataEntry.__init__(self, author=author, category=category, content=content, contributor=contributor, atom_id=atom_id, link=link, published=published, rights=rights, source=source, summary=summary, control=control, title=title, updated=updated, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def BatchEntryFromString(xml_string): return atom.CreateClassFromXMLString(BatchEntry, xml_string) class BatchInterrupted(atom.AtomBase): """The batch:interrupted element sent if batch request was interrupted. Only appears in a feed if some of the batch entries could not be processed. See: http://code.google.com/apis/gdata/batch.html#Handling_Errors """ _tag = 'interrupted' _namespace = BATCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['reason'] = 'reason' _attributes['success'] = 'success' _attributes['failures'] = 'failures' _attributes['parsed'] = 'parsed' def __init__(self, reason=None, success=None, failures=None, parsed=None, extension_elements=None, extension_attributes=None, text=None): self.reason = reason self.success = success self.failures = failures self.parsed = parsed atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def BatchInterruptedFromString(xml_string): return atom.CreateClassFromXMLString(BatchInterrupted, xml_string) class BatchFeed(GDataFeed): """A feed containing a list of batch request entries.""" _tag = GDataFeed._tag _namespace = GDataFeed._namespace _children = GDataFeed._children.copy() _attributes = GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BatchEntry]) _children['{%s}interrupted' % BATCH_NAMESPACE] = ('interrupted', BatchInterrupted) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, interrupted=None, extension_elements=None, extension_attributes=None, text=None): self.interrupted = interrupted GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def AddBatchEntry(self, entry=None, id_url_string=None, batch_id_string=None, operation_string=None): """Logic for populating members of a BatchEntry and adding to the feed. If the entry is not a BatchEntry, it is converted to a BatchEntry so that the batch specific members will be present. The id_url_string can be used in place of an entry if the batch operation applies to a URL. For example query and delete operations require just the URL of an entry, no body is sent in the HTTP request. If an id_url_string is sent instead of an entry, a BatchEntry is created and added to the feed. This method also assigns the desired batch id to the entry so that it can be referenced in the server's response. If the batch_id_string is None, this method will assign a batch_id to be the index at which this entry will be in the feed's entry list. Args: entry: BatchEntry, atom.Entry, or another Entry flavor (optional) The entry which will be sent to the server as part of the batch request. The item must have a valid atom id so that the server knows which entry this request references. id_url_string: str (optional) The URL of the entry to be acted on. You can find this URL in the text member of the atom id for an entry. If an entry is not sent, this id will be used to construct a new BatchEntry which will be added to the request feed. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. Note that batch_ids should either always be specified or never, mixing could potentially result in duplicate batch ids. operation_string: str (optional) The desired batch operation which will set the batch_operation.type member of the entry. Options are 'insert', 'update', 'delete', and 'query' Raises: MissingRequiredParameters: Raised if neither an id_ url_string nor an entry are provided in the request. Returns: The added entry. """ if entry is None and id_url_string is None: raise MissingRequiredParameters('supply either an entry or URL string') if entry is None and id_url_string is not None: entry = BatchEntry(atom_id=atom.Id(text=id_url_string)) # TODO: handle cases in which the entry lacks batch_... members. #if not isinstance(entry, BatchEntry): # Convert the entry to a batch entry. if batch_id_string is not None: entry.batch_id = BatchId(text=batch_id_string) elif entry.batch_id is None or entry.batch_id.text is None: entry.batch_id = BatchId(text=str(len(self.entry))) if operation_string is not None: entry.batch_operation = BatchOperation(op_type=operation_string) self.entry.append(entry) return entry def AddInsert(self, entry, batch_id_string=None): """Add an insert request to the operations in this batch request feed. If the entry doesn't yet have an operation or a batch id, these will be set to the insert operation and a batch_id specified as a parameter. Args: entry: BatchEntry The entry which will be sent in the batch feed as an insert request. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. Note that batch_ids should either always be specified or never, mixing could potentially result in duplicate batch ids. """ entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string, operation_string=BATCH_INSERT) def AddUpdate(self, entry, batch_id_string=None): """Add an update request to the list of batch operations in this feed. Sets the operation type of the entry to insert if it is not already set and assigns the desired batch id to the entry so that it can be referenced in the server's response. Args: entry: BatchEntry The entry which will be sent to the server as an update (HTTP PUT) request. The item must have a valid atom id so that the server knows which entry to replace. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. See also comments for AddInsert. """ entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string, operation_string=BATCH_UPDATE) def AddDelete(self, url_string=None, entry=None, batch_id_string=None): """Adds a delete request to the batch request feed. This method takes either the url_string which is the atom id of the item to be deleted, or the entry itself. The atom id of the entry must be present so that the server knows which entry should be deleted. Args: url_string: str (optional) The URL of the entry to be deleted. You can find this URL in the text member of the atom id for an entry. entry: BatchEntry (optional) The entry to be deleted. batch_id_string: str (optional) Raises: MissingRequiredParameters: Raised if neither a url_string nor an entry are provided in the request. """ entry = self.AddBatchEntry(entry=entry, id_url_string=url_string, batch_id_string=batch_id_string, operation_string=BATCH_DELETE) def AddQuery(self, url_string=None, entry=None, batch_id_string=None): """Adds a query request to the batch request feed. This method takes either the url_string which is the query URL whose results will be added to the result feed. The query URL will be encapsulated in a BatchEntry, and you may pass in the BatchEntry with a query URL instead of sending a url_string. Args: url_string: str (optional) entry: BatchEntry (optional) batch_id_string: str (optional) Raises: MissingRequiredParameters """ entry = self.AddBatchEntry(entry=entry, id_url_string=url_string, batch_id_string=batch_id_string, operation_string=BATCH_QUERY) def GetBatchLink(self): for link in self.link: if link.rel == 'http://schemas.google.com/g/2005#batch': return link return None def BatchFeedFromString(xml_string): return atom.CreateClassFromXMLString(BatchFeed, xml_string) class EntryLink(atom.AtomBase): """The gd:entryLink element""" _tag = 'entryLink' _namespace = GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() # The entry used to be an atom.Entry, now it is a GDataEntry. _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', GDataEntry) _attributes['rel'] = 'rel' _attributes['readOnly'] = 'read_only' _attributes['href'] = 'href' def __init__(self, href=None, read_only=None, rel=None, entry=None, extension_elements=None, extension_attributes=None, text=None): self.href = href self.read_only = read_only self.rel = rel self.entry = entry self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EntryLinkFromString(xml_string): return atom.CreateClassFromXMLString(EntryLink, xml_string) class FeedLink(atom.AtomBase): """The gd:feedLink element""" _tag = 'feedLink' _namespace = GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}feed' % atom.ATOM_NAMESPACE] = ('feed', GDataFeed) _attributes['rel'] = 'rel' _attributes['readOnly'] = 'read_only' _attributes['countHint'] = 'count_hint' _attributes['href'] = 'href' def __init__(self, count_hint=None, href=None, read_only=None, rel=None, feed=None, extension_elements=None, extension_attributes=None, text=None): self.count_hint = count_hint self.href = href self.read_only = read_only self.rel = rel self.feed = feed self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def FeedLinkFromString(xml_string): return atom.CreateClassFromXMLString(FeedLink, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """SpreadsheetsService extends the GDataService to streamline Google Spreadsheets operations. SpreadsheetService: Provides methods to query feeds and manipulate items. Extends GDataService. DictionaryToParamList: Function which converts a dictionary into a list of URL arguments (represented as strings). This is a utility function used in CRUD operations. """ __author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)' import gdata import atom.service import gdata.service import gdata.spreadsheet import atom class Error(Exception): """Base class for exceptions in this module.""" pass class RequestError(Error): pass class SpreadsheetsService(gdata.service.GDataService): """Client for the Google Spreadsheets service.""" def __init__(self, email=None, password=None, source=None, server='spreadsheets.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Spreadsheets service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'spreadsheets.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='wise', source=source, server=server, additional_headers=additional_headers, **kwargs) def GetSpreadsheetsFeed(self, key=None, query=None, visibility='private', projection='full'): """Gets a spreadsheets feed or a specific entry if a key is defined Args: key: string (optional) The spreadsheet key defined in /ccc?key= query: DocumentQuery (optional) Query parameters Returns: If there is no key, then a SpreadsheetsSpreadsheetsFeed. If there is a key, then a SpreadsheetsSpreadsheet. """ uri = ('https://%s/feeds/spreadsheets/%s/%s' % (self.server, visibility, projection)) if key is not None: uri = '%s/%s' % (uri, key) if query != None: query.feed = uri uri = query.ToUri() if key: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsSpreadsheetFromString) else: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsSpreadsheetsFeedFromString) def GetWorksheetsFeed(self, key, wksht_id=None, query=None, visibility='private', projection='full'): """Gets a worksheets feed or a specific entry if a wksht is defined Args: key: string The spreadsheet key defined in /ccc?key= wksht_id: string (optional) The id for a specific worksheet entry query: DocumentQuery (optional) Query parameters Returns: If there is no wksht_id, then a SpreadsheetsWorksheetsFeed. If there is a wksht_id, then a SpreadsheetsWorksheet. """ uri = ('https://%s/feeds/worksheets/%s/%s/%s' % (self.server, key, visibility, projection)) if wksht_id != None: uri = '%s/%s' % (uri, wksht_id) if query != None: query.feed = uri uri = query.ToUri() if wksht_id: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString) else: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsWorksheetsFeedFromString) def AddWorksheet(self, title, row_count, col_count, key): """Creates a new worksheet in the desired spreadsheet. The new worksheet is appended to the end of the list of worksheets. The new worksheet will only have the available number of columns and cells specified. Args: title: str The title which will be displayed in the list of worksheets. row_count: int or str The number of rows in the new worksheet. col_count: int or str The number of columns in the new worksheet. key: str The spreadsheet key to the spreadsheet to which the new worksheet should be added. Returns: A SpreadsheetsWorksheet if the new worksheet was created succesfully. """ new_worksheet = gdata.spreadsheet.SpreadsheetsWorksheet( title=atom.Title(text=title), row_count=gdata.spreadsheet.RowCount(text=str(row_count)), col_count=gdata.spreadsheet.ColCount(text=str(col_count))) return self.Post(new_worksheet, 'https://%s/feeds/worksheets/%s/private/full' % (self.server, key), converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString) def UpdateWorksheet(self, worksheet_entry, url=None): """Changes the size and/or title of the desired worksheet. Args: worksheet_entry: SpreadsheetWorksheet The new contents of the worksheet. url: str (optional) The URL to which the edited worksheet entry should be sent. If the url is None, the edit URL from the worksheet will be used. Returns: A SpreadsheetsWorksheet with the new information about the worksheet. """ target_url = url or worksheet_entry.GetEditLink().href return self.Put(worksheet_entry, target_url, converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString) def DeleteWorksheet(self, worksheet_entry=None, url=None): """Removes the desired worksheet from the spreadsheet Args: worksheet_entry: SpreadsheetWorksheet (optional) The worksheet to be deleted. If this is none, then the DELETE reqest is sent to the url specified in the url parameter. url: str (optaional) The URL to which the DELETE request should be sent. If left as None, the worksheet's edit URL is used. Returns: True if the worksheet was deleted successfully. """ if url: target_url = url else: target_url = worksheet_entry.GetEditLink().href return self.Delete(target_url) def GetCellsFeed(self, key, wksht_id='default', cell=None, query=None, visibility='private', projection='full'): """Gets a cells feed or a specific entry if a cell is defined Args: key: string The spreadsheet key defined in /ccc?key= wksht_id: string The id for a specific worksheet entry cell: string (optional) The R1C1 address of the cell query: DocumentQuery (optional) Query parameters Returns: If there is no cell, then a SpreadsheetsCellsFeed. If there is a cell, then a SpreadsheetsCell. """ uri = ('https://%s/feeds/cells/%s/%s/%s/%s' % (self.server, key, wksht_id, visibility, projection)) if cell != None: uri = '%s/%s' % (uri, cell) if query != None: query.feed = uri uri = query.ToUri() if cell: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsCellFromString) else: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString) def GetListFeed(self, key, wksht_id='default', row_id=None, query=None, visibility='private', projection='full'): """Gets a list feed or a specific entry if a row_id is defined Args: key: string The spreadsheet key defined in /ccc?key= wksht_id: string The id for a specific worksheet entry row_id: string (optional) The row_id of a row in the list query: DocumentQuery (optional) Query parameters Returns: If there is no row_id, then a SpreadsheetsListFeed. If there is a row_id, then a SpreadsheetsList. """ uri = ('https://%s/feeds/list/%s/%s/%s/%s' % (self.server, key, wksht_id, visibility, projection)) if row_id is not None: uri = '%s/%s' % (uri, row_id) if query is not None: query.feed = uri uri = query.ToUri() if row_id: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsListFromString) else: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsListFeedFromString) def UpdateCell(self, row, col, inputValue, key, wksht_id='default'): """Updates an existing cell. Args: row: int The row the cell to be editted is in col: int The column the cell to be editted is in inputValue: str the new value of the cell key: str The key of the spreadsheet in which this cell resides. wksht_id: str The ID of the worksheet which holds this cell. Returns: The updated cell entry """ row = str(row) col = str(col) # make the new cell new_cell = gdata.spreadsheet.Cell(row=row, col=col, inputValue=inputValue) # get the edit uri and PUT cell = 'R%sC%s' % (row, col) entry = self.GetCellsFeed(key, wksht_id, cell) for a_link in entry.link: if a_link.rel == 'edit': entry.cell = new_cell return self.Put(entry, a_link.href, converter=gdata.spreadsheet.SpreadsheetsCellFromString) def _GenerateCellsBatchUrl(self, spreadsheet_key, worksheet_id): return ('https://spreadsheets.google.com/feeds/cells/%s/%s/' 'private/full/batch' % (spreadsheet_key, worksheet_id)) def ExecuteBatch(self, batch_feed, url=None, spreadsheet_key=None, worksheet_id=None, converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString): """Sends a batch request feed to the server. The batch request needs to be sent to the batch URL for a particular worksheet. You can specify the worksheet by providing the spreadsheet_key and worksheet_id, or by sending the URL from the cells feed's batch link. Args: batch_feed: gdata.spreadsheet.SpreadsheetsCellFeed A feed containing BatchEntry elements which contain the desired CRUD operation and any necessary data to modify a cell. url: str (optional) The batch URL for the cells feed to which these changes should be applied. This can be found by calling cells_feed.GetBatchLink().href. spreadsheet_key: str (optional) Used to generate the batch request URL if the url argument is None. If using the spreadsheet key to generate the URL, the worksheet id is also required. worksheet_id: str (optional) Used if the url is not provided, it is oart of the batch feed target URL. This is used with the spreadsheet key. converter: Function (optional) Function to be executed on the server's response. This function should take one string as a parameter. The default value is SpreadsheetsCellsFeedFromString which will turn the result into a gdata.spreadsheet.SpreadsheetsCellsFeed object. Returns: A gdata.BatchFeed containing the results. """ if url is None: url = self._GenerateCellsBatchUrl(spreadsheet_key, worksheet_id) return self.Post(batch_feed, url, converter=converter) def InsertRow(self, row_data, key, wksht_id='default'): """Inserts a new row with the provided data Args: uri: string The post uri of the list feed row_data: dict A dictionary of column header to row data Returns: The inserted row """ new_entry = gdata.spreadsheet.SpreadsheetsList() for k, v in row_data.iteritems(): new_custom = gdata.spreadsheet.Custom() new_custom.column = k new_custom.text = v new_entry.custom[new_custom.column] = new_custom # Generate the post URL for the worksheet which will receive the new entry. post_url = 'https://spreadsheets.google.com/feeds/list/%s/%s/private/full'%( key, wksht_id) return self.Post(new_entry, post_url, converter=gdata.spreadsheet.SpreadsheetsListFromString) def UpdateRow(self, entry, new_row_data): """Updates a row with the provided data If you want to add additional information to a row, it is often easier to change the values in entry.custom, then use the Put method instead of UpdateRow. This UpdateRow method will replace the contents of the row with new_row_data - it will change all columns not just the columns specified in the new_row_data dict. Args: entry: gdata.spreadsheet.SpreadsheetsList The entry to be updated new_row_data: dict A dictionary of column header to row data Returns: The updated row """ entry.custom = {} for k, v in new_row_data.iteritems(): new_custom = gdata.spreadsheet.Custom() new_custom.column = k new_custom.text = v entry.custom[k] = new_custom for a_link in entry.link: if a_link.rel == 'edit': return self.Put(entry, a_link.href, converter=gdata.spreadsheet.SpreadsheetsListFromString) def DeleteRow(self, entry): """Deletes a row, the provided entry Args: entry: gdata.spreadsheet.SpreadsheetsList The row to be deleted Returns: The delete response """ for a_link in entry.link: if a_link.rel == 'edit': return self.Delete(a_link.href) class DocumentQuery(gdata.service.Query): def _GetTitleQuery(self): return self['title'] def _SetTitleQuery(self, document_query): self['title'] = document_query title = property(_GetTitleQuery, _SetTitleQuery, doc="""The title query parameter""") def _GetTitleExactQuery(self): return self['title-exact'] def _SetTitleExactQuery(self, document_query): self['title-exact'] = document_query title_exact = property(_GetTitleExactQuery, _SetTitleExactQuery, doc="""The title-exact query parameter""") class CellQuery(gdata.service.Query): def _GetMinRowQuery(self): return self['min-row'] def _SetMinRowQuery(self, cell_query): self['min-row'] = cell_query min_row = property(_GetMinRowQuery, _SetMinRowQuery, doc="""The min-row query parameter""") def _GetMaxRowQuery(self): return self['max-row'] def _SetMaxRowQuery(self, cell_query): self['max-row'] = cell_query max_row = property(_GetMaxRowQuery, _SetMaxRowQuery, doc="""The max-row query parameter""") def _GetMinColQuery(self): return self['min-col'] def _SetMinColQuery(self, cell_query): self['min-col'] = cell_query min_col = property(_GetMinColQuery, _SetMinColQuery, doc="""The min-col query parameter""") def _GetMaxColQuery(self): return self['max-col'] def _SetMaxColQuery(self, cell_query): self['max-col'] = cell_query max_col = property(_GetMaxColQuery, _SetMaxColQuery, doc="""The max-col query parameter""") def _GetRangeQuery(self): return self['range'] def _SetRangeQuery(self, cell_query): self['range'] = cell_query range = property(_GetRangeQuery, _SetRangeQuery, doc="""The range query parameter""") def _GetReturnEmptyQuery(self): return self['return-empty'] def _SetReturnEmptyQuery(self, cell_query): self['return-empty'] = cell_query return_empty = property(_GetReturnEmptyQuery, _SetReturnEmptyQuery, doc="""The return-empty query parameter""") class ListQuery(gdata.service.Query): def _GetSpreadsheetQuery(self): return self['sq'] def _SetSpreadsheetQuery(self, list_query): self['sq'] = list_query sq = property(_GetSpreadsheetQuery, _SetSpreadsheetQuery, doc="""The sq query parameter""") def _GetOrderByQuery(self): return self['orderby'] def _SetOrderByQuery(self, list_query): self['orderby'] = list_query orderby = property(_GetOrderByQuery, _SetOrderByQuery, doc="""The orderby query parameter""") def _GetReverseQuery(self): return self['reverse'] def _SetReverseQuery(self, list_query): self['reverse'] = list_query reverse = property(_GetReverseQuery, _SetReverseQuery, doc="""The reverse query parameter""")
Python
#!/usr/bin/python # # Copyright Google 2007-2008, all rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import StringIO import gdata import gdata.service import gdata.spreadsheet import gdata.spreadsheet.service import gdata.docs import gdata.docs.service """Make the Google Documents API feel more like using a database. This module contains a client and other classes which make working with the Google Documents List Data API and the Google Spreadsheets Data API look a bit more like working with a heirarchical database. Using the DatabaseClient, you can create or find spreadsheets and use them like a database, with worksheets representing tables and rows representing records. Example Usage: # Create a new database, a new table, and add records. client = gdata.spreadsheet.text_db.DatabaseClient(username='jo@example.com', password='12345') database = client.CreateDatabase('My Text Database') table = database.CreateTable('addresses', ['name','email', 'phonenumber', 'mailingaddress']) record = table.AddRecord({'name':'Bob', 'email':'bob@example.com', 'phonenumber':'555-555-1234', 'mailingaddress':'900 Imaginary St.'}) # Edit a record record.content['email'] = 'bob2@example.com' record.Push() # Delete a table table.Delete Warnings: Care should be exercised when using this module on spreadsheets which contain formulas. This module treats all rows as containing text and updating a row will overwrite any formula with the output of the formula. The intended use case is to allow easy storage of text data in a spreadsheet. Error: Domain specific extension of Exception. BadCredentials: Error raised is username or password was incorrect. CaptchaRequired: Raised if a login attempt failed and a CAPTCHA challenge was issued. DatabaseClient: Communicates with Google Docs APIs servers. Database: Represents a spreadsheet and interacts with tables. Table: Represents a worksheet and interacts with records. RecordResultSet: A list of records in a table. Record: Represents a row in a worksheet allows manipulation of text data. """ __author__ = 'api.jscudder (Jeffrey Scudder)' class Error(Exception): pass class BadCredentials(Error): pass class CaptchaRequired(Error): pass class DatabaseClient(object): """Allows creation and finding of Google Spreadsheets databases. The DatabaseClient simplifies the process of creating and finding Google Spreadsheets and will talk to both the Google Spreadsheets API and the Google Documents List API. """ def __init__(self, username=None, password=None): """Constructor for a Database Client. If the username and password are present, the constructor will contact the Google servers to authenticate. Args: username: str (optional) Example: jo@example.com password: str (optional) """ self.__docs_client = gdata.docs.service.DocsService() self.__spreadsheets_client = ( gdata.spreadsheet.service.SpreadsheetsService()) self.SetCredentials(username, password) def SetCredentials(self, username, password): """Attempts to log in to Google APIs using the provided credentials. If the username or password are None, the client will not request auth tokens. Args: username: str (optional) Example: jo@example.com password: str (optional) """ self.__docs_client.email = username self.__docs_client.password = password self.__spreadsheets_client.email = username self.__spreadsheets_client.password = password if username and password: try: self.__docs_client.ProgrammaticLogin() self.__spreadsheets_client.ProgrammaticLogin() except gdata.service.CaptchaRequired: raise CaptchaRequired('Please visit https://www.google.com/accounts/' 'DisplayUnlockCaptcha to unlock your account.') except gdata.service.BadAuthentication: raise BadCredentials('Username or password incorrect.') def CreateDatabase(self, name): """Creates a new Google Spreadsheet with the desired name. Args: name: str The title for the spreadsheet. Returns: A Database instance representing the new spreadsheet. """ # Create a Google Spreadsheet to form the foundation of this database. # Spreadsheet is created by uploading a file to the Google Documents # List API. virtual_csv_file = StringIO.StringIO(',,,') virtual_media_source = gdata.MediaSource(file_handle=virtual_csv_file, content_type='text/csv', content_length=3) db_entry = self.__docs_client.UploadSpreadsheet(virtual_media_source, name) return Database(spreadsheet_entry=db_entry, database_client=self) def GetDatabases(self, spreadsheet_key=None, name=None): """Finds spreadsheets which have the unique key or title. If querying on the spreadsheet_key there will be at most one result, but searching by name could yield multiple results. Args: spreadsheet_key: str The unique key for the spreadsheet, this usually in the the form 'pk23...We' or 'o23...423.12,,,3'. name: str The title of the spreadsheets. Returns: A list of Database objects representing the desired spreadsheets. """ if spreadsheet_key: db_entry = self.__docs_client.GetDocumentListEntry( r'/feeds/documents/private/full/spreadsheet%3A' + spreadsheet_key) return [Database(spreadsheet_entry=db_entry, database_client=self)] else: title_query = gdata.docs.service.DocumentQuery() title_query['title'] = name db_feed = self.__docs_client.QueryDocumentListFeed(title_query.ToUri()) matching_databases = [] for entry in db_feed.entry: matching_databases.append(Database(spreadsheet_entry=entry, database_client=self)) return matching_databases def _GetDocsClient(self): return self.__docs_client def _GetSpreadsheetsClient(self): return self.__spreadsheets_client class Database(object): """Provides interface to find and create tables. The database represents a Google Spreadsheet. """ def __init__(self, spreadsheet_entry=None, database_client=None): """Constructor for a database object. Args: spreadsheet_entry: gdata.docs.DocumentListEntry The Atom entry which represents the Google Spreadsheet. The spreadsheet's key is extracted from the entry and stored as a member. database_client: DatabaseClient A client which can talk to the Google Spreadsheets servers to perform operations on worksheets within this spreadsheet. """ self.entry = spreadsheet_entry if self.entry: id_parts = spreadsheet_entry.id.text.split('/') self.spreadsheet_key = id_parts[-1].replace('spreadsheet%3A', '') self.client = database_client def CreateTable(self, name, fields=None): """Add a new worksheet to this spreadsheet and fill in column names. Args: name: str The title of the new worksheet. fields: list of strings The column names which are placed in the first row of this worksheet. These names are converted into XML tags by the server. To avoid changes during the translation process I recommend using all lowercase alphabetic names. For example ['somelongname', 'theothername'] Returns: Table representing the newly created worksheet. """ worksheet = self.client._GetSpreadsheetsClient().AddWorksheet(title=name, row_count=1, col_count=len(fields), key=self.spreadsheet_key) return Table(name=name, worksheet_entry=worksheet, database_client=self.client, spreadsheet_key=self.spreadsheet_key, fields=fields) def GetTables(self, worksheet_id=None, name=None): """Searches for a worksheet with the specified ID or name. The list of results should have one table at most, or no results if the id or name were not found. Args: worksheet_id: str The ID of the worksheet, example: 'od6' name: str The title of the worksheet. Returns: A list of length 0 or 1 containing the desired Table. A list is returned to make this method feel like GetDatabases and GetRecords. """ if worksheet_id: worksheet_entry = self.client._GetSpreadsheetsClient().GetWorksheetsFeed( self.spreadsheet_key, wksht_id=worksheet_id) return [Table(name=worksheet_entry.title.text, worksheet_entry=worksheet_entry, database_client=self.client, spreadsheet_key=self.spreadsheet_key)] else: matching_tables = [] query = None if name: query = gdata.spreadsheet.service.DocumentQuery() query.title = name worksheet_feed = self.client._GetSpreadsheetsClient().GetWorksheetsFeed( self.spreadsheet_key, query=query) for entry in worksheet_feed.entry: matching_tables.append(Table(name=entry.title.text, worksheet_entry=entry, database_client=self.client, spreadsheet_key=self.spreadsheet_key)) return matching_tables def Delete(self): """Deletes the entire database spreadsheet from Google Spreadsheets.""" entry = self.client._GetDocsClient().Get( r'http://docs.google.com/feeds/documents/private/full/spreadsheet%3A' + self.spreadsheet_key) self.client._GetDocsClient().Delete(entry.GetEditLink().href) class Table(object): def __init__(self, name=None, worksheet_entry=None, database_client=None, spreadsheet_key=None, fields=None): self.name = name self.entry = worksheet_entry id_parts = worksheet_entry.id.text.split('/') self.worksheet_id = id_parts[-1] self.spreadsheet_key = spreadsheet_key self.client = database_client self.fields = fields or [] if fields: self.SetFields(fields) def LookupFields(self): """Queries to find the column names in the first row of the worksheet. Useful when you have retrieved the table from the server and you don't know the column names. """ if self.entry: first_row_contents = [] query = gdata.spreadsheet.service.CellQuery() query.max_row = '1' query.min_row = '1' feed = self.client._GetSpreadsheetsClient().GetCellsFeed( self.spreadsheet_key, wksht_id=self.worksheet_id, query=query) for entry in feed.entry: first_row_contents.append(entry.content.text) # Get the next set of cells if needed. next_link = feed.GetNextLink() while next_link: feed = self.client._GetSpreadsheetsClient().Get(next_link.href, converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString) for entry in feed.entry: first_row_contents.append(entry.content.text) next_link = feed.GetNextLink() # Convert the contents of the cells to valid headers. self.fields = ConvertStringsToColumnHeaders(first_row_contents) def SetFields(self, fields): """Changes the contents of the cells in the first row of this worksheet. Args: fields: list of strings The names in the list comprise the first row of the worksheet. These names are converted into XML tags by the server. To avoid changes during the translation process I recommend using all lowercase alphabetic names. For example ['somelongname', 'theothername'] """ # TODO: If the table already had fields, we might want to clear out the, # current column headers. self.fields = fields i = 0 for column_name in fields: i = i + 1 # TODO: speed this up by using a batch request to update cells. self.client._GetSpreadsheetsClient().UpdateCell(1, i, column_name, self.spreadsheet_key, self.worksheet_id) def Delete(self): """Deletes this worksheet from the spreadsheet.""" worksheet = self.client._GetSpreadsheetsClient().GetWorksheetsFeed( self.spreadsheet_key, wksht_id=self.worksheet_id) self.client._GetSpreadsheetsClient().DeleteWorksheet( worksheet_entry=worksheet) def AddRecord(self, data): """Adds a new row to this worksheet. Args: data: dict of strings Mapping of string values to column names. Returns: Record which represents this row of the spreadsheet. """ new_row = self.client._GetSpreadsheetsClient().InsertRow(data, self.spreadsheet_key, wksht_id=self.worksheet_id) return Record(content=data, row_entry=new_row, spreadsheet_key=self.spreadsheet_key, worksheet_id=self.worksheet_id, database_client=self.client) def GetRecord(self, row_id=None, row_number=None): """Gets a single record from the worksheet based on row ID or number. Args: row_id: The ID for the individual row. row_number: str or int The position of the desired row. Numbering begins at 1, which refers to the second row in the worksheet since the first row is used for column names. Returns: Record for the desired row. """ if row_id: row_entry = self.client._GetSpreadsheetsClient().GetListFeed( self.spreadsheet_key, wksht_id=self.worksheet_id, row_id=row_id) return Record(content=None, row_entry=row_entry, spreadsheet_key=self.spreadsheet_key, worksheet_id=self.worksheet_id, database_client=self.client) else: row_query = gdata.spreadsheet.service.ListQuery() row_query.start_index = str(row_number) row_query.max_results = '1' row_feed = self.client._GetSpreadsheetsClient().GetListFeed( self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query) if len(row_feed.entry) >= 1: return Record(content=None, row_entry=row_feed.entry[0], spreadsheet_key=self.spreadsheet_key, worksheet_id=self.worksheet_id, database_client=self.client) else: return None def GetRecords(self, start_row, end_row): """Gets all rows between the start and end row numbers inclusive. Args: start_row: str or int end_row: str or int Returns: RecordResultSet for the desired rows. """ start_row = int(start_row) end_row = int(end_row) max_rows = end_row - start_row + 1 row_query = gdata.spreadsheet.service.ListQuery() row_query.start_index = str(start_row) row_query.max_results = str(max_rows) rows_feed = self.client._GetSpreadsheetsClient().GetListFeed( self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query) return RecordResultSet(rows_feed, self.client, self.spreadsheet_key, self.worksheet_id) def FindRecords(self, query_string): """Performs a query against the worksheet to find rows which match. For details on query string syntax see the section on sq under http://code.google.com/apis/spreadsheets/reference.html#list_Parameters Args: query_string: str Examples: 'name == john' to find all rows with john in the name column, '(cost < 19.50 and name != toy) or cost > 500' Returns: RecordResultSet with the first group of matches. """ row_query = gdata.spreadsheet.service.ListQuery() row_query.sq = query_string matching_feed = self.client._GetSpreadsheetsClient().GetListFeed( self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query) return RecordResultSet(matching_feed, self.client, self.spreadsheet_key, self.worksheet_id) class RecordResultSet(list): """A collection of rows which allows fetching of the next set of results. The server may not send all rows in the requested range because there are too many. Using this result set you can access the first set of results as if it is a list, then get the next batch (if there are more results) by calling GetNext(). """ def __init__(self, feed, client, spreadsheet_key, worksheet_id): self.client = client self.spreadsheet_key = spreadsheet_key self.worksheet_id = worksheet_id self.feed = feed list(self) for entry in self.feed.entry: self.append(Record(content=None, row_entry=entry, spreadsheet_key=spreadsheet_key, worksheet_id=worksheet_id, database_client=client)) def GetNext(self): """Fetches the next batch of rows in the result set. Returns: A new RecordResultSet. """ next_link = self.feed.GetNextLink() if next_link and next_link.href: new_feed = self.client._GetSpreadsheetsClient().Get(next_link.href, converter=gdata.spreadsheet.SpreadsheetsListFeedFromString) return RecordResultSet(new_feed, self.client, self.spreadsheet_key, self.worksheet_id) class Record(object): """Represents one row in a worksheet and provides a dictionary of values. Attributes: custom: dict Represents the contents of the row with cell values mapped to column headers. """ def __init__(self, content=None, row_entry=None, spreadsheet_key=None, worksheet_id=None, database_client=None): """Constructor for a record. Args: content: dict of strings Mapping of string values to column names. row_entry: gdata.spreadsheet.SpreadsheetsList The Atom entry representing this row in the worksheet. spreadsheet_key: str The ID of the spreadsheet in which this row belongs. worksheet_id: str The ID of the worksheet in which this row belongs. database_client: DatabaseClient The client which can be used to talk the Google Spreadsheets server to edit this row. """ self.entry = row_entry self.spreadsheet_key = spreadsheet_key self.worksheet_id = worksheet_id if row_entry: self.row_id = row_entry.id.text.split('/')[-1] else: self.row_id = None self.client = database_client self.content = content or {} if not content: self.ExtractContentFromEntry(row_entry) def ExtractContentFromEntry(self, entry): """Populates the content and row_id based on content of the entry. This method is used in the Record's contructor. Args: entry: gdata.spreadsheet.SpreadsheetsList The Atom entry representing this row in the worksheet. """ self.content = {} if entry: self.row_id = entry.id.text.split('/')[-1] for label, custom in entry.custom.iteritems(): self.content[label] = custom.text def Push(self): """Send the content of the record to spreadsheets to edit the row. All items in the content dictionary will be sent. Items which have been removed from the content may remain in the row. The content member of the record will not be modified so additional fields in the row might be absent from this local copy. """ self.entry = self.client._GetSpreadsheetsClient().UpdateRow(self.entry, self.content) def Pull(self): """Query Google Spreadsheets to get the latest data from the server. Fetches the entry for this row and repopulates the content dictionary with the data found in the row. """ if self.row_id: self.entry = self.client._GetSpreadsheetsClient().GetListFeed( self.spreadsheet_key, wksht_id=self.worksheet_id, row_id=self.row_id) self.ExtractContentFromEntry(self.entry) def Delete(self): self.client._GetSpreadsheetsClient().DeleteRow(self.entry) def ConvertStringsToColumnHeaders(proposed_headers): """Converts a list of strings to column names which spreadsheets accepts. When setting values in a record, the keys which represent column names must fit certain rules. They are all lower case, contain no spaces or special characters. If two columns have the same name after being sanitized, the columns further to the right have _2, _3 _4, etc. appended to them. If there are column names which consist of all special characters, or if the column header is blank, an obfuscated value will be used for a column name. This method does not handle blank column names or column names with only special characters. """ headers = [] for input_string in proposed_headers: # TODO: probably a more efficient way to do this. Perhaps regex. sanitized = input_string.lower().replace('_', '').replace( ':', '').replace(' ', '') # When the same sanitized header appears multiple times in the first row # of a spreadsheet, _n is appended to the name to make it unique. header_count = headers.count(sanitized) if header_count > 0: headers.append('%s_%i' % (sanitized, header_count+1)) else: headers.append(sanitized) return headers
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains extensions to Atom objects used with Google Spreadsheets. """ __author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)' try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata import re import string # XML namespaces which are often used in Google Spreadsheets entities. GSPREADSHEETS_NAMESPACE = 'http://schemas.google.com/spreadsheets/2006' GSPREADSHEETS_TEMPLATE = '{http://schemas.google.com/spreadsheets/2006}%s' GSPREADSHEETS_EXTENDED_NAMESPACE = ('http://schemas.google.com/spreadsheets' '/2006/extended') GSPREADSHEETS_EXTENDED_TEMPLATE = ('{http://schemas.google.com/spreadsheets' '/2006/extended}%s') class ColCount(atom.AtomBase): """The Google Spreadsheets colCount element """ _tag = 'colCount' _namespace = GSPREADSHEETS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def ColCountFromString(xml_string): return atom.CreateClassFromXMLString(ColCount, xml_string) class RowCount(atom.AtomBase): """The Google Spreadsheets rowCount element """ _tag = 'rowCount' _namespace = GSPREADSHEETS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def RowCountFromString(xml_string): return atom.CreateClassFromXMLString(RowCount, xml_string) class Cell(atom.AtomBase): """The Google Spreadsheets cell element """ _tag = 'cell' _namespace = GSPREADSHEETS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['row'] = 'row' _attributes['col'] = 'col' _attributes['inputValue'] = 'inputValue' _attributes['numericValue'] = 'numericValue' def __init__(self, text=None, row=None, col=None, inputValue=None, numericValue=None, extension_elements=None, extension_attributes=None): self.text = text self.row = row self.col = col self.inputValue = inputValue self.numericValue = numericValue self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def CellFromString(xml_string): return atom.CreateClassFromXMLString(Cell, xml_string) class Custom(atom.AtomBase): """The Google Spreadsheets custom element""" _namespace = GSPREADSHEETS_EXTENDED_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, column=None, text=None, extension_elements=None, extension_attributes=None): self.column = column # The name of the column self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def _BecomeChildElement(self, tree): new_child = ElementTree.Element('') tree.append(new_child) new_child.tag = '{%s}%s' % (self.__class__._namespace, self.column) self._AddMembersToElementTree(new_child) def _ToElementTree(self): new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace, self.column)) self._AddMembersToElementTree(new_tree) return new_tree def _HarvestElementTree(self, tree): namespace_uri, local_tag = string.split(tree.tag[1:], "}", 1) self.column = local_tag # Fill in the instance members from the contents of the XML tree. for child in tree: self._ConvertElementTreeToMember(child) for attribute, value in tree.attrib.iteritems(): self._ConvertElementAttributeToMember(attribute, value) self.text = tree.text def CustomFromString(xml_string): element_tree = ElementTree.fromstring(xml_string) return _CustomFromElementTree(element_tree) def _CustomFromElementTree(element_tree): namespace_uri, local_tag = string.split(element_tree.tag[1:], "}", 1) if namespace_uri == GSPREADSHEETS_EXTENDED_NAMESPACE: new_custom = Custom() new_custom._HarvestElementTree(element_tree) new_custom.column = local_tag return new_custom return None class SpreadsheetsSpreadsheet(gdata.GDataEntry): """A Google Spreadsheets flavor of a Spreadsheet Atom Entry """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, title=None, control=None, updated=None, text=None, extension_elements=None, extension_attributes=None): self.author = author or [] self.category = category or [] self.content = content self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.published = published self.rights = rights self.source = source self.summary = summary self.control = control self.title = title self.updated = updated self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SpreadsheetsSpreadsheetFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsSpreadsheet, xml_string) class SpreadsheetsWorksheet(gdata.GDataEntry): """A Google Spreadsheets flavor of a Worksheet Atom Entry """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}rowCount' % GSPREADSHEETS_NAMESPACE] = ('row_count', RowCount) _children['{%s}colCount' % GSPREADSHEETS_NAMESPACE] = ('col_count', ColCount) def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, title=None, control=None, updated=None, row_count=None, col_count=None, text=None, extension_elements=None, extension_attributes=None): self.author = author or [] self.category = category or [] self.content = content self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.published = published self.rights = rights self.source = source self.summary = summary self.control = control self.title = title self.updated = updated self.row_count = row_count self.col_count = col_count self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SpreadsheetsWorksheetFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsWorksheet, xml_string) class SpreadsheetsCell(gdata.BatchEntry): """A Google Spreadsheets flavor of a Cell Atom Entry """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.BatchEntry._children.copy() _attributes = gdata.BatchEntry._attributes.copy() _children['{%s}cell' % GSPREADSHEETS_NAMESPACE] = ('cell', Cell) def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, title=None, control=None, updated=None, cell=None, batch_operation=None, batch_id=None, batch_status=None, text=None, extension_elements=None, extension_attributes=None): self.author = author or [] self.category = category or [] self.content = content self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.published = published self.rights = rights self.source = source self.summary = summary self.control = control self.title = title self.batch_operation = batch_operation self.batch_id = batch_id self.batch_status = batch_status self.updated = updated self.cell = cell self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SpreadsheetsCellFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsCell, xml_string) class SpreadsheetsList(gdata.GDataEntry): """A Google Spreadsheets flavor of a List Atom Entry """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, title=None, control=None, updated=None, custom=None, text=None, extension_elements=None, extension_attributes=None): self.author = author or [] self.category = category or [] self.content = content self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.published = published self.rights = rights self.source = source self.summary = summary self.control = control self.title = title self.updated = updated self.custom = custom or {} self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} # We need to overwrite _ConvertElementTreeToMember to add special logic to # convert custom attributes to members def _ConvertElementTreeToMember(self, child_tree): # Find the element's tag in this class's list of child members if self.__class__._children.has_key(child_tree.tag): member_name = self.__class__._children[child_tree.tag][0] member_class = self.__class__._children[child_tree.tag][1] # If the class member is supposed to contain a list, make sure the # matching member is set to a list, then append the new member # instance to the list. if isinstance(member_class, list): if getattr(self, member_name) is None: setattr(self, member_name, []) getattr(self, member_name).append(atom._CreateClassFromElementTree( member_class[0], child_tree)) else: setattr(self, member_name, atom._CreateClassFromElementTree(member_class, child_tree)) elif child_tree.tag.find('{%s}' % GSPREADSHEETS_EXTENDED_NAMESPACE) == 0: # If this is in the custom namespace, make add it to the custom dict. name = child_tree.tag[child_tree.tag.index('}')+1:] custom = _CustomFromElementTree(child_tree) if custom: self.custom[name] = custom else: atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree) # We need to overwtite _AddMembersToElementTree to add special logic to # convert custom members to XML nodes. def _AddMembersToElementTree(self, tree): # Convert the members of this class which are XML child nodes. # This uses the class's _children dictionary to find the members which # should become XML child nodes. member_node_names = [values[0] for tag, values in self.__class__._children.iteritems()] for member_name in member_node_names: member = getattr(self, member_name) if member is None: pass elif isinstance(member, list): for instance in member: instance._BecomeChildElement(tree) else: member._BecomeChildElement(tree) # Convert the members of this class which are XML attributes. for xml_attribute, member_name in self.__class__._attributes.iteritems(): member = getattr(self, member_name) if member is not None: tree.attrib[xml_attribute] = member # Convert all special custom item attributes to nodes for name, custom in self.custom.iteritems(): custom._BecomeChildElement(tree) # Lastly, call the ExtensionContainers's _AddMembersToElementTree to # convert any extension attributes. atom.ExtensionContainer._AddMembersToElementTree(self, tree) def SpreadsheetsListFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsList, xml_string) element_tree = ElementTree.fromstring(xml_string) return _SpreadsheetsListFromElementTree(element_tree) class SpreadsheetsSpreadsheetsFeed(gdata.GDataFeed): """A feed containing Google Spreadsheets Spreadsheets""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [SpreadsheetsSpreadsheet]) def SpreadsheetsSpreadsheetsFeedFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsSpreadsheetsFeed, xml_string) class SpreadsheetsWorksheetsFeed(gdata.GDataFeed): """A feed containing Google Spreadsheets Spreadsheets""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [SpreadsheetsWorksheet]) def SpreadsheetsWorksheetsFeedFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsWorksheetsFeed, xml_string) class SpreadsheetsCellsFeed(gdata.BatchFeed): """A feed containing Google Spreadsheets Cells""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.BatchFeed._children.copy() _attributes = gdata.BatchFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [SpreadsheetsCell]) _children['{%s}rowCount' % GSPREADSHEETS_NAMESPACE] = ('row_count', RowCount) _children['{%s}colCount' % GSPREADSHEETS_NAMESPACE] = ('col_count', ColCount) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None, row_count=None, col_count=None, interrupted=None): gdata.BatchFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text, interrupted=interrupted) self.row_count = row_count self.col_count = col_count def GetBatchLink(self): for link in self.link: if link.rel == 'http://schemas.google.com/g/2005#batch': return link return None def SpreadsheetsCellsFeedFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsCellsFeed, xml_string) class SpreadsheetsListFeed(gdata.GDataFeed): """A feed containing Google Spreadsheets Spreadsheets""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [SpreadsheetsList]) def SpreadsheetsListFeedFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsListFeed, xml_string)
Python
#!/usr/bin/env python # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' """Provides classes and methods for working with JSON-C. This module is experimental and subject to backwards incompatible changes. Jsonc: Class which represents JSON-C data and provides pythonic member access which is a bit cleaner than working with plain old dicts. parse_json: Converts a JSON-C string into a Jsonc object. jsonc_to_string: Converts a Jsonc object into a string of JSON-C. """ try: import simplejson except ImportError: try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson def _convert_to_jsonc(x): """Builds a Jsonc objects which wraps the argument's members.""" if isinstance(x, dict): jsonc_obj = Jsonc() # Recursively transform all members of the dict. # When converting a dict, we do not convert _name items into private # Jsonc members. for key, value in x.iteritems(): jsonc_obj._dict[key] = _convert_to_jsonc(value) return jsonc_obj elif isinstance(x, list): # Recursively transform all members of the list. members = [] for item in x: members.append(_convert_to_jsonc(item)) return members else: # Return the base object. return x def parse_json(json_string): """Converts a JSON-C string into a Jsonc object. Args: json_string: str or unicode The JSON to be parsed. Returns: A new Jsonc object. """ return _convert_to_jsonc(simplejson.loads(json_string)) def parse_json_file(json_file): return _convert_to_jsonc(simplejson.load(json_file)) def jsonc_to_string(jsonc_obj): """Converts a Jsonc object into a string of JSON-C.""" return simplejson.dumps(_convert_to_object(jsonc_obj)) def prettify_jsonc(jsonc_obj, indentation=2): """Converts a Jsonc object to a pretified (intented) JSON string.""" return simplejson.dumps(_convert_to_object(jsonc_obj), indent=indentation) def _convert_to_object(jsonc_obj): """Creates a new dict or list which has the data in the Jsonc object. Used to convert the Jsonc object to a plain old Python object to simplify conversion to a JSON-C string. Args: jsonc_obj: A Jsonc object to be converted into simple Python objects (dicts, lists, etc.) Returns: Either a dict, list, or other object with members converted from Jsonc objects to the corresponding simple Python object. """ if isinstance(jsonc_obj, Jsonc): plain = {} for key, value in jsonc_obj._dict.iteritems(): plain[key] = _convert_to_object(value) return plain elif isinstance(jsonc_obj, list): plain = [] for item in jsonc_obj: plain.append(_convert_to_object(item)) return plain else: return jsonc_obj def _to_jsonc_name(member_name): """Converts a Python style member name to a JSON-C style name. JSON-C uses camelCaseWithLower while Python tends to use lower_with_underscores so this method converts as follows: spam becomes spam spam_and_eggs becomes spamAndEggs Args: member_name: str or unicode The Python syle name which should be converted to JSON-C style. Returns: The JSON-C style name as a str or unicode. """ characters = [] uppercase_next = False for character in member_name: if character == '_': uppercase_next = True elif uppercase_next: characters.append(character.upper()) uppercase_next = False else: characters.append(character) return ''.join(characters) class Jsonc(object): """Represents JSON-C data in an easy to access object format. To access the members of a JSON structure which looks like this: { "data": { "totalItems": 800, "items": [ { "content": { "1": "rtsp://v5.cache3.c.youtube.com/CiILENy.../0/0/0/video.3gp" }, "viewCount": 220101, "commentCount": 22, "favoriteCount": 201 } ] }, "apiVersion": "2.0" } You would do the following: x = gdata.core.parse_json(the_above_string) # Gives you 800 x.data.total_items # Should be 22 x.data.items[0].comment_count # The apiVersion is '2.0' x.api_version To create a Jsonc object which would produce the above JSON, you would do: gdata.core.Jsonc( api_version='2.0', data=gdata.core.Jsonc( total_items=800, items=[ gdata.core.Jsonc( view_count=220101, comment_count=22, favorite_count=201, content={ '1': ('rtsp://v5.cache3.c.youtube.com' '/CiILENy.../0/0/0/video.3gp')})])) or x = gdata.core.Jsonc() x.api_version = '2.0' x.data = gdata.core.Jsonc() x.data.total_items = 800 x.data.items = [] # etc. How it works: The JSON-C data is stored in an internal dictionary (._dict) and the getattr, setattr, and delattr methods rewrite the name which you provide to mirror the expected format in JSON-C. (For more details on name conversion see _to_jsonc_name.) You may also access members using getitem, setitem, delitem as you would for a dictionary. For example x.data.total_items is equivalent to x['data']['totalItems'] (Not all dict methods are supported so if you need something other than the item operations, then you will want to use the ._dict member). You may need to use getitem or the _dict member to access certain properties in cases where the JSON-C syntax does not map neatly to Python objects. For example the YouTube Video feed has some JSON like this: "content": {"1": "rtsp://v5.cache3.c.youtube.com..."...} You cannot do x.content.1 in Python, so you would use the getitem as follows: x.content['1'] or you could use the _dict member as follows: x.content._dict['1'] If you need to create a new object with such a mapping you could use. x.content = gdata.core.Jsonc(_dict={'1': 'rtsp://cache3.c.youtube.com...'}) """ def __init__(self, _dict=None, **kwargs): json = _dict or {} for key, value in kwargs.iteritems(): if key.startswith('_'): object.__setattr__(self, key, value) else: json[_to_jsonc_name(key)] = _convert_to_jsonc(value) object.__setattr__(self, '_dict', json) def __setattr__(self, name, value): if name.startswith('_'): object.__setattr__(self, name, value) else: object.__getattribute__( self, '_dict')[_to_jsonc_name(name)] = _convert_to_jsonc(value) def __getattr__(self, name): if name.startswith('_'): object.__getattribute__(self, name) else: try: return object.__getattribute__(self, '_dict')[_to_jsonc_name(name)] except KeyError: raise AttributeError( 'No member for %s or [\'%s\']' % (name, _to_jsonc_name(name))) def __delattr__(self, name): if name.startswith('_'): object.__delattr__(self, name) else: try: del object.__getattribute__(self, '_dict')[_to_jsonc_name(name)] except KeyError: raise AttributeError( 'No member for %s (or [\'%s\'])' % (name, _to_jsonc_name(name))) # For container methods pass-through to the underlying dict. def __getitem__(self, key): return self._dict[key] def __setitem__(self, key, value): self._dict[key] = value def __delitem__(self, key): del self._dict[key]
Python
#!/usr/bin/python # # Copyright (C) 2010-2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Extend the gdata client for the Content API for Shopping. TODO: 1. Proper MCA Support. 2. Better datafeed Support. """ __author__ = 'afshar (Ali Afshar)' import gdata.client import atom.data from gdata.contentforshopping.data import (ProductEntry, ProductFeed, DatafeedFeed, ClientAccountFeed, ClientAccount) CFS_VERSION = 'v1' CFS_HOST = 'content.googleapis.com' CFS_URI = 'https://%s/content' % CFS_HOST CFS_PROJECTION = 'generic' class ContentForShoppingClient(gdata.client.GDClient): """Client for Content for Shopping API. :param account_id: Merchant account ID. This value will be used by default for all requests, but may be overridden on a request-by-request basis. :param api_version: The version of the API to target. Default value: 'v1'. :param **kwargs: Pass all addtional keywords to the GDClient constructor. """ api_version = '1.0' def __init__(self, account_id=None, api_version=CFS_VERSION, **kwargs): self.cfs_account_id = account_id self.cfs_api_version = api_version gdata.client.GDClient.__init__(self, **kwargs) def _create_uri(self, account_id, resource, path=(), use_projection=True): """Create a request uri from the given arguments. If arguments are None, use the default client attributes. """ account_id = account_id or self.cfs_account_id if account_id is None: raise ValueError('No Account ID set. ' 'Either set for the client, or per request') segments = [CFS_URI, self.cfs_api_version, account_id, resource] if use_projection: segments.append(CFS_PROJECTION) segments.extend(path) return '/'.join(segments) def _create_product_id(self, id, country, language): return 'online:%s:%s:%s' % (language, country, id) def _create_batch_feed(self, entries, operation, feed=None): if feed is None: feed = ProductFeed() for entry in entries: entry.batch_operation = gdata.data.BatchOperation(type=operation) feed.entry.append(entry) return feed def get_products(self, start_index=None, max_results=None, account_id=None, auth_token=None): """Get a feed of products for the account. :param max_results: The maximum number of results to return (default 25, maximum 250). :param start_index: The starting index of the feed to return (default 1, maximum 10000) :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client """ uri = self._create_uri(account_id, 'items/products') return self.get_feed(uri, auth_token=auth_token, desired_class=gdata.contentforshopping.data.ProductFeed) def get_product(self, id, country, language, account_id=None, auth_token=None): """Get a product by id, country and language. :param id: The product ID :param country: The country (target_country) :param language: The language (content_language) """ pid = self._create_product_id(id, country, language) uri = self._create_uri(account_id, 'items/products', [pid]) return self.get_entry(uri, desired_class=ProductEntry, auth_token=auth_token) def insert_product(self, product, account_id=None, auth_token=None): """Create a new product, by posting the product entry feed. :param product: A :class:`gdata.contentforshopping.data.ProductEntry` with the required product data. :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client """ uri = self._create_uri(account_id, 'items/products') return self.post(product, uri=uri, auth_token=auth_token) def insert_products(self, products, account_id=None, auth_token=None): """Insert the products using a batch request :param products: A list of product entries """ feed = self._create_batch_feed(products, 'insert') return self.batch(feed) def delete_products(self, products, account_id=None, auth_token=None): """Delete the products using a batch request. :param products: A list of product entries .. note:: Entries must have the atom:id element set. """ feed = self._create_batch_feed(products, 'delete') return self.batch(feed) def update_products(self, products, account_id=None, auth_token=None): """Update the products using a batch request :param products: A list of product entries .. note:: Entries must have the atom:id element set. """ feed = self._create_batch_feed(products, 'update') return self.batch(feed) def batch(self, feed, account_id=None, auth_token=None): """Send a batch request. :param feed: The feed of batch entries to send. :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client """ uri = self._create_uri(account_id, 'items/products', ['batch']) return self.post(feed, uri=uri, auth_token=auth_token, desired_class=ProductFeed) def update_product(self, product, account_id=None, auth_token=None): """Update a product, by putting the product entry feed. :param product: A :class:`gdata.contentforshopping.data.ProductEntry` with the required product data. :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client """ pid = self._create_product_id(product.id.text, product.target_country.text, product.content_language.text) uri = self._create_uri(account_id, 'items/products', [pid]) return self.update(product, uri=uri, auth_token=auth_token) def get_datafeeds(self, account_id=None): """Get the feed of datafeeds. """ uri = self._create_uri(account_id, 'datafeeds/products', use_projection=False) return self.get_feed(uri, desired_class=DatafeedFeed) def insert_datafeed(self, entry, account_id=None, auth_token=None): """Insert a datafeed. """ uri = self._create_uri(account_id, 'datafeeds/products', use_projection=False) return self.post(entry, uri=uri, auth_token=auth_token) def get_client_accounts(self, account_id=None, auth_token=None): """Get the feed of managed accounts :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client """ uri = self._create_uri(account_id, 'managedaccounts/products', use_projection=False) return self.get_feed(uri, desired_class=ClientAccountFeed, auth_token=auth_token) def insert_client_account(self, entry, account_id=None, auth_token=None): """Insert a client account entry :param entry: An entry of type ClientAccount :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client """ uri = self._create_uri(account_id, 'managedaccounts/products', use_projection=False) return self.post(entry, uri=uri, auth_token=auth_token) def update_client_account(self, entry, client_account_id, account_id=None, auth_token=None): """Update a client account :param entry: An entry of type ClientAccount to update to :param client_account_id: The client account ID :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client """ uri = self._create_uri(account_id, 'managedaccounts/products', [client_account_id], use_projection=False) return self.update(entry, uri=uri, auth_token=auth_token) def delete_client_account(self, client_account_id, account_id=None, auth_token=None): """Delete a client account :param client_account_id: The client account ID :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client """ uri = self._create_uri(account_id, 'managedaccounts/products', [client_account_id], use_projection=False) return self.delete(uri, auth_token=auth_token)
Python
#!/usr/bin/python # # Copyright (C) 2010-2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """GData definitions for Content API for Shopping""" __author__ = 'afshar (Ali Afshar)' import atom.core import atom.data import gdata.data SC_NAMESPACE_TEMPLATE = ('{http://schemas.google.com/' 'structuredcontent/2009}%s') SCP_NAMESPACE_TEMPLATE = ('{http://schemas.google.com/' 'structuredcontent/2009/products}%s') class ProductId(atom.core.XmlElement): """sc:id element It is required that all inserted products are provided with a unique alphanumeric ID, in this element. """ _qname = SC_NAMESPACE_TEMPLATE % 'id' class RequiredDestination(atom.core.XmlElement): """sc:required_destination element This element defines the required destination for a product, namely "ProductSearch", "ProductAds" or "CommerceSearch". It should be added to the app:control element (ProductEntry's "control" attribute) to specify where the product should appear in search APIs. By default, when omitted, the api attempts to upload to as many destinations as possible. """ _qname = SC_NAMESPACE_TEMPLATE % 'required_destination' dest = 'dest' class ExcludedDestination(atom.core.XmlElement): """sc:excluded_destination element This element defines the required destination for a product, namely "ProductSearch", "ProductAds" or "CommerceSearch". It should be added to the app:control element (ProductEntry's "control" attribute) to specify where the product should not appear in search APIs. By default, when omitted, the api attempts to upload to as many destinations as possible. """ _qname = SC_NAMESPACE_TEMPLATE % 'excluded_destination' dest = 'dest' class ProductControl(atom.data.Control): """ app:control element overridden to provide additional elements in the sc namespace. """ required_destination = RequiredDestination excluded_destination = ExcludedDestination class ContentLanguage(atom.core.XmlElement): """ sc:content_language element Language used in the item content for the product """ _qname = SC_NAMESPACE_TEMPLATE % 'content_language' class TargetCountry(atom.core.XmlElement): """ sc:target_country element The target country of the product """ _qname = SC_NAMESPACE_TEMPLATE % 'target_country' class ImageLink(atom.core.XmlElement): """sc:image_link element This is the URL of an associated image for a product. Please use full size images (400x400 pixels or larger), not thumbnails. """ _qname = SC_NAMESPACE_TEMPLATE % 'image_link' class ExpirationDate(atom.core.XmlElement): """sc:expiration_date This is the date when the product listing will expire. If omitted, this will default to 30 days after the product was created. """ _qname = SC_NAMESPACE_TEMPLATE % 'expiration_date' class Adult(atom.core.XmlElement): """sc:adult element Indicates whether the content is targeted towards adults, with possible values of "true" or "false". Defaults to "false". """ _qname = SC_NAMESPACE_TEMPLATE % 'adult' class Author(atom.core.XmlElement): """ scp:author element Defines the author of the information, recommended for books. """ _qname = SCP_NAMESPACE_TEMPLATE % 'author' class Availability(atom.core.XmlElement): """ scp:availability element The retailer's suggested label for product availability. Supported values include: 'in stock', 'out of stock', 'limited availability'. """ _qname = SCP_NAMESPACE_TEMPLATE % 'availability' class Brand(atom.core.XmlElement): """ scp:brand element The brand of the product """ _qname = SCP_NAMESPACE_TEMPLATE % 'brand' class Color(atom.core.XmlElement): """scp:color element The color of the product. """ _qname = SCP_NAMESPACE_TEMPLATE % 'color' class Condition(atom.core.XmlElement): """scp:condition element The condition of the product, one of "new", "used", "refurbished" """ _qname = SCP_NAMESPACE_TEMPLATE % 'condition' class Edition(atom.core.XmlElement): """scp:edition element The edition of the product. Recommended for products with multiple editions such as collectors' editions etc, such as books. """ _qname = SCP_NAMESPACE_TEMPLATE % 'edition' class Feature(atom.core.XmlElement): """scp:feature element A product feature. A product may have multiple features, each being text, for example a smartphone may have features: "wifi", "gps" etc. """ _qname = SCP_NAMESPACE_TEMPLATE % 'feature' class FeaturedProduct(atom.core.XmlElement): """scp:featured_product element Used to indicate that this item is a special, featured product; Supported values are: "true", "false". """ _qname = SCP_NAMESPACE_TEMPLATE % 'featured_product' class Genre(atom.core.XmlElement): """scp:genre element Describes the genre of a product, eg "comedy". Strongly recommended for media. """ _qname = SCP_NAMESPACE_TEMPLATE % 'genre' class Gtin(atom.core.XmlElement): """scp:gtin element GTIN of the product (isbn/upc/ean) """ _qname = SCP_NAMESPACE_TEMPLATE % 'gtin' class Manufacturer(atom.core.XmlElement): """scp:manufacturer element Manufacturer of the product. """ _qname = SCP_NAMESPACE_TEMPLATE % 'manufacturer' class Mpn(atom.core.XmlElement): """scp:mpn element Manufacturer's Part Number. A unique code determined by the manufacturer for the product. """ _qname = SCP_NAMESPACE_TEMPLATE % 'mpn' class Price(atom.core.XmlElement): """scp:price element The price of the product. The unit attribute must be set, and should represent the currency. Note: Required Element """ _qname = SCP_NAMESPACE_TEMPLATE % 'price' unit = 'unit' class ProductType(atom.core.XmlElement): """scp:product_type element Describes the type of product. A taxonomy of available product types is listed at http://www.google.com/basepages/producttype/taxonomy.txt and the entire line in the taxonomy should be included, for example "Electronics > Video > Projectors". """ _qname = SCP_NAMESPACE_TEMPLATE % 'product_type' class Quantity(atom.core.XmlElement): """scp:quantity element The number of items available. A value of 0 indicates items that are currently out of stock. """ _qname = SCP_NAMESPACE_TEMPLATE % 'quantity' class ShippingCountry(atom.core.XmlElement): """scp:shipping_country element The two-letter ISO 3166 country code for the country to which an item will ship. This element should be placed inside the scp:shipping element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'shipping_country' class ShippingPrice(atom.core.XmlElement): """scp:shipping_price element Fixed shipping price, represented as a number. Specify the currency as the "unit" attribute". This element should be placed inside the scp:shipping element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'shipping_price' unit = 'unit' class ShippingRegion(atom.core.XmlElement): """scp:shipping_region element The geographic region to which a shipping rate applies, e.g., in the US, the two-letter state abbreviation, ZIP code, or ZIP code range using * wildcard. This element should be placed inside the scp:shipping element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'shipping_region' class ShippingService(atom.core.XmlElement): """scp:shipping_service element A free-form description of the service class or delivery speed. This element should be placed inside the scp:shipping element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'shipping_service' class Shipping(atom.core.XmlElement): """scp:shipping element Container for the shipping rules as provided by the shipping_country, shipping_price, shipping_region and shipping_service tags. """ _qname = SCP_NAMESPACE_TEMPLATE % 'shipping' shipping_price = ShippingPrice shipping_country = ShippingCountry shipping_service = ShippingService shipping_region = ShippingRegion class ShippingWeight(atom.core.XmlElement): """scp:shipping_weight element The shipping weight of a product. Requires a value and a unit using the unit attribute. Valid units include lb, pound, oz, ounce, g, gram, kg, kilogram. """ _qname = SCP_NAMESPACE_TEMPLATE % 'shipping_weight' unit = 'unit' class Size(atom.core.XmlElement): """scp:size element Available sizes of an item. Appropriate values include: "small", "medium", "large", etc. The product enttry may contain multiple sizes, to indicate the available sizes. """ _qname = SCP_NAMESPACE_TEMPLATE % 'size' class TaxRate(atom.core.XmlElement): """scp:tax_rate element The tax rate as a percent of the item price, i.e., number, as a percentage. This element should be placed inside the scp:tax (Tax class) element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'tax_rate' class TaxCountry(atom.core.XmlElement): """scp:tax_country element The country an item is taxed in (as a two-letter ISO 3166 country code). This element should be placed inside the scp:tax (Tax class) element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'tax_country' class TaxRegion(atom.core.XmlElement): """scp:tax_region element The geographic region that a tax rate applies to, e.g., in the US, the two-letter state abbreviation, ZIP code, or ZIP code range using * wildcard. This element should be placed inside the scp:tax (Tax class) element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'tax_region' class TaxShip(atom.core.XmlElement): """scp:tax_ship element Whether tax is charged on shipping for this product. The default value is "false". This element should be placed inside the scp:tax (Tax class) element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'tax_ship' class Tax(atom.core.XmlElement): """scp:tax element Container for the tax rules for this product. Containing the tax_rate, tax_country, tax_region, and tax_ship elements """ _qname = SCP_NAMESPACE_TEMPLATE % 'tax' tax_rate = TaxRate tax_country = TaxCountry tax_region = TaxRegion tax_ship = TaxShip class Year(atom.core.XmlElement): """scp:year element The year the product was produced. Expects four digits """ _qname = SCP_NAMESPACE_TEMPLATE % 'year' class ProductEntry(gdata.data.BatchEntry): """Product entry containing product information The elements of this entry that are used are made up of five different namespaces. They are: atom: - Atom app: - Atom Publishing Protocol gd: - Google Data API sc: - Content API for Shopping, general attributes scp: - Content API for Shopping, product attributes Only the sc and scp namespace elements are defined here, but additional useful elements are defined in superclasses, and are documented here because they are part of the required Content for Shopping API. .. attribute:: title The title of the product. This should be a :class:`atom.data.Title` element, for example:: entry = ProductEntry() entry.title = atom.data.Title(u'32GB MP3 Player') .. attribute:: author The author of the product. This should be a :class:`Author` element, for example:: entry = ProductEntry() entry.author = atom.data.Author(u'Isaac Asimov') .. attribute:: availability The avilability of a product. This should be an :class:`Availability` instance, for example:: entry = ProductEntry() entry.availability = Availability('in stock') .. attribute:: brand The brand of a product. This should be a :class:`Brand` element, for example:: entry = ProductEntry() entry.brand = Brand(u'Sony') .. attribute:: color The color of a product. This should be a :class:`Color` element, for example:: entry = ProductEntry() entry.color = Color(u'purple') .. attribute:: condition The condition of a product. This should be a :class:`Condition` element, for example:: entry = ProductEntry() entry.condition = Condition(u'new') .. attribute:: content_language The language for the product. This should be a :class:`ContentLanguage` element, for example:: entry = ProductEntry() entry.content_language = ContentLanguage('EN') .. attribute:: edition The edition of the product. This should be a :class:`Edition` element, for example:: entry = ProductEntry() entry.edition = Edition('1') .. attribute:: expiration The expiration date of this product listing. This should be a :class:`ExpirationDate` element, for example:: entry = ProductEntry() entry.expiration_date = ExpirationDate('2011-22-03') .. attribute:: feature A list of features for this product. Each feature should be a :class:`Feature` element, for example:: entry = ProductEntry() entry.feature.append(Feature(u'wifi')) entry.feature.append(Feature(u'gps')) .. attribute:: featured_product Whether the product is featured. This should be a :class:`FeaturedProduct` element, for example:: entry = ProductEntry() entry.featured_product = FeaturedProduct('true') .. attribute:: genre The genre of the product. This should be a :class:`Genre` element, for example:: entry = ProductEntry() entry.genre = Genre(u'comedy') .. attribute:: image_link A list of links to images of the product. Each link should be an :class:`ImageLink` element, for example:: entry = ProductEntry() entry.image_link.append(ImageLink('http://myshop/cdplayer.jpg')) .. attribute:: manufacturer The manufacturer of the product. This should be a :class:`Manufacturer` element, for example:: entry = ProductEntry() entry.manufacturer = Manufacturer('Sony') .. attribute:: mpn The manufacturer's part number for this product. This should be a :class:`Mpn` element, for example:: entry = ProductEntry() entry.mpn = Mpn('cd700199US') .. attribute:: price The price for this product. This should be a :class:`Price` element, including a unit argument to indicate the currency, for example:: entry = ProductEntry() entry.price = Price('20.00', unit='USD') .. attribute:: gtin The gtin for this product. This should be a :class:`Gtin` element, for example:: entry = ProductEntry() entry.gtin = Gtin('A888998877997') .. attribute:: product_type The type of product. This should be a :class:`ProductType` element, for example:: entry = ProductEntry() entry.product_type = ProductType("Electronics > Video > Projectors") .. attribute:: publisher The publisher of this product. This should be a :class:`Publisher` element, for example:: entry = ProductEntry() entry.publisher = Publisher(u'Oxford University Press') .. attribute:: quantity The quantity of product available in stock. This should be a :class:`Quantity` element, for example:: entry = ProductEntry() entry.quantity = Quantity('100') .. attribute:: shipping The shipping rules for the product. This should be a :class:`Shipping` with the necessary rules embedded as elements, for example:: entry = ProductEntry() entry.shipping = Shipping() entry.shipping.shipping_price = ShippingPrice('10.00', unit='USD') .. attribute:: shipping_weight The shipping weight for this product. This should be a :class:`ShippingWeight` element, including a unit parameter for the unit of weight, for example:: entry = ProductEntry() entry.shipping_weight = ShippingWeight('10.45', unit='kg') .. attribute:: size A list of the available sizes for this product. Each item in this list should be a :class:`Size` element, for example:: entry = ProductEntry() entry.size.append(Size('Small')) entry.size.append(Size('Medium')) entry.size.append(Size('Large')) .. attribute:: target_country The target country for the product. This should be a :class:`TargetCountry` element, for example:: entry = ProductEntry() entry.target_country = TargetCountry('US') .. attribute:: tax The tax rules for this product. This should be a :class:`Tax` element, with the tax rule elements embedded within, for example:: entry = ProductEntry() entry.tax = Tax() entry.tax.tax_rate = TaxRate('17.5') .. attribute:: year The year the product was created. This should be a :class:`Year` element, for example:: entry = ProductEntry() entry.year = Year('2001') #TODO Document these atom elements which are part of the required API <title> <link> <entry> <id> <category> <content> <author> <created> <updated> """ author = Author product_id = ProductId availability = Availability brand = Brand color = Color condition = Condition content_language = ContentLanguage edition = Edition expiration_date = ExpirationDate feature = [Feature] featured_product = FeaturedProduct genre = Genre image_link = [ImageLink] manufacturer = Manufacturer mpn = Mpn price = Price gtin = Gtin product_type = ProductType quantity = Quantity shipping = Shipping shipping_weight = ShippingWeight size = [Size] target_country = TargetCountry tax = Tax year = Year control = ProductControl # opensearch needs overriding for wrong version # see http://code.google.com/p/gdata-python-client/issues/detail?id=483 class TotalResults(gdata.data.TotalResults): _qname = gdata.data.TotalResults._qname[1] class ItemsPerPage(gdata.data.ItemsPerPage): _qname = gdata.data.ItemsPerPage._qname[1] class StartIndex(gdata.data.StartIndex): _qname = gdata.data.StartIndex._qname[1] class ProductFeed(gdata.data.BatchFeed): """Represents a feed of a merchant's products.""" entry = [ProductEntry] total_results = TotalResults items_per_page = ItemsPerPage start_index = StartIndex def build_entry(product_id=None, title=None, content=None, link=None, condition=None, target_country=None, content_language=None, price=None, price_unit=None, tax_rate=None, shipping_price=None, shipping_price_unit=None, image_links=(), expiration_date=None, adult=None, author=None, brand=None, color=None, edition=None, features=(), featured_product=None, genre=None, manufacturer=None, mpn=None, gtin=None, product_type=None, quantity=None, shipping_country=None, shipping_region=None, shipping_service=None, shipping_weight=None, shipping_weight_unit=None, sizes=(), tax_country=None, tax_region=None, tax_ship=None, year=None, product=None): """Create a new product with the required attributes. This function exists as an alternative constructor to help alleviate the boilerplate involved in creating product definitions. You may well want to fine-tune your products after creating them. Documentation of each attribute attempts to explain the "long-hand" way of achieving the same goal. :param product_id: The unique ID for this product. This is equivalent to creating and setting an product_id element:: entry = ProductEntry() entry.product_id = ProductId(product_id) :param title: The title of this product. This is equivalent to creating and setting a title element:: entry = ProductEntry entry.title = atom.data.Title(title) :param content: The description of this product. This is equivalent to creating and setting the content element:: entry.content = atom.data.Content(content) :param link: The uri of the link to a page describing the product. This is equivalent to creating and setting the link element:: entry.link = atom.data.Link(href=link, rel='alternate', type='text/html') :param condition: The condition of the product. This is equivalent to creating and setting the condition element:: entry.condition = Condition(condition) :param target_country: The target country of the product This is equivalent to creating and setting the target_country element:: entry.target_country = TargetCountry(target_country) :param content_language: The language of the content This is equivalent to creating and setting the content_language element:: entry.content_language = ContentLanguage(content_language) :param price: The price of the product This is equivalent to creating and setting the price element, using the price_unit parameter as the unit:: entry.price = Price(price, unit=price_unit) :param price_unit: The price unit of the product See price parameter. :param tax_rate: The tax rate for this product This is equivalent to creating and setting the tax element and its required children:: entry.tax = Tax() entry.tax.tax_rate = TaxRate(tax_rate) :param shipping_price: Thie price of shipping for this product This is equivalent to creating and setting the shipping element and its required children. The unit for the price is taken from the shipping_price_unit parameter:: entry.shipping = Shipping() entry.shipping.shipping_price = ShippingPrice(shipping_price, unit=shipping_price_unit) :param shipping_price_unit: The unit of the shipping price See shipping_price :param image_links: A sequence of links for images for this product. This is equivalent to creating a single image_link element for each image:: for image_link in image_links: entry.image_link.append(ImageLink(image_link)) :param expiration_date: The date that this product listing expires This is equivalent to creating and setting an expiration_date element:: entry.expiration_date = ExpirationDate(expiration_date) :param adult: Whether this product listing contains adult content This is equivalent to creating and setting the adult element:: entry.adult = Adult(adult) :param author: The author of the product This is equivalent to creating and setting the author element:: entry.author = Author(author) :param brand: The brand of the product This is equivalent to creating and setting the brand element:: entry.brand = Brand(brand) :param color: The color of the product This is equivalent to creating and setting the color element:: entry.color = Color(color) :param edition: The edition of the product This is equivalent to creating and setting the edition element:: entry.edition = Edition('1') :param features=(): Features for this product Each feature in the provided sequence will create a Feature element in the entry, equivalent to:: for feature in features: entry.feature.append(Feature(feature))) :param featured_product: Whether this product is featured This is equivalent to creating and setting the featured_product element:: entry.featured_product = FeaturedProduct(featured_product) :param genre: The genre of the product This is equivalent to creating and setting the genre element:: entry.genre = Genre(genre) :param manufacturer: The manufacturer of the product This is equivalent to creating and setting the manufacturer element:: entry.manufacturer = Manufacturer(manufacturer) :param mpn: The manufacturer's part number for a product This is equivalent to creating and setting the mpn element:: entry.mpn = Mpn(mpn) :param gtin: The gtin for a product This is equivalent to creating and setting the gtin element:: entry.gtin = Gtin(gtin) :param product_type: The type of a product This is equivalent to creating and setting the product_type element:: entry.product_type = ProductType(product_type) :param quantity: The quantity of the product in stock This is equivalent to creating and setting the quantity element:: entry.quantity = Quantity(quantity) :param shipping_country: The country that this product can be shipped to This is equivalent to creating a Shipping element, and creating and setting the required element within:: entry.shipping = Shipping() entry.shipping.shipping_country = ShippingCountry(shipping_country) :param shipping_region: The region that this product can be shipped to This is equivalent to creating a Shipping element, and creating and setting the required element within:: entry.shipping = Shipping() entry.shipping.shipping_region = ShippingRegion(shipping_region) :param shipping_service: The service for shipping. This is equivalent to creating a Shipping element, and creating and setting the required element within:: entry.shipping = Shipping() entry.shipping.shipping_service = ShippingRegion(shipping_service) :param shipping_weight: The shipping weight of a product Along with the shipping_weight_unit, this is equivalent to creating and setting the shipping_weight element:: entry.shipping_weight = ShippingWeight(shipping_weight, unit=shipping_weight_unit) :param shipping_weight_unit: The unit of shipping weight See shipping_weight. :param: The sizes that are available for this product. Each size of a list will add a size element to the entry, like so:: for size in sizes: product.size.append(Size(size)) :param tax_country: The country that tax rules will apply This is equivalent to creating a Tax element, and creating and setting the required sub-element:: entry.tax = Tax() entry.tax.tax_country = TaxCountry(tax_country) :param tax_region: The region that the tax rule applies in This is equivalent to creating a Tax element, and creating and setting the required sub-element:: entry.tax = Tax() entry.tax.tax_region = TaxRegion(tax_region) :param tax_ship: Whether shipping cost is taxable This is equivalent to creating a Tax element, and creating and setting the required sub-element:: entry.tax = Tax() entry.tax.tax_ship = TaxShip(tax_ship) :param year: The year the product was created This is equivalent to creating and setting a year element:: entry.year = Year('2001') """ product = product or ProductEntry() if product_id is not None: product.product_id = ProductId(product_id) if content is not None: product.content = atom.data.Content(content) if title is not None: product.title = atom.data.Title(title) if condition is not None: product.condition = Condition(condition) if price is not None: product.price = Price(price, unit=price_unit) if content_language is not None: product.content_language = ContentLanguage(content_language) if target_country is not None: product.target_country = TargetCountry(target_country) if tax_rate is not None: product.tax = Tax() product.tax.tax_rate = TaxRate(tax_rate) if shipping_price is not None: if shipping_price_unit is None: raise ValueError('Must provide shipping_price_unit if ' 'shipping_price is provided') product.shipping = Shipping() product.shipping.shipping_price = ShippingPrice(shipping_price, unit=shipping_price_unit) if link is not None: product.link.append(atom.data.Link(href=link, type='text/html', rel='alternate')) for image_link in image_links: product.image_link.append(ImageLink(image_link)) if expiration_date is not None: product.expiration_date = ExpirationDate(expiration_date) if adult is not None: product.adult = Adult(adult) if author is not None: product.author = Author(author) if brand is not None: product.brand = Brand(brand) if color is not None: product.color = Color(color) if edition is not None: product.edition = Edition(edition) for feature in features: product.feature.append(Feature(feature)) if featured_product is not None: product.featured_product = FeaturedProduct(featured_product) if genre is not None: product.genre = Genre(genre) if manufacturer is not None: product.manufacturer = Manufacturer(manufacturer) if mpn is not None: product.mpn = Mpn(mpn) if gtin is not None: product.gtin = Gtin(gtin) if product_type is not None: product.product_type = ProductType(product_type) if quantity is not None: product.quantity = Quantity(quantity) if shipping_country is not None: product.shipping.shipping_country = ShippingCountry( shipping_country) if shipping_region is not None: product.shipping.shipping_region = ShippingRegion(shipping_region) if shipping_service is not None: product.shipping.shipping_service = ShippingService( shipping_service) if shipping_weight is not None: product.shipping_weight = ShippingWeight(shipping_weight) if shipping_weight_unit is not None: product.shipping_weight.unit = shipping_weight_unit for size in sizes: product.size.append(Size(size)) if tax_country is not None: product.tax.tax_country = TaxCountry(tax_country) if tax_region is not None: product.tax.tax_region = TaxRegion(tax_region) if tax_ship is not None: product.tax.tax_ship = TaxShip(tax_ship) if year is not None: product.year = Year(year) return product class Edited(atom.core.XmlElement): """sc:edited element """ _qname = SC_NAMESPACE_TEMPLATE % 'edited' class AttributeLanguage(atom.core.XmlElement): """sc:attribute_language element """ _qname = SC_NAMESPACE_TEMPLATE % 'attribute_language' class Channel(atom.core.XmlElement): """sc:channel element """ _qname = SC_NAMESPACE_TEMPLATE % 'channel' class FeedFileName(atom.core.XmlElement): """sc:feed_file_name element """ _qname = SC_NAMESPACE_TEMPLATE % 'feed_file_name' class FeedType(atom.core.XmlElement): """sc:feed_type element """ _qname = SC_NAMESPACE_TEMPLATE % 'feed_type' class UseQuotedFields(atom.core.XmlElement): """sc:use_quoted_fields element """ _qname = SC_NAMESPACE_TEMPLATE % 'use_quoted_fields' class FileFormat(atom.core.XmlElement): """sc:file_format element """ _qname = SC_NAMESPACE_TEMPLATE % 'file_format' use_quoted_fields = UseQuotedFields format = 'format' class ProcessingStatus(atom.core.XmlElement): """sc:processing_status element """ _qname = SC_NAMESPACE_TEMPLATE % 'processing_status' class DatafeedEntry(gdata.data.GDEntry): """An entry for a Datafeed """ content_language = ContentLanguage target_country = TargetCountry feed_file_name = FeedFileName file_format = FileFormat attribute_language = AttributeLanguage processing_status = ProcessingStatus edited = Edited feed_type = FeedType class DatafeedFeed(gdata.data.GDFeed): """A datafeed feed """ entry = [DatafeedEntry] class AdultContent(atom.core.XmlElement): """sc:adult_content element """ _qname = SC_NAMESPACE_TEMPLATE % 'adult_content' class InternalId(atom.core.XmlElement): """sc:internal_id element """ _qname = SC_NAMESPACE_TEMPLATE % 'internal_id' class ReviewsUrl(atom.core.XmlElement): """sc:reviews_url element """ _qname = SC_NAMESPACE_TEMPLATE % 'reviews_url' class ClientAccount(gdata.data.GDEntry): """A multiclient account entry """ adult_content = AdultContent internal_id = InternalId reviews_url = ReviewsUrl class ClientAccountFeed(gdata.data.GDFeed): """A multiclient account feed """ entry = [ClientAccount]
Python
#!/usr/bin/python # # Copyright (C) 2010-2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Support for the Content API for Shopping See: http://code.google.com/apis/shopping/content/index.html """
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # Refactored in 2009 to work for Google Analytics by Sal Uryasev at Juice Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ AccountsService extends the GDataService to streamline Google Analytics account information operations. AnalyticsDataService: Provides methods to query google analytics data feeds. Extends GDataService. DataQuery: Queries a Google Analytics Data list feed. AccountQuery: Queries a Google Analytics Account list feed. """ __author__ = 'api.suryasev (Sal Uryasev)' import urllib import atom import gdata.service import gdata.analytics class AccountsService(gdata.service.GDataService): """Client extension for the Google Analytics Account List feed.""" def __init__(self, email="", password=None, source=None, server='www.google.com/analytics', additional_headers=None, **kwargs): """Creates a client for the Google Analytics service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='analytics', source=source, server=server, additional_headers=additional_headers, **kwargs) def QueryAccountListFeed(self, uri): """Retrieves an AccountListFeed by retrieving a URI based off the Document List feed, including any query parameters. An AccountListFeed object can be used to construct these parameters. Args: uri: string The URI of the feed being retrieved possibly with query parameters. Returns: An AccountListFeed object representing the feed returned by the server. """ return self.Get(uri, converter=gdata.analytics.AccountListFeedFromString) def GetAccountListEntry(self, uri): """Retrieves a particular AccountListEntry by its unique URI. Args: uri: string The unique URI of an entry in an Account List feed. Returns: An AccountLisFeed object representing the retrieved entry. """ return self.Get(uri, converter=gdata.analytics.AccountListEntryFromString) def GetAccountList(self, max_results=1000, text_query=None, params=None, categories=None): """Retrieves a feed containing all of a user's accounts and profiles.""" q = gdata.analytics.service.AccountQuery(max_results=max_results, text_query=text_query, params=params, categories=categories); return self.QueryAccountListFeed(q.ToUri()) class AnalyticsDataService(gdata.service.GDataService): """Client extension for the Google Analytics service Data List feed.""" def __init__(self, email=None, password=None, source=None, server='www.google.com/analytics', additional_headers=None, **kwargs): """Creates a client for the Google Analytics service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'docs.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__(self, email=email, password=password, service='analytics', source=source, server=server, additional_headers=additional_headers, **kwargs) def GetData(self, ids='', dimensions='', metrics='', sort='', filters='', start_date='', end_date='', start_index='', max_results=''): """Retrieves a feed containing a user's data ids: comma-separated string of analytics accounts. dimensions: comma-separated string of dimensions. metrics: comma-separated string of metrics. sort: comma-separated string of dimensions and metrics for sorting. This may be previxed with a minus to sort in reverse order. (e.g. '-ga:keyword') If ommited, the first dimension passed in will be used. filters: comma-separated string of filter parameters. (e.g. 'ga:keyword==google') start_date: start date for data pull. end_date: end date for data pull. start_index: used in combination with max_results to pull more than 1000 entries. This defaults to 1. max_results: maximum results that the pull will return. This defaults to, and maxes out at 1000. """ q = gdata.analytics.service.DataQuery(ids=ids, dimensions=dimensions, metrics=metrics, filters=filters, sort=sort, start_date=start_date, end_date=end_date, start_index=start_index, max_results=max_results); return self.AnalyticsDataFeed(q.ToUri()) def AnalyticsDataFeed(self, uri): """Retrieves an AnalyticsListFeed by retrieving a URI based off the Document List feed, including any query parameters. An AnalyticsListFeed object can be used to construct these parameters. Args: uri: string The URI of the feed being retrieved possibly with query parameters. Returns: An AnalyticsListFeed object representing the feed returned by the server. """ return self.Get(uri, converter=gdata.analytics.AnalyticsDataFeedFromString) """ Account Fetching """ def QueryAccountListFeed(self, uri): """Retrieves an Account ListFeed by retrieving a URI based off the Account List feed, including any query parameters. A AccountQuery object can be used to construct these parameters. Args: uri: string The URI of the feed being retrieved possibly with query parameters. Returns: An AccountListFeed object representing the feed returned by the server. """ return self.Get(uri, converter=gdata.analytics.AccountListFeedFromString) def GetAccountListEntry(self, uri): """Retrieves a particular AccountListEntry by its unique URI. Args: uri: string The unique URI of an entry in an Account List feed. Returns: An AccountListEntry object representing the retrieved entry. """ return self.Get(uri, converter=gdata.analytics.AccountListEntryFromString) def GetAccountList(self, username="default", max_results=1000, start_index=1): """Retrieves a feed containing all of a user's accounts and profiles. The username parameter is soon to be deprecated, with 'default' becoming the only allowed parameter. """ if not username: raise Exception("username is a required parameter") q = gdata.analytics.service.AccountQuery(username=username, max_results=max_results, start_index=start_index); return self.QueryAccountListFeed(q.ToUri()) class DataQuery(gdata.service.Query): """Object used to construct a URI to a data feed""" def __init__(self, feed='/feeds/data', text_query=None, params=None, categories=None, ids="", dimensions="", metrics="", sort="", filters="", start_date="", end_date="", start_index="", max_results=""): """Constructor for Analytics List Query Args: feed: string (optional) The path for the feed. (e.g. '/feeds/data') text_query: string (optional) The contents of the q query parameter. This string is URL escaped upon conversion to a URI. params: dict (optional) Parameter value string pairs which become URL params when translated to a URI. These parameters are added to the query's items. categories: list (optional) List of category strings which should be included as query categories. See gdata.service.Query for additional documentation. ids: comma-separated string of analytics accounts. dimensions: comma-separated string of dimensions. metrics: comma-separated string of metrics. sort: comma-separated string of dimensions and metrics. This may be previxed with a minus to sort in reverse order (e.g. '-ga:keyword'). If ommited, the first dimension passed in will be used. filters: comma-separated string of filter parameters (e.g. 'ga:keyword==google'). start_date: start date for data pull. end_date: end date for data pull. start_index: used in combination with max_results to pull more than 1000 entries. This defaults to 1. max_results: maximum results that the pull will return. This defaults to, and maxes out at 1000. Yields: A DocumentQuery object used to construct a URI based on the Document List feed. """ self.elements = {'ids': ids, 'dimensions': dimensions, 'metrics': metrics, 'sort': sort, 'filters': filters, 'start-date': start_date, 'end-date': end_date, 'start-index': start_index, 'max-results': max_results} gdata.service.Query.__init__(self, feed, text_query, params, categories) def ToUri(self): """Generates a URI from the query parameters set in the object. Returns: A string containing the URI used to retrieve entries from the Analytics List feed. """ old_feed = self.feed self.feed = '/'.join([old_feed]) + '?' + \ urllib.urlencode(dict([(key, value) for key, value in \ self.elements.iteritems() if value])) new_feed = gdata.service.Query.ToUri(self) self.feed = old_feed return new_feed class AccountQuery(gdata.service.Query): """Object used to construct a URI to query the Google Account List feed""" def __init__(self, feed='/feeds/accounts', start_index=1, max_results=1000, username='default', text_query=None, params=None, categories=None): """Constructor for Account List Query Args: feed: string (optional) The path for the feed. (e.g. '/feeds/documents') visibility: string (optional) The visibility chosen for the current feed. projection: string (optional) The projection chosen for the current feed. text_query: string (optional) The contents of the q query parameter. This string is URL escaped upon conversion to a URI. params: dict (optional) Parameter value string pairs which become URL params when translated to a URI. These parameters are added to the query's items. categories: list (optional) List of category strings which should be included as query categories. See gdata.service.Query for additional documentation. username: string (deprecated) This value should now always be passed as 'default'. Yields: A DocumentQuery object used to construct a URI based on the Document List feed. """ self.max_results = max_results self.start_index = start_index self.username = username gdata.service.Query.__init__(self, feed, text_query, params, categories) def ToUri(self): """Generates a URI from the query parameters set in the object. Returns: A string containing the URI used to retrieve entries from the Account List feed. """ old_feed = self.feed self.feed = '/'.join([old_feed, self.username]) + '?' + \ '&'.join(['max-results=' + str(self.max_results), 'start-index=' + str(self.start_index)]) new_feed = self.feed self.feed = old_feed return new_feed
Python
#!/usr/bin/python # # Copyright 2010 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Streamlines requests to the Google Analytics APIs.""" __author__ = 'api.nickm@google.com (Nick Mihailovski)' import atom.data import gdata.client import gdata.analytics.data import gdata.gauth class AnalyticsClient(gdata.client.GDClient): """Client extension for the Google Analytics API service.""" api_version = '2' auth_service = 'analytics' auth_scopes = gdata.gauth.AUTH_SCOPES['analytics'] account_type = 'GOOGLE' ssl = True def __init__(self, auth_token=None, **kwargs): """Initializes a new client for the Google Analytics Data Export API. Args: auth_token: gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken (optional) Authorizes this client to edit the user's data. kwargs: The other parameters to pass to gdata.client.GDClient constructor. """ gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs) def get_account_feed(self, feed_uri, auth_token=None, **kwargs): """Makes a request to the Analytics API Account Feed. Args: feed_uri: str or gdata.analytics.AccountFeedQuery The Analytics Account Feed uri to define what data to retrieve from the API. Can also be used with a gdata.analytics.AccountFeedQuery object. """ return self.get_feed(feed_uri, desired_class=gdata.analytics.data.AccountFeed, auth_token=auth_token, **kwargs) GetAccountFeed = get_account_feed def get_data_feed(self, feed_uri, auth_token=None, **kwargs): """Makes a request to the Analytics API Data Feed. Args: feed_uri: str or gdata.analytics.AccountFeedQuery The Analytics Data Feed uri to define what data to retrieve from the API. Can also be used with a gdata.analytics.AccountFeedQuery object. """ return self.get_feed(feed_uri, desired_class=gdata.analytics.data.DataFeed, auth_token=auth_token, **kwargs) GetDataFeed = get_data_feed def get_management_feed(self, feed_uri, auth_token=None, **kwargs): """Makes a request to the Google Analytics Management API. The Management API provides read-only access to configuration data for Google Analytics and supercedes the Data Export API Account Feed. The Management API supports 5 feeds: account, web property, profile, goal, advanced segment. You can access each feed through the respective management query class below. All requests return the same data object. Args: feed_uri: str or AccountQuery, WebPropertyQuery, ProfileQuery, GoalQuery, MgmtAdvSegFeedQuery The Management API Feed uri to define which feed to retrieve. Either use a string or one of the wrapper classes. """ return self.get_feed(feed_uri, desired_class=gdata.analytics.data.ManagementFeed, auth_token=auth_token, **kwargs) GetMgmtFeed = GetManagementFeed = get_management_feed class AnalyticsBaseQuery(gdata.client.GDQuery): """Abstracts common configuration across all query objects. Attributes: scheme: string The default scheme. Should always be https. host: string The default host. """ scheme = 'https' host = 'www.google.com' class AccountFeedQuery(AnalyticsBaseQuery): """Account Feed query class to simplify constructing Account Feed Urls. To use this class, you can either pass a dict in the constructor that has all the data feed query parameters as keys: queryUrl = AccountFeedQuery({'max-results': '10000'}) Alternatively you can add new parameters directly to the query object: queryUrl = AccountFeedQuery() queryUrl.query['max-results'] = '10000' Args: query: dict (optional) Contains all the GA Data Feed query parameters as keys. """ path = '/analytics/feeds/accounts/default' def __init__(self, query={}, **kwargs): self.query = query gdata.client.GDQuery(self, **kwargs) class DataFeedQuery(AnalyticsBaseQuery): """Data Feed query class to simplify constructing Data Feed Urls. To use this class, you can either pass a dict in the constructor that has all the data feed query parameters as keys: queryUrl = DataFeedQuery({'start-date': '2008-10-01'}) Alternatively you can add new parameters directly to the query object: queryUrl = DataFeedQuery() queryUrl.query['start-date'] = '2008-10-01' Args: query: dict (optional) Contains all the GA Data Feed query parameters as keys. """ path = '/analytics/feeds/data' def __init__(self, query={}, **kwargs): self.query = query gdata.client.GDQuery(self, **kwargs) class AccountQuery(AnalyticsBaseQuery): """Management API Account Feed query class. Example Usage: queryUrl = AccountQuery() queryUrl = AccountQuery({'max-results': 100}) queryUrl2 = AccountQuery() queryUrl2.query['max-results'] = 100 Args: query: dict (optional) A dictionary of query parameters. """ path = '/analytics/feeds/datasources/ga/accounts' def __init__(self, query={}, **kwargs): self.query = query gdata.client.GDQuery(self, **kwargs) class WebPropertyQuery(AnalyticsBaseQuery): """Management API Web Property Feed query class. Example Usage: queryUrl = WebPropertyQuery() queryUrl = WebPropertyQuery('123', {'max-results': 100}) queryUrl = WebPropertyQuery(acct_id='123', query={'max-results': 100}) queryUrl2 = WebPropertyQuery() queryUrl2.acct_id = '1234' queryUrl2.query['max-results'] = 100 Args: acct_id: string (optional) The account ID to filter results. Default is ~all. query: dict (optional) A dictionary of query parameters. """ def __init__(self, acct_id='~all', query={}, **kwargs): self.acct_id = acct_id self.query = query gdata.client.GDQuery(self, **kwargs) @property def path(self): """Wrapper for path attribute.""" return ('/analytics/feeds/datasources/ga/accounts/%s/webproperties' % self.acct_id) class ProfileQuery(AnalyticsBaseQuery): """Management API Profile Feed query class. Example Usage: queryUrl = ProfileQuery() queryUrl = ProfileQuery('123', 'UA-123-1', {'max-results': 100}) queryUrl = ProfileQuery(acct_id='123', web_prop_id='UA-123-1', query={'max-results': 100}) queryUrl2 = ProfileQuery() queryUrl2.acct_id = '123' queryUrl2.web_prop_id = 'UA-123-1' queryUrl2.query['max-results'] = 100 Args: acct_id: string (optional) The account ID to filter results. Default is ~all. web_prop_id: string (optional) The web property ID to filter results. Default is ~all. query: dict (optional) A dictionary of query parameters. """ def __init__(self, acct_id='~all', web_prop_id='~all', query={}, **kwargs): self.acct_id = acct_id self.web_prop_id = web_prop_id self.query = query gdata.client.GDQuery(self, **kwargs) @property def path(self): """Wrapper for path attribute.""" return ('/analytics/feeds/datasources/ga/accounts/%s/webproperties' '/%s/profiles' % (self.acct_id, self.web_prop_id)) class GoalQuery(AnalyticsBaseQuery): """Management API Goal Feed query class. Example Usage: queryUrl = GoalQuery() queryUrl = GoalQuery('123', 'UA-123-1', '555', {'max-results': 100}) queryUrl = GoalQuery(acct_id='123', web_prop_id='UA-123-1', profile_id='555', query={'max-results': 100}) queryUrl2 = GoalQuery() queryUrl2.acct_id = '123' queryUrl2.web_prop_id = 'UA-123-1' queryUrl2.query['max-results'] = 100 Args: acct_id: string (optional) The account ID to filter results. Default is ~all. web_prop_id: string (optional) The web property ID to filter results. Default is ~all. profile_id: string (optional) The profile ID to filter results. Default is ~all. query: dict (optional) A dictionary of query parameters. """ def __init__(self, acct_id='~all', web_prop_id='~all', profile_id='~all', query={}, **kwargs): self.acct_id = acct_id self.web_prop_id = web_prop_id self.profile_id = profile_id self.query = query or {} gdata.client.GDQuery(self, **kwargs) @property def path(self): """Wrapper for path attribute.""" return ('/analytics/feeds/datasources/ga/accounts/%s/webproperties' '/%s/profiles/%s/goals' % (self.acct_id, self.web_prop_id, self.profile_id)) class AdvSegQuery(AnalyticsBaseQuery): """Management API Goal Feed query class. Example Usage: queryUrl = AdvSegQuery() queryUrl = AdvSegQuery({'max-results': 100}) queryUrl1 = AdvSegQuery() queryUrl1.query['max-results'] = 100 Args: query: dict (optional) A dictionary of query parameters. """ path = '/analytics/feeds/datasources/ga/segments' def __init__(self, query={}, **kwargs): self.query = query gdata.client.GDQuery(self, **kwargs)
Python
#!/usr/bin/python # # Copyright 2010 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model classes for parsing and generating XML for both the Google Analytics Data Export and Management APIs. Although both APIs operate on different parts of Google Analytics, they share common XML elements and are released in the same module. The Management API supports 5 feeds all using the same ManagementFeed data class. """ __author__ = 'api.nickm@google.com (Nick Mihailovski)' import gdata.data import atom.core import atom.data # XML Namespace used in Google Analytics API entities. DXP_NS = '{http://schemas.google.com/analytics/2009}%s' GA_NS = '{http://schemas.google.com/ga/2009}%s' GD_NS = '{http://schemas.google.com/g/2005}%s' class GetProperty(object): """Utility class to simplify retrieving Property objects.""" def get_property(self, name): """Helper method to return a propery object by its name attribute. Args: name: string The name of the <dxp:property> element to retrieve. Returns: A property object corresponding to the matching <dxp:property> element. if no property is found, None is returned. """ for prop in self.property: if prop.name == name: return prop return None GetProperty = get_property class GetMetric(object): """Utility class to simplify retrieving Metric objects.""" def get_metric(self, name): """Helper method to return a propery value by its name attribute Args: name: string The name of the <dxp:metric> element to retrieve. Returns: A property object corresponding to the matching <dxp:metric> element. if no property is found, None is returned. """ for met in self.metric: if met.name == name: return met return None GetMetric = get_metric class GetDimension(object): """Utility class to simplify retrieving Dimension objects.""" def get_dimension(self, name): """Helper method to return a dimention object by its name attribute Args: name: string The name of the <dxp:dimension> element to retrieve. Returns: A dimension object corresponding to the matching <dxp:dimension> element. if no dimension is found, None is returned. """ for dim in self.dimension: if dim.name == name: return dim return None GetDimension = get_dimension class GaLinkFinder(object): """Utility class to return specific links in Google Analytics feeds.""" def get_parent_links(self): """Returns a list of all the parent links in an entry.""" links = [] for link in self.link: if link.rel == link.parent(): links.append(link) return links GetParentLinks = get_parent_links def get_child_links(self): """Returns a list of all the child links in an entry.""" links = [] for link in self.link: if link.rel == link.child(): links.append(link) return links GetChildLinks = get_child_links def get_child_link(self, target_kind): """Utility method to return one child link. Returns: A child link with the given target_kind. None if the target_kind was not found. """ for link in self.link: if link.rel == link.child() and link.target_kind == target_kind: return link return None GetChildLink = get_child_link class StartDate(atom.core.XmlElement): """Analytics Feed <dxp:startDate>""" _qname = DXP_NS % 'startDate' class EndDate(atom.core.XmlElement): """Analytics Feed <dxp:endDate>""" _qname = DXP_NS % 'endDate' class Metric(atom.core.XmlElement): """Analytics Feed <dxp:metric>""" _qname = DXP_NS % 'metric' name = 'name' type = 'type' value = 'value' confidence_interval = 'confidenceInterval' class Aggregates(atom.core.XmlElement, GetMetric): """Analytics Data Feed <dxp:aggregates>""" _qname = DXP_NS % 'aggregates' metric = [Metric] class ContainsSampledData(atom.core.XmlElement): """Analytics Data Feed <dxp:containsSampledData>""" _qname = DXP_NS % 'containsSampledData' class TableId(atom.core.XmlElement): """Analytics Feed <dxp:tableId>""" _qname = DXP_NS % 'tableId' class TableName(atom.core.XmlElement): """Analytics Feed <dxp:tableName>""" _qname = DXP_NS % 'tableName' class Property(atom.core.XmlElement): """Analytics Feed <dxp:property>""" _qname = DXP_NS % 'property' name = 'name' value = 'value' class Definition(atom.core.XmlElement): """Analytics Feed <dxp:definition>""" _qname = DXP_NS % 'definition' class Segment(atom.core.XmlElement): """Analytics Feed <dxp:segment>""" _qname = DXP_NS % 'segment' id = 'id' name = 'name' definition = Definition class Engagement(atom.core.XmlElement): """Analytics Feed <dxp:engagement>""" _qname = GA_NS % 'engagement' type = 'type' comparison = 'comparison' threshold_value = 'thresholdValue' class Step(atom.core.XmlElement): """Analytics Feed <dxp:step>""" _qname = GA_NS % 'step' number = 'number' name = 'name' path = 'path' class Destination(atom.core.XmlElement): """Analytics Feed <dxp:destination>""" _qname = GA_NS % 'destination' step = [Step] expression = 'expression' case_sensitive = 'caseSensitive' match_type = 'matchType' step1_required = 'step1Required' class Goal(atom.core.XmlElement): """Analytics Feed <dxp:goal>""" _qname = GA_NS % 'goal' destination = Destination engagement = Engagement number = 'number' name = 'name' value = 'value' active = 'active' class CustomVariable(atom.core.XmlElement): """Analytics Data Feed <dxp:customVariable>""" _qname = GA_NS % 'customVariable' index = 'index' name = 'name' scope = 'scope' class DataSource(atom.core.XmlElement, GetProperty): """Analytics Data Feed <dxp:dataSource>""" _qname = DXP_NS % 'dataSource' table_id = TableId table_name = TableName property = [Property] class Dimension(atom.core.XmlElement): """Analytics Feed <dxp:dimension>""" _qname = DXP_NS % 'dimension' name = 'name' value = 'value' class AnalyticsLink(atom.data.Link): """Subclass of link <link>""" target_kind = GD_NS % 'targetKind' @classmethod def parent(cls): """Parent target_kind""" return '%s#parent' % GA_NS[1:-3] @classmethod def child(cls): """Child target_kind""" return '%s#child' % GA_NS[1:-3] # Account Feed. class AccountEntry(gdata.data.GDEntry, GetProperty): """Analytics Account Feed <entry>""" _qname = atom.data.ATOM_TEMPLATE % 'entry' table_id = TableId property = [Property] goal = [Goal] custom_variable = [CustomVariable] class AccountFeed(gdata.data.GDFeed): """Analytics Account Feed <feed>""" _qname = atom.data.ATOM_TEMPLATE % 'feed' segment = [Segment] entry = [AccountEntry] # Data Feed. class DataEntry(gdata.data.GDEntry, GetMetric, GetDimension): """Analytics Data Feed <entry>""" _qname = atom.data.ATOM_TEMPLATE % 'entry' dimension = [Dimension] metric = [Metric] def get_object(self, name): """Returns either a Dimension or Metric object with the same name as the name parameter. Args: name: string The name of the object to retrieve. Returns: Either a Dimension or Object that has the same as the name parameter. """ output = self.GetDimension(name) if not output: output = self.GetMetric(name) return output GetObject = get_object class DataFeed(gdata.data.GDFeed): """Analytics Data Feed <feed>. Although there is only one datasource, it is stored in an array to replicate the design of the Java client library and ensure backwards compatibility if new data sources are added in the future. """ _qname = atom.data.ATOM_TEMPLATE % 'feed' start_date = StartDate end_date = EndDate aggregates = Aggregates contains_sampled_data = ContainsSampledData data_source = [DataSource] entry = [DataEntry] segment = Segment def has_sampled_data(self): """Returns whether this feed has sampled data.""" if (self.contains_sampled_data.text == 'true'): return True return False HasSampledData = has_sampled_data # Management Feed. class ManagementEntry(gdata.data.GDEntry, GetProperty, GaLinkFinder): """Analytics Managememt Entry <entry>.""" _qname = atom.data.ATOM_TEMPLATE % 'entry' kind = GD_NS % 'kind' property = [Property] goal = Goal segment = Segment link = [AnalyticsLink] class ManagementFeed(gdata.data.GDFeed): """Analytics Management Feed <feed>. This class holds the data for all 5 Management API feeds: Account, Web Property, Profile, Goal, and Advanced Segment Feeds. """ _qname = atom.data.ATOM_TEMPLATE % 'feed' entry = [ManagementEntry] kind = GD_NS % 'kind'
Python
#!/usr/bin/python # # Original Copyright (C) 2006 Google Inc. # Refactored in 2009 to work for Google Analytics by Sal Uryasev at Juice Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Note that this module will not function without specifically adding # 'analytics': [ #Google Analytics # 'https://www.google.com/analytics/feeds/'], # to CLIENT_LOGIN_SCOPES in the gdata/service.py file """Contains extensions to Atom objects used with Google Analytics.""" __author__ = 'api.suryasev (Sal Uryasev)' import atom import gdata GAN_NAMESPACE = 'http://schemas.google.com/analytics/2009' class TableId(gdata.GDataEntry): """tableId element.""" _tag = 'tableId' _namespace = GAN_NAMESPACE class Property(gdata.GDataEntry): _tag = 'property' _namespace = GAN_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _attributes['name'] = 'name' _attributes['value'] = 'value' def __init__(self, name=None, value=None, *args, **kwargs): self.name = name self.value = value super(Property, self).__init__(*args, **kwargs) def __str__(self): return self.value def __repr__(self): return self.value class AccountListEntry(gdata.GDataEntry): """The Google Documents version of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}tableId' % GAN_NAMESPACE] = ('tableId', [TableId]) _children['{%s}property' % GAN_NAMESPACE] = ('property', [Property]) def __init__(self, tableId=None, property=None, *args, **kwargs): self.tableId = tableId self.property = property super(AccountListEntry, self).__init__(*args, **kwargs) def AccountListEntryFromString(xml_string): """Converts an XML string into an AccountListEntry object. Args: xml_string: string The XML describing a Document List feed entry. Returns: A AccountListEntry object corresponding to the given XML. """ return atom.CreateClassFromXMLString(AccountListEntry, xml_string) class AccountListFeed(gdata.GDataFeed): """A feed containing a list of Google Documents Items""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [AccountListEntry]) def AccountListFeedFromString(xml_string): """Converts an XML string into an AccountListFeed object. Args: xml_string: string The XML describing an AccountList feed. Returns: An AccountListFeed object corresponding to the given XML. All properties are also linked to with a direct reference from each entry object for convenience. (e.g. entry.AccountName) """ feed = atom.CreateClassFromXMLString(AccountListFeed, xml_string) for entry in feed.entry: for pro in entry.property: entry.__dict__[pro.name.replace('ga:','')] = pro for td in entry.tableId: td.__dict__['value'] = td.text return feed class Dimension(gdata.GDataEntry): _tag = 'dimension' _namespace = GAN_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _attributes['name'] = 'name' _attributes['value'] = 'value' _attributes['type'] = 'type' _attributes['confidenceInterval'] = 'confidence_interval' def __init__(self, name=None, value=None, type=None, confidence_interval = None, *args, **kwargs): self.name = name self.value = value self.type = type self.confidence_interval = confidence_interval super(Dimension, self).__init__(*args, **kwargs) def __str__(self): return self.value def __repr__(self): return self.value class Metric(gdata.GDataEntry): _tag = 'metric' _namespace = GAN_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _attributes['name'] = 'name' _attributes['value'] = 'value' _attributes['type'] = 'type' _attributes['confidenceInterval'] = 'confidence_interval' def __init__(self, name=None, value=None, type=None, confidence_interval = None, *args, **kwargs): self.name = name self.value = value self.type = type self.confidence_interval = confidence_interval super(Metric, self).__init__(*args, **kwargs) def __str__(self): return self.value def __repr__(self): return self.value class AnalyticsDataEntry(gdata.GDataEntry): """The Google Analytics version of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}dimension' % GAN_NAMESPACE] = ('dimension', [Dimension]) _children['{%s}metric' % GAN_NAMESPACE] = ('metric', [Metric]) def __init__(self, dimension=None, metric=None, *args, **kwargs): self.dimension = dimension self.metric = metric super(AnalyticsDataEntry, self).__init__(*args, **kwargs) class AnalyticsDataFeed(gdata.GDataFeed): """A feed containing a list of Google Analytics Data Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [AnalyticsDataEntry]) """ Data Feed """ def AnalyticsDataFeedFromString(xml_string): """Converts an XML string into an AccountListFeed object. Args: xml_string: string The XML describing an AccountList feed. Returns: An AccountListFeed object corresponding to the given XML. Each metric and dimension is also referenced directly from the entry for easier access. (e.g. entry.keyword.value) """ feed = atom.CreateClassFromXMLString(AnalyticsDataFeed, xml_string) if feed.entry: for entry in feed.entry: for met in entry.metric: entry.__dict__[met.name.replace('ga:','')] = met if entry.dimension is not None: for dim in entry.dimension: entry.__dict__[dim.name.replace('ga:','')] = dim return feed
Python
"""TLS Lite + xmlrpclib.""" import xmlrpclib import httplib from gdata.tlslite.integration.HTTPTLSConnection import HTTPTLSConnection from gdata.tlslite.integration.ClientHelper import ClientHelper class XMLRPCTransport(xmlrpclib.Transport, ClientHelper): """Handles an HTTPS transaction to an XML-RPC server.""" def __init__(self, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings=None): """Create a new XMLRPCTransport. An instance of this class can be passed to L{xmlrpclib.ServerProxy} to use TLS with XML-RPC calls:: from tlslite.api import XMLRPCTransport from xmlrpclib import ServerProxy transport = XMLRPCTransport(user="alice", password="abra123") server = ServerProxy("https://localhost", transport) For client authentication, use one of these argument combinations: - username, password (SRP) - username, sharedKey (shared-key) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP or shared-keys, or you can do certificate-based server authentication with one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) Certificate-based server authentication is compatible with SRP or certificate-based client authentication. It is not compatible with shared-keys. The constructor does not perform the TLS handshake itself, but simply stores these arguments for later. The handshake is performed only when this class needs to connect with the server. Thus you should be prepared to handle TLS-specific exceptions when calling methods of L{xmlrpclib.ServerProxy}. See the client handshake functions in L{tlslite.TLSConnection.TLSConnection} for details on which exceptions might be raised. @type username: str @param username: SRP or shared-key username. Requires the 'password' or 'sharedKey' argument. @type password: str @param password: SRP password for mutual authentication. Requires the 'username' argument. @type sharedKey: str @param sharedKey: Shared key for mutual authentication. Requires the 'username' argument. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes the SRP or shared-key related arguments. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: Private key for client authentication. Requires the 'certChain' argument. Excludes the SRP or shared-key related arguments. @type cryptoID: str @param cryptoID: cryptoID for server authentication. Mutually exclusive with the 'x509...' arguments. @type protocol: str @param protocol: cryptoID protocol URI for server authentication. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: Hex-encoded X.509 fingerprint for server authentication. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed to use this parameter. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. """ ClientHelper.__init__(self, username, password, sharedKey, certChain, privateKey, cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName, settings) def make_connection(self, host): # create a HTTPS connection object from a host descriptor host, extra_headers, x509 = self.get_host_info(host) http = HTTPTLSConnection(host, None, self.username, self.password, self.sharedKey, self.certChain, self.privateKey, self.checker.cryptoID, self.checker.protocol, self.checker.x509Fingerprint, self.checker.x509TrustList, self.checker.x509CommonName, self.settings) http2 = httplib.HTTP() http2._setup(http) return http2
Python
"""TLS Lite + imaplib.""" import socket from imaplib import IMAP4 from gdata.tlslite.TLSConnection import TLSConnection from gdata.tlslite.integration.ClientHelper import ClientHelper # IMAP TLS PORT IMAP4_TLS_PORT = 993 class IMAP4_TLS(IMAP4, ClientHelper): """This class extends L{imaplib.IMAP4} with TLS support.""" def __init__(self, host = '', port = IMAP4_TLS_PORT, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings=None): """Create a new IMAP4_TLS. For client authentication, use one of these argument combinations: - username, password (SRP) - username, sharedKey (shared-key) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP or shared-keys, or you can do certificate-based server authentication with one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) Certificate-based server authentication is compatible with SRP or certificate-based client authentication. It is not compatible with shared-keys. The caller should be prepared to handle TLS-specific exceptions. See the client handshake functions in L{tlslite.TLSConnection.TLSConnection} for details on which exceptions might be raised. @type host: str @param host: Server to connect to. @type port: int @param port: Port to connect to. @type username: str @param username: SRP or shared-key username. Requires the 'password' or 'sharedKey' argument. @type password: str @param password: SRP password for mutual authentication. Requires the 'username' argument. @type sharedKey: str @param sharedKey: Shared key for mutual authentication. Requires the 'username' argument. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes the SRP or shared-key related arguments. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: Private key for client authentication. Requires the 'certChain' argument. Excludes the SRP or shared-key related arguments. @type cryptoID: str @param cryptoID: cryptoID for server authentication. Mutually exclusive with the 'x509...' arguments. @type protocol: str @param protocol: cryptoID protocol URI for server authentication. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: Hex-encoded X.509 fingerprint for server authentication. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed to use this parameter. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. """ ClientHelper.__init__(self, username, password, sharedKey, certChain, privateKey, cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName, settings) IMAP4.__init__(self, host, port) def open(self, host = '', port = IMAP4_TLS_PORT): """Setup connection to remote server on "host:port". This connection will be used by the routines: read, readline, send, shutdown. """ self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, port)) self.sock = TLSConnection(self.sock) self.sock.closeSocket = True ClientHelper._handshake(self, self.sock) self.file = self.sock.makefile('rb')
Python
class IntegrationHelper: def __init__(self, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings = None): self.username = None self.password = None self.sharedKey = None self.certChain = None self.privateKey = None self.checker = None #SRP Authentication if username and password and not \ (sharedKey or certChain or privateKey): self.username = username self.password = password #Shared Key Authentication elif username and sharedKey and not \ (password or certChain or privateKey): self.username = username self.sharedKey = sharedKey #Certificate Chain Authentication elif certChain and privateKey and not \ (username or password or sharedKey): self.certChain = certChain self.privateKey = privateKey #No Authentication elif not password and not username and not \ sharedKey and not certChain and not privateKey: pass else: raise ValueError("Bad parameters") #Authenticate the server based on its cryptoID or fingerprint if sharedKey and (cryptoID or protocol or x509Fingerprint): raise ValueError("Can't use shared keys with other forms of"\ "authentication") self.checker = Checker(cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName) self.settings = settings
Python
"""TLS Lite + poplib.""" import socket from poplib import POP3 from gdata.tlslite.TLSConnection import TLSConnection from gdata.tlslite.integration.ClientHelper import ClientHelper # POP TLS PORT POP3_TLS_PORT = 995 class POP3_TLS(POP3, ClientHelper): """This class extends L{poplib.POP3} with TLS support.""" def __init__(self, host, port = POP3_TLS_PORT, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings=None): """Create a new POP3_TLS. For client authentication, use one of these argument combinations: - username, password (SRP) - username, sharedKey (shared-key) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP or shared-keys, or you can do certificate-based server authentication with one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) Certificate-based server authentication is compatible with SRP or certificate-based client authentication. It is not compatible with shared-keys. The caller should be prepared to handle TLS-specific exceptions. See the client handshake functions in L{tlslite.TLSConnection.TLSConnection} for details on which exceptions might be raised. @type host: str @param host: Server to connect to. @type port: int @param port: Port to connect to. @type username: str @param username: SRP or shared-key username. Requires the 'password' or 'sharedKey' argument. @type password: str @param password: SRP password for mutual authentication. Requires the 'username' argument. @type sharedKey: str @param sharedKey: Shared key for mutual authentication. Requires the 'username' argument. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes the SRP or shared-key related arguments. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: Private key for client authentication. Requires the 'certChain' argument. Excludes the SRP or shared-key related arguments. @type cryptoID: str @param cryptoID: cryptoID for server authentication. Mutually exclusive with the 'x509...' arguments. @type protocol: str @param protocol: cryptoID protocol URI for server authentication. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: Hex-encoded X.509 fingerprint for server authentication. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed to use this parameter. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. """ self.host = host self.port = port msg = "getaddrinfo returns an empty list" self.sock = None for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) except socket.error, msg: if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg ### New code below (all else copied from poplib) ClientHelper.__init__(self, username, password, sharedKey, certChain, privateKey, cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName, settings) self.sock = TLSConnection(self.sock) self.sock.closeSocket = True ClientHelper._handshake(self, self.sock) ### self.file = self.sock.makefile('rb') self._debugging = 0 self.welcome = self._getresp()
Python
"""TLS Lite + Twisted.""" from twisted.protocols.policies import ProtocolWrapper, WrappingFactory from twisted.python.failure import Failure from AsyncStateMachine import AsyncStateMachine from gdata.tlslite.TLSConnection import TLSConnection from gdata.tlslite.errors import * import socket import errno #The TLSConnection is created around a "fake socket" that #plugs it into the underlying Twisted transport class _FakeSocket: def __init__(self, wrapper): self.wrapper = wrapper self.data = "" def send(self, data): ProtocolWrapper.write(self.wrapper, data) return len(data) def recv(self, numBytes): if self.data == "": raise socket.error, (errno.EWOULDBLOCK, "") returnData = self.data[:numBytes] self.data = self.data[numBytes:] return returnData class TLSTwistedProtocolWrapper(ProtocolWrapper, AsyncStateMachine): """This class can wrap Twisted protocols to add TLS support. Below is a complete example of using TLS Lite with a Twisted echo server. There are two server implementations below. Echo is the original protocol, which is oblivious to TLS. Echo1 subclasses Echo and negotiates TLS when the client connects. Echo2 subclasses Echo and negotiates TLS when the client sends "STARTTLS":: from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor from twisted.protocols.policies import WrappingFactory from twisted.protocols.basic import LineReceiver from twisted.python import log from twisted.python.failure import Failure import sys from tlslite.api import * s = open("./serverX509Cert.pem").read() x509 = X509() x509.parse(s) certChain = X509CertChain([x509]) s = open("./serverX509Key.pem").read() privateKey = parsePEMKey(s, private=True) verifierDB = VerifierDB("verifierDB") verifierDB.open() class Echo(LineReceiver): def connectionMade(self): self.transport.write("Welcome to the echo server!\\r\\n") def lineReceived(self, line): self.transport.write(line + "\\r\\n") class Echo1(Echo): def connectionMade(self): if not self.transport.tlsStarted: self.transport.setServerHandshakeOp(certChain=certChain, privateKey=privateKey, verifierDB=verifierDB) else: Echo.connectionMade(self) def connectionLost(self, reason): pass #Handle any TLS exceptions here class Echo2(Echo): def lineReceived(self, data): if data == "STARTTLS": self.transport.setServerHandshakeOp(certChain=certChain, privateKey=privateKey, verifierDB=verifierDB) else: Echo.lineReceived(self, data) def connectionLost(self, reason): pass #Handle any TLS exceptions here factory = Factory() factory.protocol = Echo1 #factory.protocol = Echo2 wrappingFactory = WrappingFactory(factory) wrappingFactory.protocol = TLSTwistedProtocolWrapper log.startLogging(sys.stdout) reactor.listenTCP(1079, wrappingFactory) reactor.run() This class works as follows: Data comes in and is given to the AsyncStateMachine for handling. AsyncStateMachine will forward events to this class, and we'll pass them on to the ProtocolHandler, which will proxy them to the wrapped protocol. The wrapped protocol may then call back into this class, and these calls will be proxied into the AsyncStateMachine. The call graph looks like this: - self.dataReceived - AsyncStateMachine.inReadEvent - self.out(Connect|Close|Read)Event - ProtocolWrapper.(connectionMade|loseConnection|dataReceived) - self.(loseConnection|write|writeSequence) - AsyncStateMachine.(setCloseOp|setWriteOp) """ #WARNING: IF YOU COPY-AND-PASTE THE ABOVE CODE, BE SURE TO REMOVE #THE EXTRA ESCAPING AROUND "\\r\\n" def __init__(self, factory, wrappedProtocol): ProtocolWrapper.__init__(self, factory, wrappedProtocol) AsyncStateMachine.__init__(self) self.fakeSocket = _FakeSocket(self) self.tlsConnection = TLSConnection(self.fakeSocket) self.tlsStarted = False self.connectionLostCalled = False def connectionMade(self): try: ProtocolWrapper.connectionMade(self) except TLSError, e: self.connectionLost(Failure(e)) ProtocolWrapper.loseConnection(self) def dataReceived(self, data): try: if not self.tlsStarted: ProtocolWrapper.dataReceived(self, data) else: self.fakeSocket.data += data while self.fakeSocket.data: AsyncStateMachine.inReadEvent(self) except TLSError, e: self.connectionLost(Failure(e)) ProtocolWrapper.loseConnection(self) def connectionLost(self, reason): if not self.connectionLostCalled: ProtocolWrapper.connectionLost(self, reason) self.connectionLostCalled = True def outConnectEvent(self): ProtocolWrapper.connectionMade(self) def outCloseEvent(self): ProtocolWrapper.loseConnection(self) def outReadEvent(self, data): if data == "": ProtocolWrapper.loseConnection(self) else: ProtocolWrapper.dataReceived(self, data) def setServerHandshakeOp(self, **args): self.tlsStarted = True AsyncStateMachine.setServerHandshakeOp(self, **args) def loseConnection(self): if not self.tlsStarted: ProtocolWrapper.loseConnection(self) else: AsyncStateMachine.setCloseOp(self) def write(self, data): if not self.tlsStarted: ProtocolWrapper.write(self, data) else: #Because of the FakeSocket, write operations are guaranteed to #terminate immediately. AsyncStateMachine.setWriteOp(self, data) def writeSequence(self, seq): if not self.tlsStarted: ProtocolWrapper.writeSequence(self, seq) else: #Because of the FakeSocket, write operations are guaranteed to #terminate immediately. AsyncStateMachine.setWriteOp(self, "".join(seq))
Python
"""TLS Lite + asyncore.""" import asyncore from gdata.tlslite.TLSConnection import TLSConnection from AsyncStateMachine import AsyncStateMachine class TLSAsyncDispatcherMixIn(AsyncStateMachine): """This class can be "mixed in" with an L{asyncore.dispatcher} to add TLS support. This class essentially sits between the dispatcher and the select loop, intercepting events and only calling the dispatcher when applicable. In the case of handle_read(), a read operation will be activated, and when it completes, the bytes will be placed in a buffer where the dispatcher can retrieve them by calling recv(), and the dispatcher's handle_read() will be called. In the case of handle_write(), the dispatcher's handle_write() will be called, and when it calls send(), a write operation will be activated. To use this class, you must combine it with an asyncore.dispatcher, and pass in a handshake operation with setServerHandshakeOp(). Below is an example of using this class with medusa. This class is mixed in with http_channel to create http_tls_channel. Note: 1. the mix-in is listed first in the inheritance list 2. the input buffer size must be at least 16K, otherwise the dispatcher might not read all the bytes from the TLS layer, leaving some bytes in limbo. 3. IE seems to have a problem receiving a whole HTTP response in a single TLS record, so HTML pages containing '\\r\\n\\r\\n' won't be displayed on IE. Add the following text into 'start_medusa.py', in the 'HTTP Server' section:: from tlslite.api import * s = open("./serverX509Cert.pem").read() x509 = X509() x509.parse(s) certChain = X509CertChain([x509]) s = open("./serverX509Key.pem").read() privateKey = parsePEMKey(s, private=True) class http_tls_channel(TLSAsyncDispatcherMixIn, http_server.http_channel): ac_in_buffer_size = 16384 def __init__ (self, server, conn, addr): http_server.http_channel.__init__(self, server, conn, addr) TLSAsyncDispatcherMixIn.__init__(self, conn) self.tlsConnection.ignoreAbruptClose = True self.setServerHandshakeOp(certChain=certChain, privateKey=privateKey) hs.channel_class = http_tls_channel If the TLS layer raises an exception, the exception will be caught in asyncore.dispatcher, which will call close() on this class. The TLS layer always closes the TLS connection before raising an exception, so the close operation will complete right away, causing asyncore.dispatcher.close() to be called, which closes the socket and removes this instance from the asyncore loop. """ def __init__(self, sock=None): AsyncStateMachine.__init__(self) if sock: self.tlsConnection = TLSConnection(sock) #Calculate the sibling I'm being mixed in with. #This is necessary since we override functions #like readable(), handle_read(), etc., but we #also want to call the sibling's versions. for cl in self.__class__.__bases__: if cl != TLSAsyncDispatcherMixIn and cl != AsyncStateMachine: self.siblingClass = cl break else: raise AssertionError() def readable(self): result = self.wantsReadEvent() if result != None: return result return self.siblingClass.readable(self) def writable(self): result = self.wantsWriteEvent() if result != None: return result return self.siblingClass.writable(self) def handle_read(self): self.inReadEvent() def handle_write(self): self.inWriteEvent() def outConnectEvent(self): self.siblingClass.handle_connect(self) def outCloseEvent(self): asyncore.dispatcher.close(self) def outReadEvent(self, readBuffer): self.readBuffer = readBuffer self.siblingClass.handle_read(self) def outWriteEvent(self): self.siblingClass.handle_write(self) def recv(self, bufferSize=16384): if bufferSize < 16384 or self.readBuffer == None: raise AssertionError() returnValue = self.readBuffer self.readBuffer = None return returnValue def send(self, writeBuffer): self.setWriteOp(writeBuffer) return len(writeBuffer) def close(self): if hasattr(self, "tlsConnection"): self.setCloseOp() else: asyncore.dispatcher.close(self)
Python
"""TLS Lite + SocketServer.""" from gdata.tlslite.TLSConnection import TLSConnection class TLSSocketServerMixIn: """ This class can be mixed in with any L{SocketServer.TCPServer} to add TLS support. To use this class, define a new class that inherits from it and some L{SocketServer.TCPServer} (with the mix-in first). Then implement the handshake() method, doing some sort of server handshake on the connection argument. If the handshake method returns True, the RequestHandler will be triggered. Below is a complete example of a threaded HTTPS server:: from SocketServer import * from BaseHTTPServer import * from SimpleHTTPServer import * from tlslite.api import * s = open("./serverX509Cert.pem").read() x509 = X509() x509.parse(s) certChain = X509CertChain([x509]) s = open("./serverX509Key.pem").read() privateKey = parsePEMKey(s, private=True) sessionCache = SessionCache() class MyHTTPServer(ThreadingMixIn, TLSSocketServerMixIn, HTTPServer): def handshake(self, tlsConnection): try: tlsConnection.handshakeServer(certChain=certChain, privateKey=privateKey, sessionCache=sessionCache) tlsConnection.ignoreAbruptClose = True return True except TLSError, error: print "Handshake failure:", str(error) return False httpd = MyHTTPServer(('localhost', 443), SimpleHTTPRequestHandler) httpd.serve_forever() """ def finish_request(self, sock, client_address): tlsConnection = TLSConnection(sock) if self.handshake(tlsConnection) == True: self.RequestHandlerClass(tlsConnection, client_address, self) tlsConnection.close() #Implement this method to do some form of handshaking. Return True #if the handshake finishes properly and the request is authorized. def handshake(self, tlsConnection): raise NotImplementedError()
Python
"""TLS Lite + smtplib.""" from smtplib import SMTP from gdata.tlslite.TLSConnection import TLSConnection from gdata.tlslite.integration.ClientHelper import ClientHelper class SMTP_TLS(SMTP): """This class extends L{smtplib.SMTP} with TLS support.""" def starttls(self, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings=None): """Puts the connection to the SMTP server into TLS mode. If the server supports TLS, this will encrypt the rest of the SMTP session. For client authentication, use one of these argument combinations: - username, password (SRP) - username, sharedKey (shared-key) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP or shared-keys, or you can do certificate-based server authentication with one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) Certificate-based server authentication is compatible with SRP or certificate-based client authentication. It is not compatible with shared-keys. The caller should be prepared to handle TLS-specific exceptions. See the client handshake functions in L{tlslite.TLSConnection.TLSConnection} for details on which exceptions might be raised. @type username: str @param username: SRP or shared-key username. Requires the 'password' or 'sharedKey' argument. @type password: str @param password: SRP password for mutual authentication. Requires the 'username' argument. @type sharedKey: str @param sharedKey: Shared key for mutual authentication. Requires the 'username' argument. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes the SRP or shared-key related arguments. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: Private key for client authentication. Requires the 'certChain' argument. Excludes the SRP or shared-key related arguments. @type cryptoID: str @param cryptoID: cryptoID for server authentication. Mutually exclusive with the 'x509...' arguments. @type protocol: str @param protocol: cryptoID protocol URI for server authentication. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: Hex-encoded X.509 fingerprint for server authentication. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed to use this parameter. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. """ (resp, reply) = self.docmd("STARTTLS") if resp == 220: helper = ClientHelper( username, password, sharedKey, certChain, privateKey, cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName, settings) conn = TLSConnection(self.sock) conn.closeSocket = True helper._handshake(conn) self.sock = conn self.file = conn.makefile('rb') return (resp, reply)
Python
"""TLS Lite + httplib.""" import socket import httplib from gdata.tlslite.TLSConnection import TLSConnection from gdata.tlslite.integration.ClientHelper import ClientHelper class HTTPBaseTLSConnection(httplib.HTTPConnection): """This abstract class provides a framework for adding TLS support to httplib.""" default_port = 443 def __init__(self, host, port=None, strict=None): if strict == None: #Python 2.2 doesn't support strict httplib.HTTPConnection.__init__(self, host, port) else: httplib.HTTPConnection.__init__(self, host, port, strict) def connect(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if hasattr(sock, 'settimeout'): sock.settimeout(10) sock.connect((self.host, self.port)) #Use a TLSConnection to emulate a socket self.sock = TLSConnection(sock) #When httplib closes this, close the socket self.sock.closeSocket = True self._handshake(self.sock) def _handshake(self, tlsConnection): """Called to perform some sort of handshake. This method must be overridden in a subclass to do some type of handshake. This method will be called after the socket has been connected but before any data has been sent. If this method does not raise an exception, the TLS connection will be considered valid. This method may (or may not) be called every time an HTTP request is performed, depending on whether the underlying HTTP connection is persistent. @type tlsConnection: L{tlslite.TLSConnection.TLSConnection} @param tlsConnection: The connection to perform the handshake on. """ raise NotImplementedError() class HTTPTLSConnection(HTTPBaseTLSConnection, ClientHelper): """This class extends L{HTTPBaseTLSConnection} to support the common types of handshaking.""" def __init__(self, host, port=None, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings = None): """Create a new HTTPTLSConnection. For client authentication, use one of these argument combinations: - username, password (SRP) - username, sharedKey (shared-key) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP or shared-keys, or you can do certificate-based server authentication with one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) Certificate-based server authentication is compatible with SRP or certificate-based client authentication. It is not compatible with shared-keys. The constructor does not perform the TLS handshake itself, but simply stores these arguments for later. The handshake is performed only when this class needs to connect with the server. Thus you should be prepared to handle TLS-specific exceptions when calling methods inherited from L{httplib.HTTPConnection} such as request(), connect(), and send(). See the client handshake functions in L{tlslite.TLSConnection.TLSConnection} for details on which exceptions might be raised. @type host: str @param host: Server to connect to. @type port: int @param port: Port to connect to. @type username: str @param username: SRP or shared-key username. Requires the 'password' or 'sharedKey' argument. @type password: str @param password: SRP password for mutual authentication. Requires the 'username' argument. @type sharedKey: str @param sharedKey: Shared key for mutual authentication. Requires the 'username' argument. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes the SRP or shared-key related arguments. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: Private key for client authentication. Requires the 'certChain' argument. Excludes the SRP or shared-key related arguments. @type cryptoID: str @param cryptoID: cryptoID for server authentication. Mutually exclusive with the 'x509...' arguments. @type protocol: str @param protocol: cryptoID protocol URI for server authentication. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: Hex-encoded X.509 fingerprint for server authentication. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed to use this parameter. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. """ HTTPBaseTLSConnection.__init__(self, host, port) ClientHelper.__init__(self, username, password, sharedKey, certChain, privateKey, cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName, settings) def _handshake(self, tlsConnection): ClientHelper._handshake(self, tlsConnection)
Python
"""Classes for integrating TLS Lite with other packages.""" __all__ = ["AsyncStateMachine", "HTTPTLSConnection", "POP3_TLS", "IMAP4_TLS", "SMTP_TLS", "XMLRPCTransport", "TLSSocketServerMixIn", "TLSAsyncDispatcherMixIn", "TLSTwistedProtocolWrapper"] try: import twisted del twisted except ImportError: del __all__[__all__.index("TLSTwistedProtocolWrapper")]
Python
""" A state machine for using TLS Lite with asynchronous I/O. """ class AsyncStateMachine: """ This is an abstract class that's used to integrate TLS Lite with asyncore and Twisted. This class signals wantsReadsEvent() and wantsWriteEvent(). When the underlying socket has become readable or writeable, the event should be passed to this class by calling inReadEvent() or inWriteEvent(). This class will then try to read or write through the socket, and will update its state appropriately. This class will forward higher-level events to its subclass. For example, when a complete TLS record has been received, outReadEvent() will be called with the decrypted data. """ def __init__(self): self._clear() def _clear(self): #These store the various asynchronous operations (i.e. #generators). Only one of them, at most, is ever active at a #time. self.handshaker = None self.closer = None self.reader = None self.writer = None #This stores the result from the last call to the #currently active operation. If 0 it indicates that the #operation wants to read, if 1 it indicates that the #operation wants to write. If None, there is no active #operation. self.result = None def _checkAssert(self, maxActive=1): #This checks that only one operation, at most, is #active, and that self.result is set appropriately. activeOps = 0 if self.handshaker: activeOps += 1 if self.closer: activeOps += 1 if self.reader: activeOps += 1 if self.writer: activeOps += 1 if self.result == None: if activeOps != 0: raise AssertionError() elif self.result in (0,1): if activeOps != 1: raise AssertionError() else: raise AssertionError() if activeOps > maxActive: raise AssertionError() def wantsReadEvent(self): """If the state machine wants to read. If an operation is active, this returns whether or not the operation wants to read from the socket. If an operation is not active, this returns None. @rtype: bool or None @return: If the state machine wants to read. """ if self.result != None: return self.result == 0 return None def wantsWriteEvent(self): """If the state machine wants to write. If an operation is active, this returns whether or not the operation wants to write to the socket. If an operation is not active, this returns None. @rtype: bool or None @return: If the state machine wants to write. """ if self.result != None: return self.result == 1 return None def outConnectEvent(self): """Called when a handshake operation completes. May be overridden in subclass. """ pass def outCloseEvent(self): """Called when a close operation completes. May be overridden in subclass. """ pass def outReadEvent(self, readBuffer): """Called when a read operation completes. May be overridden in subclass.""" pass def outWriteEvent(self): """Called when a write operation completes. May be overridden in subclass.""" pass def inReadEvent(self): """Tell the state machine it can read from the socket.""" try: self._checkAssert() if self.handshaker: self._doHandshakeOp() elif self.closer: self._doCloseOp() elif self.reader: self._doReadOp() elif self.writer: self._doWriteOp() else: self.reader = self.tlsConnection.readAsync(16384) self._doReadOp() except: self._clear() raise def inWriteEvent(self): """Tell the state machine it can write to the socket.""" try: self._checkAssert() if self.handshaker: self._doHandshakeOp() elif self.closer: self._doCloseOp() elif self.reader: self._doReadOp() elif self.writer: self._doWriteOp() else: self.outWriteEvent() except: self._clear() raise def _doHandshakeOp(self): try: self.result = self.handshaker.next() except StopIteration: self.handshaker = None self.result = None self.outConnectEvent() def _doCloseOp(self): try: self.result = self.closer.next() except StopIteration: self.closer = None self.result = None self.outCloseEvent() def _doReadOp(self): self.result = self.reader.next() if not self.result in (0,1): readBuffer = self.result self.reader = None self.result = None self.outReadEvent(readBuffer) def _doWriteOp(self): try: self.result = self.writer.next() except StopIteration: self.writer = None self.result = None def setHandshakeOp(self, handshaker): """Start a handshake operation. @type handshaker: generator @param handshaker: A generator created by using one of the asynchronous handshake functions (i.e. handshakeServerAsync, or handshakeClientxxx(..., async=True). """ try: self._checkAssert(0) self.handshaker = handshaker self._doHandshakeOp() except: self._clear() raise def setServerHandshakeOp(self, **args): """Start a handshake operation. The arguments passed to this function will be forwarded to L{tlslite.TLSConnection.TLSConnection.handshakeServerAsync}. """ handshaker = self.tlsConnection.handshakeServerAsync(**args) self.setHandshakeOp(handshaker) def setCloseOp(self): """Start a close operation. """ try: self._checkAssert(0) self.closer = self.tlsConnection.closeAsync() self._doCloseOp() except: self._clear() raise def setWriteOp(self, writeBuffer): """Start a write operation. @type writeBuffer: str @param writeBuffer: The string to transmit. """ try: self._checkAssert(0) self.writer = self.tlsConnection.writeAsync(writeBuffer) self._doWriteOp() except: self._clear() raise
Python
""" A helper class for using TLS Lite with stdlib clients (httplib, xmlrpclib, imaplib, poplib). """ from gdata.tlslite.Checker import Checker class ClientHelper: """This is a helper class used to integrate TLS Lite with various TLS clients (e.g. poplib, smtplib, httplib, etc.)""" def __init__(self, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings = None): """ For client authentication, use one of these argument combinations: - username, password (SRP) - username, sharedKey (shared-key) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP or shared-keys, or you can do certificate-based server authentication with one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) Certificate-based server authentication is compatible with SRP or certificate-based client authentication. It is not compatible with shared-keys. The constructor does not perform the TLS handshake itself, but simply stores these arguments for later. The handshake is performed only when this class needs to connect with the server. Then you should be prepared to handle TLS-specific exceptions. See the client handshake functions in L{tlslite.TLSConnection.TLSConnection} for details on which exceptions might be raised. @type username: str @param username: SRP or shared-key username. Requires the 'password' or 'sharedKey' argument. @type password: str @param password: SRP password for mutual authentication. Requires the 'username' argument. @type sharedKey: str @param sharedKey: Shared key for mutual authentication. Requires the 'username' argument. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes the SRP or shared-key related arguments. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: Private key for client authentication. Requires the 'certChain' argument. Excludes the SRP or shared-key related arguments. @type cryptoID: str @param cryptoID: cryptoID for server authentication. Mutually exclusive with the 'x509...' arguments. @type protocol: str @param protocol: cryptoID protocol URI for server authentication. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: Hex-encoded X.509 fingerprint for server authentication. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed to use this parameter. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. """ self.username = None self.password = None self.sharedKey = None self.certChain = None self.privateKey = None self.checker = None #SRP Authentication if username and password and not \ (sharedKey or certChain or privateKey): self.username = username self.password = password #Shared Key Authentication elif username and sharedKey and not \ (password or certChain or privateKey): self.username = username self.sharedKey = sharedKey #Certificate Chain Authentication elif certChain and privateKey and not \ (username or password or sharedKey): self.certChain = certChain self.privateKey = privateKey #No Authentication elif not password and not username and not \ sharedKey and not certChain and not privateKey: pass else: raise ValueError("Bad parameters") #Authenticate the server based on its cryptoID or fingerprint if sharedKey and (cryptoID or protocol or x509Fingerprint): raise ValueError("Can't use shared keys with other forms of"\ "authentication") self.checker = Checker(cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName) self.settings = settings self.tlsSession = None def _handshake(self, tlsConnection): if self.username and self.password: tlsConnection.handshakeClientSRP(username=self.username, password=self.password, checker=self.checker, settings=self.settings, session=self.tlsSession) elif self.username and self.sharedKey: tlsConnection.handshakeClientSharedKey(username=self.username, sharedKey=self.sharedKey, settings=self.settings) else: tlsConnection.handshakeClientCert(certChain=self.certChain, privateKey=self.privateKey, checker=self.checker, settings=self.settings, session=self.tlsSession) self.tlsSession = tlsConnection.session
Python
"""Class for caching TLS sessions.""" import thread import time class SessionCache: """This class is used by the server to cache TLS sessions. Caching sessions allows the client to use TLS session resumption and avoid the expense of a full handshake. To use this class, simply pass a SessionCache instance into the server handshake function. This class is thread-safe. """ #References to these instances #are also held by the caller, who may change the 'resumable' #flag, so the SessionCache must return the same instances #it was passed in. def __init__(self, maxEntries=10000, maxAge=14400): """Create a new SessionCache. @type maxEntries: int @param maxEntries: The maximum size of the cache. When this limit is reached, the oldest sessions will be deleted as necessary to make room for new ones. The default is 10000. @type maxAge: int @param maxAge: The number of seconds before a session expires from the cache. The default is 14400 (i.e. 4 hours).""" self.lock = thread.allocate_lock() # Maps sessionIDs to sessions self.entriesDict = {} #Circular list of (sessionID, timestamp) pairs self.entriesList = [(None,None)] * maxEntries self.firstIndex = 0 self.lastIndex = 0 self.maxAge = maxAge def __getitem__(self, sessionID): self.lock.acquire() try: self._purge() #Delete old items, so we're assured of a new one session = self.entriesDict[sessionID] #When we add sessions they're resumable, but it's possible #for the session to be invalidated later on (if a fatal alert #is returned), so we have to check for resumability before #returning the session. if session.valid(): return session else: raise KeyError() finally: self.lock.release() def __setitem__(self, sessionID, session): self.lock.acquire() try: #Add the new element self.entriesDict[sessionID] = session self.entriesList[self.lastIndex] = (sessionID, time.time()) self.lastIndex = (self.lastIndex+1) % len(self.entriesList) #If the cache is full, we delete the oldest element to make an #empty space if self.lastIndex == self.firstIndex: del(self.entriesDict[self.entriesList[self.firstIndex][0]]) self.firstIndex = (self.firstIndex+1) % len(self.entriesList) finally: self.lock.release() #Delete expired items def _purge(self): currentTime = time.time() #Search through the circular list, deleting expired elements until #we reach a non-expired element. Since elements in list are #ordered in time, we can break once we reach the first non-expired #element index = self.firstIndex while index != self.lastIndex: if currentTime - self.entriesList[index][1] > self.maxAge: del(self.entriesDict[self.entriesList[index][0]]) index = (index+1) % len(self.entriesList) else: break self.firstIndex = index def _test(): import doctest, SessionCache return doctest.testmod(SessionCache) if __name__ == "__main__": _test()
Python
"""Class representing a TLS session.""" from utils.compat import * from mathtls import * from constants import * class Session: """ This class represents a TLS session. TLS distinguishes between connections and sessions. A new handshake creates both a connection and a session. Data is transmitted over the connection. The session contains a more permanent record of the handshake. The session can be inspected to determine handshake results. The session can also be used to create a new connection through "session resumption". If the client and server both support this, they can create a new connection based on an old session without the overhead of a full handshake. The session for a L{tlslite.TLSConnection.TLSConnection} can be retrieved from the connection's 'session' attribute. @type srpUsername: str @ivar srpUsername: The client's SRP username (or None). @type sharedKeyUsername: str @ivar sharedKeyUsername: The client's shared-key username (or None). @type clientCertChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @ivar clientCertChain: The client's certificate chain (or None). @type serverCertChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @ivar serverCertChain: The server's certificate chain (or None). """ def __init__(self): self.masterSecret = createByteArraySequence([]) self.sessionID = createByteArraySequence([]) self.cipherSuite = 0 self.srpUsername = None self.sharedKeyUsername = None self.clientCertChain = None self.serverCertChain = None self.resumable = False self.sharedKey = False def _clone(self): other = Session() other.masterSecret = self.masterSecret other.sessionID = self.sessionID other.cipherSuite = self.cipherSuite other.srpUsername = self.srpUsername other.sharedKeyUsername = self.sharedKeyUsername other.clientCertChain = self.clientCertChain other.serverCertChain = self.serverCertChain other.resumable = self.resumable other.sharedKey = self.sharedKey return other def _calcMasterSecret(self, version, premasterSecret, clientRandom, serverRandom): if version == (3,0): self.masterSecret = PRF_SSL(premasterSecret, concatArrays(clientRandom, serverRandom), 48) elif version in ((3,1), (3,2)): self.masterSecret = PRF(premasterSecret, "master secret", concatArrays(clientRandom, serverRandom), 48) else: raise AssertionError() def valid(self): """If this session can be used for session resumption. @rtype: bool @return: If this session can be used for session resumption. """ return self.resumable or self.sharedKey def _setResumable(self, boolean): #Only let it be set if this isn't a shared key if not self.sharedKey: #Only let it be set to True if the sessionID is non-null if (not boolean) or (boolean and self.sessionID): self.resumable = boolean def getCipherName(self): """Get the name of the cipher used with this connection. @rtype: str @return: The name of the cipher used with this connection. Either 'aes128', 'aes256', 'rc4', or '3des'. """ if self.cipherSuite in CipherSuite.aes128Suites: return "aes128" elif self.cipherSuite in CipherSuite.aes256Suites: return "aes256" elif self.cipherSuite in CipherSuite.rc4Suites: return "rc4" elif self.cipherSuite in CipherSuite.tripleDESSuites: return "3des" else: return None def _createSharedKey(self, sharedKeyUsername, sharedKey): if len(sharedKeyUsername)>16: raise ValueError() if len(sharedKey)>47: raise ValueError() self.sharedKeyUsername = sharedKeyUsername self.sessionID = createByteArrayZeros(16) for x in range(len(sharedKeyUsername)): self.sessionID[x] = ord(sharedKeyUsername[x]) premasterSecret = createByteArrayZeros(48) sharedKey = chr(len(sharedKey)) + sharedKey for x in range(48): premasterSecret[x] = ord(sharedKey[x % len(sharedKey)]) self.masterSecret = PRF(premasterSecret, "shared secret", createByteArraySequence([]), 48) self.sharedKey = True return self
Python
""" MAIN CLASS FOR TLS LITE (START HERE!). """ from __future__ import generators import socket from utils.compat import formatExceptionTrace from TLSRecordLayer import TLSRecordLayer from Session import Session from constants import * from utils.cryptomath import getRandomBytes from errors import * from messages import * from mathtls import * from HandshakeSettings import HandshakeSettings class TLSConnection(TLSRecordLayer): """ This class wraps a socket and provides TLS handshaking and data transfer. To use this class, create a new instance, passing a connected socket into the constructor. Then call some handshake function. If the handshake completes without raising an exception, then a TLS connection has been negotiated. You can transfer data over this connection as if it were a socket. This class provides both synchronous and asynchronous versions of its key functions. The synchronous versions should be used when writing single-or multi-threaded code using blocking sockets. The asynchronous versions should be used when performing asynchronous, event-based I/O with non-blocking sockets. Asynchronous I/O is a complicated subject; typically, you should not use the asynchronous functions directly, but should use some framework like asyncore or Twisted which TLS Lite integrates with (see L{tlslite.integration.TLSAsyncDispatcherMixIn.TLSAsyncDispatcherMixIn} or L{tlslite.integration.TLSTwistedProtocolWrapper.TLSTwistedProtocolWrapper}). """ def __init__(self, sock): """Create a new TLSConnection instance. @param sock: The socket data will be transmitted on. The socket should already be connected. It may be in blocking or non-blocking mode. @type sock: L{socket.socket} """ TLSRecordLayer.__init__(self, sock) def handshakeClientSRP(self, username, password, session=None, settings=None, checker=None, async=False): """Perform an SRP handshake in the role of client. This function performs a TLS/SRP handshake. SRP mutually authenticates both parties to each other using only a username and password. This function may also perform a combined SRP and server-certificate handshake, if the server chooses to authenticate itself with a certificate chain in addition to doing SRP. TLS/SRP is non-standard. Most TLS implementations don't support it. See U{http://www.ietf.org/html.charters/tls-charter.html} or U{http://trevp.net/tlssrp/} for the latest information on TLS/SRP. Like any handshake function, this can be called on a closed TLS connection, or on a TLS connection that is already open. If called on an open connection it performs a re-handshake. If the function completes without raising an exception, the TLS connection will be open and available for data transfer. If an exception is raised, the connection will have been automatically closed (if it was ever open). @type username: str @param username: The SRP username. @type password: str @param password: The SRP password. @type session: L{tlslite.Session.Session} @param session: A TLS session to attempt to resume. This session must be an SRP session performed with the same username and password as were passed in. If the resumption does not succeed, a full SRP handshake will be performed. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. @type checker: L{tlslite.Checker.Checker} @param checker: A Checker instance. This instance will be invoked to examine the other party's authentication credentials, if the handshake completes succesfully. @type async: bool @param async: If False, this function will block until the handshake is completed. If True, this function will return a generator. Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or will raise StopIteration if the handshake operation is completed. @rtype: None or an iterable @return: If 'async' is True, a generator object will be returned. @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. @raise tlslite.errors.TLSAuthenticationError: If the checker doesn't like the other party's authentication credentials. """ handshaker = self._handshakeClientAsync(srpParams=(username, password), session=session, settings=settings, checker=checker) if async: return handshaker for result in handshaker: pass def handshakeClientCert(self, certChain=None, privateKey=None, session=None, settings=None, checker=None, async=False): """Perform a certificate-based handshake in the role of client. This function performs an SSL or TLS handshake. The server will authenticate itself using an X.509 or cryptoID certificate chain. If the handshake succeeds, the server's certificate chain will be stored in the session's serverCertChain attribute. Unless a checker object is passed in, this function does no validation or checking of the server's certificate chain. If the server requests client authentication, the client will send the passed-in certificate chain, and use the passed-in private key to authenticate itself. If no certificate chain and private key were passed in, the client will attempt to proceed without client authentication. The server may or may not allow this. Like any handshake function, this can be called on a closed TLS connection, or on a TLS connection that is already open. If called on an open connection it performs a re-handshake. If the function completes without raising an exception, the TLS connection will be open and available for data transfer. If an exception is raised, the connection will have been automatically closed (if it was ever open). @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: The certificate chain to be used if the server requests client authentication. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: The private key to be used if the server requests client authentication. @type session: L{tlslite.Session.Session} @param session: A TLS session to attempt to resume. If the resumption does not succeed, a full handshake will be performed. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. @type checker: L{tlslite.Checker.Checker} @param checker: A Checker instance. This instance will be invoked to examine the other party's authentication credentials, if the handshake completes succesfully. @type async: bool @param async: If False, this function will block until the handshake is completed. If True, this function will return a generator. Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or will raise StopIteration if the handshake operation is completed. @rtype: None or an iterable @return: If 'async' is True, a generator object will be returned. @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. @raise tlslite.errors.TLSAuthenticationError: If the checker doesn't like the other party's authentication credentials. """ handshaker = self._handshakeClientAsync(certParams=(certChain, privateKey), session=session, settings=settings, checker=checker) if async: return handshaker for result in handshaker: pass def handshakeClientUnknown(self, srpCallback=None, certCallback=None, session=None, settings=None, checker=None, async=False): """Perform a to-be-determined type of handshake in the role of client. This function performs an SSL or TLS handshake. If the server requests client certificate authentication, the certCallback will be invoked and should return a (certChain, privateKey) pair. If the callback returns None, the library will attempt to proceed without client authentication. The server may or may not allow this. If the server requests SRP authentication, the srpCallback will be invoked and should return a (username, password) pair. If the callback returns None, the local implementation will signal a user_canceled error alert. After the handshake completes, the client can inspect the connection's session attribute to determine what type of authentication was performed. Like any handshake function, this can be called on a closed TLS connection, or on a TLS connection that is already open. If called on an open connection it performs a re-handshake. If the function completes without raising an exception, the TLS connection will be open and available for data transfer. If an exception is raised, the connection will have been automatically closed (if it was ever open). @type srpCallback: callable @param srpCallback: The callback to be used if the server requests SRP authentication. If None, the client will not offer support for SRP ciphersuites. @type certCallback: callable @param certCallback: The callback to be used if the server requests client certificate authentication. @type session: L{tlslite.Session.Session} @param session: A TLS session to attempt to resume. If the resumption does not succeed, a full handshake will be performed. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. @type checker: L{tlslite.Checker.Checker} @param checker: A Checker instance. This instance will be invoked to examine the other party's authentication credentials, if the handshake completes succesfully. @type async: bool @param async: If False, this function will block until the handshake is completed. If True, this function will return a generator. Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or will raise StopIteration if the handshake operation is completed. @rtype: None or an iterable @return: If 'async' is True, a generator object will be returned. @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. @raise tlslite.errors.TLSAuthenticationError: If the checker doesn't like the other party's authentication credentials. """ handshaker = self._handshakeClientAsync(unknownParams=(srpCallback, certCallback), session=session, settings=settings, checker=checker) if async: return handshaker for result in handshaker: pass def handshakeClientSharedKey(self, username, sharedKey, settings=None, checker=None, async=False): """Perform a shared-key handshake in the role of client. This function performs a shared-key handshake. Using shared symmetric keys of high entropy (128 bits or greater) mutually authenticates both parties to each other. TLS with shared-keys is non-standard. Most TLS implementations don't support it. See U{http://www.ietf.org/html.charters/tls-charter.html} for the latest information on TLS with shared-keys. If the shared-keys Internet-Draft changes or is superceded, TLS Lite will track those changes, so the shared-key support in later versions of TLS Lite may become incompatible with this version. Like any handshake function, this can be called on a closed TLS connection, or on a TLS connection that is already open. If called on an open connection it performs a re-handshake. If the function completes without raising an exception, the TLS connection will be open and available for data transfer. If an exception is raised, the connection will have been automatically closed (if it was ever open). @type username: str @param username: The shared-key username. @type sharedKey: str @param sharedKey: The shared key. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. @type checker: L{tlslite.Checker.Checker} @param checker: A Checker instance. This instance will be invoked to examine the other party's authentication credentials, if the handshake completes succesfully. @type async: bool @param async: If False, this function will block until the handshake is completed. If True, this function will return a generator. Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or will raise StopIteration if the handshake operation is completed. @rtype: None or an iterable @return: If 'async' is True, a generator object will be returned. @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. @raise tlslite.errors.TLSAuthenticationError: If the checker doesn't like the other party's authentication credentials. """ handshaker = self._handshakeClientAsync(sharedKeyParams=(username, sharedKey), settings=settings, checker=checker) if async: return handshaker for result in handshaker: pass def _handshakeClientAsync(self, srpParams=(), certParams=(), unknownParams=(), sharedKeyParams=(), session=None, settings=None, checker=None, recursive=False): handshaker = self._handshakeClientAsyncHelper(srpParams=srpParams, certParams=certParams, unknownParams=unknownParams, sharedKeyParams=sharedKeyParams, session=session, settings=settings, recursive=recursive) for result in self._handshakeWrapperAsync(handshaker, checker): yield result def _handshakeClientAsyncHelper(self, srpParams, certParams, unknownParams, sharedKeyParams, session, settings, recursive): if not recursive: self._handshakeStart(client=True) #Unpack parameters srpUsername = None # srpParams password = None # srpParams clientCertChain = None # certParams privateKey = None # certParams srpCallback = None # unknownParams certCallback = None # unknownParams #session # sharedKeyParams (or session) #settings # settings if srpParams: srpUsername, password = srpParams elif certParams: clientCertChain, privateKey = certParams elif unknownParams: srpCallback, certCallback = unknownParams elif sharedKeyParams: session = Session()._createSharedKey(*sharedKeyParams) if not settings: settings = HandshakeSettings() settings = settings._filter() #Validate parameters if srpUsername and not password: raise ValueError("Caller passed a username but no password") if password and not srpUsername: raise ValueError("Caller passed a password but no username") if clientCertChain and not privateKey: raise ValueError("Caller passed a certChain but no privateKey") if privateKey and not clientCertChain: raise ValueError("Caller passed a privateKey but no certChain") if clientCertChain: foundType = False try: import cryptoIDlib.CertChain if isinstance(clientCertChain, cryptoIDlib.CertChain.CertChain): if "cryptoID" not in settings.certificateTypes: raise ValueError("Client certificate doesn't "\ "match Handshake Settings") settings.certificateTypes = ["cryptoID"] foundType = True except ImportError: pass if not foundType and isinstance(clientCertChain, X509CertChain): if "x509" not in settings.certificateTypes: raise ValueError("Client certificate doesn't match "\ "Handshake Settings") settings.certificateTypes = ["x509"] foundType = True if not foundType: raise ValueError("Unrecognized certificate type") if session: if not session.valid(): session = None #ignore non-resumable sessions... elif session.resumable and \ (session.srpUsername != srpUsername): raise ValueError("Session username doesn't match") #Add Faults to parameters if srpUsername and self.fault == Fault.badUsername: srpUsername += "GARBAGE" if password and self.fault == Fault.badPassword: password += "GARBAGE" if sharedKeyParams: identifier = sharedKeyParams[0] sharedKey = sharedKeyParams[1] if self.fault == Fault.badIdentifier: identifier += "GARBAGE" session = Session()._createSharedKey(identifier, sharedKey) elif self.fault == Fault.badSharedKey: sharedKey += "GARBAGE" session = Session()._createSharedKey(identifier, sharedKey) #Initialize locals serverCertChain = None cipherSuite = 0 certificateType = CertificateType.x509 premasterSecret = None #Get client nonce clientRandom = getRandomBytes(32) #Initialize acceptable ciphersuites cipherSuites = [] if srpParams: cipherSuites += CipherSuite.getSrpRsaSuites(settings.cipherNames) cipherSuites += CipherSuite.getSrpSuites(settings.cipherNames) elif certParams: cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames) elif unknownParams: if srpCallback: cipherSuites += \ CipherSuite.getSrpRsaSuites(settings.cipherNames) cipherSuites += \ CipherSuite.getSrpSuites(settings.cipherNames) cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames) elif sharedKeyParams: cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames) else: cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames) #Initialize acceptable certificate types certificateTypes = settings._getCertificateTypes() #Tentatively set the version to the client's minimum version. #We'll use this for the ClientHello, and if an error occurs #parsing the Server Hello, we'll use this version for the response self.version = settings.maxVersion #Either send ClientHello (with a resumable session)... if session: #If it's a resumable (i.e. not a shared-key session), then its #ciphersuite must be one of the acceptable ciphersuites if (not sharedKeyParams) and \ session.cipherSuite not in cipherSuites: raise ValueError("Session's cipher suite not consistent "\ "with parameters") else: clientHello = ClientHello() clientHello.create(settings.maxVersion, clientRandom, session.sessionID, cipherSuites, certificateTypes, session.srpUsername) #Or send ClientHello (without) else: clientHello = ClientHello() clientHello.create(settings.maxVersion, clientRandom, createByteArraySequence([]), cipherSuites, certificateTypes, srpUsername) for result in self._sendMsg(clientHello): yield result #Get ServerHello (or missing_srp_username) for result in self._getMsg((ContentType.handshake, ContentType.alert), HandshakeType.server_hello): if result in (0,1): yield result else: break msg = result if isinstance(msg, ServerHello): serverHello = msg elif isinstance(msg, Alert): alert = msg #If it's not a missing_srp_username, re-raise if alert.description != AlertDescription.missing_srp_username: self._shutdown(False) raise TLSRemoteAlert(alert) #If we're not in SRP callback mode, we won't have offered SRP #without a username, so we shouldn't get this alert if not srpCallback: for result in self._sendError(\ AlertDescription.unexpected_message): yield result srpParams = srpCallback() #If the callback returns None, cancel the handshake if srpParams == None: for result in self._sendError(AlertDescription.user_canceled): yield result #Recursively perform handshake for result in self._handshakeClientAsyncHelper(srpParams, None, None, None, None, settings, True): yield result return #Get the server version. Do this before anything else, so any #error alerts will use the server's version self.version = serverHello.server_version #Future responses from server must use this version self._versionCheck = True #Check ServerHello if serverHello.server_version < settings.minVersion: for result in self._sendError(\ AlertDescription.protocol_version, "Too old version: %s" % str(serverHello.server_version)): yield result if serverHello.server_version > settings.maxVersion: for result in self._sendError(\ AlertDescription.protocol_version, "Too new version: %s" % str(serverHello.server_version)): yield result if serverHello.cipher_suite not in cipherSuites: for result in self._sendError(\ AlertDescription.illegal_parameter, "Server responded with incorrect ciphersuite"): yield result if serverHello.certificate_type not in certificateTypes: for result in self._sendError(\ AlertDescription.illegal_parameter, "Server responded with incorrect certificate type"): yield result if serverHello.compression_method != 0: for result in self._sendError(\ AlertDescription.illegal_parameter, "Server responded with incorrect compression method"): yield result #Get the server nonce serverRandom = serverHello.random #If the server agrees to resume if session and session.sessionID and \ serverHello.session_id == session.sessionID: #If a shared-key, we're flexible about suites; otherwise the #server-chosen suite has to match the session's suite if sharedKeyParams: session.cipherSuite = serverHello.cipher_suite elif serverHello.cipher_suite != session.cipherSuite: for result in self._sendError(\ AlertDescription.illegal_parameter,\ "Server's ciphersuite doesn't match session"): yield result #Set the session for this connection self.session = session #Calculate pending connection states self._calcPendingStates(clientRandom, serverRandom, settings.cipherImplementations) #Exchange ChangeCipherSpec and Finished messages for result in self._getFinished(): yield result for result in self._sendFinished(): yield result #Mark the connection as open self._handshakeDone(resumed=True) #If server DOES NOT agree to resume else: if sharedKeyParams: for result in self._sendError(\ AlertDescription.user_canceled, "Was expecting a shared-key resumption"): yield result #We've already validated these cipherSuite = serverHello.cipher_suite certificateType = serverHello.certificate_type #If the server chose an SRP suite... if cipherSuite in CipherSuite.srpSuites: #Get ServerKeyExchange, ServerHelloDone for result in self._getMsg(ContentType.handshake, HandshakeType.server_key_exchange, cipherSuite): if result in (0,1): yield result else: break serverKeyExchange = result for result in self._getMsg(ContentType.handshake, HandshakeType.server_hello_done): if result in (0,1): yield result else: break serverHelloDone = result #If the server chose an SRP+RSA suite... elif cipherSuite in CipherSuite.srpRsaSuites: #Get Certificate, ServerKeyExchange, ServerHelloDone for result in self._getMsg(ContentType.handshake, HandshakeType.certificate, certificateType): if result in (0,1): yield result else: break serverCertificate = result for result in self._getMsg(ContentType.handshake, HandshakeType.server_key_exchange, cipherSuite): if result in (0,1): yield result else: break serverKeyExchange = result for result in self._getMsg(ContentType.handshake, HandshakeType.server_hello_done): if result in (0,1): yield result else: break serverHelloDone = result #If the server chose an RSA suite... elif cipherSuite in CipherSuite.rsaSuites: #Get Certificate[, CertificateRequest], ServerHelloDone for result in self._getMsg(ContentType.handshake, HandshakeType.certificate, certificateType): if result in (0,1): yield result else: break serverCertificate = result for result in self._getMsg(ContentType.handshake, (HandshakeType.server_hello_done, HandshakeType.certificate_request)): if result in (0,1): yield result else: break msg = result certificateRequest = None if isinstance(msg, CertificateRequest): certificateRequest = msg for result in self._getMsg(ContentType.handshake, HandshakeType.server_hello_done): if result in (0,1): yield result else: break serverHelloDone = result elif isinstance(msg, ServerHelloDone): serverHelloDone = msg else: raise AssertionError() #Calculate SRP premaster secret, if server chose an SRP or #SRP+RSA suite if cipherSuite in CipherSuite.srpSuites + \ CipherSuite.srpRsaSuites: #Get and check the server's group parameters and B value N = serverKeyExchange.srp_N g = serverKeyExchange.srp_g s = serverKeyExchange.srp_s B = serverKeyExchange.srp_B if (g,N) not in goodGroupParameters: for result in self._sendError(\ AlertDescription.untrusted_srp_parameters, "Unknown group parameters"): yield result if numBits(N) < settings.minKeySize: for result in self._sendError(\ AlertDescription.untrusted_srp_parameters, "N value is too small: %d" % numBits(N)): yield result if numBits(N) > settings.maxKeySize: for result in self._sendError(\ AlertDescription.untrusted_srp_parameters, "N value is too large: %d" % numBits(N)): yield result if B % N == 0: for result in self._sendError(\ AlertDescription.illegal_parameter, "Suspicious B value"): yield result #Check the server's signature, if server chose an #SRP+RSA suite if cipherSuite in CipherSuite.srpRsaSuites: #Hash ServerKeyExchange/ServerSRPParams hashBytes = serverKeyExchange.hash(clientRandom, serverRandom) #Extract signature bytes from ServerKeyExchange sigBytes = serverKeyExchange.signature if len(sigBytes) == 0: for result in self._sendError(\ AlertDescription.illegal_parameter, "Server sent an SRP ServerKeyExchange "\ "message without a signature"): yield result #Get server's public key from the Certificate message for result in self._getKeyFromChain(serverCertificate, settings): if result in (0,1): yield result else: break publicKey, serverCertChain = result #Verify signature if not publicKey.verify(sigBytes, hashBytes): for result in self._sendError(\ AlertDescription.decrypt_error, "Signature failed to verify"): yield result #Calculate client's ephemeral DH values (a, A) a = bytesToNumber(getRandomBytes(32)) A = powMod(g, a, N) #Calculate client's static DH values (x, v) x = makeX(bytesToString(s), srpUsername, password) v = powMod(g, x, N) #Calculate u u = makeU(N, A, B) #Calculate premaster secret k = makeK(N, g) S = powMod((B - (k*v)) % N, a+(u*x), N) if self.fault == Fault.badA: A = N S = 0 premasterSecret = numberToBytes(S) #Send ClientKeyExchange for result in self._sendMsg(\ ClientKeyExchange(cipherSuite).createSRP(A)): yield result #Calculate RSA premaster secret, if server chose an RSA suite elif cipherSuite in CipherSuite.rsaSuites: #Handle the presence of a CertificateRequest if certificateRequest: if unknownParams and certCallback: certParamsNew = certCallback() if certParamsNew: clientCertChain, privateKey = certParamsNew #Get server's public key from the Certificate message for result in self._getKeyFromChain(serverCertificate, settings): if result in (0,1): yield result else: break publicKey, serverCertChain = result #Calculate premaster secret premasterSecret = getRandomBytes(48) premasterSecret[0] = settings.maxVersion[0] premasterSecret[1] = settings.maxVersion[1] if self.fault == Fault.badPremasterPadding: premasterSecret[0] = 5 if self.fault == Fault.shortPremasterSecret: premasterSecret = premasterSecret[:-1] #Encrypt premaster secret to server's public key encryptedPreMasterSecret = publicKey.encrypt(premasterSecret) #If client authentication was requested, send Certificate #message, either with certificates or empty if certificateRequest: clientCertificate = Certificate(certificateType) if clientCertChain: #Check to make sure we have the same type of #certificates the server requested wrongType = False if certificateType == CertificateType.x509: if not isinstance(clientCertChain, X509CertChain): wrongType = True elif certificateType == CertificateType.cryptoID: if not isinstance(clientCertChain, cryptoIDlib.CertChain.CertChain): wrongType = True if wrongType: for result in self._sendError(\ AlertDescription.handshake_failure, "Client certificate is of wrong type"): yield result clientCertificate.create(clientCertChain) for result in self._sendMsg(clientCertificate): yield result else: #The server didn't request client auth, so we #zeroize these so the clientCertChain won't be #stored in the session. privateKey = None clientCertChain = None #Send ClientKeyExchange clientKeyExchange = ClientKeyExchange(cipherSuite, self.version) clientKeyExchange.createRSA(encryptedPreMasterSecret) for result in self._sendMsg(clientKeyExchange): yield result #If client authentication was requested and we have a #private key, send CertificateVerify if certificateRequest and privateKey: if self.version == (3,0): #Create a temporary session object, just for the #purpose of creating the CertificateVerify session = Session() session._calcMasterSecret(self.version, premasterSecret, clientRandom, serverRandom) verifyBytes = self._calcSSLHandshakeHash(\ session.masterSecret, "") elif self.version in ((3,1), (3,2)): verifyBytes = stringToBytes(\ self._handshake_md5.digest() + \ self._handshake_sha.digest()) if self.fault == Fault.badVerifyMessage: verifyBytes[0] = ((verifyBytes[0]+1) % 256) signedBytes = privateKey.sign(verifyBytes) certificateVerify = CertificateVerify() certificateVerify.create(signedBytes) for result in self._sendMsg(certificateVerify): yield result #Create the session object self.session = Session() self.session._calcMasterSecret(self.version, premasterSecret, clientRandom, serverRandom) self.session.sessionID = serverHello.session_id self.session.cipherSuite = cipherSuite self.session.srpUsername = srpUsername self.session.clientCertChain = clientCertChain self.session.serverCertChain = serverCertChain #Calculate pending connection states self._calcPendingStates(clientRandom, serverRandom, settings.cipherImplementations) #Exchange ChangeCipherSpec and Finished messages for result in self._sendFinished(): yield result for result in self._getFinished(): yield result #Mark the connection as open self.session._setResumable(True) self._handshakeDone(resumed=False) def handshakeServer(self, sharedKeyDB=None, verifierDB=None, certChain=None, privateKey=None, reqCert=False, sessionCache=None, settings=None, checker=None): """Perform a handshake in the role of server. This function performs an SSL or TLS handshake. Depending on the arguments and the behavior of the client, this function can perform a shared-key, SRP, or certificate-based handshake. It can also perform a combined SRP and server-certificate handshake. Like any handshake function, this can be called on a closed TLS connection, or on a TLS connection that is already open. If called on an open connection it performs a re-handshake. This function does not send a Hello Request message before performing the handshake, so if re-handshaking is required, the server must signal the client to begin the re-handshake through some other means. If the function completes without raising an exception, the TLS connection will be open and available for data transfer. If an exception is raised, the connection will have been automatically closed (if it was ever open). @type sharedKeyDB: L{tlslite.SharedKeyDB.SharedKeyDB} @param sharedKeyDB: A database of shared symmetric keys associated with usernames. If the client performs a shared-key handshake, the session's sharedKeyUsername attribute will be set. @type verifierDB: L{tlslite.VerifierDB.VerifierDB} @param verifierDB: A database of SRP password verifiers associated with usernames. If the client performs an SRP handshake, the session's srpUsername attribute will be set. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: The certificate chain to be used if the client requests server certificate authentication. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: The private key to be used if the client requests server certificate authentication. @type reqCert: bool @param reqCert: Whether to request client certificate authentication. This only applies if the client chooses server certificate authentication; if the client chooses SRP or shared-key authentication, this will be ignored. If the client performs a client certificate authentication, the sessions's clientCertChain attribute will be set. @type sessionCache: L{tlslite.SessionCache.SessionCache} @param sessionCache: An in-memory cache of resumable sessions. The client can resume sessions from this cache. Alternatively, if the client performs a full handshake, a new session will be added to the cache. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites and SSL/TLS version chosen by the server. @type checker: L{tlslite.Checker.Checker} @param checker: A Checker instance. This instance will be invoked to examine the other party's authentication credentials, if the handshake completes succesfully. @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. @raise tlslite.errors.TLSAuthenticationError: If the checker doesn't like the other party's authentication credentials. """ for result in self.handshakeServerAsync(sharedKeyDB, verifierDB, certChain, privateKey, reqCert, sessionCache, settings, checker): pass def handshakeServerAsync(self, sharedKeyDB=None, verifierDB=None, certChain=None, privateKey=None, reqCert=False, sessionCache=None, settings=None, checker=None): """Start a server handshake operation on the TLS connection. This function returns a generator which behaves similarly to handshakeServer(). Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or it will raise StopIteration if the handshake operation is complete. @rtype: iterable @return: A generator; see above for details. """ handshaker = self._handshakeServerAsyncHelper(\ sharedKeyDB=sharedKeyDB, verifierDB=verifierDB, certChain=certChain, privateKey=privateKey, reqCert=reqCert, sessionCache=sessionCache, settings=settings) for result in self._handshakeWrapperAsync(handshaker, checker): yield result def _handshakeServerAsyncHelper(self, sharedKeyDB, verifierDB, certChain, privateKey, reqCert, sessionCache, settings): self._handshakeStart(client=False) if (not sharedKeyDB) and (not verifierDB) and (not certChain): raise ValueError("Caller passed no authentication credentials") if certChain and not privateKey: raise ValueError("Caller passed a certChain but no privateKey") if privateKey and not certChain: raise ValueError("Caller passed a privateKey but no certChain") if not settings: settings = HandshakeSettings() settings = settings._filter() #Initialize acceptable cipher suites cipherSuites = [] if verifierDB: if certChain: cipherSuites += \ CipherSuite.getSrpRsaSuites(settings.cipherNames) cipherSuites += CipherSuite.getSrpSuites(settings.cipherNames) if sharedKeyDB or certChain: cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames) #Initialize acceptable certificate type certificateType = None if certChain: try: import cryptoIDlib.CertChain if isinstance(certChain, cryptoIDlib.CertChain.CertChain): certificateType = CertificateType.cryptoID except ImportError: pass if isinstance(certChain, X509CertChain): certificateType = CertificateType.x509 if certificateType == None: raise ValueError("Unrecognized certificate type") #Initialize locals clientCertChain = None serverCertChain = None #We may set certChain to this later postFinishedError = None #Tentatively set version to most-desirable version, so if an error #occurs parsing the ClientHello, this is what we'll use for the #error alert self.version = settings.maxVersion #Get ClientHello for result in self._getMsg(ContentType.handshake, HandshakeType.client_hello): if result in (0,1): yield result else: break clientHello = result #If client's version is too low, reject it if clientHello.client_version < settings.minVersion: self.version = settings.minVersion for result in self._sendError(\ AlertDescription.protocol_version, "Too old version: %s" % str(clientHello.client_version)): yield result #If client's version is too high, propose my highest version elif clientHello.client_version > settings.maxVersion: self.version = settings.maxVersion else: #Set the version to the client's version self.version = clientHello.client_version #Get the client nonce; create server nonce clientRandom = clientHello.random serverRandom = getRandomBytes(32) #Calculate the first cipher suite intersection. #This is the 'privileged' ciphersuite. We'll use it if we're #doing a shared-key resumption or a new negotiation. In fact, #the only time we won't use it is if we're resuming a non-sharedkey #session, in which case we use the ciphersuite from the session. # #Given the current ciphersuite ordering, this means we prefer SRP #over non-SRP. for cipherSuite in cipherSuites: if cipherSuite in clientHello.cipher_suites: break else: for result in self._sendError(\ AlertDescription.handshake_failure): yield result #If resumption was requested... if clientHello.session_id and (sharedKeyDB or sessionCache): session = None #Check in the sharedKeys container if sharedKeyDB and len(clientHello.session_id)==16: try: #Trim off zero padding, if any for x in range(16): if clientHello.session_id[x]==0: break self.allegedSharedKeyUsername = bytesToString(\ clientHello.session_id[:x]) session = sharedKeyDB[self.allegedSharedKeyUsername] if not session.sharedKey: raise AssertionError() #use privileged ciphersuite session.cipherSuite = cipherSuite except KeyError: pass #Then check in the session cache if sessionCache and not session: try: session = sessionCache[bytesToString(\ clientHello.session_id)] if session.sharedKey: raise AssertionError() if not session.resumable: raise AssertionError() #Check for consistency with ClientHello if session.cipherSuite not in cipherSuites: for result in self._sendError(\ AlertDescription.handshake_failure): yield result if session.cipherSuite not in clientHello.cipher_suites: for result in self._sendError(\ AlertDescription.handshake_failure): yield result if clientHello.srp_username: if clientHello.srp_username != session.srpUsername: for result in self._sendError(\ AlertDescription.handshake_failure): yield result except KeyError: pass #If a session is found.. if session: #Set the session self.session = session #Send ServerHello serverHello = ServerHello() serverHello.create(self.version, serverRandom, session.sessionID, session.cipherSuite, certificateType) for result in self._sendMsg(serverHello): yield result #From here on, the client's messages must have the right version self._versionCheck = True #Calculate pending connection states self._calcPendingStates(clientRandom, serverRandom, settings.cipherImplementations) #Exchange ChangeCipherSpec and Finished messages for result in self._sendFinished(): yield result for result in self._getFinished(): yield result #Mark the connection as open self._handshakeDone(resumed=True) return #If not a resumption... #TRICKY: we might have chosen an RSA suite that was only deemed #acceptable because of the shared-key resumption. If the shared- #key resumption failed, because the identifier wasn't recognized, #we might fall through to here, where we have an RSA suite #chosen, but no certificate. if cipherSuite in CipherSuite.rsaSuites and not certChain: for result in self._sendError(\ AlertDescription.handshake_failure): yield result #If an RSA suite is chosen, check for certificate type intersection #(We do this check down here because if the mismatch occurs but the # client is using a shared-key session, it's okay) if cipherSuite in CipherSuite.rsaSuites + \ CipherSuite.srpRsaSuites: if certificateType not in clientHello.certificate_types: for result in self._sendError(\ AlertDescription.handshake_failure, "the client doesn't support my certificate type"): yield result #Move certChain -> serverCertChain, now that we're using it serverCertChain = certChain #Create sessionID if sessionCache: sessionID = getRandomBytes(32) else: sessionID = createByteArraySequence([]) #If we've selected an SRP suite, exchange keys and calculate #premaster secret: if cipherSuite in CipherSuite.srpSuites + CipherSuite.srpRsaSuites: #If there's no SRP username... if not clientHello.srp_username: #Ask the client to re-send ClientHello with one for result in self._sendMsg(Alert().create(\ AlertDescription.missing_srp_username, AlertLevel.warning)): yield result #Get ClientHello for result in self._getMsg(ContentType.handshake, HandshakeType.client_hello): if result in (0,1): yield result else: break clientHello = result #Check ClientHello #If client's version is too low, reject it (COPIED CODE; BAD!) if clientHello.client_version < settings.minVersion: self.version = settings.minVersion for result in self._sendError(\ AlertDescription.protocol_version, "Too old version: %s" % str(clientHello.client_version)): yield result #If client's version is too high, propose my highest version elif clientHello.client_version > settings.maxVersion: self.version = settings.maxVersion else: #Set the version to the client's version self.version = clientHello.client_version #Recalculate the privileged cipher suite, making sure to #pick an SRP suite cipherSuites = [c for c in cipherSuites if c in \ CipherSuite.srpSuites + \ CipherSuite.srpRsaSuites] for cipherSuite in cipherSuites: if cipherSuite in clientHello.cipher_suites: break else: for result in self._sendError(\ AlertDescription.handshake_failure): yield result #Get the client nonce; create server nonce clientRandom = clientHello.random serverRandom = getRandomBytes(32) #The username better be there, this time if not clientHello.srp_username: for result in self._sendError(\ AlertDescription.illegal_parameter, "Client resent a hello, but without the SRP"\ " username"): yield result #Get username self.allegedSrpUsername = clientHello.srp_username #Get parameters from username try: entry = verifierDB[self.allegedSrpUsername] except KeyError: for result in self._sendError(\ AlertDescription.unknown_srp_username): yield result (N, g, s, v) = entry #Calculate server's ephemeral DH values (b, B) b = bytesToNumber(getRandomBytes(32)) k = makeK(N, g) B = (powMod(g, b, N) + (k*v)) % N #Create ServerKeyExchange, signing it if necessary serverKeyExchange = ServerKeyExchange(cipherSuite) serverKeyExchange.createSRP(N, g, stringToBytes(s), B) if cipherSuite in CipherSuite.srpRsaSuites: hashBytes = serverKeyExchange.hash(clientRandom, serverRandom) serverKeyExchange.signature = privateKey.sign(hashBytes) #Send ServerHello[, Certificate], ServerKeyExchange, #ServerHelloDone msgs = [] serverHello = ServerHello() serverHello.create(self.version, serverRandom, sessionID, cipherSuite, certificateType) msgs.append(serverHello) if cipherSuite in CipherSuite.srpRsaSuites: certificateMsg = Certificate(certificateType) certificateMsg.create(serverCertChain) msgs.append(certificateMsg) msgs.append(serverKeyExchange) msgs.append(ServerHelloDone()) for result in self._sendMsgs(msgs): yield result #From here on, the client's messages must have the right version self._versionCheck = True #Get and check ClientKeyExchange for result in self._getMsg(ContentType.handshake, HandshakeType.client_key_exchange, cipherSuite): if result in (0,1): yield result else: break clientKeyExchange = result A = clientKeyExchange.srp_A if A % N == 0: postFinishedError = (AlertDescription.illegal_parameter, "Suspicious A value") #Calculate u u = makeU(N, A, B) #Calculate premaster secret S = powMod((A * powMod(v,u,N)) % N, b, N) premasterSecret = numberToBytes(S) #If we've selected an RSA suite, exchange keys and calculate #premaster secret: elif cipherSuite in CipherSuite.rsaSuites: #Send ServerHello, Certificate[, CertificateRequest], #ServerHelloDone msgs = [] msgs.append(ServerHello().create(self.version, serverRandom, sessionID, cipherSuite, certificateType)) msgs.append(Certificate(certificateType).create(serverCertChain)) if reqCert: msgs.append(CertificateRequest()) msgs.append(ServerHelloDone()) for result in self._sendMsgs(msgs): yield result #From here on, the client's messages must have the right version self._versionCheck = True #Get [Certificate,] (if was requested) if reqCert: if self.version == (3,0): for result in self._getMsg((ContentType.handshake, ContentType.alert), HandshakeType.certificate, certificateType): if result in (0,1): yield result else: break msg = result if isinstance(msg, Alert): #If it's not a no_certificate alert, re-raise alert = msg if alert.description != \ AlertDescription.no_certificate: self._shutdown(False) raise TLSRemoteAlert(alert) elif isinstance(msg, Certificate): clientCertificate = msg if clientCertificate.certChain and \ clientCertificate.certChain.getNumCerts()!=0: clientCertChain = clientCertificate.certChain else: raise AssertionError() elif self.version in ((3,1), (3,2)): for result in self._getMsg(ContentType.handshake, HandshakeType.certificate, certificateType): if result in (0,1): yield result else: break clientCertificate = result if clientCertificate.certChain and \ clientCertificate.certChain.getNumCerts()!=0: clientCertChain = clientCertificate.certChain else: raise AssertionError() #Get ClientKeyExchange for result in self._getMsg(ContentType.handshake, HandshakeType.client_key_exchange, cipherSuite): if result in (0,1): yield result else: break clientKeyExchange = result #Decrypt ClientKeyExchange premasterSecret = privateKey.decrypt(\ clientKeyExchange.encryptedPreMasterSecret) randomPreMasterSecret = getRandomBytes(48) versionCheck = (premasterSecret[0], premasterSecret[1]) if not premasterSecret: premasterSecret = randomPreMasterSecret elif len(premasterSecret)!=48: premasterSecret = randomPreMasterSecret elif versionCheck != clientHello.client_version: if versionCheck != self.version: #Tolerate buggy IE clients premasterSecret = randomPreMasterSecret #Get and check CertificateVerify, if relevant if clientCertChain: if self.version == (3,0): #Create a temporary session object, just for the purpose #of checking the CertificateVerify session = Session() session._calcMasterSecret(self.version, premasterSecret, clientRandom, serverRandom) verifyBytes = self._calcSSLHandshakeHash(\ session.masterSecret, "") elif self.version in ((3,1), (3,2)): verifyBytes = stringToBytes(self._handshake_md5.digest() +\ self._handshake_sha.digest()) for result in self._getMsg(ContentType.handshake, HandshakeType.certificate_verify): if result in (0,1): yield result else: break certificateVerify = result publicKey = clientCertChain.getEndEntityPublicKey() if len(publicKey) < settings.minKeySize: postFinishedError = (AlertDescription.handshake_failure, "Client's public key too small: %d" % len(publicKey)) if len(publicKey) > settings.maxKeySize: postFinishedError = (AlertDescription.handshake_failure, "Client's public key too large: %d" % len(publicKey)) if not publicKey.verify(certificateVerify.signature, verifyBytes): postFinishedError = (AlertDescription.decrypt_error, "Signature failed to verify") #Create the session object self.session = Session() self.session._calcMasterSecret(self.version, premasterSecret, clientRandom, serverRandom) self.session.sessionID = sessionID self.session.cipherSuite = cipherSuite self.session.srpUsername = self.allegedSrpUsername self.session.clientCertChain = clientCertChain self.session.serverCertChain = serverCertChain #Calculate pending connection states self._calcPendingStates(clientRandom, serverRandom, settings.cipherImplementations) #Exchange ChangeCipherSpec and Finished messages for result in self._getFinished(): yield result #If we were holding a post-finished error until receiving the client #finished message, send it now. We delay the call until this point #because calling sendError() throws an exception, and our caller might #shut down the socket upon receiving the exception. If he did, and the #client was still sending its ChangeCipherSpec or Finished messages, it #would cause a socket error on the client side. This is a lot of #consideration to show to misbehaving clients, but this would also #cause problems with fault-testing. if postFinishedError: for result in self._sendError(*postFinishedError): yield result for result in self._sendFinished(): yield result #Add the session object to the session cache if sessionCache and sessionID: sessionCache[bytesToString(sessionID)] = self.session #Mark the connection as open self.session._setResumable(True) self._handshakeDone(resumed=False) def _handshakeWrapperAsync(self, handshaker, checker): if not self.fault: try: for result in handshaker: yield result if checker: try: checker(self) except TLSAuthenticationError: alert = Alert().create(AlertDescription.close_notify, AlertLevel.fatal) for result in self._sendMsg(alert): yield result raise except: self._shutdown(False) raise else: try: for result in handshaker: yield result if checker: try: checker(self) except TLSAuthenticationError: alert = Alert().create(AlertDescription.close_notify, AlertLevel.fatal) for result in self._sendMsg(alert): yield result raise except socket.error, e: raise TLSFaultError("socket error!") except TLSAbruptCloseError, e: raise TLSFaultError("abrupt close error!") except TLSAlert, alert: if alert.description not in Fault.faultAlerts[self.fault]: raise TLSFaultError(str(alert)) else: pass except: self._shutdown(False) raise else: raise TLSFaultError("No error!") def _getKeyFromChain(self, certificate, settings): #Get and check cert chain from the Certificate message certChain = certificate.certChain if not certChain or certChain.getNumCerts() == 0: for result in self._sendError(AlertDescription.illegal_parameter, "Other party sent a Certificate message without "\ "certificates"): yield result #Get and check public key from the cert chain publicKey = certChain.getEndEntityPublicKey() if len(publicKey) < settings.minKeySize: for result in self._sendError(AlertDescription.handshake_failure, "Other party's public key too small: %d" % len(publicKey)): yield result if len(publicKey) > settings.maxKeySize: for result in self._sendError(AlertDescription.handshake_failure, "Other party's public key too large: %d" % len(publicKey)): yield result yield publicKey, certChain
Python
"""Base class for SharedKeyDB and VerifierDB.""" import anydbm import thread class BaseDB: def __init__(self, filename, type): self.type = type self.filename = filename if self.filename: self.db = None else: self.db = {} self.lock = thread.allocate_lock() def create(self): """Create a new on-disk database. @raise anydbm.error: If there's a problem creating the database. """ if self.filename: self.db = anydbm.open(self.filename, "n") #raises anydbm.error self.db["--Reserved--type"] = self.type self.db.sync() else: self.db = {} def open(self): """Open a pre-existing on-disk database. @raise anydbm.error: If there's a problem opening the database. @raise ValueError: If the database is not of the right type. """ if not self.filename: raise ValueError("Can only open on-disk databases") self.db = anydbm.open(self.filename, "w") #raises anydbm.error try: if self.db["--Reserved--type"] != self.type: raise ValueError("Not a %s database" % self.type) except KeyError: raise ValueError("Not a recognized database") def __getitem__(self, username): if self.db == None: raise AssertionError("DB not open") self.lock.acquire() try: valueStr = self.db[username] finally: self.lock.release() return self._getItem(username, valueStr) def __setitem__(self, username, value): if self.db == None: raise AssertionError("DB not open") valueStr = self._setItem(username, value) self.lock.acquire() try: self.db[username] = valueStr if self.filename: self.db.sync() finally: self.lock.release() def __delitem__(self, username): if self.db == None: raise AssertionError("DB not open") self.lock.acquire() try: del(self.db[username]) if self.filename: self.db.sync() finally: self.lock.release() def __contains__(self, username): """Check if the database contains the specified username. @type username: str @param username: The username to check for. @rtype: bool @return: True if the database contains the username, False otherwise. """ if self.db == None: raise AssertionError("DB not open") self.lock.acquire() try: return self.db.has_key(username) finally: self.lock.release() def check(self, username, param): value = self.__getitem__(username) return self._checkItem(value, username, param) def keys(self): """Return a list of usernames in the database. @rtype: list @return: The usernames in the database. """ if self.db == None: raise AssertionError("DB not open") self.lock.acquire() try: usernames = self.db.keys() finally: self.lock.release() usernames = [u for u in usernames if not u.startswith("--Reserved--")] return usernames
Python
"""Class for setting handshake parameters.""" from constants import CertificateType from utils import cryptomath from utils import cipherfactory class HandshakeSettings: """This class encapsulates various parameters that can be used with a TLS handshake. @sort: minKeySize, maxKeySize, cipherNames, certificateTypes, minVersion, maxVersion @type minKeySize: int @ivar minKeySize: The minimum bit length for asymmetric keys. If the other party tries to use SRP, RSA, or Diffie-Hellman parameters smaller than this length, an alert will be signalled. The default is 1023. @type maxKeySize: int @ivar maxKeySize: The maximum bit length for asymmetric keys. If the other party tries to use SRP, RSA, or Diffie-Hellman parameters larger than this length, an alert will be signalled. The default is 8193. @type cipherNames: list @ivar cipherNames: The allowed ciphers, in order of preference. The allowed values in this list are 'aes256', 'aes128', '3des', and 'rc4'. If these settings are used with a client handshake, they determine the order of the ciphersuites offered in the ClientHello message. If these settings are used with a server handshake, the server will choose whichever ciphersuite matches the earliest entry in this list. NOTE: If '3des' is used in this list, but TLS Lite can't find an add-on library that supports 3DES, then '3des' will be silently removed. The default value is ['aes256', 'aes128', '3des', 'rc4']. @type certificateTypes: list @ivar certificateTypes: The allowed certificate types, in order of preference. The allowed values in this list are 'x509' and 'cryptoID'. This list is only used with a client handshake. The client will advertise to the server which certificate types are supported, and will check that the server uses one of the appropriate types. NOTE: If 'cryptoID' is used in this list, but cryptoIDlib is not installed, then 'cryptoID' will be silently removed. @type minVersion: tuple @ivar minVersion: The minimum allowed SSL/TLS version. This variable can be set to (3,0) for SSL 3.0, (3,1) for TLS 1.0, or (3,2) for TLS 1.1. If the other party wishes to use a lower version, a protocol_version alert will be signalled. The default is (3,0). @type maxVersion: tuple @ivar maxVersion: The maximum allowed SSL/TLS version. This variable can be set to (3,0) for SSL 3.0, (3,1) for TLS 1.0, or (3,2) for TLS 1.1. If the other party wishes to use a higher version, a protocol_version alert will be signalled. The default is (3,2). (WARNING: Some servers may (improperly) reject clients which offer support for TLS 1.1. In this case, try lowering maxVersion to (3,1)). """ def __init__(self): self.minKeySize = 1023 self.maxKeySize = 8193 self.cipherNames = ["aes256", "aes128", "3des", "rc4"] self.cipherImplementations = ["cryptlib", "openssl", "pycrypto", "python"] self.certificateTypes = ["x509", "cryptoID"] self.minVersion = (3,0) self.maxVersion = (3,2) #Filters out options that are not supported def _filter(self): other = HandshakeSettings() other.minKeySize = self.minKeySize other.maxKeySize = self.maxKeySize other.cipherNames = self.cipherNames other.cipherImplementations = self.cipherImplementations other.certificateTypes = self.certificateTypes other.minVersion = self.minVersion other.maxVersion = self.maxVersion if not cipherfactory.tripleDESPresent: other.cipherNames = [e for e in self.cipherNames if e != "3des"] if len(other.cipherNames)==0: raise ValueError("No supported ciphers") try: import cryptoIDlib except ImportError: other.certificateTypes = [e for e in self.certificateTypes \ if e != "cryptoID"] if len(other.certificateTypes)==0: raise ValueError("No supported certificate types") if not cryptomath.cryptlibpyLoaded: other.cipherImplementations = [e for e in \ self.cipherImplementations if e != "cryptlib"] if not cryptomath.m2cryptoLoaded: other.cipherImplementations = [e for e in \ other.cipherImplementations if e != "openssl"] if not cryptomath.pycryptoLoaded: other.cipherImplementations = [e for e in \ other.cipherImplementations if e != "pycrypto"] if len(other.cipherImplementations)==0: raise ValueError("No supported cipher implementations") if other.minKeySize<512: raise ValueError("minKeySize too small") if other.minKeySize>16384: raise ValueError("minKeySize too large") if other.maxKeySize<512: raise ValueError("maxKeySize too small") if other.maxKeySize>16384: raise ValueError("maxKeySize too large") for s in other.cipherNames: if s not in ("aes256", "aes128", "rc4", "3des"): raise ValueError("Unknown cipher name: '%s'" % s) for s in other.cipherImplementations: if s not in ("cryptlib", "openssl", "python", "pycrypto"): raise ValueError("Unknown cipher implementation: '%s'" % s) for s in other.certificateTypes: if s not in ("x509", "cryptoID"): raise ValueError("Unknown certificate type: '%s'" % s) if other.minVersion > other.maxVersion: raise ValueError("Versions set incorrectly") if not other.minVersion in ((3,0), (3,1), (3,2)): raise ValueError("minVersion set incorrectly") if not other.maxVersion in ((3,0), (3,1), (3,2)): raise ValueError("maxVersion set incorrectly") return other def _getCertificateTypes(self): l = [] for ct in self.certificateTypes: if ct == "x509": l.append(CertificateType.x509) elif ct == "cryptoID": l.append(CertificateType.cryptoID) else: raise AssertionError() return l
Python
"""Class representing an X.509 certificate.""" from utils.ASN1Parser import ASN1Parser from utils.cryptomath import * from utils.keyfactory import _createPublicRSAKey class X509: """This class represents an X.509 certificate. @type bytes: L{array.array} of unsigned bytes @ivar bytes: The DER-encoded ASN.1 certificate @type publicKey: L{tlslite.utils.RSAKey.RSAKey} @ivar publicKey: The subject public key from the certificate. """ def __init__(self): self.bytes = createByteArraySequence([]) self.publicKey = None def parse(self, s): """Parse a PEM-encoded X.509 certificate. @type s: str @param s: A PEM-encoded X.509 certificate (i.e. a base64-encoded certificate wrapped with "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" tags). """ start = s.find("-----BEGIN CERTIFICATE-----") end = s.find("-----END CERTIFICATE-----") if start == -1: raise SyntaxError("Missing PEM prefix") if end == -1: raise SyntaxError("Missing PEM postfix") s = s[start+len("-----BEGIN CERTIFICATE-----") : end] bytes = base64ToBytes(s) self.parseBinary(bytes) return self def parseBinary(self, bytes): """Parse a DER-encoded X.509 certificate. @type bytes: str or L{array.array} of unsigned bytes @param bytes: A DER-encoded X.509 certificate. """ if isinstance(bytes, type("")): bytes = stringToBytes(bytes) self.bytes = bytes p = ASN1Parser(bytes) #Get the tbsCertificate tbsCertificateP = p.getChild(0) #Is the optional version field present? #This determines which index the key is at. if tbsCertificateP.value[0]==0xA0: subjectPublicKeyInfoIndex = 6 else: subjectPublicKeyInfoIndex = 5 #Get the subjectPublicKeyInfo subjectPublicKeyInfoP = tbsCertificateP.getChild(\ subjectPublicKeyInfoIndex) #Get the algorithm algorithmP = subjectPublicKeyInfoP.getChild(0) rsaOID = algorithmP.value if list(rsaOID) != [6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0]: raise SyntaxError("Unrecognized AlgorithmIdentifier") #Get the subjectPublicKey subjectPublicKeyP = subjectPublicKeyInfoP.getChild(1) #Adjust for BIT STRING encapsulation if (subjectPublicKeyP.value[0] !=0): raise SyntaxError() subjectPublicKeyP = ASN1Parser(subjectPublicKeyP.value[1:]) #Get the modulus and exponent modulusP = subjectPublicKeyP.getChild(0) publicExponentP = subjectPublicKeyP.getChild(1) #Decode them into numbers n = bytesToNumber(modulusP.value) e = bytesToNumber(publicExponentP.value) #Create a public key instance self.publicKey = _createPublicRSAKey(n, e) def getFingerprint(self): """Get the hex-encoded fingerprint of this certificate. @rtype: str @return: A hex-encoded fingerprint. """ return sha.sha(self.bytes).hexdigest() def getCommonName(self): """Get the Subject's Common Name from the certificate. The cryptlib_py module must be installed in order to use this function. @rtype: str or None @return: The CN component of the certificate's subject DN, if present. """ import cryptlib_py import array c = cryptlib_py.cryptImportCert(self.bytes, cryptlib_py.CRYPT_UNUSED) name = cryptlib_py.CRYPT_CERTINFO_COMMONNAME try: try: length = cryptlib_py.cryptGetAttributeString(c, name, None) returnVal = array.array('B', [0] * length) cryptlib_py.cryptGetAttributeString(c, name, returnVal) returnVal = returnVal.tostring() except cryptlib_py.CryptException, e: if e[0] == cryptlib_py.CRYPT_ERROR_NOTFOUND: returnVal = None return returnVal finally: cryptlib_py.cryptDestroyCert(c) def writeBytes(self): return self.bytes
Python
"""Class for storing SRP password verifiers.""" from utils.cryptomath import * from utils.compat import * import mathtls from BaseDB import BaseDB class VerifierDB(BaseDB): """This class represent an in-memory or on-disk database of SRP password verifiers. A VerifierDB can be passed to a server handshake to authenticate a client based on one of the verifiers. This class is thread-safe. """ def __init__(self, filename=None): """Create a new VerifierDB instance. @type filename: str @param filename: Filename for an on-disk database, or None for an in-memory database. If the filename already exists, follow this with a call to open(). To create a new on-disk database, follow this with a call to create(). """ BaseDB.__init__(self, filename, "verifier") def _getItem(self, username, valueStr): (N, g, salt, verifier) = valueStr.split(" ") N = base64ToNumber(N) g = base64ToNumber(g) salt = base64ToString(salt) verifier = base64ToNumber(verifier) return (N, g, salt, verifier) def __setitem__(self, username, verifierEntry): """Add a verifier entry to the database. @type username: str @param username: The username to associate the verifier with. Must be less than 256 characters in length. Must not already be in the database. @type verifierEntry: tuple @param verifierEntry: The verifier entry to add. Use L{tlslite.VerifierDB.VerifierDB.makeVerifier} to create a verifier entry. """ BaseDB.__setitem__(self, username, verifierEntry) def _setItem(self, username, value): if len(username)>=256: raise ValueError("username too long") N, g, salt, verifier = value N = numberToBase64(N) g = numberToBase64(g) salt = stringToBase64(salt) verifier = numberToBase64(verifier) valueStr = " ".join( (N, g, salt, verifier) ) return valueStr def _checkItem(self, value, username, param): (N, g, salt, verifier) = value x = mathtls.makeX(salt, username, param) v = powMod(g, x, N) return (verifier == v) def makeVerifier(username, password, bits): """Create a verifier entry which can be stored in a VerifierDB. @type username: str @param username: The username for this verifier. Must be less than 256 characters in length. @type password: str @param password: The password for this verifier. @type bits: int @param bits: This values specifies which SRP group parameters to use. It must be one of (1024, 1536, 2048, 3072, 4096, 6144, 8192). Larger values are more secure but slower. 2048 is a good compromise between safety and speed. @rtype: tuple @return: A tuple which may be stored in a VerifierDB. """ return mathtls.makeVerifier(username, password, bits) makeVerifier = staticmethod(makeVerifier)
Python
"""Miscellaneous helper functions.""" from utils.compat import * from utils.cryptomath import * import hmac import md5 import sha #1024, 1536, 2048, 3072, 4096, 6144, and 8192 bit groups] goodGroupParameters = [(2,0xEEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE48E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B297BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9AFD5138FE8376435B9FC61D2FC0EB06E3),\ (2,0x9DEF3CAFB939277AB1F12A8617A47BBBDBA51DF499AC4C80BEEEA9614B19CC4D5F4F5F556E27CBDE51C6A94BE4607A291558903BA0D0F84380B655BB9A22E8DCDF028A7CEC67F0D08134B1C8B97989149B609E0BE3BAB63D47548381DBC5B1FC764E3F4B53DD9DA1158BFD3E2B9C8CF56EDF019539349627DB2FD53D24B7C48665772E437D6C7F8CE442734AF7CCB7AE837C264AE3A9BEB87F8A2FE9B8B5292E5A021FFF5E91479E8CE7A28C2442C6F315180F93499A234DCF76E3FED135F9BB),\ (2,0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73),\ (2,0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF),\ (5,0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199FFFFFFFFFFFFFFFF),\ (5,0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DCC4024FFFFFFFFFFFFFFFF),\ (5,0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD922222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC50846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E7160C980DD98EDD3DFFFFFFFFFFFFFFFFF)] def P_hash(hashModule, secret, seed, length): bytes = createByteArrayZeros(length) secret = bytesToString(secret) seed = bytesToString(seed) A = seed index = 0 while 1: A = hmac.HMAC(secret, A, hashModule).digest() output = hmac.HMAC(secret, A+seed, hashModule).digest() for c in output: if index >= length: return bytes bytes[index] = ord(c) index += 1 return bytes def PRF(secret, label, seed, length): #Split the secret into left and right halves S1 = secret[ : int(math.ceil(len(secret)/2.0))] S2 = secret[ int(math.floor(len(secret)/2.0)) : ] #Run the left half through P_MD5 and the right half through P_SHA1 p_md5 = P_hash(md5, S1, concatArrays(stringToBytes(label), seed), length) p_sha1 = P_hash(sha, S2, concatArrays(stringToBytes(label), seed), length) #XOR the output values and return the result for x in range(length): p_md5[x] ^= p_sha1[x] return p_md5 def PRF_SSL(secret, seed, length): secretStr = bytesToString(secret) seedStr = bytesToString(seed) bytes = createByteArrayZeros(length) index = 0 for x in range(26): A = chr(ord('A')+x) * (x+1) # 'A', 'BB', 'CCC', etc.. input = secretStr + sha.sha(A + secretStr + seedStr).digest() output = md5.md5(input).digest() for c in output: if index >= length: return bytes bytes[index] = ord(c) index += 1 return bytes def makeX(salt, username, password): if len(username)>=256: raise ValueError("username too long") if len(salt)>=256: raise ValueError("salt too long") return stringToNumber(sha.sha(salt + sha.sha(username + ":" + password)\ .digest()).digest()) #This function is used by VerifierDB.makeVerifier def makeVerifier(username, password, bits): bitsIndex = {1024:0, 1536:1, 2048:2, 3072:3, 4096:4, 6144:5, 8192:6}[bits] g,N = goodGroupParameters[bitsIndex] salt = bytesToString(getRandomBytes(16)) x = makeX(salt, username, password) verifier = powMod(g, x, N) return N, g, salt, verifier def PAD(n, x): nLength = len(numberToString(n)) s = numberToString(x) if len(s) < nLength: s = ("\0" * (nLength-len(s))) + s return s def makeU(N, A, B): return stringToNumber(sha.sha(PAD(N, A) + PAD(N, B)).digest()) def makeK(N, g): return stringToNumber(sha.sha(numberToString(N) + PAD(N, g)).digest()) """ MAC_SSL Modified from Python HMAC by Trevor """ class MAC_SSL: """MAC_SSL class. This supports the API for Cryptographic Hash Functions (PEP 247). """ def __init__(self, key, msg = None, digestmod = None): """Create a new MAC_SSL object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. Defaults to the md5 module. """ if digestmod is None: import md5 digestmod = md5 if key == None: #TREVNEW - for faster copying return #TREVNEW self.digestmod = digestmod self.outer = digestmod.new() self.inner = digestmod.new() self.digest_size = digestmod.digest_size ipad = "\x36" * 40 opad = "\x5C" * 40 self.inner.update(key) self.inner.update(ipad) self.outer.update(key) self.outer.update(opad) if msg is not None: self.update(msg) def update(self, msg): """Update this hashing object with the string msg. """ self.inner.update(msg) def copy(self): """Return a separate copy of this hashing object. An update to this copy won't affect the original object. """ other = MAC_SSL(None) #TREVNEW - for faster copying other.digest_size = self.digest_size #TREVNEW other.digestmod = self.digestmod other.inner = self.inner.copy() other.outer = self.outer.copy() return other def digest(self): """Return the hash value of this hashing object. This returns a string containing 8-bit data. The object is not altered in any way by this function; you can continue updating the object after calling this function. """ h = self.outer.copy() h.update(self.inner.digest()) return h.digest() def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead. """ return "".join([hex(ord(x))[2:].zfill(2) for x in tuple(self.digest())])
Python
"""Class returned by TLSConnection.makefile().""" class FileObject: """This class provides a file object interface to a L{tlslite.TLSConnection.TLSConnection}. Call makefile() on a TLSConnection to create a FileObject instance. This class was copied, with minor modifications, from the _fileobject class in socket.py. Note that fileno() is not implemented.""" default_bufsize = 16384 #TREV: changed from 8192 def __init__(self, sock, mode='rb', bufsize=-1): self._sock = sock self.mode = mode # Not actually used in this version if bufsize < 0: bufsize = self.default_bufsize self.bufsize = bufsize self.softspace = False if bufsize == 0: self._rbufsize = 1 elif bufsize == 1: self._rbufsize = self.default_bufsize else: self._rbufsize = bufsize self._wbufsize = bufsize self._rbuf = "" # A string self._wbuf = [] # A list of strings def _getclosed(self): return self._sock is not None closed = property(_getclosed, doc="True if the file is closed") def close(self): try: if self._sock: for result in self._sock._decrefAsync(): #TREV pass finally: self._sock = None def __del__(self): try: self.close() except: # close() may fail if __init__ didn't complete pass def flush(self): if self._wbuf: buffer = "".join(self._wbuf) self._wbuf = [] self._sock.sendall(buffer) #def fileno(self): # raise NotImplementedError() #TREV def write(self, data): data = str(data) # XXX Should really reject non-string non-buffers if not data: return self._wbuf.append(data) if (self._wbufsize == 0 or self._wbufsize == 1 and '\n' in data or self._get_wbuf_len() >= self._wbufsize): self.flush() def writelines(self, list): # XXX We could do better here for very long lists # XXX Should really reject non-string non-buffers self._wbuf.extend(filter(None, map(str, list))) if (self._wbufsize <= 1 or self._get_wbuf_len() >= self._wbufsize): self.flush() def _get_wbuf_len(self): buf_len = 0 for x in self._wbuf: buf_len += len(x) return buf_len def read(self, size=-1): data = self._rbuf if size < 0: # Read until EOF buffers = [] if data: buffers.append(data) self._rbuf = "" if self._rbufsize <= 1: recv_size = self.default_bufsize else: recv_size = self._rbufsize while True: data = self._sock.recv(recv_size) if not data: break buffers.append(data) return "".join(buffers) else: # Read until size bytes or EOF seen, whichever comes first buf_len = len(data) if buf_len >= size: self._rbuf = data[size:] return data[:size] buffers = [] if data: buffers.append(data) self._rbuf = "" while True: left = size - buf_len recv_size = max(self._rbufsize, left) data = self._sock.recv(recv_size) if not data: break buffers.append(data) n = len(data) if n >= left: self._rbuf = data[left:] buffers[-1] = data[:left] break buf_len += n return "".join(buffers) def readline(self, size=-1): data = self._rbuf if size < 0: # Read until \n or EOF, whichever comes first if self._rbufsize <= 1: # Speed up unbuffered case assert data == "" buffers = [] recv = self._sock.recv while data != "\n": data = recv(1) if not data: break buffers.append(data) return "".join(buffers) nl = data.find('\n') if nl >= 0: nl += 1 self._rbuf = data[nl:] return data[:nl] buffers = [] if data: buffers.append(data) self._rbuf = "" while True: data = self._sock.recv(self._rbufsize) if not data: break buffers.append(data) nl = data.find('\n') if nl >= 0: nl += 1 self._rbuf = data[nl:] buffers[-1] = data[:nl] break return "".join(buffers) else: # Read until size bytes or \n or EOF seen, whichever comes first nl = data.find('\n', 0, size) if nl >= 0: nl += 1 self._rbuf = data[nl:] return data[:nl] buf_len = len(data) if buf_len >= size: self._rbuf = data[size:] return data[:size] buffers = [] if data: buffers.append(data) self._rbuf = "" while True: data = self._sock.recv(self._rbufsize) if not data: break buffers.append(data) left = size - buf_len nl = data.find('\n', 0, left) if nl >= 0: nl += 1 self._rbuf = data[nl:] buffers[-1] = data[:nl] break n = len(data) if n >= left: self._rbuf = data[left:] buffers[-1] = data[:left] break buf_len += n return "".join(buffers) def readlines(self, sizehint=0): total = 0 list = [] while True: line = self.readline() if not line: break list.append(line) total += len(line) if sizehint and total >= sizehint: break return list # Iterator protocols def __iter__(self): return self def next(self): line = self.readline() if not line: raise StopIteration return line
Python
"""Class representing an X.509 certificate chain.""" from utils import cryptomath class X509CertChain: """This class represents a chain of X.509 certificates. @type x509List: list @ivar x509List: A list of L{tlslite.X509.X509} instances, starting with the end-entity certificate and with every subsequent certificate certifying the previous. """ def __init__(self, x509List=None): """Create a new X509CertChain. @type x509List: list @param x509List: A list of L{tlslite.X509.X509} instances, starting with the end-entity certificate and with every subsequent certificate certifying the previous. """ if x509List: self.x509List = x509List else: self.x509List = [] def getNumCerts(self): """Get the number of certificates in this chain. @rtype: int """ return len(self.x509List) def getEndEntityPublicKey(self): """Get the public key from the end-entity certificate. @rtype: L{tlslite.utils.RSAKey.RSAKey} """ if self.getNumCerts() == 0: raise AssertionError() return self.x509List[0].publicKey def getFingerprint(self): """Get the hex-encoded fingerprint of the end-entity certificate. @rtype: str @return: A hex-encoded fingerprint. """ if self.getNumCerts() == 0: raise AssertionError() return self.x509List[0].getFingerprint() def getCommonName(self): """Get the Subject's Common Name from the end-entity certificate. The cryptlib_py module must be installed in order to use this function. @rtype: str or None @return: The CN component of the certificate's subject DN, if present. """ if self.getNumCerts() == 0: raise AssertionError() return self.x509List[0].getCommonName() def validate(self, x509TrustList): """Check the validity of the certificate chain. This checks that every certificate in the chain validates with the subsequent one, until some certificate validates with (or is identical to) one of the passed-in root certificates. The cryptlib_py module must be installed in order to use this function. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The certificate chain must extend to one of these certificates to be considered valid. """ import cryptlib_py c1 = None c2 = None lastC = None rootC = None try: rootFingerprints = [c.getFingerprint() for c in x509TrustList] #Check that every certificate in the chain validates with the #next one for cert1, cert2 in zip(self.x509List, self.x509List[1:]): #If we come upon a root certificate, we're done. if cert1.getFingerprint() in rootFingerprints: return True c1 = cryptlib_py.cryptImportCert(cert1.writeBytes(), cryptlib_py.CRYPT_UNUSED) c2 = cryptlib_py.cryptImportCert(cert2.writeBytes(), cryptlib_py.CRYPT_UNUSED) try: cryptlib_py.cryptCheckCert(c1, c2) except: return False cryptlib_py.cryptDestroyCert(c1) c1 = None cryptlib_py.cryptDestroyCert(c2) c2 = None #If the last certificate is one of the root certificates, we're #done. if self.x509List[-1].getFingerprint() in rootFingerprints: return True #Otherwise, find a root certificate that the last certificate #chains to, and validate them. lastC = cryptlib_py.cryptImportCert(self.x509List[-1].writeBytes(), cryptlib_py.CRYPT_UNUSED) for rootCert in x509TrustList: rootC = cryptlib_py.cryptImportCert(rootCert.writeBytes(), cryptlib_py.CRYPT_UNUSED) if self._checkChaining(lastC, rootC): try: cryptlib_py.cryptCheckCert(lastC, rootC) return True except: return False return False finally: if not (c1 is None): cryptlib_py.cryptDestroyCert(c1) if not (c2 is None): cryptlib_py.cryptDestroyCert(c2) if not (lastC is None): cryptlib_py.cryptDestroyCert(lastC) if not (rootC is None): cryptlib_py.cryptDestroyCert(rootC) def _checkChaining(self, lastC, rootC): import cryptlib_py import array def compareNames(name): try: length = cryptlib_py.cryptGetAttributeString(lastC, name, None) lastName = array.array('B', [0] * length) cryptlib_py.cryptGetAttributeString(lastC, name, lastName) lastName = lastName.tostring() except cryptlib_py.CryptException, e: if e[0] == cryptlib_py.CRYPT_ERROR_NOTFOUND: lastName = None try: length = cryptlib_py.cryptGetAttributeString(rootC, name, None) rootName = array.array('B', [0] * length) cryptlib_py.cryptGetAttributeString(rootC, name, rootName) rootName = rootName.tostring() except cryptlib_py.CryptException, e: if e[0] == cryptlib_py.CRYPT_ERROR_NOTFOUND: rootName = None return lastName == rootName cryptlib_py.cryptSetAttribute(lastC, cryptlib_py.CRYPT_CERTINFO_ISSUERNAME, cryptlib_py.CRYPT_UNUSED) if not compareNames(cryptlib_py.CRYPT_CERTINFO_COUNTRYNAME): return False if not compareNames(cryptlib_py.CRYPT_CERTINFO_LOCALITYNAME): return False if not compareNames(cryptlib_py.CRYPT_CERTINFO_ORGANIZATIONNAME): return False if not compareNames(cryptlib_py.CRYPT_CERTINFO_ORGANIZATIONALUNITNAME): return False if not compareNames(cryptlib_py.CRYPT_CERTINFO_COMMONNAME): return False return True
Python
"""Constants used in various places.""" class CertificateType: x509 = 0 openpgp = 1 cryptoID = 2 class HandshakeType: hello_request = 0 client_hello = 1 server_hello = 2 certificate = 11 server_key_exchange = 12 certificate_request = 13 server_hello_done = 14 certificate_verify = 15 client_key_exchange = 16 finished = 20 class ContentType: change_cipher_spec = 20 alert = 21 handshake = 22 application_data = 23 all = (20,21,22,23) class AlertLevel: warning = 1 fatal = 2 class AlertDescription: """ @cvar bad_record_mac: A TLS record failed to decrypt properly. If this occurs during a shared-key or SRP handshake it most likely indicates a bad password. It may also indicate an implementation error, or some tampering with the data in transit. This alert will be signalled by the server if the SRP password is bad. It may also be signalled by the server if the SRP username is unknown to the server, but it doesn't wish to reveal that fact. This alert will be signalled by the client if the shared-key username is bad. @cvar handshake_failure: A problem occurred while handshaking. This typically indicates a lack of common ciphersuites between client and server, or some other disagreement (about SRP parameters or key sizes, for example). @cvar protocol_version: The other party's SSL/TLS version was unacceptable. This indicates that the client and server couldn't agree on which version of SSL or TLS to use. @cvar user_canceled: The handshake is being cancelled for some reason. """ close_notify = 0 unexpected_message = 10 bad_record_mac = 20 decryption_failed = 21 record_overflow = 22 decompression_failure = 30 handshake_failure = 40 no_certificate = 41 #SSLv3 bad_certificate = 42 unsupported_certificate = 43 certificate_revoked = 44 certificate_expired = 45 certificate_unknown = 46 illegal_parameter = 47 unknown_ca = 48 access_denied = 49 decode_error = 50 decrypt_error = 51 export_restriction = 60 protocol_version = 70 insufficient_security = 71 internal_error = 80 user_canceled = 90 no_renegotiation = 100 unknown_srp_username = 120 missing_srp_username = 121 untrusted_srp_parameters = 122 class CipherSuite: TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA = 0x0050 TLS_SRP_SHA_WITH_AES_128_CBC_SHA = 0x0053 TLS_SRP_SHA_WITH_AES_256_CBC_SHA = 0x0056 TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA = 0x0051 TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA = 0x0054 TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA = 0x0057 TLS_RSA_WITH_3DES_EDE_CBC_SHA = 0x000A TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035 TLS_RSA_WITH_RC4_128_SHA = 0x0005 srpSuites = [] srpSuites.append(TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA) srpSuites.append(TLS_SRP_SHA_WITH_AES_128_CBC_SHA) srpSuites.append(TLS_SRP_SHA_WITH_AES_256_CBC_SHA) def getSrpSuites(ciphers): suites = [] for cipher in ciphers: if cipher == "aes128": suites.append(CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA) elif cipher == "aes256": suites.append(CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA) elif cipher == "3des": suites.append(CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA) return suites getSrpSuites = staticmethod(getSrpSuites) srpRsaSuites = [] srpRsaSuites.append(TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA) srpRsaSuites.append(TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA) srpRsaSuites.append(TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA) def getSrpRsaSuites(ciphers): suites = [] for cipher in ciphers: if cipher == "aes128": suites.append(CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA) elif cipher == "aes256": suites.append(CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA) elif cipher == "3des": suites.append(CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA) return suites getSrpRsaSuites = staticmethod(getSrpRsaSuites) rsaSuites = [] rsaSuites.append(TLS_RSA_WITH_3DES_EDE_CBC_SHA) rsaSuites.append(TLS_RSA_WITH_AES_128_CBC_SHA) rsaSuites.append(TLS_RSA_WITH_AES_256_CBC_SHA) rsaSuites.append(TLS_RSA_WITH_RC4_128_SHA) def getRsaSuites(ciphers): suites = [] for cipher in ciphers: if cipher == "aes128": suites.append(CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA) elif cipher == "aes256": suites.append(CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA) elif cipher == "rc4": suites.append(CipherSuite.TLS_RSA_WITH_RC4_128_SHA) elif cipher == "3des": suites.append(CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA) return suites getRsaSuites = staticmethod(getRsaSuites) tripleDESSuites = [] tripleDESSuites.append(TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA) tripleDESSuites.append(TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA) tripleDESSuites.append(TLS_RSA_WITH_3DES_EDE_CBC_SHA) aes128Suites = [] aes128Suites.append(TLS_SRP_SHA_WITH_AES_128_CBC_SHA) aes128Suites.append(TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA) aes128Suites.append(TLS_RSA_WITH_AES_128_CBC_SHA) aes256Suites = [] aes256Suites.append(TLS_SRP_SHA_WITH_AES_256_CBC_SHA) aes256Suites.append(TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA) aes256Suites.append(TLS_RSA_WITH_AES_256_CBC_SHA) rc4Suites = [] rc4Suites.append(TLS_RSA_WITH_RC4_128_SHA) class Fault: badUsername = 101 badPassword = 102 badA = 103 clientSrpFaults = range(101,104) badVerifyMessage = 601 clientCertFaults = range(601,602) badPremasterPadding = 501 shortPremasterSecret = 502 clientNoAuthFaults = range(501,503) badIdentifier = 401 badSharedKey = 402 clientSharedKeyFaults = range(401,403) badB = 201 serverFaults = range(201,202) badFinished = 300 badMAC = 301 badPadding = 302 genericFaults = range(300,303) faultAlerts = {\ badUsername: (AlertDescription.unknown_srp_username, \ AlertDescription.bad_record_mac),\ badPassword: (AlertDescription.bad_record_mac,),\ badA: (AlertDescription.illegal_parameter,),\ badIdentifier: (AlertDescription.handshake_failure,),\ badSharedKey: (AlertDescription.bad_record_mac,),\ badPremasterPadding: (AlertDescription.bad_record_mac,),\ shortPremasterSecret: (AlertDescription.bad_record_mac,),\ badVerifyMessage: (AlertDescription.decrypt_error,),\ badFinished: (AlertDescription.decrypt_error,),\ badMAC: (AlertDescription.bad_record_mac,),\ badPadding: (AlertDescription.bad_record_mac,) } faultNames = {\ badUsername: "bad username",\ badPassword: "bad password",\ badA: "bad A",\ badIdentifier: "bad identifier",\ badSharedKey: "bad sharedkey",\ badPremasterPadding: "bad premaster padding",\ shortPremasterSecret: "short premaster secret",\ badVerifyMessage: "bad verify message",\ badFinished: "bad finished message",\ badMAC: "bad MAC",\ badPadding: "bad padding" }
Python
""" TLS Lite is a free python library that implements SSL v3, TLS v1, and TLS v1.1. TLS Lite supports non-traditional authentication methods such as SRP, shared keys, and cryptoIDs, in addition to X.509 certificates. TLS Lite is pure python, however it can access OpenSSL, cryptlib, pycrypto, and GMPY for faster crypto operations. TLS Lite integrates with httplib, xmlrpclib, poplib, imaplib, smtplib, SocketServer, asyncore, and Twisted. To use, do:: from tlslite.api import * Then use the L{tlslite.TLSConnection.TLSConnection} class with a socket, or use one of the integration classes in L{tlslite.integration}. @version: 0.3.8 """ __version__ = "0.3.8" __all__ = ["api", "BaseDB", "Checker", "constants", "errors", "FileObject", "HandshakeSettings", "mathtls", "messages", "Session", "SessionCache", "SharedKeyDB", "TLSConnection", "TLSRecordLayer", "VerifierDB", "X509", "X509CertChain", "integration", "utils"]
Python
"""Classes representing TLS messages.""" from utils.compat import * from utils.cryptomath import * from errors import * from utils.codec import * from constants import * from X509 import X509 from X509CertChain import X509CertChain import sha import md5 class RecordHeader3: def __init__(self): self.type = 0 self.version = (0,0) self.length = 0 self.ssl2 = False def create(self, version, type, length): self.type = type self.version = version self.length = length return self def write(self): w = Writer(5) w.add(self.type, 1) w.add(self.version[0], 1) w.add(self.version[1], 1) w.add(self.length, 2) return w.bytes def parse(self, p): self.type = p.get(1) self.version = (p.get(1), p.get(1)) self.length = p.get(2) self.ssl2 = False return self class RecordHeader2: def __init__(self): self.type = 0 self.version = (0,0) self.length = 0 self.ssl2 = True def parse(self, p): if p.get(1)!=128: raise SyntaxError() self.type = ContentType.handshake self.version = (2,0) #We don't support 2-byte-length-headers; could be a problem self.length = p.get(1) return self class Msg: def preWrite(self, trial): if trial: w = Writer() else: length = self.write(True) w = Writer(length) return w def postWrite(self, w, trial): if trial: return w.index else: return w.bytes class Alert(Msg): def __init__(self): self.contentType = ContentType.alert self.level = 0 self.description = 0 def create(self, description, level=AlertLevel.fatal): self.level = level self.description = description return self def parse(self, p): p.setLengthCheck(2) self.level = p.get(1) self.description = p.get(1) p.stopLengthCheck() return self def write(self): w = Writer(2) w.add(self.level, 1) w.add(self.description, 1) return w.bytes class HandshakeMsg(Msg): def preWrite(self, handshakeType, trial): if trial: w = Writer() w.add(handshakeType, 1) w.add(0, 3) else: length = self.write(True) w = Writer(length) w.add(handshakeType, 1) w.add(length-4, 3) return w class ClientHello(HandshakeMsg): def __init__(self, ssl2=False): self.contentType = ContentType.handshake self.ssl2 = ssl2 self.client_version = (0,0) self.random = createByteArrayZeros(32) self.session_id = createByteArraySequence([]) self.cipher_suites = [] # a list of 16-bit values self.certificate_types = [CertificateType.x509] self.compression_methods = [] # a list of 8-bit values self.srp_username = None # a string def create(self, version, random, session_id, cipher_suites, certificate_types=None, srp_username=None): self.client_version = version self.random = random self.session_id = session_id self.cipher_suites = cipher_suites self.certificate_types = certificate_types self.compression_methods = [0] self.srp_username = srp_username return self def parse(self, p): if self.ssl2: self.client_version = (p.get(1), p.get(1)) cipherSpecsLength = p.get(2) sessionIDLength = p.get(2) randomLength = p.get(2) self.cipher_suites = p.getFixList(3, int(cipherSpecsLength/3)) self.session_id = p.getFixBytes(sessionIDLength) self.random = p.getFixBytes(randomLength) if len(self.random) < 32: zeroBytes = 32-len(self.random) self.random = createByteArrayZeros(zeroBytes) + self.random self.compression_methods = [0]#Fake this value #We're not doing a stopLengthCheck() for SSLv2, oh well.. else: p.startLengthCheck(3) self.client_version = (p.get(1), p.get(1)) self.random = p.getFixBytes(32) self.session_id = p.getVarBytes(1) self.cipher_suites = p.getVarList(2, 2) self.compression_methods = p.getVarList(1, 1) if not p.atLengthCheck(): totalExtLength = p.get(2) soFar = 0 while soFar != totalExtLength: extType = p.get(2) extLength = p.get(2) if extType == 6: self.srp_username = bytesToString(p.getVarBytes(1)) elif extType == 7: self.certificate_types = p.getVarList(1, 1) else: p.getFixBytes(extLength) soFar += 4 + extLength p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.client_hello, trial) w.add(self.client_version[0], 1) w.add(self.client_version[1], 1) w.addFixSeq(self.random, 1) w.addVarSeq(self.session_id, 1, 1) w.addVarSeq(self.cipher_suites, 2, 2) w.addVarSeq(self.compression_methods, 1, 1) extLength = 0 if self.certificate_types and self.certificate_types != \ [CertificateType.x509]: extLength += 5 + len(self.certificate_types) if self.srp_username: extLength += 5 + len(self.srp_username) if extLength > 0: w.add(extLength, 2) if self.certificate_types and self.certificate_types != \ [CertificateType.x509]: w.add(7, 2) w.add(len(self.certificate_types)+1, 2) w.addVarSeq(self.certificate_types, 1, 1) if self.srp_username: w.add(6, 2) w.add(len(self.srp_username)+1, 2) w.addVarSeq(stringToBytes(self.srp_username), 1, 1) return HandshakeMsg.postWrite(self, w, trial) class ServerHello(HandshakeMsg): def __init__(self): self.contentType = ContentType.handshake self.server_version = (0,0) self.random = createByteArrayZeros(32) self.session_id = createByteArraySequence([]) self.cipher_suite = 0 self.certificate_type = CertificateType.x509 self.compression_method = 0 def create(self, version, random, session_id, cipher_suite, certificate_type): self.server_version = version self.random = random self.session_id = session_id self.cipher_suite = cipher_suite self.certificate_type = certificate_type self.compression_method = 0 return self def parse(self, p): p.startLengthCheck(3) self.server_version = (p.get(1), p.get(1)) self.random = p.getFixBytes(32) self.session_id = p.getVarBytes(1) self.cipher_suite = p.get(2) self.compression_method = p.get(1) if not p.atLengthCheck(): totalExtLength = p.get(2) soFar = 0 while soFar != totalExtLength: extType = p.get(2) extLength = p.get(2) if extType == 7: self.certificate_type = p.get(1) else: p.getFixBytes(extLength) soFar += 4 + extLength p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.server_hello, trial) w.add(self.server_version[0], 1) w.add(self.server_version[1], 1) w.addFixSeq(self.random, 1) w.addVarSeq(self.session_id, 1, 1) w.add(self.cipher_suite, 2) w.add(self.compression_method, 1) extLength = 0 if self.certificate_type and self.certificate_type != \ CertificateType.x509: extLength += 5 if extLength != 0: w.add(extLength, 2) if self.certificate_type and self.certificate_type != \ CertificateType.x509: w.add(7, 2) w.add(1, 2) w.add(self.certificate_type, 1) return HandshakeMsg.postWrite(self, w, trial) class Certificate(HandshakeMsg): def __init__(self, certificateType): self.certificateType = certificateType self.contentType = ContentType.handshake self.certChain = None def create(self, certChain): self.certChain = certChain return self def parse(self, p): p.startLengthCheck(3) if self.certificateType == CertificateType.x509: chainLength = p.get(3) index = 0 certificate_list = [] while index != chainLength: certBytes = p.getVarBytes(3) x509 = X509() x509.parseBinary(certBytes) certificate_list.append(x509) index += len(certBytes)+3 if certificate_list: self.certChain = X509CertChain(certificate_list) elif self.certificateType == CertificateType.cryptoID: s = bytesToString(p.getVarBytes(2)) if s: try: import cryptoIDlib.CertChain except ImportError: raise SyntaxError(\ "cryptoID cert chain received, cryptoIDlib not present") self.certChain = cryptoIDlib.CertChain.CertChain().parse(s) else: raise AssertionError() p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.certificate, trial) if self.certificateType == CertificateType.x509: chainLength = 0 if self.certChain: certificate_list = self.certChain.x509List else: certificate_list = [] #determine length for cert in certificate_list: bytes = cert.writeBytes() chainLength += len(bytes)+3 #add bytes w.add(chainLength, 3) for cert in certificate_list: bytes = cert.writeBytes() w.addVarSeq(bytes, 1, 3) elif self.certificateType == CertificateType.cryptoID: if self.certChain: bytes = stringToBytes(self.certChain.write()) else: bytes = createByteArraySequence([]) w.addVarSeq(bytes, 1, 2) else: raise AssertionError() return HandshakeMsg.postWrite(self, w, trial) class CertificateRequest(HandshakeMsg): def __init__(self): self.contentType = ContentType.handshake self.certificate_types = [] #treat as opaque bytes for now self.certificate_authorities = createByteArraySequence([]) def create(self, certificate_types, certificate_authorities): self.certificate_types = certificate_types self.certificate_authorities = certificate_authorities return self def parse(self, p): p.startLengthCheck(3) self.certificate_types = p.getVarList(1, 1) self.certificate_authorities = p.getVarBytes(2) p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.certificate_request, trial) w.addVarSeq(self.certificate_types, 1, 1) w.addVarSeq(self.certificate_authorities, 1, 2) return HandshakeMsg.postWrite(self, w, trial) class ServerKeyExchange(HandshakeMsg): def __init__(self, cipherSuite): self.cipherSuite = cipherSuite self.contentType = ContentType.handshake self.srp_N = 0L self.srp_g = 0L self.srp_s = createByteArraySequence([]) self.srp_B = 0L self.signature = createByteArraySequence([]) def createSRP(self, srp_N, srp_g, srp_s, srp_B): self.srp_N = srp_N self.srp_g = srp_g self.srp_s = srp_s self.srp_B = srp_B return self def parse(self, p): p.startLengthCheck(3) self.srp_N = bytesToNumber(p.getVarBytes(2)) self.srp_g = bytesToNumber(p.getVarBytes(2)) self.srp_s = p.getVarBytes(1) self.srp_B = bytesToNumber(p.getVarBytes(2)) if self.cipherSuite in CipherSuite.srpRsaSuites: self.signature = p.getVarBytes(2) p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.server_key_exchange, trial) w.addVarSeq(numberToBytes(self.srp_N), 1, 2) w.addVarSeq(numberToBytes(self.srp_g), 1, 2) w.addVarSeq(self.srp_s, 1, 1) w.addVarSeq(numberToBytes(self.srp_B), 1, 2) if self.cipherSuite in CipherSuite.srpRsaSuites: w.addVarSeq(self.signature, 1, 2) return HandshakeMsg.postWrite(self, w, trial) def hash(self, clientRandom, serverRandom): oldCipherSuite = self.cipherSuite self.cipherSuite = None try: bytes = clientRandom + serverRandom + self.write()[4:] s = bytesToString(bytes) return stringToBytes(md5.md5(s).digest() + sha.sha(s).digest()) finally: self.cipherSuite = oldCipherSuite class ServerHelloDone(HandshakeMsg): def __init__(self): self.contentType = ContentType.handshake def create(self): return self def parse(self, p): p.startLengthCheck(3) p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.server_hello_done, trial) return HandshakeMsg.postWrite(self, w, trial) class ClientKeyExchange(HandshakeMsg): def __init__(self, cipherSuite, version=None): self.cipherSuite = cipherSuite self.version = version self.contentType = ContentType.handshake self.srp_A = 0 self.encryptedPreMasterSecret = createByteArraySequence([]) def createSRP(self, srp_A): self.srp_A = srp_A return self def createRSA(self, encryptedPreMasterSecret): self.encryptedPreMasterSecret = encryptedPreMasterSecret return self def parse(self, p): p.startLengthCheck(3) if self.cipherSuite in CipherSuite.srpSuites + \ CipherSuite.srpRsaSuites: self.srp_A = bytesToNumber(p.getVarBytes(2)) elif self.cipherSuite in CipherSuite.rsaSuites: if self.version in ((3,1), (3,2)): self.encryptedPreMasterSecret = p.getVarBytes(2) elif self.version == (3,0): self.encryptedPreMasterSecret = \ p.getFixBytes(len(p.bytes)-p.index) else: raise AssertionError() else: raise AssertionError() p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.client_key_exchange, trial) if self.cipherSuite in CipherSuite.srpSuites + \ CipherSuite.srpRsaSuites: w.addVarSeq(numberToBytes(self.srp_A), 1, 2) elif self.cipherSuite in CipherSuite.rsaSuites: if self.version in ((3,1), (3,2)): w.addVarSeq(self.encryptedPreMasterSecret, 1, 2) elif self.version == (3,0): w.addFixSeq(self.encryptedPreMasterSecret, 1) else: raise AssertionError() else: raise AssertionError() return HandshakeMsg.postWrite(self, w, trial) class CertificateVerify(HandshakeMsg): def __init__(self): self.contentType = ContentType.handshake self.signature = createByteArraySequence([]) def create(self, signature): self.signature = signature return self def parse(self, p): p.startLengthCheck(3) self.signature = p.getVarBytes(2) p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.certificate_verify, trial) w.addVarSeq(self.signature, 1, 2) return HandshakeMsg.postWrite(self, w, trial) class ChangeCipherSpec(Msg): def __init__(self): self.contentType = ContentType.change_cipher_spec self.type = 1 def create(self): self.type = 1 return self def parse(self, p): p.setLengthCheck(1) self.type = p.get(1) p.stopLengthCheck() return self def write(self, trial=False): w = Msg.preWrite(self, trial) w.add(self.type,1) return Msg.postWrite(self, w, trial) class Finished(HandshakeMsg): def __init__(self, version): self.contentType = ContentType.handshake self.version = version self.verify_data = createByteArraySequence([]) def create(self, verify_data): self.verify_data = verify_data return self def parse(self, p): p.startLengthCheck(3) if self.version == (3,0): self.verify_data = p.getFixBytes(36) elif self.version in ((3,1), (3,2)): self.verify_data = p.getFixBytes(12) else: raise AssertionError() p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.finished, trial) w.addFixSeq(self.verify_data, 1) return HandshakeMsg.postWrite(self, w, trial) class ApplicationData(Msg): def __init__(self): self.contentType = ContentType.application_data self.bytes = createByteArraySequence([]) def create(self, bytes): self.bytes = bytes return self def parse(self, p): self.bytes = p.bytes return self def write(self): return self.bytes
Python
"""Helper class for TLSConnection.""" from __future__ import generators from utils.compat import * from utils.cryptomath import * from utils.cipherfactory import createAES, createRC4, createTripleDES from utils.codec import * from errors import * from messages import * from mathtls import * from constants import * from utils.cryptomath import getRandomBytes from utils import hmac from FileObject import FileObject import sha import md5 import socket import errno import traceback class _ConnectionState: def __init__(self): self.macContext = None self.encContext = None self.seqnum = 0 def getSeqNumStr(self): w = Writer(8) w.add(self.seqnum, 8) seqnumStr = bytesToString(w.bytes) self.seqnum += 1 return seqnumStr class TLSRecordLayer: """ This class handles data transmission for a TLS connection. Its only subclass is L{tlslite.TLSConnection.TLSConnection}. We've separated the code in this class from TLSConnection to make things more readable. @type sock: socket.socket @ivar sock: The underlying socket object. @type session: L{tlslite.Session.Session} @ivar session: The session corresponding to this connection. Due to TLS session resumption, multiple connections can correspond to the same underlying session. @type version: tuple @ivar version: The TLS version being used for this connection. (3,0) means SSL 3.0, and (3,1) means TLS 1.0. @type closed: bool @ivar closed: If this connection is closed. @type resumed: bool @ivar resumed: If this connection is based on a resumed session. @type allegedSharedKeyUsername: str or None @ivar allegedSharedKeyUsername: This is set to the shared-key username asserted by the client, whether the handshake succeeded or not. If the handshake fails, this can be inspected to determine if a guessing attack is in progress against a particular user account. @type allegedSrpUsername: str or None @ivar allegedSrpUsername: This is set to the SRP username asserted by the client, whether the handshake succeeded or not. If the handshake fails, this can be inspected to determine if a guessing attack is in progress against a particular user account. @type closeSocket: bool @ivar closeSocket: If the socket should be closed when the connection is closed (writable). If you set this to True, TLS Lite will assume the responsibility of closing the socket when the TLS Connection is shutdown (either through an error or through the user calling close()). The default is False. @type ignoreAbruptClose: bool @ivar ignoreAbruptClose: If an abrupt close of the socket should raise an error (writable). If you set this to True, TLS Lite will not raise a L{tlslite.errors.TLSAbruptCloseError} exception if the underlying socket is unexpectedly closed. Such an unexpected closure could be caused by an attacker. However, it also occurs with some incorrect TLS implementations. You should set this to True only if you're not worried about an attacker truncating the connection, and only if necessary to avoid spurious errors. The default is False. @sort: __init__, read, readAsync, write, writeAsync, close, closeAsync, getCipherImplementation, getCipherName """ def __init__(self, sock): self.sock = sock #My session object (Session instance; read-only) self.session = None #Am I a client or server? self._client = None #Buffers for processing messages self._handshakeBuffer = [] self._readBuffer = "" #Handshake digests self._handshake_md5 = md5.md5() self._handshake_sha = sha.sha() #TLS Protocol Version self.version = (0,0) #read-only self._versionCheck = False #Once we choose a version, this is True #Current and Pending connection states self._writeState = _ConnectionState() self._readState = _ConnectionState() self._pendingWriteState = _ConnectionState() self._pendingReadState = _ConnectionState() #Is the connection open? self.closed = True #read-only self._refCount = 0 #Used to trigger closure #Is this a resumed (or shared-key) session? self.resumed = False #read-only #What username did the client claim in his handshake? self.allegedSharedKeyUsername = None self.allegedSrpUsername = None #On a call to close(), do we close the socket? (writeable) self.closeSocket = False #If the socket is abruptly closed, do we ignore it #and pretend the connection was shut down properly? (writeable) self.ignoreAbruptClose = False #Fault we will induce, for testing purposes self.fault = None #********************************************************* # Public Functions START #********************************************************* def read(self, max=None, min=1): """Read some data from the TLS connection. This function will block until at least 'min' bytes are available (or the connection is closed). If an exception is raised, the connection will have been automatically closed. @type max: int @param max: The maximum number of bytes to return. @type min: int @param min: The minimum number of bytes to return @rtype: str @return: A string of no more than 'max' bytes, and no fewer than 'min' (unless the connection has been closed, in which case fewer than 'min' bytes may be returned). @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. """ for result in self.readAsync(max, min): pass return result def readAsync(self, max=None, min=1): """Start a read operation on the TLS connection. This function returns a generator which behaves similarly to read(). Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or a string if the read operation has completed. @rtype: iterable @return: A generator; see above for details. """ try: while len(self._readBuffer)<min and not self.closed: try: for result in self._getMsg(ContentType.application_data): if result in (0,1): yield result applicationData = result self._readBuffer += bytesToString(applicationData.write()) except TLSRemoteAlert, alert: if alert.description != AlertDescription.close_notify: raise except TLSAbruptCloseError: if not self.ignoreAbruptClose: raise else: self._shutdown(True) if max == None: max = len(self._readBuffer) returnStr = self._readBuffer[:max] self._readBuffer = self._readBuffer[max:] yield returnStr except: self._shutdown(False) raise def write(self, s): """Write some data to the TLS connection. This function will block until all the data has been sent. If an exception is raised, the connection will have been automatically closed. @type s: str @param s: The data to transmit to the other party. @raise socket.error: If a socket error occurs. """ for result in self.writeAsync(s): pass def writeAsync(self, s): """Start a write operation on the TLS connection. This function returns a generator which behaves similarly to write(). Successive invocations of the generator will return 1 if it is waiting to write to the socket, or will raise StopIteration if the write operation has completed. @rtype: iterable @return: A generator; see above for details. """ try: if self.closed: raise ValueError() index = 0 blockSize = 16384 skipEmptyFrag = False while 1: startIndex = index * blockSize endIndex = startIndex + blockSize if startIndex >= len(s): break if endIndex > len(s): endIndex = len(s) block = stringToBytes(s[startIndex : endIndex]) applicationData = ApplicationData().create(block) for result in self._sendMsg(applicationData, skipEmptyFrag): yield result skipEmptyFrag = True #only send an empy fragment on 1st message index += 1 except: self._shutdown(False) raise def close(self): """Close the TLS connection. This function will block until it has exchanged close_notify alerts with the other party. After doing so, it will shut down the TLS connection. Further attempts to read through this connection will return "". Further attempts to write through this connection will raise ValueError. If makefile() has been called on this connection, the connection will be not be closed until the connection object and all file objects have been closed. Even if an exception is raised, the connection will have been closed. @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. """ if not self.closed: for result in self._decrefAsync(): pass def closeAsync(self): """Start a close operation on the TLS connection. This function returns a generator which behaves similarly to close(). Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or will raise StopIteration if the close operation has completed. @rtype: iterable @return: A generator; see above for details. """ if not self.closed: for result in self._decrefAsync(): yield result def _decrefAsync(self): self._refCount -= 1 if self._refCount == 0 and not self.closed: try: for result in self._sendMsg(Alert().create(\ AlertDescription.close_notify, AlertLevel.warning)): yield result alert = None while not alert: for result in self._getMsg((ContentType.alert, \ ContentType.application_data)): if result in (0,1): yield result if result.contentType == ContentType.alert: alert = result if alert.description == AlertDescription.close_notify: self._shutdown(True) else: raise TLSRemoteAlert(alert) except (socket.error, TLSAbruptCloseError): #If the other side closes the socket, that's okay self._shutdown(True) except: self._shutdown(False) raise def getCipherName(self): """Get the name of the cipher used with this connection. @rtype: str @return: The name of the cipher used with this connection. Either 'aes128', 'aes256', 'rc4', or '3des'. """ if not self._writeState.encContext: return None return self._writeState.encContext.name def getCipherImplementation(self): """Get the name of the cipher implementation used with this connection. @rtype: str @return: The name of the cipher implementation used with this connection. Either 'python', 'cryptlib', 'openssl', or 'pycrypto'. """ if not self._writeState.encContext: return None return self._writeState.encContext.implementation #Emulate a socket, somewhat - def send(self, s): """Send data to the TLS connection (socket emulation). @raise socket.error: If a socket error occurs. """ self.write(s) return len(s) def sendall(self, s): """Send data to the TLS connection (socket emulation). @raise socket.error: If a socket error occurs. """ self.write(s) def recv(self, bufsize): """Get some data from the TLS connection (socket emulation). @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. """ return self.read(bufsize) def makefile(self, mode='r', bufsize=-1): """Create a file object for the TLS connection (socket emulation). @rtype: L{tlslite.FileObject.FileObject} """ self._refCount += 1 return FileObject(self, mode, bufsize) def getsockname(self): """Return the socket's own address (socket emulation).""" return self.sock.getsockname() def getpeername(self): """Return the remote address to which the socket is connected (socket emulation).""" return self.sock.getpeername() def settimeout(self, value): """Set a timeout on blocking socket operations (socket emulation).""" return self.sock.settimeout(value) def gettimeout(self): """Return the timeout associated with socket operations (socket emulation).""" return self.sock.gettimeout() def setsockopt(self, level, optname, value): """Set the value of the given socket option (socket emulation).""" return self.sock.setsockopt(level, optname, value) #********************************************************* # Public Functions END #********************************************************* def _shutdown(self, resumable): self._writeState = _ConnectionState() self._readState = _ConnectionState() #Don't do this: self._readBuffer = "" self.version = (0,0) self._versionCheck = False self.closed = True if self.closeSocket: self.sock.close() #Even if resumable is False, we'll never toggle this on if not resumable and self.session: self.session.resumable = False def _sendError(self, alertDescription, errorStr=None): alert = Alert().create(alertDescription, AlertLevel.fatal) for result in self._sendMsg(alert): yield result self._shutdown(False) raise TLSLocalAlert(alert, errorStr) def _sendMsgs(self, msgs): skipEmptyFrag = False for msg in msgs: for result in self._sendMsg(msg, skipEmptyFrag): yield result skipEmptyFrag = True def _sendMsg(self, msg, skipEmptyFrag=False): bytes = msg.write() contentType = msg.contentType #Whenever we're connected and asked to send a message, #we first send an empty Application Data message. This prevents #an attacker from launching a chosen-plaintext attack based on #knowing the next IV. if not self.closed and not skipEmptyFrag and self.version == (3,1): if self._writeState.encContext: if self._writeState.encContext.isBlockCipher: for result in self._sendMsg(ApplicationData(), skipEmptyFrag=True): yield result #Update handshake hashes if contentType == ContentType.handshake: bytesStr = bytesToString(bytes) self._handshake_md5.update(bytesStr) self._handshake_sha.update(bytesStr) #Calculate MAC if self._writeState.macContext: seqnumStr = self._writeState.getSeqNumStr() bytesStr = bytesToString(bytes) mac = self._writeState.macContext.copy() mac.update(seqnumStr) mac.update(chr(contentType)) if self.version == (3,0): mac.update( chr( int(len(bytes)/256) ) ) mac.update( chr( int(len(bytes)%256) ) ) elif self.version in ((3,1), (3,2)): mac.update(chr(self.version[0])) mac.update(chr(self.version[1])) mac.update( chr( int(len(bytes)/256) ) ) mac.update( chr( int(len(bytes)%256) ) ) else: raise AssertionError() mac.update(bytesStr) macString = mac.digest() macBytes = stringToBytes(macString) if self.fault == Fault.badMAC: macBytes[0] = (macBytes[0]+1) % 256 #Encrypt for Block or Stream Cipher if self._writeState.encContext: #Add padding and encrypt (for Block Cipher): if self._writeState.encContext.isBlockCipher: #Add TLS 1.1 fixed block if self.version == (3,2): bytes = self.fixedIVBlock + bytes #Add padding: bytes = bytes + (macBytes + paddingBytes) currentLength = len(bytes) + len(macBytes) + 1 blockLength = self._writeState.encContext.block_size paddingLength = blockLength-(currentLength % blockLength) paddingBytes = createByteArraySequence([paddingLength] * \ (paddingLength+1)) if self.fault == Fault.badPadding: paddingBytes[0] = (paddingBytes[0]+1) % 256 endBytes = concatArrays(macBytes, paddingBytes) bytes = concatArrays(bytes, endBytes) #Encrypt plaintext = stringToBytes(bytes) ciphertext = self._writeState.encContext.encrypt(plaintext) bytes = stringToBytes(ciphertext) #Encrypt (for Stream Cipher) else: bytes = concatArrays(bytes, macBytes) plaintext = bytesToString(bytes) ciphertext = self._writeState.encContext.encrypt(plaintext) bytes = stringToBytes(ciphertext) #Add record header and send r = RecordHeader3().create(self.version, contentType, len(bytes)) s = bytesToString(concatArrays(r.write(), bytes)) while 1: try: bytesSent = self.sock.send(s) #Might raise socket.error except socket.error, why: if why[0] == errno.EWOULDBLOCK: yield 1 continue else: raise if bytesSent == len(s): return s = s[bytesSent:] yield 1 def _getMsg(self, expectedType, secondaryType=None, constructorType=None): try: if not isinstance(expectedType, tuple): expectedType = (expectedType,) #Spin in a loop, until we've got a non-empty record of a type we #expect. The loop will be repeated if: # - we receive a renegotiation attempt; we send no_renegotiation, # then try again # - we receive an empty application-data fragment; we try again while 1: for result in self._getNextRecord(): if result in (0,1): yield result recordHeader, p = result #If this is an empty application-data fragment, try again if recordHeader.type == ContentType.application_data: if p.index == len(p.bytes): continue #If we received an unexpected record type... if recordHeader.type not in expectedType: #If we received an alert... if recordHeader.type == ContentType.alert: alert = Alert().parse(p) #We either received a fatal error, a warning, or a #close_notify. In any case, we're going to close the #connection. In the latter two cases we respond with #a close_notify, but ignore any socket errors, since #the other side might have already closed the socket. if alert.level == AlertLevel.warning or \ alert.description == AlertDescription.close_notify: #If the sendMsg() call fails because the socket has #already been closed, we will be forgiving and not #report the error nor invalidate the "resumability" #of the session. try: alertMsg = Alert() alertMsg.create(AlertDescription.close_notify, AlertLevel.warning) for result in self._sendMsg(alertMsg): yield result except socket.error: pass if alert.description == \ AlertDescription.close_notify: self._shutdown(True) elif alert.level == AlertLevel.warning: self._shutdown(False) else: #Fatal alert: self._shutdown(False) #Raise the alert as an exception raise TLSRemoteAlert(alert) #If we received a renegotiation attempt... if recordHeader.type == ContentType.handshake: subType = p.get(1) reneg = False if self._client: if subType == HandshakeType.hello_request: reneg = True else: if subType == HandshakeType.client_hello: reneg = True #Send no_renegotiation, then try again if reneg: alertMsg = Alert() alertMsg.create(AlertDescription.no_renegotiation, AlertLevel.warning) for result in self._sendMsg(alertMsg): yield result continue #Otherwise: this is an unexpected record, but neither an #alert nor renegotiation for result in self._sendError(\ AlertDescription.unexpected_message, "received type=%d" % recordHeader.type): yield result break #Parse based on content_type if recordHeader.type == ContentType.change_cipher_spec: yield ChangeCipherSpec().parse(p) elif recordHeader.type == ContentType.alert: yield Alert().parse(p) elif recordHeader.type == ContentType.application_data: yield ApplicationData().parse(p) elif recordHeader.type == ContentType.handshake: #Convert secondaryType to tuple, if it isn't already if not isinstance(secondaryType, tuple): secondaryType = (secondaryType,) #If it's a handshake message, check handshake header if recordHeader.ssl2: subType = p.get(1) if subType != HandshakeType.client_hello: for result in self._sendError(\ AlertDescription.unexpected_message, "Can only handle SSLv2 ClientHello messages"): yield result if HandshakeType.client_hello not in secondaryType: for result in self._sendError(\ AlertDescription.unexpected_message): yield result subType = HandshakeType.client_hello else: subType = p.get(1) if subType not in secondaryType: for result in self._sendError(\ AlertDescription.unexpected_message, "Expecting %s, got %s" % (str(secondaryType), subType)): yield result #Update handshake hashes sToHash = bytesToString(p.bytes) self._handshake_md5.update(sToHash) self._handshake_sha.update(sToHash) #Parse based on handshake type if subType == HandshakeType.client_hello: yield ClientHello(recordHeader.ssl2).parse(p) elif subType == HandshakeType.server_hello: yield ServerHello().parse(p) elif subType == HandshakeType.certificate: yield Certificate(constructorType).parse(p) elif subType == HandshakeType.certificate_request: yield CertificateRequest().parse(p) elif subType == HandshakeType.certificate_verify: yield CertificateVerify().parse(p) elif subType == HandshakeType.server_key_exchange: yield ServerKeyExchange(constructorType).parse(p) elif subType == HandshakeType.server_hello_done: yield ServerHelloDone().parse(p) elif subType == HandshakeType.client_key_exchange: yield ClientKeyExchange(constructorType, \ self.version).parse(p) elif subType == HandshakeType.finished: yield Finished(self.version).parse(p) else: raise AssertionError() #If an exception was raised by a Parser or Message instance: except SyntaxError, e: for result in self._sendError(AlertDescription.decode_error, formatExceptionTrace(e)): yield result #Returns next record or next handshake message def _getNextRecord(self): #If there's a handshake message waiting, return it if self._handshakeBuffer: recordHeader, bytes = self._handshakeBuffer[0] self._handshakeBuffer = self._handshakeBuffer[1:] yield (recordHeader, Parser(bytes)) return #Otherwise... #Read the next record header bytes = createByteArraySequence([]) recordHeaderLength = 1 ssl2 = False while 1: try: s = self.sock.recv(recordHeaderLength-len(bytes)) except socket.error, why: if why[0] == errno.EWOULDBLOCK: yield 0 continue else: raise #If the connection was abruptly closed, raise an error if len(s)==0: raise TLSAbruptCloseError() bytes += stringToBytes(s) if len(bytes)==1: if bytes[0] in ContentType.all: ssl2 = False recordHeaderLength = 5 elif bytes[0] == 128: ssl2 = True recordHeaderLength = 2 else: raise SyntaxError() if len(bytes) == recordHeaderLength: break #Parse the record header if ssl2: r = RecordHeader2().parse(Parser(bytes)) else: r = RecordHeader3().parse(Parser(bytes)) #Check the record header fields if r.length > 18432: for result in self._sendError(AlertDescription.record_overflow): yield result #Read the record contents bytes = createByteArraySequence([]) while 1: try: s = self.sock.recv(r.length - len(bytes)) except socket.error, why: if why[0] == errno.EWOULDBLOCK: yield 0 continue else: raise #If the connection is closed, raise a socket error if len(s)==0: raise TLSAbruptCloseError() bytes += stringToBytes(s) if len(bytes) == r.length: break #Check the record header fields (2) #We do this after reading the contents from the socket, so that #if there's an error, we at least don't leave extra bytes in the #socket.. # # THIS CHECK HAS NO SECURITY RELEVANCE (?), BUT COULD HURT INTEROP. # SO WE LEAVE IT OUT FOR NOW. # #if self._versionCheck and r.version != self.version: # for result in self._sendError(AlertDescription.protocol_version, # "Version in header field: %s, should be %s" % (str(r.version), # str(self.version))): # yield result #Decrypt the record for result in self._decryptRecord(r.type, bytes): if result in (0,1): yield result else: break bytes = result p = Parser(bytes) #If it doesn't contain handshake messages, we can just return it if r.type != ContentType.handshake: yield (r, p) #If it's an SSLv2 ClientHello, we can return it as well elif r.ssl2: yield (r, p) else: #Otherwise, we loop through and add the handshake messages to the #handshake buffer while 1: if p.index == len(bytes): #If we're at the end if not self._handshakeBuffer: for result in self._sendError(\ AlertDescription.decode_error, \ "Received empty handshake record"): yield result break #There needs to be at least 4 bytes to get a header if p.index+4 > len(bytes): for result in self._sendError(\ AlertDescription.decode_error, "A record has a partial handshake message (1)"): yield result p.get(1) # skip handshake type msgLength = p.get(3) if p.index+msgLength > len(bytes): for result in self._sendError(\ AlertDescription.decode_error, "A record has a partial handshake message (2)"): yield result handshakePair = (r, bytes[p.index-4 : p.index+msgLength]) self._handshakeBuffer.append(handshakePair) p.index += msgLength #We've moved at least one handshake message into the #handshakeBuffer, return the first one recordHeader, bytes = self._handshakeBuffer[0] self._handshakeBuffer = self._handshakeBuffer[1:] yield (recordHeader, Parser(bytes)) def _decryptRecord(self, recordType, bytes): if self._readState.encContext: #Decrypt if it's a block cipher if self._readState.encContext.isBlockCipher: blockLength = self._readState.encContext.block_size if len(bytes) % blockLength != 0: for result in self._sendError(\ AlertDescription.decryption_failed, "Encrypted data not a multiple of blocksize"): yield result ciphertext = bytesToString(bytes) plaintext = self._readState.encContext.decrypt(ciphertext) if self.version == (3,2): #For TLS 1.1, remove explicit IV plaintext = plaintext[self._readState.encContext.block_size : ] bytes = stringToBytes(plaintext) #Check padding paddingGood = True paddingLength = bytes[-1] if (paddingLength+1) > len(bytes): paddingGood=False totalPaddingLength = 0 else: if self.version == (3,0): totalPaddingLength = paddingLength+1 elif self.version in ((3,1), (3,2)): totalPaddingLength = paddingLength+1 paddingBytes = bytes[-totalPaddingLength:-1] for byte in paddingBytes: if byte != paddingLength: paddingGood = False totalPaddingLength = 0 else: raise AssertionError() #Decrypt if it's a stream cipher else: paddingGood = True ciphertext = bytesToString(bytes) plaintext = self._readState.encContext.decrypt(ciphertext) bytes = stringToBytes(plaintext) totalPaddingLength = 0 #Check MAC macGood = True macLength = self._readState.macContext.digest_size endLength = macLength + totalPaddingLength if endLength > len(bytes): macGood = False else: #Read MAC startIndex = len(bytes) - endLength endIndex = startIndex + macLength checkBytes = bytes[startIndex : endIndex] #Calculate MAC seqnumStr = self._readState.getSeqNumStr() bytes = bytes[:-endLength] bytesStr = bytesToString(bytes) mac = self._readState.macContext.copy() mac.update(seqnumStr) mac.update(chr(recordType)) if self.version == (3,0): mac.update( chr( int(len(bytes)/256) ) ) mac.update( chr( int(len(bytes)%256) ) ) elif self.version in ((3,1), (3,2)): mac.update(chr(self.version[0])) mac.update(chr(self.version[1])) mac.update( chr( int(len(bytes)/256) ) ) mac.update( chr( int(len(bytes)%256) ) ) else: raise AssertionError() mac.update(bytesStr) macString = mac.digest() macBytes = stringToBytes(macString) #Compare MACs if macBytes != checkBytes: macGood = False if not (paddingGood and macGood): for result in self._sendError(AlertDescription.bad_record_mac, "MAC failure (or padding failure)"): yield result yield bytes def _handshakeStart(self, client): self._client = client self._handshake_md5 = md5.md5() self._handshake_sha = sha.sha() self._handshakeBuffer = [] self.allegedSharedKeyUsername = None self.allegedSrpUsername = None self._refCount = 1 def _handshakeDone(self, resumed): self.resumed = resumed self.closed = False def _calcPendingStates(self, clientRandom, serverRandom, implementations): if self.session.cipherSuite in CipherSuite.aes128Suites: macLength = 20 keyLength = 16 ivLength = 16 createCipherFunc = createAES elif self.session.cipherSuite in CipherSuite.aes256Suites: macLength = 20 keyLength = 32 ivLength = 16 createCipherFunc = createAES elif self.session.cipherSuite in CipherSuite.rc4Suites: macLength = 20 keyLength = 16 ivLength = 0 createCipherFunc = createRC4 elif self.session.cipherSuite in CipherSuite.tripleDESSuites: macLength = 20 keyLength = 24 ivLength = 8 createCipherFunc = createTripleDES else: raise AssertionError() if self.version == (3,0): createMACFunc = MAC_SSL elif self.version in ((3,1), (3,2)): createMACFunc = hmac.HMAC outputLength = (macLength*2) + (keyLength*2) + (ivLength*2) #Calculate Keying Material from Master Secret if self.version == (3,0): keyBlock = PRF_SSL(self.session.masterSecret, concatArrays(serverRandom, clientRandom), outputLength) elif self.version in ((3,1), (3,2)): keyBlock = PRF(self.session.masterSecret, "key expansion", concatArrays(serverRandom,clientRandom), outputLength) else: raise AssertionError() #Slice up Keying Material clientPendingState = _ConnectionState() serverPendingState = _ConnectionState() p = Parser(keyBlock) clientMACBlock = bytesToString(p.getFixBytes(macLength)) serverMACBlock = bytesToString(p.getFixBytes(macLength)) clientKeyBlock = bytesToString(p.getFixBytes(keyLength)) serverKeyBlock = bytesToString(p.getFixBytes(keyLength)) clientIVBlock = bytesToString(p.getFixBytes(ivLength)) serverIVBlock = bytesToString(p.getFixBytes(ivLength)) clientPendingState.macContext = createMACFunc(clientMACBlock, digestmod=sha) serverPendingState.macContext = createMACFunc(serverMACBlock, digestmod=sha) clientPendingState.encContext = createCipherFunc(clientKeyBlock, clientIVBlock, implementations) serverPendingState.encContext = createCipherFunc(serverKeyBlock, serverIVBlock, implementations) #Assign new connection states to pending states if self._client: self._pendingWriteState = clientPendingState self._pendingReadState = serverPendingState else: self._pendingWriteState = serverPendingState self._pendingReadState = clientPendingState if self.version == (3,2) and ivLength: #Choose fixedIVBlock for TLS 1.1 (this is encrypted with the CBC #residue to create the IV for each sent block) self.fixedIVBlock = getRandomBytes(ivLength) def _changeWriteState(self): self._writeState = self._pendingWriteState self._pendingWriteState = _ConnectionState() def _changeReadState(self): self._readState = self._pendingReadState self._pendingReadState = _ConnectionState() def _sendFinished(self): #Send ChangeCipherSpec for result in self._sendMsg(ChangeCipherSpec()): yield result #Switch to pending write state self._changeWriteState() #Calculate verification data verifyData = self._calcFinished(True) if self.fault == Fault.badFinished: verifyData[0] = (verifyData[0]+1)%256 #Send Finished message under new state finished = Finished(self.version).create(verifyData) for result in self._sendMsg(finished): yield result def _getFinished(self): #Get and check ChangeCipherSpec for result in self._getMsg(ContentType.change_cipher_spec): if result in (0,1): yield result changeCipherSpec = result if changeCipherSpec.type != 1: for result in self._sendError(AlertDescription.illegal_parameter, "ChangeCipherSpec type incorrect"): yield result #Switch to pending read state self._changeReadState() #Calculate verification data verifyData = self._calcFinished(False) #Get and check Finished message under new state for result in self._getMsg(ContentType.handshake, HandshakeType.finished): if result in (0,1): yield result finished = result if finished.verify_data != verifyData: for result in self._sendError(AlertDescription.decrypt_error, "Finished message is incorrect"): yield result def _calcFinished(self, send=True): if self.version == (3,0): if (self._client and send) or (not self._client and not send): senderStr = "\x43\x4C\x4E\x54" else: senderStr = "\x53\x52\x56\x52" verifyData = self._calcSSLHandshakeHash(self.session.masterSecret, senderStr) return verifyData elif self.version in ((3,1), (3,2)): if (self._client and send) or (not self._client and not send): label = "client finished" else: label = "server finished" handshakeHashes = stringToBytes(self._handshake_md5.digest() + \ self._handshake_sha.digest()) verifyData = PRF(self.session.masterSecret, label, handshakeHashes, 12) return verifyData else: raise AssertionError() #Used for Finished messages and CertificateVerify messages in SSL v3 def _calcSSLHandshakeHash(self, masterSecret, label): masterSecretStr = bytesToString(masterSecret) imac_md5 = self._handshake_md5.copy() imac_sha = self._handshake_sha.copy() imac_md5.update(label + masterSecretStr + '\x36'*48) imac_sha.update(label + masterSecretStr + '\x36'*40) md5Str = md5.md5(masterSecretStr + ('\x5c'*48) + \ imac_md5.digest()).digest() shaStr = sha.sha(masterSecretStr + ('\x5c'*40) + \ imac_sha.digest()).digest() return stringToBytes(md5Str + shaStr)
Python
"""Import this module for easy access to TLS Lite objects. The TLS Lite API consists of classes, functions, and variables spread throughout this package. Instead of importing them individually with:: from tlslite.TLSConnection import TLSConnection from tlslite.HandshakeSettings import HandshakeSettings from tlslite.errors import * . . It's easier to do:: from tlslite.api import * This imports all the important objects (TLSConnection, Checker, HandshakeSettings, etc.) into the global namespace. In particular, it imports:: from constants import AlertLevel, AlertDescription, Fault from errors import * from Checker import Checker from HandshakeSettings import HandshakeSettings from Session import Session from SessionCache import SessionCache from SharedKeyDB import SharedKeyDB from TLSConnection import TLSConnection from VerifierDB import VerifierDB from X509 import X509 from X509CertChain import X509CertChain from integration.HTTPTLSConnection import HTTPTLSConnection from integration.POP3_TLS import POP3_TLS from integration.IMAP4_TLS import IMAP4_TLS from integration.SMTP_TLS import SMTP_TLS from integration.XMLRPCTransport import XMLRPCTransport from integration.TLSSocketServerMixIn import TLSSocketServerMixIn from integration.TLSAsyncDispatcherMixIn import TLSAsyncDispatcherMixIn from integration.TLSTwistedProtocolWrapper import TLSTwistedProtocolWrapper from utils.cryptomath import cryptlibpyLoaded, m2cryptoLoaded, gmpyLoaded, pycryptoLoaded, prngName from utils.keyfactory import generateRSAKey, parsePEMKey, parseXMLKey, parseAsPublicKey, parsePrivateKey """ from constants import AlertLevel, AlertDescription, Fault from errors import * from Checker import Checker from HandshakeSettings import HandshakeSettings from Session import Session from SessionCache import SessionCache from SharedKeyDB import SharedKeyDB from TLSConnection import TLSConnection from VerifierDB import VerifierDB from X509 import X509 from X509CertChain import X509CertChain from integration.HTTPTLSConnection import HTTPTLSConnection from integration.TLSSocketServerMixIn import TLSSocketServerMixIn from integration.TLSAsyncDispatcherMixIn import TLSAsyncDispatcherMixIn from integration.POP3_TLS import POP3_TLS from integration.IMAP4_TLS import IMAP4_TLS from integration.SMTP_TLS import SMTP_TLS from integration.XMLRPCTransport import XMLRPCTransport try: import twisted del(twisted) from integration.TLSTwistedProtocolWrapper import TLSTwistedProtocolWrapper except ImportError: pass from utils.cryptomath import cryptlibpyLoaded, m2cryptoLoaded, gmpyLoaded, \ pycryptoLoaded, prngName from utils.keyfactory import generateRSAKey, parsePEMKey, parseXMLKey, \ parseAsPublicKey, parsePrivateKey
Python
"""Class for post-handshake certificate checking.""" from utils.cryptomath import hashAndBase64 from X509 import X509 from X509CertChain import X509CertChain from errors import * class Checker: """This class is passed to a handshake function to check the other party's certificate chain. If a handshake function completes successfully, but the Checker judges the other party's certificate chain to be missing or inadequate, a subclass of L{tlslite.errors.TLSAuthenticationError} will be raised. Currently, the Checker can check either an X.509 or a cryptoID chain (for the latter, cryptoIDlib must be installed). """ def __init__(self, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, checkResumedSession=False): """Create a new Checker instance. You must pass in one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) @type cryptoID: str @param cryptoID: A cryptoID which the other party's certificate chain must match. The cryptoIDlib module must be installed. Mutually exclusive with all of the 'x509...' arguments. @type protocol: str @param protocol: A cryptoID protocol URI which the other party's certificate chain must match. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: A hex-encoded X.509 end-entity fingerprint which the other party's end-entity certificate must match. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type checkResumedSession: bool @param checkResumedSession: If resumed sessions should be checked. This defaults to False, on the theory that if the session was checked once, we don't need to bother re-checking it. """ if cryptoID and (x509Fingerprint or x509TrustList): raise ValueError() if x509Fingerprint and x509TrustList: raise ValueError() if x509CommonName and not x509TrustList: raise ValueError() if protocol and not cryptoID: raise ValueError() if cryptoID: import cryptoIDlib #So we raise an error here if x509TrustList: import cryptlib_py #So we raise an error here self.cryptoID = cryptoID self.protocol = protocol self.x509Fingerprint = x509Fingerprint self.x509TrustList = x509TrustList self.x509CommonName = x509CommonName self.checkResumedSession = checkResumedSession def __call__(self, connection): """Check a TLSConnection. When a Checker is passed to a handshake function, this will be called at the end of the function. @type connection: L{tlslite.TLSConnection.TLSConnection} @param connection: The TLSConnection to examine. @raise tlslite.errors.TLSAuthenticationError: If the other party's certificate chain is missing or bad. """ if not self.checkResumedSession and connection.resumed: return if self.cryptoID or self.x509Fingerprint or self.x509TrustList: if connection._client: chain = connection.session.serverCertChain else: chain = connection.session.clientCertChain if self.x509Fingerprint or self.x509TrustList: if isinstance(chain, X509CertChain): if self.x509Fingerprint: if chain.getFingerprint() != self.x509Fingerprint: raise TLSFingerprintError(\ "X.509 fingerprint mismatch: %s, %s" % \ (chain.getFingerprint(), self.x509Fingerprint)) else: #self.x509TrustList if not chain.validate(self.x509TrustList): raise TLSValidationError("X.509 validation failure") if self.x509CommonName and \ (chain.getCommonName() != self.x509CommonName): raise TLSAuthorizationError(\ "X.509 Common Name mismatch: %s, %s" % \ (chain.getCommonName(), self.x509CommonName)) elif chain: raise TLSAuthenticationTypeError() else: raise TLSNoAuthenticationError() elif self.cryptoID: import cryptoIDlib.CertChain if isinstance(chain, cryptoIDlib.CertChain.CertChain): if chain.cryptoID != self.cryptoID: raise TLSFingerprintError(\ "cryptoID mismatch: %s, %s" % \ (chain.cryptoID, self.cryptoID)) if self.protocol: if not chain.checkProtocol(self.protocol): raise TLSAuthorizationError(\ "cryptoID protocol mismatch") if not chain.validate(): raise TLSValidationError("cryptoID validation failure") elif chain: raise TLSAuthenticationTypeError() else: raise TLSNoAuthenticationError()
Python
"""OpenSSL/M2Crypto 3DES implementation.""" from cryptomath import * from TripleDES import * if m2cryptoLoaded: def new(key, mode, IV): return OpenSSL_TripleDES(key, mode, IV) class OpenSSL_TripleDES(TripleDES): def __init__(self, key, mode, IV): TripleDES.__init__(self, key, mode, IV, "openssl") self.key = key self.IV = IV def _createContext(self, encrypt): context = m2.cipher_ctx_new() cipherType = m2.des_ede3_cbc() m2.cipher_init(context, cipherType, self.key, self.IV, encrypt) return context def encrypt(self, plaintext): TripleDES.encrypt(self, plaintext) context = self._createContext(1) ciphertext = m2.cipher_update(context, plaintext) m2.cipher_ctx_free(context) self.IV = ciphertext[-self.block_size:] return ciphertext def decrypt(self, ciphertext): TripleDES.decrypt(self, ciphertext) context = self._createContext(0) #I think M2Crypto has a bug - it fails to decrypt and return the last block passed in. #To work around this, we append sixteen zeros to the string, below: plaintext = m2.cipher_update(context, ciphertext+('\0'*16)) #If this bug is ever fixed, then plaintext will end up having a garbage #plaintext block on the end. That's okay - the below code will ignore it. plaintext = plaintext[:len(ciphertext)] m2.cipher_ctx_free(context) self.IV = ciphertext[-self.block_size:] return plaintext
Python
"""Cryptlib AES implementation.""" from cryptomath import * from AES import * if cryptlibpyLoaded: def new(key, mode, IV): return Cryptlib_AES(key, mode, IV) class Cryptlib_AES(AES): def __init__(self, key, mode, IV): AES.__init__(self, key, mode, IV, "cryptlib") self.context = cryptlib_py.cryptCreateContext(cryptlib_py.CRYPT_UNUSED, cryptlib_py.CRYPT_ALGO_AES) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_MODE, cryptlib_py.CRYPT_MODE_CBC) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_KEYSIZE, len(key)) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_KEY, key) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_IV, IV) def __del__(self): cryptlib_py.cryptDestroyContext(self.context) def encrypt(self, plaintext): AES.encrypt(self, plaintext) bytes = stringToBytes(plaintext) cryptlib_py.cryptEncrypt(self.context, bytes) return bytesToString(bytes) def decrypt(self, ciphertext): AES.decrypt(self, ciphertext) bytes = stringToBytes(ciphertext) cryptlib_py.cryptDecrypt(self.context, bytes) return bytesToString(bytes)
Python
"""Factory functions for asymmetric cryptography. @sort: generateRSAKey, parseXMLKey, parsePEMKey, parseAsPublicKey, parseAsPrivateKey """ from compat import * from RSAKey import RSAKey from Python_RSAKey import Python_RSAKey import cryptomath if cryptomath.m2cryptoLoaded: from OpenSSL_RSAKey import OpenSSL_RSAKey if cryptomath.pycryptoLoaded: from PyCrypto_RSAKey import PyCrypto_RSAKey # ************************************************************************** # Factory Functions for RSA Keys # ************************************************************************** def generateRSAKey(bits, implementations=["openssl", "python"]): """Generate an RSA key with the specified bit length. @type bits: int @param bits: Desired bit length of the new key's modulus. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: A new RSA private key. """ for implementation in implementations: if implementation == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_RSAKey.generate(bits) elif implementation == "python": return Python_RSAKey.generate(bits) raise ValueError("No acceptable implementations") def parseXMLKey(s, private=False, public=False, implementations=["python"]): """Parse an XML-format key. The XML format used here is specific to tlslite and cryptoIDlib. The format can store the public component of a key, or the public and private components. For example:: <publicKey xmlns="http://trevp.net/rsa"> <n>4a5yzB8oGNlHo866CAspAC47M4Fvx58zwK8pou... <e>Aw==</e> </publicKey> <privateKey xmlns="http://trevp.net/rsa"> <n>4a5yzB8oGNlHo866CAspAC47M4Fvx58zwK8pou... <e>Aw==</e> <d>JZ0TIgUxWXmL8KJ0VqyG1V0J3ern9pqIoB0xmy... <p>5PreIj6z6ldIGL1V4+1C36dQFHNCQHJvW52GXc... <q>/E/wDit8YXPCxx126zTq2ilQ3IcW54NJYyNjiZ... <dP>mKc+wX8inDowEH45Qp4slRo1YveBgExKPROu6... <dQ>qDVKtBz9lk0shL5PR3ickXDgkwS576zbl2ztB... <qInv>j6E8EA7dNsTImaXexAmLA1DoeArsYeFAInr... </privateKey> @type s: str @param s: A string containing an XML public or private key. @type private: bool @param private: If True, a L{SyntaxError} will be raised if the private key component is not present. @type public: bool @param public: If True, the private key component (if present) will be discarded, so this function will always return a public key. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: An RSA key. @raise SyntaxError: If the key is not properly formatted. """ for implementation in implementations: if implementation == "python": key = Python_RSAKey.parseXML(s) break else: raise ValueError("No acceptable implementations") return _parseKeyHelper(key, private, public) #Parse as an OpenSSL or Python key def parsePEMKey(s, private=False, public=False, passwordCallback=None, implementations=["openssl", "python"]): """Parse a PEM-format key. The PEM format is used by OpenSSL and other tools. The format is typically used to store both the public and private components of a key. For example:: -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDYscuoMzsGmW0pAYsmyHltxB2TdwHS0dImfjCMfaSDkfLdZY5+ dOWORVns9etWnr194mSGA1F0Pls/VJW8+cX9+3vtJV8zSdANPYUoQf0TP7VlJxkH dSRkUbEoz5bAAs/+970uos7n7iXQIni+3erUTdYEk2iWnMBjTljfgbK/dQIDAQAB AoGAJHoJZk75aKr7DSQNYIHuruOMdv5ZeDuJvKERWxTrVJqE32/xBKh42/IgqRrc esBN9ZregRCd7YtxoL+EVUNWaJNVx2mNmezEznrc9zhcYUrgeaVdFO2yBF1889zO gCOVwrO8uDgeyj6IKa25H6c1N13ih/o7ZzEgWbGG+ylU1yECQQDv4ZSJ4EjSh/Fl aHdz3wbBa/HKGTjC8iRy476Cyg2Fm8MZUe9Yy3udOrb5ZnS2MTpIXt5AF3h2TfYV VoFXIorjAkEA50FcJmzT8sNMrPaV8vn+9W2Lu4U7C+K/O2g1iXMaZms5PC5zV5aV CKXZWUX1fq2RaOzlbQrpgiolhXpeh8FjxwJBAOFHzSQfSsTNfttp3KUpU0LbiVvv i+spVSnA0O4rq79KpVNmK44Mq67hsW1P11QzrzTAQ6GVaUBRv0YS061td1kCQHnP wtN2tboFR6lABkJDjxoGRvlSt4SOPr7zKGgrWjeiuTZLHXSAnCY+/hr5L9Q3ZwXG 6x6iBdgLjVIe4BZQNtcCQQDXGv/gWinCNTN3MPWfTW/RGzuMYVmyBFais0/VrgdH h1dLpztmpQqfyH/zrBXQ9qL/zR4ojS6XYneO/U18WpEe -----END RSA PRIVATE KEY----- To generate a key like this with OpenSSL, run:: openssl genrsa 2048 > key.pem This format also supports password-encrypted private keys. TLS Lite can only handle password-encrypted private keys when OpenSSL and M2Crypto are installed. In this case, passwordCallback will be invoked to query the user for the password. @type s: str @param s: A string containing a PEM-encoded public or private key. @type private: bool @param private: If True, a L{SyntaxError} will be raised if the private key component is not present. @type public: bool @param public: If True, the private key component (if present) will be discarded, so this function will always return a public key. @type passwordCallback: callable @param passwordCallback: This function will be called, with no arguments, if the PEM-encoded private key is password-encrypted. The callback should return the password string. If the password is incorrect, SyntaxError will be raised. If no callback is passed and the key is password-encrypted, a prompt will be displayed at the console. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: An RSA key. @raise SyntaxError: If the key is not properly formatted. """ for implementation in implementations: if implementation == "openssl" and cryptomath.m2cryptoLoaded: key = OpenSSL_RSAKey.parse(s, passwordCallback) break elif implementation == "python": key = Python_RSAKey.parsePEM(s) break else: raise ValueError("No acceptable implementations") return _parseKeyHelper(key, private, public) def _parseKeyHelper(key, private, public): if private: if not key.hasPrivateKey(): raise SyntaxError("Not a private key!") if public: return _createPublicKey(key) if private: if hasattr(key, "d"): return _createPrivateKey(key) else: return key return key def parseAsPublicKey(s): """Parse an XML or PEM-formatted public key. @type s: str @param s: A string containing an XML or PEM-encoded public or private key. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: An RSA public key. @raise SyntaxError: If the key is not properly formatted. """ try: return parsePEMKey(s, public=True) except: return parseXMLKey(s, public=True) def parsePrivateKey(s): """Parse an XML or PEM-formatted private key. @type s: str @param s: A string containing an XML or PEM-encoded private key. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: An RSA private key. @raise SyntaxError: If the key is not properly formatted. """ try: return parsePEMKey(s, private=True) except: return parseXMLKey(s, private=True) def _createPublicKey(key): """ Create a new public key. Discard any private component, and return the most efficient key possible. """ if not isinstance(key, RSAKey): raise AssertionError() return _createPublicRSAKey(key.n, key.e) def _createPrivateKey(key): """ Create a new private key. Return the most efficient key possible. """ if not isinstance(key, RSAKey): raise AssertionError() if not key.hasPrivateKey(): raise AssertionError() return _createPrivateRSAKey(key.n, key.e, key.d, key.p, key.q, key.dP, key.dQ, key.qInv) def _createPublicRSAKey(n, e, implementations = ["openssl", "pycrypto", "python"]): for implementation in implementations: if implementation == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_RSAKey(n, e) elif implementation == "pycrypto" and cryptomath.pycryptoLoaded: return PyCrypto_RSAKey(n, e) elif implementation == "python": return Python_RSAKey(n, e) raise ValueError("No acceptable implementations") def _createPrivateRSAKey(n, e, d, p, q, dP, dQ, qInv, implementations = ["pycrypto", "python"]): for implementation in implementations: if implementation == "pycrypto" and cryptomath.pycryptoLoaded: return PyCrypto_RSAKey(n, e, d, p, q, dP, dQ, qInv) elif implementation == "python": return Python_RSAKey(n, e, d, p, q, dP, dQ, qInv) raise ValueError("No acceptable implementations")
Python
"""Abstract class for RC4.""" from compat import * #For False class RC4: def __init__(self, keyBytes, implementation): if len(keyBytes) < 16 or len(keyBytes) > 256: raise ValueError() self.isBlockCipher = False self.name = "rc4" self.implementation = implementation def encrypt(self, plaintext): raise NotImplementedError() def decrypt(self, ciphertext): raise NotImplementedError()
Python
"""Abstract class for RSA.""" from cryptomath import * class RSAKey: """This is an abstract base class for RSA keys. Particular implementations of RSA keys, such as L{OpenSSL_RSAKey.OpenSSL_RSAKey}, L{Python_RSAKey.Python_RSAKey}, and L{PyCrypto_RSAKey.PyCrypto_RSAKey}, inherit from this. To create or parse an RSA key, don't use one of these classes directly. Instead, use the factory functions in L{tlslite.utils.keyfactory}. """ def __init__(self, n=0, e=0): """Create a new RSA key. If n and e are passed in, the new key will be initialized. @type n: int @param n: RSA modulus. @type e: int @param e: RSA public exponent. """ raise NotImplementedError() def __len__(self): """Return the length of this key in bits. @rtype: int """ return numBits(self.n) def hasPrivateKey(self): """Return whether or not this key has a private component. @rtype: bool """ raise NotImplementedError() def hash(self): """Return the cryptoID <keyHash> value corresponding to this key. @rtype: str """ raise NotImplementedError() def getSigningAlgorithm(self): """Return the cryptoID sigAlgo value corresponding to this key. @rtype: str """ return "pkcs1-sha1" def hashAndSign(self, bytes): """Hash and sign the passed-in bytes. This requires the key to have a private component. It performs a PKCS1-SHA1 signature on the passed-in data. @type bytes: str or L{array.array} of unsigned bytes @param bytes: The value which will be hashed and signed. @rtype: L{array.array} of unsigned bytes. @return: A PKCS1-SHA1 signature on the passed-in data. """ if not isinstance(bytes, type("")): bytes = bytesToString(bytes) hashBytes = stringToBytes(sha1(bytes).digest()) prefixedHashBytes = self._addPKCS1SHA1Prefix(hashBytes) sigBytes = self.sign(prefixedHashBytes) return sigBytes def hashAndVerify(self, sigBytes, bytes): """Hash and verify the passed-in bytes with the signature. This verifies a PKCS1-SHA1 signature on the passed-in data. @type sigBytes: L{array.array} of unsigned bytes @param sigBytes: A PKCS1-SHA1 signature. @type bytes: str or L{array.array} of unsigned bytes @param bytes: The value which will be hashed and verified. @rtype: bool @return: Whether the signature matches the passed-in data. """ if not isinstance(bytes, type("")): bytes = bytesToString(bytes) hashBytes = stringToBytes(sha1(bytes).digest()) prefixedHashBytes = self._addPKCS1SHA1Prefix(hashBytes) return self.verify(sigBytes, prefixedHashBytes) def sign(self, bytes): """Sign the passed-in bytes. This requires the key to have a private component. It performs a PKCS1 signature on the passed-in data. @type bytes: L{array.array} of unsigned bytes @param bytes: The value which will be signed. @rtype: L{array.array} of unsigned bytes. @return: A PKCS1 signature on the passed-in data. """ if not self.hasPrivateKey(): raise AssertionError() paddedBytes = self._addPKCS1Padding(bytes, 1) m = bytesToNumber(paddedBytes) if m >= self.n: raise ValueError() c = self._rawPrivateKeyOp(m) sigBytes = numberToBytes(c) return sigBytes def verify(self, sigBytes, bytes): """Verify the passed-in bytes with the signature. This verifies a PKCS1 signature on the passed-in data. @type sigBytes: L{array.array} of unsigned bytes @param sigBytes: A PKCS1 signature. @type bytes: L{array.array} of unsigned bytes @param bytes: The value which will be verified. @rtype: bool @return: Whether the signature matches the passed-in data. """ paddedBytes = self._addPKCS1Padding(bytes, 1) c = bytesToNumber(sigBytes) if c >= self.n: return False m = self._rawPublicKeyOp(c) checkBytes = numberToBytes(m) return checkBytes == paddedBytes def encrypt(self, bytes): """Encrypt the passed-in bytes. This performs PKCS1 encryption of the passed-in data. @type bytes: L{array.array} of unsigned bytes @param bytes: The value which will be encrypted. @rtype: L{array.array} of unsigned bytes. @return: A PKCS1 encryption of the passed-in data. """ paddedBytes = self._addPKCS1Padding(bytes, 2) m = bytesToNumber(paddedBytes) if m >= self.n: raise ValueError() c = self._rawPublicKeyOp(m) encBytes = numberToBytes(c) return encBytes def decrypt(self, encBytes): """Decrypt the passed-in bytes. This requires the key to have a private component. It performs PKCS1 decryption of the passed-in data. @type encBytes: L{array.array} of unsigned bytes @param encBytes: The value which will be decrypted. @rtype: L{array.array} of unsigned bytes or None. @return: A PKCS1 decryption of the passed-in data or None if the data is not properly formatted. """ if not self.hasPrivateKey(): raise AssertionError() c = bytesToNumber(encBytes) if c >= self.n: return None m = self._rawPrivateKeyOp(c) decBytes = numberToBytes(m) if (len(decBytes) != numBytes(self.n)-1): #Check first byte return None if decBytes[0] != 2: #Check second byte return None for x in range(len(decBytes)-1): #Scan through for zero separator if decBytes[x]== 0: break else: return None return decBytes[x+1:] #Return everything after the separator def _rawPrivateKeyOp(self, m): raise NotImplementedError() def _rawPublicKeyOp(self, c): raise NotImplementedError() def acceptsPassword(self): """Return True if the write() method accepts a password for use in encrypting the private key. @rtype: bool """ raise NotImplementedError() def write(self, password=None): """Return a string containing the key. @rtype: str @return: A string describing the key, in whichever format (PEM or XML) is native to the implementation. """ raise NotImplementedError() def writeXMLPublicKey(self, indent=''): """Return a string containing the key. @rtype: str @return: A string describing the public key, in XML format. """ return Python_RSAKey(self.n, self.e).write(indent) def generate(bits): """Generate a new key with the specified bit length. @rtype: L{tlslite.utils.RSAKey.RSAKey} """ raise NotImplementedError() generate = staticmethod(generate) # ************************************************************************** # Helper Functions for RSA Keys # ************************************************************************** def _addPKCS1SHA1Prefix(self, bytes): prefixBytes = createByteArraySequence(\ [48,33,48,9,6,5,43,14,3,2,26,5,0,4,20]) prefixedBytes = prefixBytes + bytes return prefixedBytes def _addPKCS1Padding(self, bytes, blockType): padLength = (numBytes(self.n) - (len(bytes)+3)) if blockType == 1: #Signature padding pad = [0xFF] * padLength elif blockType == 2: #Encryption padding pad = createByteArraySequence([]) while len(pad) < padLength: padBytes = getRandomBytes(padLength * 2) pad = [b for b in padBytes if b != 0] pad = pad[:padLength] else: raise AssertionError() #NOTE: To be proper, we should add [0,blockType]. However, #the zero is lost when the returned padding is converted #to a number, so we don't even bother with it. Also, #adding it would cause a misalignment in verify() padding = createByteArraySequence([blockType] + pad + [0]) paddedBytes = padding + bytes return paddedBytes
Python
"""Classes for reading/writing binary data (such as TLS records).""" from compat import * class Writer: def __init__(self, length=0): #If length is zero, then this is just a "trial run" to determine length self.index = 0 self.bytes = createByteArrayZeros(length) def add(self, x, length): if self.bytes: newIndex = self.index+length-1 while newIndex >= self.index: self.bytes[newIndex] = x & 0xFF x >>= 8 newIndex -= 1 self.index += length def addFixSeq(self, seq, length): if self.bytes: for e in seq: self.add(e, length) else: self.index += len(seq)*length def addVarSeq(self, seq, length, lengthLength): if self.bytes: self.add(len(seq)*length, lengthLength) for e in seq: self.add(e, length) else: self.index += lengthLength + (len(seq)*length) class Parser: def __init__(self, bytes): self.bytes = bytes self.index = 0 def get(self, length): if self.index + length > len(self.bytes): raise SyntaxError() x = 0 for count in range(length): x <<= 8 x |= self.bytes[self.index] self.index += 1 return x def getFixBytes(self, lengthBytes): bytes = self.bytes[self.index : self.index+lengthBytes] self.index += lengthBytes return bytes def getVarBytes(self, lengthLength): lengthBytes = self.get(lengthLength) return self.getFixBytes(lengthBytes) def getFixList(self, length, lengthList): l = [0] * lengthList for x in range(lengthList): l[x] = self.get(length) return l def getVarList(self, length, lengthLength): lengthList = self.get(lengthLength) if lengthList % length != 0: raise SyntaxError() lengthList = int(lengthList/length) l = [0] * lengthList for x in range(lengthList): l[x] = self.get(length) return l def startLengthCheck(self, lengthLength): self.lengthCheck = self.get(lengthLength) self.indexCheck = self.index def setLengthCheck(self, length): self.lengthCheck = length self.indexCheck = self.index def stopLengthCheck(self): if (self.index - self.indexCheck) != self.lengthCheck: raise SyntaxError() def atLengthCheck(self): if (self.index - self.indexCheck) < self.lengthCheck: return False elif (self.index - self.indexCheck) == self.lengthCheck: return True else: raise SyntaxError()
Python
"""PyCrypto RC4 implementation.""" from cryptomath import * from RC4 import * if pycryptoLoaded: import Crypto.Cipher.ARC4 def new(key): return PyCrypto_RC4(key) class PyCrypto_RC4(RC4): def __init__(self, key): RC4.__init__(self, key, "pycrypto") self.context = Crypto.Cipher.ARC4.new(key) def encrypt(self, plaintext): return self.context.encrypt(plaintext) def decrypt(self, ciphertext): return self.context.decrypt(ciphertext)
Python
"""Factory functions for symmetric cryptography.""" import os import Python_AES import Python_RC4 import cryptomath tripleDESPresent = False if cryptomath.m2cryptoLoaded: import OpenSSL_AES import OpenSSL_RC4 import OpenSSL_TripleDES tripleDESPresent = True if cryptomath.cryptlibpyLoaded: import Cryptlib_AES import Cryptlib_RC4 import Cryptlib_TripleDES tripleDESPresent = True if cryptomath.pycryptoLoaded: import PyCrypto_AES import PyCrypto_RC4 import PyCrypto_TripleDES tripleDESPresent = True # ************************************************************************** # Factory Functions for AES # ************************************************************************** def createAES(key, IV, implList=None): """Create a new AES object. @type key: str @param key: A 16, 24, or 32 byte string. @type IV: str @param IV: A 16 byte string @rtype: L{tlslite.utils.AES} @return: An AES object. """ if implList == None: implList = ["cryptlib", "openssl", "pycrypto", "python"] for impl in implList: if impl == "cryptlib" and cryptomath.cryptlibpyLoaded: return Cryptlib_AES.new(key, 2, IV) elif impl == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_AES.new(key, 2, IV) elif impl == "pycrypto" and cryptomath.pycryptoLoaded: return PyCrypto_AES.new(key, 2, IV) elif impl == "python": return Python_AES.new(key, 2, IV) raise NotImplementedError() def createRC4(key, IV, implList=None): """Create a new RC4 object. @type key: str @param key: A 16 to 32 byte string. @type IV: object @param IV: Ignored, whatever it is. @rtype: L{tlslite.utils.RC4} @return: An RC4 object. """ if implList == None: implList = ["cryptlib", "openssl", "pycrypto", "python"] if len(IV) != 0: raise AssertionError() for impl in implList: if impl == "cryptlib" and cryptomath.cryptlibpyLoaded: return Cryptlib_RC4.new(key) elif impl == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_RC4.new(key) elif impl == "pycrypto" and cryptomath.pycryptoLoaded: return PyCrypto_RC4.new(key) elif impl == "python": return Python_RC4.new(key) raise NotImplementedError() #Create a new TripleDES instance def createTripleDES(key, IV, implList=None): """Create a new 3DES object. @type key: str @param key: A 24 byte string. @type IV: str @param IV: An 8 byte string @rtype: L{tlslite.utils.TripleDES} @return: A 3DES object. """ if implList == None: implList = ["cryptlib", "openssl", "pycrypto"] for impl in implList: if impl == "cryptlib" and cryptomath.cryptlibpyLoaded: return Cryptlib_TripleDES.new(key, 2, IV) elif impl == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_TripleDES.new(key, 2, IV) elif impl == "pycrypto" and cryptomath.pycryptoLoaded: return PyCrypto_TripleDES.new(key, 2, IV) raise NotImplementedError()
Python
"""Class for parsing ASN.1""" from compat import * from codec import * #Takes a byte array which has a DER TLV field at its head class ASN1Parser: def __init__(self, bytes): p = Parser(bytes) p.get(1) #skip Type #Get Length self.length = self._getASN1Length(p) #Get Value self.value = p.getFixBytes(self.length) #Assuming this is a sequence... def getChild(self, which): p = Parser(self.value) for x in range(which+1): markIndex = p.index p.get(1) #skip Type length = self._getASN1Length(p) p.getFixBytes(length) return ASN1Parser(p.bytes[markIndex : p.index]) #Decode the ASN.1 DER length field def _getASN1Length(self, p): firstLength = p.get(1) if firstLength<=127: return firstLength else: lengthLength = firstLength & 0x7F return p.get(lengthLength)
Python
"""Abstract class for 3DES.""" from compat import * #For True class TripleDES: def __init__(self, key, mode, IV, implementation): if len(key) != 24: raise ValueError() if mode != 2: raise ValueError() if len(IV) != 8: raise ValueError() self.isBlockCipher = True self.block_size = 8 self.implementation = implementation self.name = "3des" #CBC-Mode encryption, returns ciphertext #WARNING: *MAY* modify the input as well def encrypt(self, plaintext): assert(len(plaintext) % 8 == 0) #CBC-Mode decryption, returns plaintext #WARNING: *MAY* modify the input as well def decrypt(self, ciphertext): assert(len(ciphertext) % 8 == 0)
Python
"""Abstract class for AES.""" class AES: def __init__(self, key, mode, IV, implementation): if len(key) not in (16, 24, 32): raise AssertionError() if mode != 2: raise AssertionError() if len(IV) != 16: raise AssertionError() self.isBlockCipher = True self.block_size = 16 self.implementation = implementation if len(key)==16: self.name = "aes128" elif len(key)==24: self.name = "aes192" elif len(key)==32: self.name = "aes256" else: raise AssertionError() #CBC-Mode encryption, returns ciphertext #WARNING: *MAY* modify the input as well def encrypt(self, plaintext): assert(len(plaintext) % 16 == 0) #CBC-Mode decryption, returns plaintext #WARNING: *MAY* modify the input as well def decrypt(self, ciphertext): assert(len(ciphertext) % 16 == 0)
Python
"""Pure-Python RC4 implementation.""" from RC4 import RC4 from cryptomath import * def new(key): return Python_RC4(key) class Python_RC4(RC4): def __init__(self, key): RC4.__init__(self, key, "python") keyBytes = stringToBytes(key) S = [i for i in range(256)] j = 0 for i in range(256): j = (j + S[i] + keyBytes[i % len(keyBytes)]) % 256 S[i], S[j] = S[j], S[i] self.S = S self.i = 0 self.j = 0 def encrypt(self, plaintext): plaintextBytes = stringToBytes(plaintext) S = self.S i = self.i j = self.j for x in range(len(plaintextBytes)): i = (i + 1) % 256 j = (j + S[i]) % 256 S[i], S[j] = S[j], S[i] t = (S[i] + S[j]) % 256 plaintextBytes[x] ^= S[t] self.i = i self.j = j return bytesToString(plaintextBytes) def decrypt(self, ciphertext): return self.encrypt(ciphertext)
Python
"""PyCrypto RSA implementation.""" from cryptomath import * from RSAKey import * from Python_RSAKey import Python_RSAKey if pycryptoLoaded: from Crypto.PublicKey import RSA class PyCrypto_RSAKey(RSAKey): def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0): if not d: self.rsa = RSA.construct( (n, e) ) else: self.rsa = RSA.construct( (n, e, d, p, q) ) def __getattr__(self, name): return getattr(self.rsa, name) def hasPrivateKey(self): return self.rsa.has_private() def hash(self): return Python_RSAKey(self.n, self.e).hash() def _rawPrivateKeyOp(self, m): s = numberToString(m) byteLength = numBytes(self.n) if len(s)== byteLength: pass elif len(s) == byteLength-1: s = '\0' + s else: raise AssertionError() c = stringToNumber(self.rsa.decrypt((s,))) return c def _rawPublicKeyOp(self, c): s = numberToString(c) byteLength = numBytes(self.n) if len(s)== byteLength: pass elif len(s) == byteLength-1: s = '\0' + s else: raise AssertionError() m = stringToNumber(self.rsa.encrypt(s, None)[0]) return m def writeXMLPublicKey(self, indent=''): return Python_RSAKey(self.n, self.e).write(indent) def generate(bits): key = PyCrypto_RSAKey() def f(numBytes): return bytesToString(getRandomBytes(numBytes)) key.rsa = RSA.generate(bits, f) return key generate = staticmethod(generate)
Python
"""Miscellaneous functions to mask Python/Jython differences.""" import os import sha if os.name != "java": BaseException = Exception from sets import Set import array import math def createByteArraySequence(seq): return array.array('B', seq) def createByteArrayZeros(howMany): return array.array('B', [0] * howMany) def concatArrays(a1, a2): return a1+a2 def bytesToString(bytes): return bytes.tostring() def stringToBytes(s): bytes = createByteArrayZeros(0) bytes.fromstring(s) return bytes def numBits(n): if n==0: return 0 return int(math.floor(math.log(n, 2))+1) class CertChainBase: pass class SelfTestBase: pass class ReportFuncBase: pass #Helper functions for working with sets (from Python 2.3) def iterSet(set): return iter(set) def getListFromSet(set): return list(set) #Factory function for getting a SHA1 object def getSHA1(s): return sha.sha(s) import sys import traceback def formatExceptionTrace(e): newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) return newStr else: #Jython 2.1 is missing lots of python 2.3 stuff, #which we have to emulate here: import java import jarray BaseException = java.lang.Exception def createByteArraySequence(seq): if isinstance(seq, type("")): #If it's a string, convert seq = [ord(c) for c in seq] return jarray.array(seq, 'h') #use short instead of bytes, cause bytes are signed def createByteArrayZeros(howMany): return jarray.zeros(howMany, 'h') #use short instead of bytes, cause bytes are signed def concatArrays(a1, a2): l = list(a1)+list(a2) return createByteArraySequence(l) #WAY TOO SLOW - MUST BE REPLACED------------ def bytesToString(bytes): return "".join([chr(b) for b in bytes]) def stringToBytes(s): bytes = createByteArrayZeros(len(s)) for count, c in enumerate(s): bytes[count] = ord(c) return bytes #WAY TOO SLOW - MUST BE REPLACED------------ def numBits(n): if n==0: return 0 n= 1L * n; #convert to long, if it isn't already return n.__tojava__(java.math.BigInteger).bitLength() #This properly creates static methods for Jython class staticmethod: def __init__(self, anycallable): self.__call__ = anycallable #Properties are not supported for Jython class property: def __init__(self, anycallable): pass #True and False have to be specially defined False = 0 True = 1 class StopIteration(Exception): pass def enumerate(collection): return zip(range(len(collection)), collection) class Set: def __init__(self, seq=None): self.values = {} if seq: for e in seq: self.values[e] = None def add(self, e): self.values[e] = None def discard(self, e): if e in self.values.keys(): del(self.values[e]) def union(self, s): ret = Set() for e in self.values.keys(): ret.values[e] = None for e in s.values.keys(): ret.values[e] = None return ret def issubset(self, other): for e in self.values.keys(): if e not in other.values.keys(): return False return True def __nonzero__( self): return len(self.values.keys()) def __contains__(self, e): return e in self.values.keys() def iterSet(set): return set.values.keys() def getListFromSet(set): return set.values.keys() """ class JCE_SHA1: def __init__(self, s=None): self.md = java.security.MessageDigest.getInstance("SHA1") if s: self.update(s) def update(self, s): self.md.update(s) def copy(self): sha1 = JCE_SHA1() sha1.md = self.md.clone() return sha1 def digest(self): digest = self.md.digest() bytes = jarray.zeros(20, 'h') for count in xrange(20): x = digest[count] if x < 0: x += 256 bytes[count] = x return bytes """ #Factory function for getting a SHA1 object #The JCE_SHA1 class is way too slow... #the sha.sha object we use instead is broken in the jython 2.1 #release, and needs to be patched def getSHA1(s): #return JCE_SHA1(s) return sha.sha(s) #Adjust the string to an array of bytes def stringToJavaByteArray(s): bytes = jarray.zeros(len(s), 'b') for count, c in enumerate(s): x = ord(c) if x >= 128: x -= 256 bytes[count] = x return bytes import sys import traceback def formatExceptionTrace(e): newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) return newStr
Python
""" A pure python (slow) implementation of rijndael with a decent interface To include - from rijndael import rijndael To do a key setup - r = rijndael(key, block_size = 16) key must be a string of length 16, 24, or 32 blocksize must be 16, 24, or 32. Default is 16 To use - ciphertext = r.encrypt(plaintext) plaintext = r.decrypt(ciphertext) If any strings are of the wrong length a ValueError is thrown """ # ported from the Java reference code by Bram Cohen, bram@gawth.com, April 2001 # this code is public domain, unless someone makes # an intellectual property claim against the reference # code, in which case it can be made public domain by # deleting all the comments and renaming all the variables import copy import string #----------------------- #TREV - ADDED BECAUSE THERE'S WARNINGS ABOUT INT OVERFLOW BEHAVIOR CHANGING IN #2.4..... import os if os.name != "java": import exceptions if hasattr(exceptions, "FutureWarning"): import warnings warnings.filterwarnings("ignore", category=FutureWarning, append=1) #----------------------- shifts = [[[0, 0], [1, 3], [2, 2], [3, 1]], [[0, 0], [1, 5], [2, 4], [3, 3]], [[0, 0], [1, 7], [3, 5], [4, 4]]] # [keysize][block_size] num_rounds = {16: {16: 10, 24: 12, 32: 14}, 24: {16: 12, 24: 12, 32: 14}, 32: {16: 14, 24: 14, 32: 14}} A = [[1, 1, 1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 1], [1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1, 1], [1, 1, 1, 1, 0, 0, 0, 1]] # produce log and alog tables, needed for multiplying in the # field GF(2^m) (generator = 3) alog = [1] for i in xrange(255): j = (alog[-1] << 1) ^ alog[-1] if j & 0x100 != 0: j ^= 0x11B alog.append(j) log = [0] * 256 for i in xrange(1, 255): log[alog[i]] = i # multiply two elements of GF(2^m) def mul(a, b): if a == 0 or b == 0: return 0 return alog[(log[a & 0xFF] + log[b & 0xFF]) % 255] # substitution box based on F^{-1}(x) box = [[0] * 8 for i in xrange(256)] box[1][7] = 1 for i in xrange(2, 256): j = alog[255 - log[i]] for t in xrange(8): box[i][t] = (j >> (7 - t)) & 0x01 B = [0, 1, 1, 0, 0, 0, 1, 1] # affine transform: box[i] <- B + A*box[i] cox = [[0] * 8 for i in xrange(256)] for i in xrange(256): for t in xrange(8): cox[i][t] = B[t] for j in xrange(8): cox[i][t] ^= A[t][j] * box[i][j] # S-boxes and inverse S-boxes S = [0] * 256 Si = [0] * 256 for i in xrange(256): S[i] = cox[i][0] << 7 for t in xrange(1, 8): S[i] ^= cox[i][t] << (7-t) Si[S[i] & 0xFF] = i # T-boxes G = [[2, 1, 1, 3], [3, 2, 1, 1], [1, 3, 2, 1], [1, 1, 3, 2]] AA = [[0] * 8 for i in xrange(4)] for i in xrange(4): for j in xrange(4): AA[i][j] = G[i][j] AA[i][i+4] = 1 for i in xrange(4): pivot = AA[i][i] if pivot == 0: t = i + 1 while AA[t][i] == 0 and t < 4: t += 1 assert t != 4, 'G matrix must be invertible' for j in xrange(8): AA[i][j], AA[t][j] = AA[t][j], AA[i][j] pivot = AA[i][i] for j in xrange(8): if AA[i][j] != 0: AA[i][j] = alog[(255 + log[AA[i][j] & 0xFF] - log[pivot & 0xFF]) % 255] for t in xrange(4): if i != t: for j in xrange(i+1, 8): AA[t][j] ^= mul(AA[i][j], AA[t][i]) AA[t][i] = 0 iG = [[0] * 4 for i in xrange(4)] for i in xrange(4): for j in xrange(4): iG[i][j] = AA[i][j + 4] def mul4(a, bs): if a == 0: return 0 r = 0 for b in bs: r <<= 8 if b != 0: r = r | mul(a, b) return r T1 = [] T2 = [] T3 = [] T4 = [] T5 = [] T6 = [] T7 = [] T8 = [] U1 = [] U2 = [] U3 = [] U4 = [] for t in xrange(256): s = S[t] T1.append(mul4(s, G[0])) T2.append(mul4(s, G[1])) T3.append(mul4(s, G[2])) T4.append(mul4(s, G[3])) s = Si[t] T5.append(mul4(s, iG[0])) T6.append(mul4(s, iG[1])) T7.append(mul4(s, iG[2])) T8.append(mul4(s, iG[3])) U1.append(mul4(t, iG[0])) U2.append(mul4(t, iG[1])) U3.append(mul4(t, iG[2])) U4.append(mul4(t, iG[3])) # round constants rcon = [1] r = 1 for t in xrange(1, 30): r = mul(2, r) rcon.append(r) del A del AA del pivot del B del G del box del log del alog del i del j del r del s del t del mul del mul4 del cox del iG class rijndael: def __init__(self, key, block_size = 16): if block_size != 16 and block_size != 24 and block_size != 32: raise ValueError('Invalid block size: ' + str(block_size)) if len(key) != 16 and len(key) != 24 and len(key) != 32: raise ValueError('Invalid key size: ' + str(len(key))) self.block_size = block_size ROUNDS = num_rounds[len(key)][block_size] BC = block_size / 4 # encryption round keys Ke = [[0] * BC for i in xrange(ROUNDS + 1)] # decryption round keys Kd = [[0] * BC for i in xrange(ROUNDS + 1)] ROUND_KEY_COUNT = (ROUNDS + 1) * BC KC = len(key) / 4 # copy user material bytes into temporary ints tk = [] for i in xrange(0, KC): tk.append((ord(key[i * 4]) << 24) | (ord(key[i * 4 + 1]) << 16) | (ord(key[i * 4 + 2]) << 8) | ord(key[i * 4 + 3])) # copy values into round key arrays t = 0 j = 0 while j < KC and t < ROUND_KEY_COUNT: Ke[t / BC][t % BC] = tk[j] Kd[ROUNDS - (t / BC)][t % BC] = tk[j] j += 1 t += 1 tt = 0 rconpointer = 0 while t < ROUND_KEY_COUNT: # extrapolate using phi (the round key evolution function) tt = tk[KC - 1] tk[0] ^= (S[(tt >> 16) & 0xFF] & 0xFF) << 24 ^ \ (S[(tt >> 8) & 0xFF] & 0xFF) << 16 ^ \ (S[ tt & 0xFF] & 0xFF) << 8 ^ \ (S[(tt >> 24) & 0xFF] & 0xFF) ^ \ (rcon[rconpointer] & 0xFF) << 24 rconpointer += 1 if KC != 8: for i in xrange(1, KC): tk[i] ^= tk[i-1] else: for i in xrange(1, KC / 2): tk[i] ^= tk[i-1] tt = tk[KC / 2 - 1] tk[KC / 2] ^= (S[ tt & 0xFF] & 0xFF) ^ \ (S[(tt >> 8) & 0xFF] & 0xFF) << 8 ^ \ (S[(tt >> 16) & 0xFF] & 0xFF) << 16 ^ \ (S[(tt >> 24) & 0xFF] & 0xFF) << 24 for i in xrange(KC / 2 + 1, KC): tk[i] ^= tk[i-1] # copy values into round key arrays j = 0 while j < KC and t < ROUND_KEY_COUNT: Ke[t / BC][t % BC] = tk[j] Kd[ROUNDS - (t / BC)][t % BC] = tk[j] j += 1 t += 1 # inverse MixColumn where needed for r in xrange(1, ROUNDS): for j in xrange(BC): tt = Kd[r][j] Kd[r][j] = U1[(tt >> 24) & 0xFF] ^ \ U2[(tt >> 16) & 0xFF] ^ \ U3[(tt >> 8) & 0xFF] ^ \ U4[ tt & 0xFF] self.Ke = Ke self.Kd = Kd def encrypt(self, plaintext): if len(plaintext) != self.block_size: raise ValueError('wrong block length, expected ' + str(self.block_size) + ' got ' + str(len(plaintext))) Ke = self.Ke BC = self.block_size / 4 ROUNDS = len(Ke) - 1 if BC == 4: SC = 0 elif BC == 6: SC = 1 else: SC = 2 s1 = shifts[SC][1][0] s2 = shifts[SC][2][0] s3 = shifts[SC][3][0] a = [0] * BC # temporary work array t = [] # plaintext to ints + key for i in xrange(BC): t.append((ord(plaintext[i * 4 ]) << 24 | ord(plaintext[i * 4 + 1]) << 16 | ord(plaintext[i * 4 + 2]) << 8 | ord(plaintext[i * 4 + 3]) ) ^ Ke[0][i]) # apply round transforms for r in xrange(1, ROUNDS): for i in xrange(BC): a[i] = (T1[(t[ i ] >> 24) & 0xFF] ^ T2[(t[(i + s1) % BC] >> 16) & 0xFF] ^ T3[(t[(i + s2) % BC] >> 8) & 0xFF] ^ T4[ t[(i + s3) % BC] & 0xFF] ) ^ Ke[r][i] t = copy.copy(a) # last round is special result = [] for i in xrange(BC): tt = Ke[ROUNDS][i] result.append((S[(t[ i ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF) result.append((S[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF) result.append((S[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8)) & 0xFF) result.append((S[ t[(i + s3) % BC] & 0xFF] ^ tt ) & 0xFF) return string.join(map(chr, result), '') def decrypt(self, ciphertext): if len(ciphertext) != self.block_size: raise ValueError('wrong block length, expected ' + str(self.block_size) + ' got ' + str(len(plaintext))) Kd = self.Kd BC = self.block_size / 4 ROUNDS = len(Kd) - 1 if BC == 4: SC = 0 elif BC == 6: SC = 1 else: SC = 2 s1 = shifts[SC][1][1] s2 = shifts[SC][2][1] s3 = shifts[SC][3][1] a = [0] * BC # temporary work array t = [0] * BC # ciphertext to ints + key for i in xrange(BC): t[i] = (ord(ciphertext[i * 4 ]) << 24 | ord(ciphertext[i * 4 + 1]) << 16 | ord(ciphertext[i * 4 + 2]) << 8 | ord(ciphertext[i * 4 + 3]) ) ^ Kd[0][i] # apply round transforms for r in xrange(1, ROUNDS): for i in xrange(BC): a[i] = (T5[(t[ i ] >> 24) & 0xFF] ^ T6[(t[(i + s1) % BC] >> 16) & 0xFF] ^ T7[(t[(i + s2) % BC] >> 8) & 0xFF] ^ T8[ t[(i + s3) % BC] & 0xFF] ) ^ Kd[r][i] t = copy.copy(a) # last round is special result = [] for i in xrange(BC): tt = Kd[ROUNDS][i] result.append((Si[(t[ i ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF) result.append((Si[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF) result.append((Si[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8)) & 0xFF) result.append((Si[ t[(i + s3) % BC] & 0xFF] ^ tt ) & 0xFF) return string.join(map(chr, result), '') def encrypt(key, block): return rijndael(key, len(block)).encrypt(block) def decrypt(key, block): return rijndael(key, len(block)).decrypt(block) def test(): def t(kl, bl): b = 'b' * bl r = rijndael('a' * kl, bl) assert r.decrypt(r.encrypt(b)) == b t(16, 16) t(16, 24) t(16, 32) t(24, 16) t(24, 24) t(24, 32) t(32, 16) t(32, 24) t(32, 32)
Python
"""OpenSSL/M2Crypto RSA implementation.""" from cryptomath import * from RSAKey import * from Python_RSAKey import Python_RSAKey #copied from M2Crypto.util.py, so when we load the local copy of m2 #we can still use it def password_callback(v, prompt1='Enter private key passphrase:', prompt2='Verify passphrase:'): from getpass import getpass while 1: try: p1=getpass(prompt1) if v: p2=getpass(prompt2) if p1==p2: break else: break except KeyboardInterrupt: return None return p1 if m2cryptoLoaded: class OpenSSL_RSAKey(RSAKey): def __init__(self, n=0, e=0): self.rsa = None self._hasPrivateKey = False if (n and not e) or (e and not n): raise AssertionError() if n and e: self.rsa = m2.rsa_new() m2.rsa_set_n(self.rsa, numberToMPI(n)) m2.rsa_set_e(self.rsa, numberToMPI(e)) def __del__(self): if self.rsa: m2.rsa_free(self.rsa) def __getattr__(self, name): if name == 'e': if not self.rsa: return 0 return mpiToNumber(m2.rsa_get_e(self.rsa)) elif name == 'n': if not self.rsa: return 0 return mpiToNumber(m2.rsa_get_n(self.rsa)) else: raise AttributeError def hasPrivateKey(self): return self._hasPrivateKey def hash(self): return Python_RSAKey(self.n, self.e).hash() def _rawPrivateKeyOp(self, m): s = numberToString(m) byteLength = numBytes(self.n) if len(s)== byteLength: pass elif len(s) == byteLength-1: s = '\0' + s else: raise AssertionError() c = stringToNumber(m2.rsa_private_encrypt(self.rsa, s, m2.no_padding)) return c def _rawPublicKeyOp(self, c): s = numberToString(c) byteLength = numBytes(self.n) if len(s)== byteLength: pass elif len(s) == byteLength-1: s = '\0' + s else: raise AssertionError() m = stringToNumber(m2.rsa_public_decrypt(self.rsa, s, m2.no_padding)) return m def acceptsPassword(self): return True def write(self, password=None): bio = m2.bio_new(m2.bio_s_mem()) if self._hasPrivateKey: if password: def f(v): return password m2.rsa_write_key(self.rsa, bio, m2.des_ede_cbc(), f) else: def f(): pass m2.rsa_write_key_no_cipher(self.rsa, bio, f) else: if password: raise AssertionError() m2.rsa_write_pub_key(self.rsa, bio) s = m2.bio_read(bio, m2.bio_ctrl_pending(bio)) m2.bio_free(bio) return s def writeXMLPublicKey(self, indent=''): return Python_RSAKey(self.n, self.e).write(indent) def generate(bits): key = OpenSSL_RSAKey() def f():pass key.rsa = m2.rsa_generate_key(bits, 3, f) key._hasPrivateKey = True return key generate = staticmethod(generate) def parse(s, passwordCallback=None): if s.startswith("-----BEGIN "): if passwordCallback==None: callback = password_callback else: def f(v, prompt1=None, prompt2=None): return passwordCallback() callback = f bio = m2.bio_new(m2.bio_s_mem()) try: m2.bio_write(bio, s) key = OpenSSL_RSAKey() if s.startswith("-----BEGIN RSA PRIVATE KEY-----"): def f():pass key.rsa = m2.rsa_read_key(bio, callback) if key.rsa == None: raise SyntaxError() key._hasPrivateKey = True elif s.startswith("-----BEGIN PUBLIC KEY-----"): key.rsa = m2.rsa_read_pub_key(bio) if key.rsa == None: raise SyntaxError() key._hasPrivateKey = False else: raise SyntaxError() return key finally: m2.bio_free(bio) else: raise SyntaxError() parse = staticmethod(parse)
Python
"""OpenSSL/M2Crypto RC4 implementation.""" from cryptomath import * from RC4 import RC4 if m2cryptoLoaded: def new(key): return OpenSSL_RC4(key) class OpenSSL_RC4(RC4): def __init__(self, key): RC4.__init__(self, key, "openssl") self.rc4 = m2.rc4_new() m2.rc4_set_key(self.rc4, key) def __del__(self): m2.rc4_free(self.rc4) def encrypt(self, plaintext): return m2.rc4_update(self.rc4, plaintext) def decrypt(self, ciphertext): return self.encrypt(ciphertext)
Python
"""cryptomath module This module has basic math/crypto code.""" import os import sys import math import base64 import binascii if sys.version_info[:2] <= (2, 4): from sha import sha as sha1 else: from hashlib import sha1 from compat import * # ************************************************************************** # Load Optional Modules # ************************************************************************** # Try to load M2Crypto/OpenSSL try: from M2Crypto import m2 m2cryptoLoaded = True except ImportError: m2cryptoLoaded = False # Try to load cryptlib try: import cryptlib_py try: cryptlib_py.cryptInit() except cryptlib_py.CryptException, e: #If tlslite and cryptoIDlib are both present, #they might each try to re-initialize this, #so we're tolerant of that. if e[0] != cryptlib_py.CRYPT_ERROR_INITED: raise cryptlibpyLoaded = True except ImportError: cryptlibpyLoaded = False #Try to load GMPY try: import gmpy gmpyLoaded = True except ImportError: gmpyLoaded = False #Try to load pycrypto try: import Crypto.Cipher.AES pycryptoLoaded = True except ImportError: pycryptoLoaded = False # ************************************************************************** # PRNG Functions # ************************************************************************** # Get os.urandom PRNG try: os.urandom(1) def getRandomBytes(howMany): return stringToBytes(os.urandom(howMany)) prngName = "os.urandom" except: # Else get cryptlib PRNG if cryptlibpyLoaded: def getRandomBytes(howMany): randomKey = cryptlib_py.cryptCreateContext(cryptlib_py.CRYPT_UNUSED, cryptlib_py.CRYPT_ALGO_AES) cryptlib_py.cryptSetAttribute(randomKey, cryptlib_py.CRYPT_CTXINFO_MODE, cryptlib_py.CRYPT_MODE_OFB) cryptlib_py.cryptGenerateKey(randomKey) bytes = createByteArrayZeros(howMany) cryptlib_py.cryptEncrypt(randomKey, bytes) return bytes prngName = "cryptlib" else: #Else get UNIX /dev/urandom PRNG try: devRandomFile = open("/dev/urandom", "rb") def getRandomBytes(howMany): return stringToBytes(devRandomFile.read(howMany)) prngName = "/dev/urandom" except IOError: #Else get Win32 CryptoAPI PRNG try: import win32prng def getRandomBytes(howMany): s = win32prng.getRandomBytes(howMany) if len(s) != howMany: raise AssertionError() return stringToBytes(s) prngName ="CryptoAPI" except ImportError: #Else no PRNG :-( def getRandomBytes(howMany): raise NotImplementedError("No Random Number Generator "\ "available.") prngName = "None" # ************************************************************************** # Converter Functions # ************************************************************************** def bytesToNumber(bytes): total = 0L multiplier = 1L for count in range(len(bytes)-1, -1, -1): byte = bytes[count] total += multiplier * byte multiplier *= 256 return total def numberToBytes(n): howManyBytes = numBytes(n) bytes = createByteArrayZeros(howManyBytes) for count in range(howManyBytes-1, -1, -1): bytes[count] = int(n % 256) n >>= 8 return bytes def bytesToBase64(bytes): s = bytesToString(bytes) return stringToBase64(s) def base64ToBytes(s): s = base64ToString(s) return stringToBytes(s) def numberToBase64(n): bytes = numberToBytes(n) return bytesToBase64(bytes) def base64ToNumber(s): bytes = base64ToBytes(s) return bytesToNumber(bytes) def stringToNumber(s): bytes = stringToBytes(s) return bytesToNumber(bytes) def numberToString(s): bytes = numberToBytes(s) return bytesToString(bytes) def base64ToString(s): try: return base64.decodestring(s) except binascii.Error, e: raise SyntaxError(e) except binascii.Incomplete, e: raise SyntaxError(e) def stringToBase64(s): return base64.encodestring(s).replace("\n", "") def mpiToNumber(mpi): #mpi is an openssl-format bignum string if (ord(mpi[4]) & 0x80) !=0: #Make sure this is a positive number raise AssertionError() bytes = stringToBytes(mpi[4:]) return bytesToNumber(bytes) def numberToMPI(n): bytes = numberToBytes(n) ext = 0 #If the high-order bit is going to be set, #add an extra byte of zeros if (numBits(n) & 0x7)==0: ext = 1 length = numBytes(n) + ext bytes = concatArrays(createByteArrayZeros(4+ext), bytes) bytes[0] = (length >> 24) & 0xFF bytes[1] = (length >> 16) & 0xFF bytes[2] = (length >> 8) & 0xFF bytes[3] = length & 0xFF return bytesToString(bytes) # ************************************************************************** # Misc. Utility Functions # ************************************************************************** def numBytes(n): if n==0: return 0 bits = numBits(n) return int(math.ceil(bits / 8.0)) def hashAndBase64(s): return stringToBase64(sha1(s).digest()) def getBase64Nonce(numChars=22): #defaults to an 132 bit nonce bytes = getRandomBytes(numChars) bytesStr = "".join([chr(b) for b in bytes]) return stringToBase64(bytesStr)[:numChars] # ************************************************************************** # Big Number Math # ************************************************************************** def getRandomNumber(low, high): if low >= high: raise AssertionError() howManyBits = numBits(high) howManyBytes = numBytes(high) lastBits = howManyBits % 8 while 1: bytes = getRandomBytes(howManyBytes) if lastBits: bytes[0] = bytes[0] % (1 << lastBits) n = bytesToNumber(bytes) if n >= low and n < high: return n def gcd(a,b): a, b = max(a,b), min(a,b) while b: a, b = b, a % b return a def lcm(a, b): #This will break when python division changes, but we can't use // cause #of Jython return (a * b) / gcd(a, b) #Returns inverse of a mod b, zero if none #Uses Extended Euclidean Algorithm def invMod(a, b): c, d = a, b uc, ud = 1, 0 while c != 0: #This will break when python division changes, but we can't use // #cause of Jython q = d / c c, d = d-(q*c), c uc, ud = ud - (q * uc), uc if d == 1: return ud % b return 0 if gmpyLoaded: def powMod(base, power, modulus): base = gmpy.mpz(base) power = gmpy.mpz(power) modulus = gmpy.mpz(modulus) result = pow(base, power, modulus) return long(result) else: #Copied from Bryan G. Olson's post to comp.lang.python #Does left-to-right instead of pow()'s right-to-left, #thus about 30% faster than the python built-in with small bases def powMod(base, power, modulus): nBitScan = 5 """ Return base**power mod modulus, using multi bit scanning with nBitScan bits at a time.""" #TREV - Added support for negative exponents negativeResult = False if (power < 0): power *= -1 negativeResult = True exp2 = 2**nBitScan mask = exp2 - 1 # Break power into a list of digits of nBitScan bits. # The list is recursive so easy to read in reverse direction. nibbles = None while power: nibbles = int(power & mask), nibbles power = power >> nBitScan # Make a table of powers of base up to 2**nBitScan - 1 lowPowers = [1] for i in xrange(1, exp2): lowPowers.append((lowPowers[i-1] * base) % modulus) # To exponentiate by the first nibble, look it up in the table nib, nibbles = nibbles prod = lowPowers[nib] # For the rest, square nBitScan times, then multiply by # base^nibble while nibbles: nib, nibbles = nibbles for i in xrange(nBitScan): prod = (prod * prod) % modulus if nib: prod = (prod * lowPowers[nib]) % modulus #TREV - Added support for negative exponents if negativeResult: prodInv = invMod(prod, modulus) #Check to make sure the inverse is correct if (prod * prodInv) % modulus != 1: raise AssertionError() return prodInv return prod #Pre-calculate a sieve of the ~100 primes < 1000: def makeSieve(n): sieve = range(n) for count in range(2, int(math.sqrt(n))): if sieve[count] == 0: continue x = sieve[count] * 2 while x < len(sieve): sieve[x] = 0 x += sieve[count] sieve = [x for x in sieve[2:] if x] return sieve sieve = makeSieve(1000) def isPrime(n, iterations=5, display=False): #Trial division with sieve for x in sieve: if x >= n: return True if n % x == 0: return False #Passed trial division, proceed to Rabin-Miller #Rabin-Miller implemented per Ferguson & Schneier #Compute s, t for Rabin-Miller if display: print "*", s, t = n-1, 0 while s % 2 == 0: s, t = s/2, t+1 #Repeat Rabin-Miller x times a = 2 #Use 2 as a base for first iteration speedup, per HAC for count in range(iterations): v = powMod(a, s, n) if v==1: continue i = 0 while v != n-1: if i == t-1: return False else: v, i = powMod(v, 2, n), i+1 a = getRandomNumber(2, n) return True def getRandomPrime(bits, display=False): if bits < 10: raise AssertionError() #The 1.5 ensures the 2 MSBs are set #Thus, when used for p,q in RSA, n will have its MSB set # #Since 30 is lcm(2,3,5), we'll set our test numbers to #29 % 30 and keep them there low = (2L ** (bits-1)) * 3/2 high = 2L ** bits - 30 p = getRandomNumber(low, high) p += 29 - (p % 30) while 1: if display: print ".", p += 30 if p >= high: p = getRandomNumber(low, high) p += 29 - (p % 30) if isPrime(p, display=display): return p #Unused at the moment... def getRandomSafePrime(bits, display=False): if bits < 10: raise AssertionError() #The 1.5 ensures the 2 MSBs are set #Thus, when used for p,q in RSA, n will have its MSB set # #Since 30 is lcm(2,3,5), we'll set our test numbers to #29 % 30 and keep them there low = (2 ** (bits-2)) * 3/2 high = (2 ** (bits-1)) - 30 q = getRandomNumber(low, high) q += 29 - (q % 30) while 1: if display: print ".", q += 30 if (q >= high): q = getRandomNumber(low, high) q += 29 - (q % 30) #Ideas from Tom Wu's SRP code #Do trial division on p and q before Rabin-Miller if isPrime(q, 0, display=display): p = (2 * q) + 1 if isPrime(p, display=display): if isPrime(q, display=display): return p
Python
"""PyCrypto AES implementation.""" from cryptomath import * from AES import * if pycryptoLoaded: import Crypto.Cipher.AES def new(key, mode, IV): return PyCrypto_AES(key, mode, IV) class PyCrypto_AES(AES): def __init__(self, key, mode, IV): AES.__init__(self, key, mode, IV, "pycrypto") self.context = Crypto.Cipher.AES.new(key, mode, IV) def encrypt(self, plaintext): return self.context.encrypt(plaintext) def decrypt(self, ciphertext): return self.context.decrypt(ciphertext)
Python
"""Helper functions for XML. This module has misc. helper functions for working with XML DOM nodes.""" from compat import * import os import re if os.name == "java": # Only for Jython from javax.xml.parsers import * import java builder = DocumentBuilderFactory.newInstance().newDocumentBuilder() def parseDocument(s): stream = java.io.ByteArrayInputStream(java.lang.String(s).getBytes()) return builder.parse(stream) else: from xml.dom import minidom from xml.sax import saxutils def parseDocument(s): return minidom.parseString(s) def parseAndStripWhitespace(s): try: element = parseDocument(s).documentElement except BaseException, e: raise SyntaxError(str(e)) stripWhitespace(element) return element #Goes through a DOM tree and removes whitespace besides child elements, #as long as this whitespace is correctly tab-ified def stripWhitespace(element, tab=0): element.normalize() lastSpacer = "\n" + ("\t"*tab) spacer = lastSpacer + "\t" #Zero children aren't allowed (i.e. <empty/>) #This makes writing output simpler, and matches Canonical XML if element.childNodes.length==0: #DON'T DO len(element.childNodes) - doesn't work in Jython raise SyntaxError("Empty XML elements not allowed") #If there's a single child, it must be text context if element.childNodes.length==1: if element.firstChild.nodeType == element.firstChild.TEXT_NODE: #If it's an empty element, remove if element.firstChild.data == lastSpacer: element.removeChild(element.firstChild) return #If not text content, give an error elif element.firstChild.nodeType == element.firstChild.ELEMENT_NODE: raise SyntaxError("Bad whitespace under '%s'" % element.tagName) else: raise SyntaxError("Unexpected node type in XML document") #Otherwise there's multiple child element child = element.firstChild while child: if child.nodeType == child.ELEMENT_NODE: stripWhitespace(child, tab+1) child = child.nextSibling elif child.nodeType == child.TEXT_NODE: if child == element.lastChild: if child.data != lastSpacer: raise SyntaxError("Bad whitespace under '%s'" % element.tagName) elif child.data != spacer: raise SyntaxError("Bad whitespace under '%s'" % element.tagName) next = child.nextSibling element.removeChild(child) child = next else: raise SyntaxError("Unexpected node type in XML document") def checkName(element, name): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Missing element: '%s'" % name) if name == None: return if element.tagName != name: raise SyntaxError("Wrong element name: should be '%s', is '%s'" % (name, element.tagName)) def getChild(element, index, name=None): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Wrong node type in getChild()") child = element.childNodes.item(index) if child == None: raise SyntaxError("Missing child: '%s'" % name) checkName(child, name) return child def getChildIter(element, index): class ChildIter: def __init__(self, element, index): self.element = element self.index = index def next(self): if self.index < len(self.element.childNodes): retVal = self.element.childNodes.item(self.index) self.index += 1 else: retVal = None return retVal def checkEnd(self): if self.index != len(self.element.childNodes): raise SyntaxError("Too many elements under: '%s'" % self.element.tagName) return ChildIter(element, index) def getChildOrNone(element, index): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Wrong node type in getChild()") child = element.childNodes.item(index) return child def getLastChild(element, index, name=None): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Wrong node type in getLastChild()") child = element.childNodes.item(index) if child == None: raise SyntaxError("Missing child: '%s'" % name) if child != element.lastChild: raise SyntaxError("Too many elements under: '%s'" % element.tagName) checkName(child, name) return child #Regular expressions for syntax-checking attribute and element content nsRegEx = "http://trevp.net/cryptoID\Z" cryptoIDRegEx = "([a-km-z3-9]{5}\.){3}[a-km-z3-9]{5}\Z" urlRegEx = "http(s)?://.{1,100}\Z" sha1Base64RegEx = "[A-Za-z0-9+/]{27}=\Z" base64RegEx = "[A-Za-z0-9+/]+={0,4}\Z" certsListRegEx = "(0)?(1)?(2)?(3)?(4)?(5)?(6)?(7)?(8)?(9)?\Z" keyRegEx = "[A-Z]\Z" keysListRegEx = "(A)?(B)?(C)?(D)?(E)?(F)?(G)?(H)?(I)?(J)?(K)?(L)?(M)?(N)?(O)?(P)?(Q)?(R)?(S)?(T)?(U)?(V)?(W)?(X)?(Y)?(Z)?\Z" dateTimeRegEx = "\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ\Z" shortStringRegEx = ".{1,100}\Z" exprRegEx = "[a-zA-Z0-9 ,()]{1,200}\Z" notAfterDeltaRegEx = "0|([1-9][0-9]{0,8})\Z" #A number from 0 to (1 billion)-1 booleanRegEx = "(true)|(false)" def getReqAttribute(element, attrName, regEx=""): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Wrong node type in getReqAttribute()") value = element.getAttribute(attrName) if not value: raise SyntaxError("Missing Attribute: " + attrName) if not re.match(regEx, value): raise SyntaxError("Bad Attribute Value for '%s': '%s' " % (attrName, value)) element.removeAttribute(attrName) return str(value) #de-unicode it; this is needed for bsddb, for example def getAttribute(element, attrName, regEx=""): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Wrong node type in getAttribute()") value = element.getAttribute(attrName) if value: if not re.match(regEx, value): raise SyntaxError("Bad Attribute Value for '%s': '%s' " % (attrName, value)) element.removeAttribute(attrName) return str(value) #de-unicode it; this is needed for bsddb, for example def checkNoMoreAttributes(element): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Wrong node type in checkNoMoreAttributes()") if element.attributes.length!=0: raise SyntaxError("Extra attributes on '%s'" % element.tagName) def getText(element, regEx=""): textNode = element.firstChild if textNode == None: raise SyntaxError("Empty element '%s'" % element.tagName) if textNode.nodeType != textNode.TEXT_NODE: raise SyntaxError("Non-text node: '%s'" % element.tagName) if not re.match(regEx, textNode.data): raise SyntaxError("Bad Text Value for '%s': '%s' " % (element.tagName, textNode.data)) return str(textNode.data) #de-unicode it; this is needed for bsddb, for example #Function for adding tabs to a string def indent(s, steps, ch="\t"): tabs = ch*steps if s[-1] != "\n": s = tabs + s.replace("\n", "\n"+tabs) else: s = tabs + s.replace("\n", "\n"+tabs) s = s[ : -len(tabs)] return s def escape(s): return saxutils.escape(s)
Python