code
stringlengths
1
1.72M
language
stringclasses
1 value
#!/usr/bin/python # # Copyright (C) 2008 Yu-Jie Lin # # 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 gdata.webmastertools.service import gdata.service try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import getpass username = '' password = '' username = raw_input('Please enter your username: ') password = getpass.getpass() client = gdata.webmastertools.service.GWebmasterToolsService( email=username, password=password, source='PythonWebmasterToolsSample-1') print 'Logging in' client.ProgrammaticLogin() print 'Retrieving Sites feed' feed = client.GetSitesFeed() # Format the feed print print 'You have %d site(s), last updated at %s' % ( len(feed.entry), feed.updated.text) print print "%-25s %25s %25s" % ('Site', 'Last Updated', 'Last Crawled') print '='*80 def safeElementText(element): if hasattr(element, 'text'): return element.text return '' # Format each site for entry in feed.entry: print "%-25s %25s %25s" % ( entry.title.text.replace('http://', '')[:25], entry.updated.text[:25], safeElementText(entry.crawled)[:25]) print " Preferred: %-23s Indexed: %5s GeoLoc: %10s" % ( safeElementText(entry.preferred_domain)[:30], entry.indexed.text[:5], safeElementText(entry.geolocation)[:10]) print " Crawl rate: %-10s Verified: %5s" % ( safeElementText(entry.crawl_rate)[:10], entry.verified.text[:5]) print
Python
#!/usr/bin/python # # Copyright (C) 2008 Yu-Jie Lin # # 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 urllib import gdata.webmastertools.service import gdata.service try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import getpass username = '' password = '' username = raw_input('Please enter your username: ') password = getpass.getpass() client = gdata.webmastertools.service.GWebmasterToolsService( email=username, password=password, source='PythonWebmasterToolsSample-1') EXAMPLE_SITE = 'http://www.example.com/' EXAMPLE_SITEMAP = 'http://www.example.com/sitemap-index.xml' def safeElementText(element): if hasattr(element, 'text'): return element.text return '' print 'Logging in' client.ProgrammaticLogin() print print 'Adding site: %s' % EXAMPLE_SITE entry = client.AddSite(EXAMPLE_SITE) print print "%-25s %25s %25s" % ('Site', 'Last Updated', 'Last Crawled') print '='*80 print "%-25s %25s %25s" % ( entry.title.text.replace('http://', '')[:25], entry.updated.text[:25], safeElementText(entry.crawled)[:25]) print " Preferred: %-23s Indexed: %5s GeoLoc: %10s" % ( safeElementText(entry.preferred_domain)[:30], entry.indexed.text[:5], safeElementText(entry.geolocation)[:10]) print " Crawl rate: %-10s Verified: %5s" % ( safeElementText(entry.crawl_rate)[:10], entry.verified.text[:5]) # Verifying a site. This sample won't do this since we don't own example.com #client.VerifySite(EXAMPLE_SITE, 'htmlpage') # The following needs the ownership of the site #client.UpdateGeoLocation(EXAMPLE_SITE, 'US') #client.UpdateCrawlRate(EXAMPLE_SITE, 'normal') #client.UpdatePreferredDomain(EXAMPLE_SITE, 'preferwww') #client.UpdateEnhancedImageSearch(EXAMPLE_SITE, 'true') print print 'Adding sitemap: %s' % EXAMPLE_SITEMAP entry = client.AddSitemap(EXAMPLE_SITE, EXAMPLE_SITEMAP) print entry.title.text.replace('http://', '')[:80] print " Last Updated : %29s Status: %10s" % ( entry.updated.text[:29], entry.sitemap_status.text[:10]) print " Last Downloaded: %29s URL Count: %10s" % ( safeElementText(entry.sitemap_last_downloaded)[:29], safeElementText(entry.sitemap_url_count)[:10]) # Add a mobile sitemap #entry = client.AddMobileSitemap(EXAMPLE_SITE, 'http://.../sitemap-mobile-example.xml', 'XHTML') # Add a news sitemap, your site must be included in Google News. # See also http://google.com/support/webmasters/bin/answer.py?answer=42738 #entry = client.AddNewsSitemap(EXAMPLE_SITE, 'http://.../sitemap-news-example.xml', 'Label') print print 'Deleting sitemap: %s' % EXAMPLE_SITEMAP client.DeleteSitemap(EXAMPLE_SITE, EXAMPLE_SITEMAP) print print 'Deleting site: %s' % EXAMPLE_SITE client.DeleteSite(EXAMPLE_SITE) print
Python
#!/usr/bin/python # # Copyright (C) 2008 Yu-Jie Lin # # 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 gdata.webmastertools.service import gdata.service try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import getpass username = '' password = '' site_uri = '' username = raw_input('Please enter your username: ') password = getpass.getpass() site_uri = raw_input('Please enter your site url: ') client = gdata.webmastertools.service.GWebmasterToolsService( email=username, password=password, source='PythonWebmasterToolsSample-1') print 'Logging in' client.ProgrammaticLogin() print 'Retrieving Sitemaps feed' feed = client.GetSitemapsFeed(site_uri) # Format the feed print print 'You have %d sitemap(s), last updated at %s' % ( len(feed.entry), feed.updated.text) print print '='*80 def safeElementText(element): if hasattr(element, 'text'): return element.text return '' # Format each site for entry in feed.entry: print entry.title.text.replace('http://', '')[:80] print " Last Updated : %29s Status: %10s" % ( entry.updated.text[:29], entry.sitemap_status.text[:10]) print " Last Downloaded: %29s URL Count: %10s" % ( safeElementText(entry.sitemap_last_downloaded)[:29], safeElementText(entry.sitemap_url_count)[:10]) print
Python
#!/usr/bin/python # # Copyright (C) 2007, 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. __author__ = ('api.jfisher (Jeff Fisher), ' 'e.bidelman (Eric Bidelman)') import sys import re import os.path import getopt import getpass import gdata.docs.service import gdata.spreadsheet.service def truncate(content, length=15, suffix='...'): if len(content) <= length: return content else: return content[:length] + suffix class DocsSample(object): """A DocsSample object demonstrates the Document List feed.""" def __init__(self, email, password): """Constructor for the DocsSample object. Takes an email and password corresponding to a gmail account to demonstrate the functionality of the Document List feed. Args: email: [string] The e-mail address of the account to use for the sample. password: [string] The password corresponding to the account specified by the email parameter. Returns: A DocsSample object used to run the sample demonstrating the functionality of the Document List feed. """ source = 'Document List Python Sample' self.gd_client = gdata.docs.service.DocsService() self.gd_client.ClientLogin(email, password, source=source) # Setup a spreadsheets service for downloading spreadsheets self.gs_client = gdata.spreadsheet.service.SpreadsheetsService() self.gs_client.ClientLogin(email, password, source=source) def _PrintFeed(self, feed): """Prints out the contents of a feed to the console. Args: feed: A gdata.docs.DocumentListFeed instance. """ print '\n' if not feed.entry: print 'No entries in feed.\n' print '%-18s %-12s %s' % ('TITLE', 'TYPE', 'RESOURCE ID') for entry in feed.entry: print '%-18s %-12s %s' % (truncate(entry.title.text.encode('UTF-8')), entry.GetDocumentType(), entry.resourceId.text) def _GetFileExtension(self, file_name): """Returns the uppercase file extension for a file. Args: file_name: [string] The basename of a filename. Returns: A string containing the file extension of the file. """ match = re.search('.*\.([a-zA-Z]{3,}$)', file_name) if match: return match.group(1).upper() return False def _UploadMenu(self): """Prompts that enable a user to upload a file to the Document List feed.""" file_path = '' file_path = raw_input('Enter path to file: ') if not file_path: return elif not os.path.isfile(file_path): print 'Not a valid file.' return file_name = os.path.basename(file_path) ext = self._GetFileExtension(file_name) if not ext or ext not in gdata.docs.service.SUPPORTED_FILETYPES: print 'File type not supported. Check the file extension.' return else: content_type = gdata.docs.service.SUPPORTED_FILETYPES[ext] title = '' while not title: title = raw_input('Enter name for document: ') try: ms = gdata.MediaSource(file_path=file_path, content_type=content_type) except IOError: print 'Problems reading file. Check permissions.' return if ext in ['CSV', 'ODS', 'XLS', 'XLSX']: print 'Uploading spreadsheet...' elif ext in ['PPT', 'PPS']: print 'Uploading presentation...' else: print 'Uploading word processor document...' entry = self.gd_client.Upload(ms, title) if entry: print 'Upload successful!' print 'Document now accessible at:', entry.GetAlternateLink().href else: print 'Upload error.' def _DownloadMenu(self): """Prompts that enable a user to download a local copy of a document.""" resource_id = '' resource_id = raw_input('Enter an resource id: ') file_path = '' file_path = raw_input('Save file to: ') if not file_path or not resource_id: return file_name = os.path.basename(file_path) ext = self._GetFileExtension(file_name) if not ext or ext not in gdata.docs.service.SUPPORTED_FILETYPES: print 'File type not supported. Check the file extension.' return else: content_type = gdata.docs.service.SUPPORTED_FILETYPES[ext] doc_type = resource_id[:resource_id.find(':')] # When downloading a spreadsheet, the authenticated request needs to be # sent with the spreadsheet service's auth token. if doc_type == 'spreadsheet': print 'Downloading spreadsheet to %s...' % (file_path,) docs_token = self.gd_client.GetClientLoginToken() self.gd_client.SetClientLoginToken(self.gs_client.GetClientLoginToken()) self.gd_client.Export(resource_id, file_path, gid=0) self.gd_client.SetClientLoginToken(docs_token) else: print 'Downloading document to %s...' % (file_path,) self.gd_client.Export(resource_id, file_path) def _ListDocuments(self): """Retrieves and displays a list of documents based on the user's choice.""" print 'Retrieve (all/document/folder/presentation/spreadsheet/pdf): ' category = raw_input('Enter a category: ') if category == 'all': feed = self.gd_client.GetDocumentListFeed() elif category == 'folder': query = gdata.docs.service.DocumentQuery(categories=['folder'], params={'showfolders': 'true'}) feed = self.gd_client.Query(query.ToUri()) else: query = gdata.docs.service.DocumentQuery(categories=[category]) feed = self.gd_client.Query(query.ToUri()) self._PrintFeed(feed) def _ListAclPermissions(self): """Retrieves a list of a user's folders and displays them.""" resource_id = raw_input('Enter an resource id: ') query = gdata.docs.service.DocumentAclQuery(resource_id) print '\nListing document permissions:' feed = self.gd_client.GetDocumentListAclFeed(query.ToUri()) for acl_entry in feed.entry: print '%s - %s (%s)' % (acl_entry.role.value, acl_entry.scope.value, acl_entry.scope.type) def _ModifyAclPermissions(self): """Create or updates the ACL entry on an existing document.""" resource_id = raw_input('Enter an resource id: ') email = raw_input('Enter an email address: ') role_value = raw_input('Enter a permission (reader/writer/owner/remove): ') uri = gdata.docs.service.DocumentAclQuery(resource_id).ToUri() acl_feed = self.gd_client.GetDocumentListAclFeed(uri) found_acl_entry = None for acl_entry in acl_feed.entry: if acl_entry.scope.value == email: found_acl_entry = acl_entry break if found_acl_entry: if role_value == 'remove': # delete ACL entry self.gd_client.Delete(found_acl_entry.GetEditLink().href) else: # update ACL entry found_acl_entry.role.value = role_value updated_entry = self.gd_client.Put( found_acl_entry, found_acl_entry.GetEditLink().href, converter=gdata.docs.DocumentListAclEntryFromString) else: scope = gdata.docs.Scope(value=email, type='user') role = gdata.docs.Role(value=role_value) acl_entry = gdata.docs.DocumentListAclEntry(scope=scope, role=role) inserted_entry = self.gd_client.Post( acl_entry, uri, converter=gdata.docs.DocumentListAclEntryFromString) print '\nListing document permissions:' acl_feed = self.gd_client.GetDocumentListAclFeed(uri) for acl_entry in acl_feed.entry: print '%s - %s (%s)' % (acl_entry.role.value, acl_entry.scope.value, acl_entry.scope.type) def _FullTextSearch(self): """Searches a user's documents for a text string. Provides prompts to search a user's documents and displays the results of such a search. The text_query parameter of the DocumentListQuery object corresponds to the contents of the q parameter in the feed. Note that this parameter searches the content of documents, not just their titles. """ input = raw_input('Enter search term: ') query = gdata.docs.service.DocumentQuery(text_query=input) feed = self.gd_client.Query(query.ToUri()) self._PrintFeed(feed) def _PrintMenu(self): """Displays a menu of options for the user to choose from.""" print ('\nDocument List Sample\n' '1) List your documents.\n' '2) Search your documents.\n' '3) Upload a document.\n' '4) Download a document.\n' "5) List a document's permissions.\n" "6) Add/change a document's permissions.\n" '7) Exit.\n') def _GetMenuChoice(self, max): """Retrieves the menu selection from the user. Args: max: [int] The maximum number of allowed choices (inclusive) Returns: The integer of the menu item chosen by the user. """ while True: input = raw_input('> ') try: num = int(input) except ValueError: print 'Invalid choice. Please choose a value between 1 and', max continue if num > max or num < 1: print 'Invalid choice. Please choose a value between 1 and', max else: return num def Run(self): """Prompts the user to choose funtionality to be demonstrated.""" try: while True: self._PrintMenu() choice = self._GetMenuChoice(7) if choice == 1: self._ListDocuments() elif choice == 2: self._FullTextSearch() elif choice == 3: self._UploadMenu() elif choice == 4: self._DownloadMenu() elif choice == 5: self._ListAclPermissions() elif choice == 6: self._ModifyAclPermissions() elif choice == 7: print '\nGoodbye.' return except KeyboardInterrupt: print '\nGoodbye.' return def main(): """Demonstrates use of the Docs extension using the DocsSample object.""" # Parse command line options try: opts, args = getopt.getopt(sys.argv[1:], '', ['user=', 'pw=']) except getopt.error, msg: print 'python docs_example.py --user [username] --pw [password] ' sys.exit(2) user = '' pw = '' key = '' # Process options for option, arg in opts: if option == '--user': user = arg elif option == '--pw': pw = arg while not user: print 'NOTE: Please run these tests only with a test account.' user = raw_input('Please enter your username: ') while not pw: pw = getpass.getpass() if not pw: print 'Password cannot be blank.' try: sample = DocsSample(user, pw) except gdata.service.BadAuthentication: print 'Invalid user credentials given.' return sample.Run() if __name__ == '__main__': main()
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. __author__ = 'e.bidelman@google.com (Eric Bidelman)' import getopt import mimetypes import os.path import sys import atom.data import gdata.client import gdata.data import gdata.gauth import gdata.docs.client import gdata.docs.data import gdata.sample_util APP_NAME = 'GDataResumableUploadPySample-v1.0' def get_mimetype(filename): file_ext = filename[filename.rfind('.'):] if file_ext in mimetypes.types_map: content_type = mimetypes.types_map[file_ext] else: content_type = raw_input( "Unrecognized file extension. Please enter the file's content type: ") return content_type class ResumableUploadDemo(object): """Helper class to setup a resumable upload, and upload a file.""" CREATE_SESSION_URI = '/feeds/upload/create-session/default/private/full' client = None # A gdata.client.GDClient object. uploader = None # A gdata.client.ResumableUploader object. def __init__(self, filepath, chunk_size=None, convert=None, host=None, ssl=False, debug=False): self.client = gdata.docs.client.DocsClient(source=APP_NAME) self.client.ssl = ssl self.client.http_client.debug = debug self.convert = convert if host: self.client.host = host if chunk_size: self.chunk_size = chunk_size # Authenticate the user with CLientLogin, OAuth, or AuthSub. try: gdata.sample_util.authorize_client( self.client, service=self.client.auth_service, source=APP_NAME, scopes=self.client.auth_scopes) except gdata.client.BadAuthentication: exit('Invalid user credentials given.') except gdata.client.Error: exit('Login Error') mimetypes.init() # Register common mimetypes on system. self.f = open(filepath) content_type = get_mimetype(self.f.name) file_size = os.path.getsize(self.f.name) self.uploader = gdata.client.ResumableUploader( self.client, self.f, content_type, file_size, chunk_size=self.chunk_size, desired_class=gdata.docs.data.DocsEntry) def __del__(self): if self.uploader is not None: self.uploader.file_handle.close() def UploadAutomaticChunks(self, new_entry): """Uploads an entire file, handing the chunking for you. Args: new_entry: gdata.data.docs.DocsEntry An object holding metadata to create the document with. Returns: A gdata.docs.data.DocsEntry of the created document on the server. """ uri = self.CREATE_SESSION_URI # If convert=false is used on the initial request to start a resumable # upload, the document will be treated as arbitrary file upload. if self.convert is not None: uri += '?convert=' + self.convert return self.uploader.UploadFile(uri, entry=new_entry) def UploadInManualChunks(self, new_entry): """Uploads a file, demonstrating manually chunking the file. Args: new_entry: gdata.data.docs.DocsEntry An object holding metadata to create the document with. Returns: A gdata.docs.data.DocsEntry of the created document on the server. """ uri = self.CREATE_SESSION_URI # If convert=false is used on the initial request to start a resumable # upload, the document will be treated as arbitrary file upload. if self.convert is not None: uri += '?convert=' + self.convert # Need to create the initial session manually. self.uploader._InitSession(uri, entry=new_entry) start_byte = 0 entry = None while not entry: print 'Uploading bytes: %s-%s/%s' % (start_byte, self.uploader.chunk_size - 1, self.uploader.total_file_size) entry = self.uploader.UploadChunk( start_byte, self.uploader.file_handle.read(self.uploader.chunk_size)) start_byte += self.uploader.chunk_size return entry def UploadUsingNormalPath(self): """Uploads a file using the standard DocList API upload path. This method is included to show the difference between the standard upload path and the resumable upload path. Also note, file uploads using this normal upload method max out ~10MB. Returns: A gdata.docs.data.DocsEntry of the created document on the server. """ ms = gdata.data.MediaSource( file_handle=self.f, content_type=self.uploader.content_type, content_length=self.uploader.total_file_size) uri = self.client.DOCLIST_FEED_URI # If convert=false is used on the initial request to start a resumable # upload, the document will be treated as arbitrary file upload. if self.convert is not None: uri += '?convert=' + self.convert return self.client.Upload(ms, self.f.name, folder_or_uri=uri) def main(): try: opts, args = getopt.getopt( sys.argv[1:], '', ['filepath=', 'convert=', 'chunk_size=', 'ssl', 'debug']) except getopt.error, msg: print '''python resumable_upload_sample.py --filepath= [file to upload] --convert= [document uploads will be converted to native Google Docs. Possible values are 'true' and 'false'.] --ssl [enables HTTPS if set] --debug [prints debug info if set]''' print ('Example usage: python resumable_upload_sample.py ' '--filepath=/path/to/test.doc --convert=true --ssl') sys.exit(2) filepath = None convert = 'true' # Convert to Google Docs format by default chunk_size = gdata.client.ResumableUploader.DEFAULT_CHUNK_SIZE debug = False ssl = False for option, arg in opts: if option == '--filepath': filepath = arg elif option == '--convert': convert = arg.lower() elif option == '--chunk_size': chunk_size = int(arg) elif option == '--ssl': ssl = True elif option == '--debug': debug = True if filepath is None: filepath = raw_input('Enter path to a file: ') demo = ResumableUploadDemo(filepath, chunk_size=chunk_size, convert=convert, ssl=ssl, debug=debug) title = raw_input('Enter title for the document: ') print 'Uploading %s ( %s ) @ %s bytes...' % (demo.uploader.file_handle.name, demo.uploader.content_type, demo.uploader.total_file_size) entry = demo.UploadInManualChunks( gdata.docs.data.DocsEntry(title=atom.data.Title(text=title))) print 'Done: %s' % demo.uploader.QueryUploadStatus() print 'Document uploaded: ' + entry.title.text print 'Quota used: %s' % entry.quota_bytes_used.text print 'file closed: %s' % demo.uploader.file_handle.closed if __name__ == '__main__': main()
Python
#!/usr/bin/python # # Copyright (C) 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. __author__ = 'api.jscudder (Jeffrey Scudder)' import sys import getopt import getpass import atom import gdata.contacts.data import gdata.contacts.client class ContactsSample(object): """ContactsSample object demonstrates operations with the Contacts feed.""" def __init__(self, email, password): """Constructor for the ContactsSample object. Takes an email and password corresponding to a gmail account to demonstrate the functionality of the Contacts feed. Args: email: [string] The e-mail address of the account to use for the sample. password: [string] The password corresponding to the account specified by the email parameter. Yields: A ContactsSample object used to run the sample demonstrating the functionality of the Contacts feed. """ self.gd_client = gdata.contacts.client.ContactsClient(source='GoogleInc-ContactsPythonSample-1') self.gd_client.ClientLogin(email, password, self.gd_client.source) def PrintFeed(self, feed, ctr=0): """Prints out the contents of a feed to the console. Args: feed: A gdata.contacts.ContactsFeed instance. ctr: [int] The number of entries in this feed previously printed. This allows continuous entry numbers when paging through a feed. Returns: The number of entries printed, including those previously printed as specified in ctr. This is for passing as an argument to ctr on successive calls to this method. """ if not feed.entry: print '\nNo entries in feed.\n' return 0 for i, entry in enumerate(feed.entry): print '\n%s %s' % (ctr+i+1, entry.title.text) if entry.content: print ' %s' % (entry.content.text) for email in entry.email: if email.primary and email.primary == 'true': print ' %s' % (email.address) # Show the contact groups that this contact is a member of. for group in entry.group_membership_info: print ' Member of group: %s' % (group.href) # Display extended properties. for extended_property in entry.extended_property: if extended_property.value: value = extended_property.value else: value = extended_property.GetXmlBlob() print ' Extended Property %s: %s' % (extended_property.name, value) return len(feed.entry) + ctr def PrintPaginatedFeed(self, feed, print_method): """ Print all pages of a paginated feed. This will iterate through a paginated feed, requesting each page and printing the entries contained therein. Args: feed: A gdata.contacts.ContactsFeed instance. print_method: The method which will be used to print each page of the feed. Must accept these two named arguments: feed: A gdata.contacts.ContactsFeed instance. ctr: [int] The number of entries in this feed previously printed. This allows continuous entry numbers when paging through a feed. """ ctr = 0 while feed: # Print contents of current feed ctr = print_method(feed=feed, ctr=ctr) # Prepare for next feed iteration next = feed.GetNextLink() feed = None if next: if self.PromptOperationShouldContinue(): # Another feed is available, and the user has given us permission # to fetch it feed = self.gd_client.GetContacts(next.href) else: # User has asked us to terminate feed = None def PromptOperationShouldContinue(self): """ Display a "Continue" prompt. This give is used to give users a chance to break out of a loop, just in case they have too many contacts/groups. Returns: A boolean value, True if the current operation should continue, False if the current operation should terminate. """ while True: input = raw_input("Continue [Y/n]? ") if input is 'N' or input is 'n': return False elif input is 'Y' or input is 'y' or input is '': return True def ListAllContacts(self): """Retrieves a list of contacts and displays name and primary email.""" feed = self.gd_client.GetContacts() self.PrintPaginatedFeed(feed, self.PrintContactsFeed) def PrintGroupsFeed(self, feed, ctr): if not feed.entry: print '\nNo groups in feed.\n' return 0 for i, entry in enumerate(feed.entry): print '\n%s %s' % (ctr+i+1, entry.title.text) if entry.content: print ' %s' % (entry.content.text) # Display the group id which can be used to query the contacts feed. print ' Group ID: %s' % entry.id.text # Display extended properties. for extended_property in entry.extended_property: if extended_property.value: value = extended_property.value else: value = extended_property.GetXmlBlob() print ' Extended Property %s: %s' % (extended_property.name, value) return len(feed.entry) + ctr def PrintContactsFeed(self, feed, ctr): if not feed.entry: print '\nNo contacts in feed.\n' return 0 for i, entry in enumerate(feed.entry): if not entry.name is None: family_name = entry.name.family_name is None and " " or entry.name.family_name.text print '\n%s %s: %s - %s' % (ctr+i+1, entry.name.full_name.text, entry.name.given_name.text, family_name) else: print '\n%s %s (title)' % (ctr+i+1, entry.title.text) if entry.content: print ' %s' % (entry.content.text) for p in entry.structured_postal_address: print ' %s' % (p.formatted_address.text) # Display the group id which can be used to query the contacts feed. print ' Group ID: %s' % entry.id.text # Display extended properties. for extended_property in entry.extended_property: if extended_property.value: value = extended_property.value else: value = extended_property.GetXmlBlob() print ' Extended Property %s: %s' % (extended_property.name, value) for user_defined_field in entry.user_defined_field: print ' User Defined Field %s: %s' % (user_defined_field.key, user_defined_field.value) return len(feed.entry) + ctr def ListAllGroups(self): feed = self.gd_client.GetGroups() self.PrintPaginatedFeed(feed, self.PrintGroupsFeed) def CreateMenu(self): """Prompts that enable a user to create a contact.""" name = raw_input('Enter contact\'s name: ') notes = raw_input('Enter notes for contact: ') primary_email = raw_input('Enter primary email address: ') new_contact = gdata.contacts.data.ContactEntry(name=gdata.data.Name(full_name=gdata.data.FullName(text=name))) new_contact.content = atom.data.Content(text=notes) # Create a work email address for the contact and use as primary. new_contact.email.append(gdata.data.Email(address=primary_email, primary='true', rel=gdata.data.WORK_REL)) entry = self.gd_client.CreateContact(new_contact) if entry: print 'Creation successful!' print 'ID for the new contact:', entry.id.text else: print 'Upload error.' def QueryMenu(self): """Prompts for updated-min query parameters and displays results.""" updated_min = raw_input( 'Enter updated min (example: 2007-03-16T00:00:00): ') query = gdata.contacts.client.ContactsQuery() query.updated_min = updated_min feed = self.gd_client.GetContacts(q=query) self.PrintFeed(feed) def QueryGroupsMenu(self): """Prompts for updated-min query parameters and displays results.""" updated_min = raw_input( 'Enter updated min (example: 2007-03-16T00:00:00): ') query = gdata.contacts.client.ContactsQuery(feed='/m8/feeds/groups/default/full') query.updated_min = updated_min feed = self.gd_client.GetGroups(q=query) self.PrintGroupsFeed(feed, 0) def _SelectContact(self): feed = self.gd_client.GetContacts() self.PrintFeed(feed) selection = 5000 while selection > len(feed.entry)+1 or selection < 1: selection = int(raw_input( 'Enter the number for the contact you would like to modify: ')) return feed.entry[selection-1] def UpdateContactMenu(self): selected_entry = self._SelectContact() new_name = raw_input('Enter a new name for the contact: ') if not selected_entry.name: selected_entry.name = gdata.data.Name() selected_entry.name.full_name = gdata.data.FullName(text=new_name) self.gd_client.Update(selected_entry) def DeleteContactMenu(self): selected_entry = self._SelectContact() self.gd_client.Delete(selected_entry) def PrintMenu(self): """Displays a menu of options for the user to choose from.""" print ('\nContacts Sample\n' '1) List all of your contacts.\n' '2) Create a contact.\n' '3) Query contacts on updated time.\n' '4) Modify a contact.\n' '5) Delete a contact.\n' '6) List all of your contact groups.\n' '7) Query your groups on updated time.\n' '8) Exit.\n') def GetMenuChoice(self, max): """Retrieves the menu selection from the user. Args: max: [int] The maximum number of allowed choices (inclusive) Returns: The integer of the menu item chosen by the user. """ while True: input = raw_input('> ') try: num = int(input) except ValueError: print 'Invalid choice. Please choose a value between 1 and', max continue if num > max or num < 1: print 'Invalid choice. Please choose a value between 1 and', max else: return num def Run(self): """Prompts the user to choose funtionality to be demonstrated.""" try: while True: self.PrintMenu() choice = self.GetMenuChoice(8) if choice == 1: self.ListAllContacts() elif choice == 2: self.CreateMenu() elif choice == 3: self.QueryMenu() elif choice == 4: self.UpdateContactMenu() elif choice == 5: self.DeleteContactMenu() elif choice == 6: self.ListAllGroups() elif choice == 7: self.QueryGroupsMenu() elif choice == 8: return except KeyboardInterrupt: print '\nGoodbye.' return def main(): """Demonstrates use of the Contacts extension using the ContactsSample object.""" # Parse command line options try: opts, args = getopt.getopt(sys.argv[1:], '', ['user=', 'pw=']) except getopt.error, msg: print 'python contacts_example.py --user [username] --pw [password]' sys.exit(2) user = '' pw = '' # Process options for option, arg in opts: if option == '--user': user = arg elif option == '--pw': pw = arg while not user: print 'NOTE: Please run these tests only with a test account.' user = raw_input('Please enter your username: ') while not pw: pw = getpass.getpass() if not pw: print 'Password cannot be blank.' try: sample = ContactsSample(user, pw) except gdata.client.BadAuthentication: print 'Invalid user credentials given.' return sample.Run() if __name__ == '__main__': main()
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 a Sample for Google Profiles. ProfilesSample: demonstrates operations with the Profiles feed. """ __author__ = 'jtoledo (Julian Toledo)' import getopt import getpass import sys import gdata.contacts import gdata.contacts.service class ProfilesSample(object): """ProfilesSample object demonstrates operations with the Profiles feed.""" def __init__(self, email, password, domain): """Constructor for the ProfilesSample object. Takes an email and password corresponding to a gmail account to demonstrate the functionality of the Profiles feed. Args: email: [string] The e-mail address of the account to use for the sample. password: [string] The password corresponding to the account specified by the email parameter. domain: [string] The domain for the Profiles feed """ self.gd_client = gdata.contacts.service.ContactsService( contact_list=domain) self.gd_client.email = email self.gd_client.password = password self.gd_client.source = 'GoogleInc-ProfilesPythonSample-1' self.gd_client.ProgrammaticLogin() def PrintFeed(self, feed, ctr=0): """Prints out the contents of a feed to the console. Args: feed: A gdata.profiles.ProfilesFeed instance. ctr: [int] The number of entries in this feed previously printed. This allows continuous entry numbers when paging through a feed. Returns: The number of entries printed, including those previously printed as specified in ctr. This is for passing as an ar1gument to ctr on successive calls to this method. """ if not feed.entry: print '\nNo entries in feed.\n' return 0 for entry in feed.entry: self.PrintEntry(entry) return len(feed.entry) + ctr def PrintEntry(self, entry): """Prints out the contents of a single Entry to the console. Args: entry: A gdata.contacts.ProfilesEntry """ print '\n%s' % (entry.title.text) for email in entry.email: if email.primary == 'true': print 'Email: %s (primary)' % (email.address) else: print 'Email: %s' % (email.address) if entry.nickname: print 'Nickname: %s' % (entry.nickname.text) if entry.occupation: print 'Occupation: %s' % (entry.occupation.text) if entry.gender: print 'Gender: %s' % (entry.gender.value) if entry.birthday: print 'Birthday: %s' % (entry.birthday.when) for relation in entry.relation: print 'Relation: %s %s' % (relation.rel, relation.text) for user_defined_field in entry.user_defined_field: print 'UserDefinedField: %s %s' % (user_defined_field.key, user_defined_field.value) for website in entry.website: print 'Website: %s %s' % (website.href, website.rel) for phone_number in entry.phone_number: print 'Phone Number: %s' % phone_number.text for organization in entry.organization: print 'Organization:' if organization.org_name: print ' Name: %s' % (organization.org_name.text) if organization.org_title: print ' Title: %s' % (organization.org_title.text) if organization.org_department: print ' Department: %s' % (organization.org_department.text) if organization.org_job_description: print ' Job Desc: %s' % (organization.org_job_description.text) def PrintPaginatedFeed(self, feed, print_method): """Print all pages of a paginated feed. This will iterate through a paginated feed, requesting each page and printing the entries contained therein. Args: feed: A gdata.contacts.ProfilesFeed instance. print_method: The method which will be used to print each page of the """ ctr = 0 while feed: # Print contents of current feed ctr = print_method(feed=feed, ctr=ctr) # Prepare for next feed iteration next = feed.GetNextLink() feed = None if next: if self.PromptOperationShouldContinue(): # Another feed is available, and the user has given us permission # to fetch it feed = self.gd_client.GetProfilesFeed(next.href) else: # User has asked us to terminate feed = None def PromptOperationShouldContinue(self): """Display a "Continue" prompt. This give is used to give users a chance to break out of a loop, just in case they have too many profiles/groups. Returns: A boolean value, True if the current operation should continue, False if the current operation should terminate. """ while True: key_input = raw_input('Continue [Y/n]? ') if key_input is 'N' or key_input is 'n': return False elif key_input is 'Y' or key_input is 'y' or key_input is '': return True def ListAllProfiles(self): """Retrieves a list of profiles and displays name and primary email.""" feed = self.gd_client.GetProfilesFeed() self.PrintPaginatedFeed(feed, self.PrintFeed) def SelectProfile(self): username = raw_input('Please enter your username for the profile: ') entry_uri = self.gd_client.GetFeedUri('profiles')+'/'+username try: entry = self.gd_client.GetProfile(entry_uri) self.PrintEntry(entry) except gdata.service.RequestError: print 'Invalid username for the profile.' def PrintMenu(self): """Displays a menu of options for the user to choose from.""" print ('\nProfiles Sample\n' '1) List all of your Profiles.\n' '2) Get a single Profile.\n' '3) Exit.\n') def GetMenuChoice(self, maximum): """Retrieves the menu selection from the user. Args: maximum: [int] The maximum number of allowed choices (inclusive) Returns: The integer of the menu item chosen by the user. """ while True: key_input = raw_input('> ') try: num = int(key_input) except ValueError: print 'Invalid choice. Please choose a value between 1 and', maximum continue if num > maximum or num < 1: print 'Invalid choice. Please choose a value between 1 and', maximum else: return num def Run(self): """Prompts the user to choose funtionality to be demonstrated.""" try: while True: self.PrintMenu() choice = self.GetMenuChoice(3) if choice == 1: self.ListAllProfiles() elif choice == 2: self.SelectProfile() elif choice == 3: return except KeyboardInterrupt: print '\nGoodbye.' return def main(): """Demonstrates use of the Profiles using the ProfilesSample object.""" # Parse command line options try: opts, args = getopt.getopt(sys.argv[1:], '', ['user=', 'pw=', 'domain=']) except getopt.error, msg: print 'python profiles_example.py --user [username] --pw [password]' print ' --domain [domain]' sys.exit(2) user = '' pw = '' domain = '' # Process options for option, arg in opts: if option == '--user': user = arg elif option == '--pw': pw = arg elif option == '--domain': domain = arg while not user: print 'NOTE: Please run these tests only with a test account.' user = raw_input('Please enter your email: ') while not pw: pw = getpass.getpass('Please enter password: ') if not pw: print 'Password cannot be blank.' while not domain: domain = raw_input('Please enter your Apps domain: ') try: sample = ProfilesSample(user, pw, domain) except gdata.service.BadAuthentication: print 'Invalid user credentials given.' return sample.Run() if __name__ == '__main__': main()
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. __author__ = 'api.rboyd@gmail.com (Ryan Boyd)' try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import gdata.calendar.data import gdata.calendar.client import gdata.acl.data import atom import getopt import sys import string import time class CalendarExample: def __init__(self, email, password): """Creates a CalendarService and provides ClientLogin auth details to it. The email and password are required arguments for ClientLogin. The CalendarService automatically sets the service to be 'cl', as is appropriate for calendar. The 'source' defined below is an arbitrary string, but should be used to reference your name or the name of your organization, the app name and version, with '-' between each of the three values. The account_type is specified to authenticate either Google Accounts or Google Apps accounts. See gdata.service or http://code.google.com/apis/accounts/AuthForInstalledApps.html for more info on ClientLogin. NOTE: ClientLogin should only be used for installed applications and not for multi-user web applications.""" self.cal_client = gdata.calendar.client.CalendarClient(source='Google-Calendar_Python_Sample-1.0') self.cal_client.ClientLogin(email, password, self.cal_client.source); def _PrintUserCalendars(self): """Retrieves the list of calendars to which the authenticated user either owns or subscribes to. This is the same list as is represented in the Google Calendar GUI. Although we are only printing the title of the calendar in this case, other information, including the color of the calendar, the timezone, and more. See CalendarListEntry for more details on available attributes.""" feed = self.cal_client.GetAllCalendarsFeed() print 'Printing allcalendars: %s' % feed.title.text for i, a_calendar in zip(xrange(len(feed.entry)), feed.entry): print '\t%s. %s' % (i, a_calendar.title.text,) def _PrintOwnCalendars(self): """Retrieves the list of calendars to which the authenticated user owns -- Although we are only printing the title of the calendar in this case, other information, including the color of the calendar, the timezone, and more. See CalendarListEntry for more details on available attributes.""" feed = self.cal_client.GetOwnCalendarsFeed() print 'Printing owncalendars: %s' % feed.title.text for i, a_calendar in zip(xrange(len(feed.entry)), feed.entry): print '\t%s. %s' % (i, a_calendar.title.text,) def _PrintAllEventsOnDefaultCalendar(self): """Retrieves all events on the primary calendar for the authenticated user. In reality, the server limits the result set intially returned. You can use the max_results query parameter to allow the server to send additional results back (see query parameter use in DateRangeQuery for more info). Additionally, you can page through the results returned by using the feed.GetNextLink().href value to get the location of the next set of results.""" feed = self.cal_client.GetCalendarEventFeed() print 'Events on Primary Calendar: %s' % (feed.title.text,) for i, an_event in zip(xrange(len(feed.entry)), feed.entry): print '\t%s. %s' % (i, an_event.title.text,) for p, a_participant in zip(xrange(len(an_event.who)), an_event.who): print '\t\t%s. %s' % (p, a_participant.email,) print '\t\t\t%s' % (a_participant.value,) if a_participant.attendee_status: print '\t\t\t%s' % (a_participant.attendee_status.value,) def _FullTextQuery(self, text_query='Tennis'): """Retrieves events from the calendar which match the specified full-text query. The full-text query searches the title and content of an event, but it does not search the value of extended properties at the time of this writing. It uses the default (primary) calendar of the authenticated user and uses the private visibility/full projection feed. Please see: http://code.google.com/apis/calendar/reference.html#Feeds for more information on the feed types. Note: as we're not specifying any query parameters other than the full-text query, recurring events returned will not have gd:when elements in the response. Please see the Google Calendar API query paramters reference for more info: http://code.google.com/apis/calendar/reference.html#Parameters""" print 'Full text query for events on Primary Calendar: \'%s\'' % ( text_query,) query = gdata.calendar.client.CalendarEventQuery(text_query=text_query) feed = self.cal_client.GetCalendarEventFeed(q=query) for i, an_event in zip(xrange(len(feed.entry)), feed.entry): print '\t%s. %s' % (i, an_event.title.text,) print '\t\t%s. %s' % (i, an_event.content.text,) for a_when in an_event.when: print '\t\tStart time: %s' % (a_when.start,) print '\t\tEnd time: %s' % (a_when.end,) def _DateRangeQuery(self, start_date='2007-01-01', end_date='2007-07-01'): """Retrieves events from the server which occur during the specified date range. This uses the CalendarEventQuery class to generate the URL which is used to retrieve the feed. For more information on valid query parameters, see: http://code.google.com/apis/calendar/reference.html#Parameters""" print 'Date range query for events on Primary Calendar: %s to %s' % ( start_date, end_date,) query = gdata.calendar.client.CalendarEventQuery(start_min=start_date, start_max=end_date) feed = self.cal_client.GetCalendarEventFeed(q=query) for i, an_event in zip(xrange(len(feed.entry)), feed.entry): print '\t%s. %s' % (i, an_event.title.text,) for a_when in an_event.when: print '\t\tStart time: %s' % (a_when.start,) print '\t\tEnd time: %s' % (a_when.end,) def _InsertCalendar(self, title='Little League Schedule', description='This calendar contains practice and game times', time_zone='America/Los_Angeles', hidden=False, location='Oakland', color='#2952A3'): """Creates a new calendar using the specified data.""" print 'Creating new calendar with title "%s"' % title calendar = gdata.calendar.data.CalendarEntry() calendar.title = atom.data.Title(text=title) calendar.summary = atom.data.Summary(text=description) calendar.where.append(gdata.calendar.data.CalendarWhere(value=location)) calendar.color = gdata.calendar.data.ColorProperty(value=color) calendar.timezone = gdata.calendar.data.TimeZoneProperty(value=time_zone) if hidden: calendar.hidden = gdata.calendar.data.HiddenProperty(value='true') else: calendar.hidden = gdata.calendar.data.HiddenProperty(value='false') new_calendar = self.cal_client.InsertCalendar(new_calendar=calendar) return new_calendar def _UpdateCalendar(self, calendar, title='New Title', color=None): """Updates the title and, optionally, the color of the supplied calendar""" print 'Updating the calendar titled "%s" with the title "%s"' % ( calendar.title.text, title) calendar.title = atom.data.Title(text=title) if color is not None: calendar.color = gdata.calendar.data.ColorProperty(value=color) updated_calendar = self.cal_client.Update(calendar) return updated_calendar def _DeleteAllCalendars(self): """Deletes all calendars. Note: the primary calendar cannot be deleted""" feed = self.cal_client.GetOwnCalendarsFeed() for entry in feed.entry: print 'Deleting calendar: %s' % entry.title.text try: self.cal_client.Delete(entry.GetEditLink().href) except gdata.client.RequestError, msg: if msg.body.startswith('Cannot remove primary calendar'): print '\t%s' % msg.body else: print '\tUnexpected Error: %s' % msg.body def _InsertSubscription(self, id='python.gcal.test%40gmail.com'): """Subscribes to the calendar with the specified ID.""" print 'Subscribing to the calendar with ID: %s' % id calendar = gdata.calendar.data.CalendarEntry() calendar.id = atom.data.Id(text=id) returned_calendar = self.cal_client.InsertCalendarSubscription(calendar) return returned_calendar def _UpdateCalendarSubscription(self, id='python.gcal.test%40gmail.com', color=None, hidden=None, selected=None): """Updates the subscription to the calendar with the specified ID.""" print 'Updating the calendar subscription with ID: %s' % id calendar_url = ( 'http://www.google.com/calendar/feeds/default/allcalendars/full/%s' % id) calendar_entry = self.cal_client.GetCalendarEntry(calendar_url) if color is not None: calendar_entry.color = gdata.calendar.data.ColorProperty(value=color) if hidden is not None: if hidden: calendar_entry.hidden = gdata.calendar.data.HiddenProperty(value='true') else: calendar_entry.hidden = gdata.calendar.data.HiddenProperty(value='false') if selected is not None: if selected: calendar_entry.selected = gdata.calendar.data.SelectedProperty(value='true') else: calendar_entry.selected = gdata.calendar.data.SelectedProperty(value='false') updated_calendar = self.cal_client.Update(calendar_entry) return updated_calendar def _DeleteCalendarSubscription(self, id='python.gcal.test%40gmail.com'): """Deletes the subscription to the calendar with the specified ID.""" print 'Deleting the calendar subscription with ID: %s' % id calendar_url = ( 'http://www.google.com/calendar/feeds/default/allcalendars/full/%s' % id) calendar_entry = self.cal_client.GetCalendarEntry(calendar_url) self.cal_client.Delete(calendar_entry.GetEditLink().href) def _InsertEvent(self, title='Tennis with Beth', content='Meet for a quick lesson', where='On the courts', start_time=None, end_time=None, recurrence_data=None): """Inserts a basic event using either start_time/end_time definitions or gd:recurrence RFC2445 icalendar syntax. Specifying both types of dates is not valid. Note how some members of the CalendarEventEntry class use arrays and others do not. Members which are allowed to occur more than once in the calendar or GData "kinds" specifications are stored as arrays. Even for these elements, Google Calendar may limit the number stored to 1. The general motto to use when working with the Calendar data API is that functionality not available through the GUI will not be available through the API. Please see the GData Event "kind" document: http://code.google.com/apis/gdata/elements.html#gdEventKind for more information""" event = gdata.calendar.data.CalendarEventEntry() event.title = atom.data.Title(text=title) event.content = atom.data.Content(text=content) event.where.append(gdata.data.Where(value=where)) if recurrence_data is not None: # Set a recurring event event.recurrence = gdata.data.Recurrence(text=recurrence_data) else: if start_time is None: # Use current time for the start_time and have the event last 1 hour start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime()) end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + 3600)) event.when.append(gdata.data.When(start=start_time, end=end_time)) new_event = self.cal_client.InsertEvent(event) return new_event def _InsertSingleEvent(self, title='One-time Tennis with Beth', content='Meet for a quick lesson', where='On the courts', start_time=None, end_time=None): """Uses the _InsertEvent helper method to insert a single event which does not have any recurrence syntax specified.""" new_event = self._InsertEvent(title, content, where, start_time, end_time, recurrence_data=None) print 'New single event inserted: %s' % (new_event.id.text,) print '\tEvent edit URL: %s' % (new_event.GetEditLink().href,) print '\tEvent HTML URL: %s' % (new_event.GetHtmlLink().href,) return new_event def _InsertRecurringEvent(self, title='Weekly Tennis with Beth', content='Meet for a quick lesson', where='On the courts', recurrence_data=None): """Uses the _InsertEvent helper method to insert a recurring event which has only RFC2445 icalendar recurrence syntax specified. Note the use of carriage return/newline pairs at the end of each line in the syntax. Even when specifying times (as opposed to only dates), VTIMEZONE syntax is not required if you use a standard Java timezone ID. Please see the docs for more information on gd:recurrence syntax: http://code.google.com/apis/gdata/elements.html#gdRecurrence """ if recurrence_data is None: recurrence_data = ('DTSTART;VALUE=DATE:20070501\r\n' + 'DTEND;VALUE=DATE:20070502\r\n' + 'RRULE:FREQ=WEEKLY;BYDAY=Tu;UNTIL=20070904\r\n') new_event = self._InsertEvent(title, content, where, recurrence_data=recurrence_data, start_time=None, end_time=None) print 'New recurring event inserted: %s' % (new_event.id.text,) print '\tEvent edit URL: %s' % (new_event.GetEditLink().href,) print '\tEvent HTML URL: %s' % (new_event.GetHtmlLink().href,) return new_event def _InsertQuickAddEvent(self, content="Tennis with John today 3pm-3:30pm"): """Creates an event with the quick_add property set to true so the content is processed as quick add content instead of as an event description.""" event = gdata.calendar.data.CalendarEventEntry() event.content = atom.data.Content(text=content) event.quick_add = gdata.calendar.data.QuickAddProperty(value='true') new_event = self.cal_client.InsertEvent(event) return new_event def _InsertSimpleWebContentEvent(self): """Creates a WebContent object and embeds it in a WebContentLink. The WebContentLink is appended to the existing list of links in the event entry. Finally, the calendar client inserts the event.""" # Create a WebContent object url = 'http://www.google.com/logos/worldcup06.gif' web_content = gdata.calendar.data.WebContent(url=url, width='276', height='120') # Create a WebContentLink object that contains the WebContent object title = 'World Cup' href = 'http://www.google.com/calendar/images/google-holiday.gif' type = 'image/gif' web_content_link = gdata.calendar.data.WebContentLink(title=title, href=href, link_type=type, web_content=web_content) # Create an event that contains this web content event = gdata.calendar.data.CalendarEventEntry() event.link.append(web_content_link) print 'Inserting Simple Web Content Event' new_event = self.cal_client.InsertEvent(event) return new_event def _InsertWebContentGadgetEvent(self): """Creates a WebContent object and embeds it in a WebContentLink. The WebContentLink is appended to the existing list of links in the event entry. Finally, the calendar client inserts the event. Web content gadget events display Calendar Gadgets inside Google Calendar.""" # Create a WebContent object url = 'http://google.com/ig/modules/datetime.xml' web_content = gdata.calendar.data.WebContent(url=url, width='300', height='136') web_content.web_content_gadget_pref.append( gdata.calendar.data.WebContentGadgetPref(name='color', value='green')) # Create a WebContentLink object that contains the WebContent object title = 'Date and Time Gadget' href = 'http://gdata.ops.demo.googlepages.com/birthdayicon.gif' type = 'application/x-google-gadgets+xml' web_content_link = gdata.calendar.data.WebContentLink(title=title, href=href, link_type=type, web_content=web_content) # Create an event that contains this web content event = gdata.calendar.data.CalendarEventEntry() event.link.append(web_content_link) print 'Inserting Web Content Gadget Event' new_event = self.cal_client.InsertEvent(event) return new_event def _UpdateTitle(self, event, new_title='Updated event title'): """Updates the title of the specified event with the specified new_title. Note that the UpdateEvent method (like InsertEvent) returns the CalendarEventEntry object based upon the data returned from the server after the event is inserted. This represents the 'official' state of the event on the server. The 'edit' link returned in this event can be used for future updates. Due to the use of the 'optimistic concurrency' method of version control, most GData services do not allow you to send multiple update requests using the same edit URL. Please see the docs: http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency """ previous_title = event.title.text event.title.text = new_title print 'Updating title of event from:\'%s\' to:\'%s\'' % ( previous_title, event.title.text,) return self.cal_client.Update(event) def _AddReminder(self, event, minutes=10): """Adds a reminder to the event. This uses the default reminder settings for the user to determine what type of notifications are sent (email, sms, popup, etc.) and sets the reminder for 'minutes' number of minutes before the event. Note: you can only use values for minutes as specified in the Calendar GUI.""" for a_when in event.when: if len(a_when.reminder) > 0: a_when.reminder[0].minutes = minutes else: a_when.reminder.append(gdata.data.Reminder(minutes=str(minutes))) print 'Adding %d minute reminder to event' % (minutes,) return self.cal_client.Update(event) def _AddExtendedProperty(self, event, name='http://www.example.com/schemas/2005#mycal.id', value='1234'): """Adds an arbitrary name/value pair to the event. This value is only exposed through the API. Extended properties can be used to store extra information needed by your application. The recommended format is used as the default arguments above. The use of the URL format is to specify a namespace prefix to avoid collisions between different applications.""" event.extended_property.append( gdata.calendar.data.CalendarExtendedProperty(name=name, value=value)) print 'Adding extended property to event: \'%s\'=\'%s\'' % (name, value,) return self.cal_client.Update(event) def _DeleteEvent(self, event): """Given an event object returned for the calendar server, this method deletes the event. The edit link present in the event is the URL used in the HTTP DELETE request.""" self.cal_client.Delete(event.GetEditLink().href) def _PrintAclFeed(self): """Sends a HTTP GET to the default ACL URL (http://www.google.com/calendar/feeds/default/acl/full) and displays the feed returned in the response.""" feed = self.cal_client.GetCalendarAclFeed() print feed.title.text for i, a_rule in zip(xrange(len(feed.entry)), feed.entry): print '\t%s. %s' % (i, a_rule.title.text,) print '\t\t Role: %s' % (a_rule.role.value,) print '\t\t Scope %s - %s' % (a_rule.scope.type, a_rule.scope.value) def _CreateAclRule(self, username): """Creates a ACL rule that grants the given user permission to view free/busy information on the default calendar. Note: It is not necessary to specify a title for the ACL entry. The server will set this to be the value of the role specified (in this case "freebusy").""" print 'Creating Acl rule for user: %s' % username rule = gdata.calendar.data.CalendarAclEntry() rule.scope = gdata.acl.data.AclScope(value=username, type="user") roleValue = "http://schemas.google.com/gCal/2005#%s" % ("freebusy") rule.role = gdata.acl.data.AclRole(value=roleValue) aclUrl = "https://www.google.com/calendar/feeds/default/acl/full" returned_rule = self.cal_client.InsertAclEntry(rule, aclUrl) def _RetrieveAclRule(self, username): """Builds the aclEntryUri or the entry created in the previous example. The sends a HTTP GET message and displays the entry returned in the response.""" aclEntryUri = "http://www.google.com/calendar/feeds/" aclEntryUri += "default/acl/full/user:%s" % (username) entry = self.cal_client.GetCalendarAclEntry(aclEntryUri) print '\t%s' % (entry.title.text,) print '\t\t Role: %s' % (entry.role.value,) print '\t\t Scope %s - %s' % (entry.scope.type, entry.scope.value) return entry def _UpdateAclRule(self, entry): """Modifies the value of the role in the given entry and POSTs the updated entry. Note that while the role of an ACL entry can be updated, the scope can not be modified.""" print 'Update Acl rule: %s' % (entry.GetEditLink().href) roleValue = "http://schemas.google.com/gCal/2005#%s" % ("read") entry.role = gdata.acl.data.AclRole(value=roleValue) returned_rule = self.cal_client.Update(entry) def _DeleteAclRule(self, entry): """Given an ACL entry returned for the calendar server, this method deletes the entry. The edit link present in the entry is the URL used in the HTTP DELETE request.""" self.cal_client.Delete(entry.GetEditLink().href) def _batchRequest(self, updateEntry, deleteEntry): """Execute a batch request to create, update and delete an entry.""" print 'Executing batch request to insert, update and delete entries.' # feed that holds all the batch rquest entries request_feed = gdata.calendar.data.CalendarEventFeed() # creating an event entry to insert insertEntry = gdata.calendar.data.CalendarEventEntry() insertEntry.title = atom.data.Title(text='Python: batch insert') insertEntry.content = atom.data.Content(text='my content') start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime()) end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + 3600)) insertEntry.when.append(gdata.calendar.data.When(start=start_time, end=end_time)) insertEntry.batch_id = gdata.data.BatchId(text='insert-request') # add the insert entry to the batch feed request_feed.AddInsert(entry=insertEntry) if updateEntry: updateEntry.batch_id = gdata.data.BatchId(text='update-request') updateEntry.title = atom.data.Title(text='Python: batch update') # add the update entry to the batch feed request_feed.AddUpdate(entry=updateEntry) if deleteEntry: deleteEntry.batch_id = gdata.data.BatchId(text='delete-request') # add the delete entry to the batch feed request_feed.AddDelete(entry=deleteEntry) # submit the batch request to the server response_feed = self.cal_client.ExecuteBatch(request_feed, gdata.calendar.client.DEFAULT_BATCH_URL) # iterate the response feed to get the operation status for entry in response_feed.entry: print '\tbatch id: %s' % (entry.batch_id.text,) print '\tstatus: %s' % (entry.batch_status.code,) print '\treason: %s' % (entry.batch_status.reason,) if entry.batch_id.text == 'insert-request': insertEntry = entry elif entry.batch_id.text == 'update-request': updateEntry = entry return (insertEntry, updateEntry) def Run(self, delete='false'): """Runs each of the example methods defined above. Note how the result of the _InsertSingleEvent call is used for updating the title and the result of updating the title is used for inserting the reminder and again with the insertion of the extended property. This is due to the Calendar's use of GData's optimistic concurrency versioning control system: http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency """ # Getting feeds and query results self._PrintUserCalendars() self._PrintOwnCalendars() self._PrintAllEventsOnDefaultCalendar() self._FullTextQuery() self._DateRangeQuery() # Inserting and updating events see = self._InsertSingleEvent() see_u_title = self._UpdateTitle(see, 'New title for single event') see_u_reminder = self._AddReminder(see_u_title, minutes=30) see_u_ext_prop = self._AddExtendedProperty(see_u_reminder, name='propname', value='propvalue') ree = self._InsertRecurringEvent() simple_web_content_event = self._InsertSimpleWebContentEvent() web_content_gadget_event = self._InsertWebContentGadgetEvent() quick_add_event = self._InsertQuickAddEvent() # Access Control List examples self._PrintAclFeed() self._CreateAclRule("user@gmail.com") entry = self._RetrieveAclRule("user@gmail.com") self._UpdateAclRule(entry) self._DeleteAclRule(entry) # Creating, updating and deleting calendars inserted_calendar = self._InsertCalendar() updated_calendar = self._UpdateCalendar(calendar=inserted_calendar) # Insert Subscription inserted_subscription = self._InsertSubscription() updated_subscription = self._UpdateCalendarSubscription(selected=False) # Execute a batch request (quick_add_event, see_u_ext_prop) = self._batchRequest(see_u_ext_prop, quick_add_event) # Delete entries if delete argument='true' if delete == 'true': print 'Deleting created events' self.cal_client.Delete(see_u_ext_prop) self.cal_client.Delete(ree) self.cal_client.Delete(simple_web_content_event) self.cal_client.Delete(web_content_gadget_event) self.cal_client.Delete(quick_add_event) print 'Deleting subscriptions' self._DeleteCalendarSubscription() print 'Deleting all calendars' self._DeleteAllCalendars() def main(): """Runs the CalendarExample application with the provided username and and password values. Authentication credentials are required. NOTE: It is recommended that you run this sample using a test account.""" # parse command line options try: opts, args = getopt.getopt(sys.argv[1:], "", ["user=", "pw=", "delete="]) except getopt.error, msg: print ('python calendarExample.py --user [username] --pw [password] ' + '--delete [true|false] ') sys.exit(2) user = '' pw = '' delete = 'false' # Process options for o, a in opts: if o == "--user": user = a elif o == "--pw": pw = a elif o == "--delete": delete = a if user == '' or pw == '': print ('python calendarExample.py --user [username] --pw [password] ' + '--delete [true|false] ') sys.exit(2) sample = CalendarExample(user, pw) sample.Run(delete) if __name__ == '__main__': main()
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. # This file demonstrates how to use the Google Data API's Python client library # to interface with the Codesearch service. __author__ = 'vbarathan@gmail.com (Prakash Barathan)' from gdata import service import gdata.codesearch.service import gdata import atom import getopt import sys class CodesearchExample: def __init__(self): """Creates a GData service instance to talk to Codesearch service.""" self.service = gdata.codesearch.service.CodesearchService( source='Codesearch_Python_Sample-1.0') def PrintCodeSnippets(self, query): """Prints the codesearch results for given query.""" feed = self.service.GetSnippetsFeed(query) print feed.title.text + " Results for '" + query + "'" print '============================================' for entry in feed.entry: print "" + entry.title.text for match in entry.match: print "\tline#" + match.line_number + ":" + match.text.replace('\n', '') print def main(): """The main function runs the CodesearchExample application with user specified query.""" # parse command line options try: opts, args = getopt.getopt(sys.argv[1:], "", ["query="]) except getopt.error, msg: print ('python CodesearchExample.py --query [query_text]') sys.exit(2) query = '' # Process options for o, a in opts: if o == "--query": query = a if query == '': print ('python CodesearchExample.py --query [query]') sys.exit(2) sample = CodesearchExample() sample.PrintCodeSnippets(query) if __name__ == '__main__': main()
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. # # # This sample uses the Google Spreadsheets data API and the Google # Calendar data API. The script pulls a list of birthdays from a # Google Spreadsheet and inserts them as webContent events in the # user's Google Calendar. # # The script expects a certain format in the spreadsheet: Name, # Birthday, Photo URL, and Edit URL as headers. Expected format # of the birthday is: MM/DD. Edit URL is to be left blank by the # user - the script uses this column to determine whether to insert # a new event or to update an event at the URL. # # See the spreadsheet below for an example: # http://spreadsheets.google.com/pub?key=pfMX-JDVnx47J0DxqssIQHg # __author__ = 'api.stephaniel@google.com (Stephanie Liu)' try: from xml.etree import ElementTree # for Python 2.5 users except: from elementtree import ElementTree import gdata.spreadsheet.service import gdata.calendar.service import gdata.calendar import gdata.service import atom.service import gdata.spreadsheet import atom import string import time import datetime import getopt import getpass import sys class BirthdaySample: # CONSTANTS: Expected column headers: name, birthday, photourl, editurl & # default calendar reminder set to 2 days NAME = "name" BIRTHDAY = "birthday" PHOTO_URL = "photourl" EDIT_URL = "editurl" REMINDER = 60 * 24 * 2 # minutes def __init__(self, email, password): """ Initializes spreadsheet and calendar clients. Creates SpreadsheetsService and CalendarService objects and authenticates to each with ClientLogin. For more information about ClientLogin authentication: http://code.google.com/apis/accounts/AuthForInstalledApps.html Args: email: string password: string """ self.s_client = gdata.spreadsheet.service.SpreadsheetsService() self.s_client.email = email self.s_client.password = password self.s_client.source = 'exampleCo-birthdaySample-1' self.s_client.ProgrammaticLogin() self.c_client = gdata.calendar.service.CalendarService() self.c_client.email = email self.c_client.password = password self.c_client.source = 'exampleCo-birthdaySample-1' self.c_client.ProgrammaticLogin() def _PrintFeed(self, feed): """ Prints out Spreadsheet feeds in human readable format. Generic function taken from spreadsheetsExample.py. Args: feed: SpreadsheetsCellsFeed, SpreadsheetsListFeed, SpreadsheetsWorksheetsFeed, or SpreadsheetsSpreadsheetsFeed """ for i, entry in enumerate(feed.entry): if isinstance(feed, gdata.spreadsheet.SpreadsheetsCellsFeed): print '%s %s\n' % (entry.title.text, entry.content.text) elif isinstance(feed, gdata.spreadsheet.SpreadsheetsListFeed): print '%s %s %s\n' % (i, entry.title.text, entry.content.text) else: print '%s %s\n' % (i, entry.title.text) def _PromptForSpreadsheet(self): """ Prompts user to select spreadsheet. Gets and displays titles of all spreadsheets for user to select. Generic function taken from spreadsheetsExample.py. Args: none Returns: spreadsheet ID that the user selected: string """ feed = self.s_client.GetSpreadsheetsFeed() self._PrintFeed(feed) input = raw_input('\nSelection: ') # extract and return the spreadsheet ID return feed.entry[string.atoi(input)].id.text.rsplit('/', 1)[1] def _PromptForWorksheet(self, key): """ Prompts user to select desired worksheet. Gets and displays titles of all worksheets for user to select. Generic function taken from spreadsheetsExample.py. Args: key: string Returns: the worksheet ID that the user selected: string """ feed = self.s_client.GetWorksheetsFeed(key) self._PrintFeed(feed) input = raw_input('\nSelection: ') # extract and return the worksheet ID return feed.entry[string.atoi(input)].id.text.rsplit('/', 1)[1] def _AddReminder(self, event, minutes): """ Adds a reminder to a calendar event. This function sets the reminder attribute of the CalendarEventEntry. The script sets it to 2 days by default, and this value is not settable by the user. However, it can easily be changed to take this option. Args: event: CalendarEventEntry minutes: int Returns: the updated event: CalendarEventEntry """ for a_when in event.when: if len(a_when.reminder) > 0: a_when.reminder[0].minutes = minutes else: a_when.reminder.append(gdata.calendar.Reminder(minutes=minutes)) return self.c_client.UpdateEvent(event.GetEditLink().href, event) def _CreateBirthdayWebContentEvent(self, name, birthday, photo_url): """ Create the birthday web content event. This function creates and populates a CalendarEventEntry. webContent specific attributes are set. To learn more about the webContent format: http://www.google.com/support/calendar/bin/answer.py?answer=48528 Args: name: string birthday: string - expected format (MM/DD) photo_url: string Returns: the webContent CalendarEventEntry """ title = "%s's Birthday!" % name content = "It's %s's Birthday!" % name month = string.atoi(birthday.split("/")[0]) day = string.atoi(birthday.split("/")[1]) # Get current year year = time.ctime()[-4:] year = string.atoi(year) # Calculate the "end date" for the all day event start_time = datetime.date(year, month, day) one_day = datetime.timedelta(days=1) end_time = start_time + one_day start_time_str = start_time.strftime("%Y-%m-%d") end_time_str = end_time.strftime("%Y-%m-%d") # Create yearly recurrence rule recurrence_data = ("DTSTART;VALUE=DATE:%s\r\n" "DTEND;VALUE=DATE:%s\r\n" "RRULE:FREQ=YEARLY;WKST=SU\r\n" % (start_time.strftime("%Y%m%d"), end_time.strftime("%Y%m%d"))) web_rel = "http://schemas.google.com/gCal/2005/webContent" icon_href = "http://www.perstephanie.com/images/birthdayicon.gif" icon_type = "image/gif" extension_text = ( 'gCal:webContent xmlns:gCal="http://schemas.google.com/gCal/2005"' ' url="%s" width="300" height="225"' % (photo_url)) event = gdata.calendar.CalendarEventEntry() event.title = atom.Title(text=title) event.content = atom.Content(text=content) event.recurrence = gdata.calendar.Recurrence(text=recurrence_data) event.when.append(gdata.calendar.When(start_time=start_time_str, end_time=end_time_str)) # Adding the webContent specific XML event.link.append(atom.Link(rel=web_rel, title=title, href=icon_href, link_type=icon_type)) event.link[0].extension_elements.append( atom.ExtensionElement(extension_text)) return event def _InsertBirthdayWebContentEvent(self, event): """ Insert event into the authenticated user's calendar. Args: event: CalendarEventEntry Returns: the newly created CalendarEventEntry """ edit_uri = '/calendar/feeds/default/private/full' return self.c_client.InsertEvent(event, edit_uri) def Run(self): """ Run sample. TODO: add exception handling Args: none """ key_id = self._PromptForSpreadsheet() wksht_id = self._PromptForWorksheet(key_id) feed = self.s_client.GetListFeed(key_id, wksht_id) found_name = False found_birthday = False found_photourl = False found_editurl = False # Check to make sure all headers are present # Need to find at least one instance of name, birthday, photourl # editurl if len(feed.entry) > 0: for name, custom in feed.entry[0].custom.iteritems(): if custom.column == self.NAME: found_name = True elif custom.column == self.BIRTHDAY: found_birthday = True elif custom.column == self.PHOTO_URL: found_photourl = True elif custom.column == self.EDIT_URL: found_editurl = True if not found_name and found_birthday and found_photourl and found_editurl: print ("ERROR - Unexpected number of column headers. Should have: %s," " %s, %s, and %s." % (self.NAME, self.BIRTHDAY, self.PHOTO_URL, self.EDIT_URL)) sys.exit(1) # For every row in the spreadsheet, grab all the data and either insert # a new event into the calendar, or update the existing event # Create dict to represent the row data to update edit link back to # Spreadsheet for entry in feed.entry: d = {} input_valid = True for name, custom in entry.custom.iteritems(): d[custom.column] = custom.text month = int(d[self.BIRTHDAY].split("/")[0]) day = int(d[self.BIRTHDAY].split("/")[1]) # Some input checking. Script will allow the insert to continue with # a missing name value. if d[self.NAME] is None: d[self.NAME] = " " if d[self.PHOTO_URL] is None: input_valid = False if d[self.BIRTHDAY] is None: input_valid = False elif not 1 <= month <= 12 or not 1 <= day <= 31: input_valid = False if d[self.EDIT_URL] is None and input_valid: event = self._CreateBirthdayWebContentEvent(d[self.NAME], d[self.BIRTHDAY], d[self.PHOTO_URL]) event = self._InsertBirthdayWebContentEvent(event) event = self._AddReminder(event, self.REMINDER) print "Added %s's birthday!" % d[self.NAME] elif input_valid: # Event already exists edit_link = d[self.EDIT_URL] event = self._CreateBirthdayWebContentEvent(d[self.NAME], d[self.BIRTHDAY], d[self.PHOTO_URL]) event = self.c_client.UpdateEvent(edit_link, event) event = self._AddReminder(event, self.REMINDER) print "Updated %s's birthday!" % d[self.NAME] if input_valid: d[self.EDIT_URL] = event.GetEditLink().href self.s_client.UpdateRow(entry, d) else: print "Warning - Skipping row, missing valid input." def main(): email = raw_input("Please enter your email: ") password = getpass.getpass("Please enter your password: ") sample = BirthdaySample(email, password) sample.Run() if __name__ == '__main__': main()
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. __author__ = 'e.bidelman (Eric Bidelman)' import gdata.contacts import gdata.contacts.service import gdata.docs import gdata.docs.service CONSUMER_KEY = 'yourdomain.com' CONSUMER_SECRET = 'YOUR_CONSUMER_KEY' SIG_METHOD = gdata.auth.OAuthSignatureMethod.HMAC_SHA1 requestor_id = 'any.user@yourdomain.com' # Contacts Data API ============================================================ contacts = gdata.contacts.service.ContactsService() contacts.SetOAuthInputParameters( SIG_METHOD, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, two_legged_oauth=True, requestor_id=requestor_id) # GET - fetch user's contact list print "\nList of contacts for %s:" % (requestor_id,) feed = contacts.GetContactsFeed() for entry in feed.entry: print entry.title.text # GET - fetch another user's contact list requestor_id = 'another_user@yourdomain.com' print "\nList of contacts for %s:" % (requestor_id,) contacts.GetOAuthInputParameters().requestor_id = requestor_id feed = contacts.GetContactsFeed() for entry in feed.entry: print entry.title.text # Google Documents List Data API =============================================== docs = gdata.docs.service.DocsService() docs.SetOAuthInputParameters( SIG_METHOD, CONSUMER_KEY, consumer_secret=CONSUMER_SECRET, two_legged_oauth=True, requestor_id=requestor_id) # POST - upload a document print "\nUploading document to %s's Google Documents account:" % (requestor_id,) ms = gdata.MediaSource( file_path='/path/to/test.txt', content_type=gdata.docs.service.SUPPORTED_FILETYPES['TXT']) # GET - fetch user's document list entry = docs.UploadDocument(ms, 'Company Perks') print 'Document now accessible online at:', entry.GetAlternateLink().href print "\nList of Google Documents for %s" % (requestor_id,) feed = docs.GetDocumentListFeed() for entry in feed.entry: print entry.title.text
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. # Note: # This sample demonstrates 2 Legged OAuth using v2 of the Google Data APIs. # See 2_legged_oauth.py for an example of using 2LO with v1.0 of the APIs. __author__ = 'e.bidelman (Eric Bidelman)' import gdata.gauth import gdata.contacts.client import gdata.docs.client SOURCE_APP_NAME = 'google-PyClient2LOSample-v2.0' CONSUMER_KEY = 'yourdomain.com' CONSUMER_SECRET = 'YOUR_CONSUMER_KEY' def PrintContacts(client): print '\nListing contacts for %s...' % client.auth_token.requestor_id feed = client.GetContacts() for entry in feed.entry: print entry.title.text # Contacts Data API Example ==================================================== requestor_id = 'any.user@' + CONSUMER_KEY two_legged_oauth_token = gdata.gauth.TwoLeggedOAuthHmacToken( CONSUMER_KEY, CONSUMER_SECRET, requestor_id) contacts_client = gdata.contacts.client.ContactsClient(source=SOURCE_APP_NAME) contacts_client.auth_token = two_legged_oauth_token # GET - fetch user's contact list PrintContacts(contacts_client) # GET - fetch another user's contact list contacts_client.auth_token.requestor_id = 'different.user' + CONSUMER_KEY PrintContacts(contacts_client) # Documents List Data API Example ============================================== docs_client = gdata.docs.client.DocsClient(source=SOURCE_APP_NAME) docs_client.auth_token = two_legged_oauth_token docs_client.ssl = True # POST - upload a document print "\nUploading doc to %s's account..." % docs_client.auth_token.requestor_id entry = docs_client.Upload('test.txt', 'MyDocTitle', content_type='text/plain') print 'Document now accessible online at:', entry.GetAlternateLink().href # GET - fetch the user's document list print '\nListing Google Docs for %s...' % docs_client.auth_token.requestor_id feed = docs_client.GetDocList() for entry in feed.entry: print entry.title.text
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. __author__ = 'kunalmshah.userid (Kunal Shah)' import sys import os.path import getopt import gdata.auth import gdata.docs.service class OAuthSample(object): """An OAuthSample object demonstrates the three-legged OAuth process.""" def __init__(self, consumer_key, consuer_secret): """Constructor for the OAuthSample object. Takes a consumer key and consumer secret, authenticates using OAuth mechanism and lists the document titles using Document List Data API. Uses HMAC-SHA1 signature method. Args: consumer_key: string Domain identifying third_party web application. consumer_secret: string Secret generated during registration. Returns: An OAuthSample object used to run the sample demonstrating the way to use OAuth authentication mode. """ self.consumer_key = consumer_key self.consumer_secret = consuer_secret self.gd_client = gdata.docs.service.DocsService() def _PrintFeed(self, feed): """Prints out the contents of a feed to the console. Args: feed: A gdata.docs.DocumentListFeed instance. """ if not feed.entry: print 'No entries in feed.\n' i = 1 for entry in feed.entry: print '%d. %s\n' % (i, entry.title.text.encode('UTF-8')) i += 1 def _ListAllDocuments(self): """Retrieves a list of all of a user's documents and displays them.""" feed = self.gd_client.GetDocumentListFeed() self._PrintFeed(feed) def Run(self): """Demonstrates usage of OAuth authentication mode and retrieves a list of documents using Document List Data API.""" print '\nSTEP 1: Set OAuth input parameters.' self.gd_client.SetOAuthInputParameters( gdata.auth.OAuthSignatureMethod.HMAC_SHA1, self.consumer_key, consumer_secret=self.consumer_secret) print '\nSTEP 2: Fetch OAuth Request token.' request_token = self.gd_client.FetchOAuthRequestToken() print 'Request Token fetched: %s' % request_token print '\nSTEP 3: Set the fetched OAuth token.' self.gd_client.SetOAuthToken(request_token) print 'OAuth request token set.' print '\nSTEP 4: Generate OAuth authorization URL.' auth_url = self.gd_client.GenerateOAuthAuthorizationURL() print 'Authorization URL: %s' % auth_url raw_input('Manually go to the above URL and authenticate.' 'Press a key after authorization.') print '\nSTEP 5: Upgrade to an OAuth access token.' self.gd_client.UpgradeToOAuthAccessToken() print 'Access Token: %s' % ( self.gd_client.token_store.find_token(request_token.scopes[0])) print '\nYour Documents:\n' self._ListAllDocuments() print 'STEP 6: Revoke the OAuth access token after use.' self.gd_client.RevokeOAuthToken() print 'OAuth access token revoked.' def main(): """Demonstrates usage of OAuth authentication mode. Prints a list of documents. This demo uses HMAC-SHA1 signature method. """ # Parse command line options try: opts, args = getopt.getopt(sys.argv[1:], '', ['consumer_key=', 'consumer_secret=']) except getopt.error, msg: print ('python oauth_example.py --consumer_key [oauth_consumer_key] ' '--consumer_secret [consumer_secret] ') sys.exit(2) consumer_key = '' consumer_secret = '' # Process options for option, arg in opts: if option == '--consumer_key': consumer_key = arg elif option == '--consumer_secret': consumer_secret = arg while not consumer_key: consumer_key = raw_input('Please enter consumer key: ') while not consumer_secret: consumer_secret = raw_input('Please enter consumer secret: ') sample = OAuthSample(consumer_key, consumer_secret) sample.Run() if __name__ == '__main__': main()
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. __author__ = 'e.bidelman (Eric Bidelman)' import cgi import os import gdata.auth import gdata.docs import gdata.docs.service import gdata.alt.appengine from appengine_utilities.sessions import Session from django.utils import simplejson from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app SETTINGS = { 'APP_NAME': 'google-GDataOAuthAppEngine-v1', 'CONSUMER_KEY': 'YOUR_CONSUMER_KEY', 'CONSUMER_SECRET': 'YOUR_CONSUMER_SECRET', 'SIG_METHOD': gdata.auth.OAuthSignatureMethod.HMAC_SHA1, 'SCOPES': ['http://docs.google.com/feeds/', 'https://docs.google.com/feeds/'] } gdocs = gdata.docs.service.DocsService(source=SETTINGS['APP_NAME']) gdocs.SetOAuthInputParameters(SETTINGS['SIG_METHOD'], SETTINGS['CONSUMER_KEY'], consumer_secret=SETTINGS['CONSUMER_SECRET']) gdata.alt.appengine.run_on_appengine(gdocs) class MainPage(webapp.RequestHandler): """Main page displayed to user.""" # GET / def get(self): if not users.get_current_user(): self.redirect(users.create_login_url(self.request.uri)) access_token = gdocs.token_store.find_token('%20'.join(SETTINGS['SCOPES'])) if isinstance(access_token, gdata.auth.OAuthToken): form_action = '/fetch_data' form_value = 'Now fetch my docs!' revoke_token_link = True else: form_action = '/get_oauth_token' form_value = 'Give this website access to my Google Docs' revoke_token_link = None template_values = { 'form_action': form_action, 'form_value': form_value, 'user': users.get_current_user(), 'revoke_token_link': revoke_token_link, 'oauth_token': access_token, 'consumer': gdocs.GetOAuthInputParameters().GetConsumer(), 'sig_method': gdocs.GetOAuthInputParameters().GetSignatureMethod().get_name() } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) class OAuthDance(webapp.RequestHandler): """Handler for the 3 legged OAuth dance, v1.0a.""" """This handler is responsible for fetching an initial OAuth request token, redirecting the user to the approval page. When the user grants access, they will be redirected back to this GET handler and their authorized request token will be exchanged for a long-lived access token.""" # GET /get_oauth_token def get(self): """Invoked after we're redirected back from the approval page.""" self.session = Session() oauth_token = gdata.auth.OAuthTokenFromUrl(self.request.uri) if oauth_token: oauth_token.secret = self.session['oauth_token_secret'] oauth_token.oauth_input_params = gdocs.GetOAuthInputParameters() gdocs.SetOAuthToken(oauth_token) # 3.) Exchange the authorized request token for an access token oauth_verifier = self.request.get('oauth_verifier', default_value='') access_token = gdocs.UpgradeToOAuthAccessToken( oauth_verifier=oauth_verifier) # Remember the access token in the current user's token store if access_token and users.get_current_user(): gdocs.token_store.add_token(access_token) elif access_token: gdocs.current_token = access_token gdocs.SetOAuthToken(access_token) self.redirect('/') # POST /get_oauth_token def post(self): """Fetches a request token and redirects the user to the approval page.""" self.session = Session() if users.get_current_user(): # 1.) REQUEST TOKEN STEP. Provide the data scope(s) and the page we'll # be redirected back to after the user grants access on the approval page. req_token = gdocs.FetchOAuthRequestToken( scopes=SETTINGS['SCOPES'], oauth_callback=self.request.uri) # When using HMAC, persist the token secret in order to re-create an # OAuthToken object coming back from the approval page. self.session['oauth_token_secret'] = req_token.secret # Generate the URL to redirect the user to. Add the hd paramter for a # better user experience. Leaving it off will give the user the choice # of what account (Google vs. Google Apps) to login with. domain = self.request.get('domain', default_value='default') approval_page_url = gdocs.GenerateOAuthAuthorizationURL( extra_params={'hd': domain}) # 2.) APPROVAL STEP. Redirect to user to Google's OAuth approval page. self.redirect(approval_page_url) class FetchData(OAuthDance): """Fetches the user's data.""" """This class inherits from OAuthDance in order to utilize OAuthDance.post() in case of a request error (e.g. the user has a bad token).""" # GET /fetch_data def get(self): self.redirect('/') # POST /fetch_data def post(self): """Fetches the user's data.""" try: feed = gdocs.GetDocumentListFeed() json = [] for entry in feed.entry: if entry.lastModifiedBy is not None: last_modified_by = entry.lastModifiedBy.email.text else: last_modified_by = '' if entry.lastViewed is not None: last_viewed = entry.lastViewed.text else: last_viewed = '' json.append({'title': entry.title.text, 'links': {'alternate': entry.GetHtmlLink().href}, 'published': entry.published.text, 'updated': entry.updated.text, 'resourceId': entry.resourceId.text, 'type': entry.GetDocumentType(), 'lastModifiedBy': last_modified_by, 'lastViewed': last_viewed }) self.response.out.write(simplejson.dumps(json)) except gdata.service.RequestError, error: OAuthDance.post(self) class RevokeToken(webapp.RequestHandler): # GET /revoke_token def get(self): """Revokes the current user's OAuth access token.""" try: gdocs.RevokeOAuthToken() except gdata.service.RevokingOAuthTokenFailed: pass gdocs.token_store.remove_all_tokens() self.redirect('/') def main(): application = webapp.WSGIApplication([('/', MainPage), ('/get_oauth_token', OAuthDance), ('/fetch_data', FetchData), ('/revoke_token', RevokeToken)], debug=True) run_wsgi_app(application)
Python
""" Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from google.appengine.ext import db from cache import Cache class Paginator(object): """ This class is used for maintaining pagination objects. """ @classmethod def get(cls, count=10, q_filters={}, search=None, start=None, model=None, \ order='ASC', order_by='__key__'): """ get queries the database on model, starting with key, ordered by order. It receives count + 1 items, returning count and setting a next field to the count + 1 item key. It then reverses the sort, and grabs count objects, returning the last as a the previous. Arguments: count: The amount of entries to pull on query q_filter: The filter value (optional) search: Search is used for SearchableModel searches start: The key to start the page from model: The Model object to query against. This is not a string, it must be a Model derived object. order: The order in which to pull the values. order_by: The attribute to order results by. This defaults to __key__ Returns a dict: { 'next': next_key, 'prev': prev_key, 'items': entities_pulled } """ # argument validation if model == None: raise ValueError('You must pass a model to query') # a valid model object will have a gql method. if callable(model.gql) == False: raise TypeError('model must be a valid model object.') # cache check cache_string = "gae_paginator_" for q_filter in q_filters: cache_string = cache_string + q_filter + "_" + q_filters[q_filter] + "_" cache_string = cache_string + "index" c = Cache() if c.has_key(cache_string): return c[cache_string] # build query query = model.all() if len(q_filters) > 0: for q_filter in q_filters: query.filter(q_filter + " = ", q_filters[q_filter]) if start: if order.lower() == "DESC".lower(): query.filter(order_by + " <", start) else: query.filter(order_by + " >", start) if search: query.search(search) if order.lower() == "DESC".lower(): query.order("-" + order_by) else: query.order(order_by) results = query.fetch(count + 1) if len(results) == count + 1: next = getattr(results[count - 1], order_by) # reverse the query to get the value for previous if start is not None: rquery = model.all() for q_filter in q_filters: rquery.filter(q_filter + " = ", q_filters[q_filter]) if search: query.search(search) if order.lower() == "DESC".lower(): rquery.order(order_by) else: rquery.order("-" + order_by) rresults = rquery.fetch(count) previous = getattr(results[0], order_by) else: previous = None else: next = None return { "results": results, "next": next, "previous": previous }
Python
# -*- coding: utf-8 -*- """ Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ # main python imports import datetime import pickle import random import __main__ # google appengine import from google.appengine.ext import db from google.appengine.api import memcache # settings DEFAULT_TIMEOUT = 3600 # cache expires after one hour (3600 sec) CLEAN_CHECK_PERCENT = 50 # 15% of all requests will clean the database MAX_HITS_TO_CLEAN = 100 # the maximum number of cache hits to clean on attempt class _AppEngineUtilities_Cache(db.Model): # It's up to the application to determine the format of their keys cachekey = db.StringProperty() createTime = db.DateTimeProperty(auto_now_add=True) timeout = db.DateTimeProperty() value = db.BlobProperty() class Cache(object): """ Cache is used for storing pregenerated output and/or objects in the Big Table datastore to minimize the amount of queries needed for page displays. The idea is that complex queries that generate the same results really should only be run once. Cache can be used to store pregenerated value made from queries (or other calls such as urlFetch()), or the query objects themselves. """ def __init__(self, clean_check_percent = CLEAN_CHECK_PERCENT, max_hits_to_clean = MAX_HITS_TO_CLEAN, default_timeout = DEFAULT_TIMEOUT): """ Initializer Args: clean_check_percent: how often cache initialization should run the cache cleanup max_hits_to_clean: maximum number of stale hits to clean default_timeout: default length a cache item is good for """ self.clean_check_percent = clean_check_percent self.max_hits_to_clean = max_hits_to_clean self.default_timeout = default_timeout if random.randint(1, 100) < self.clean_check_percent: self._clean_cache() if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheInitialized') def _clean_cache(self): """ _clean_cache is a routine that is run to find and delete cache items that are old. This helps keep the size of your over all datastore down. """ query = _AppEngineUtilities_Cache.all() query.filter('timeout < ', datetime.datetime.now()) results = query.fetch(self.max_hits_to_clean) db.delete(results) #for result in results: # result.delete() def _validate_key(self, key): if key == None: raise KeyError def _validate_value(self, value): if value == None: raise ValueError def _validate_timeout(self, timeout): if timeout == None: timeout = datetime.datetime.now() +\ datetime.timedelta(seconds=DEFAULT_TIMEOUT) if type(timeout) == type(1): timeout = datetime.datetime.now() + \ datetime.timedelta(seconds = timeout) if type(timeout) != datetime.datetime: raise TypeError if timeout < datetime.datetime.now(): raise ValueError return timeout def add(self, key = None, value = None, timeout = None): """ add adds an entry to the cache, if one does not already exist. """ self._validate_key(key) self._validate_value(value) timeout = self._validate_timeout(timeout) if key in self: raise KeyError cacheEntry = _AppEngineUtilities_Cache() cacheEntry.cachekey = key cacheEntry.value = pickle.dumps(value) cacheEntry.timeout = timeout # try to put the entry, if it fails silently pass # failures may happen due to timeouts, the datastore being read # only for maintenance or other applications. However, cache # not being able to write to the datastore should not # break the application try: cacheEntry.put() except: pass memcache_timeout = timeout - datetime.datetime.now() memcache.set('cache-'+key, value, int(memcache_timeout.seconds)) if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheAdded') def set(self, key = None, value = None, timeout = None): """ add adds an entry to the cache, overwriting an existing value if one already exists. """ self._validate_key(key) self._validate_value(value) timeout = self._validate_timeout(timeout) cacheEntry = self._read(key) if not cacheEntry: cacheEntry = _AppEngineUtilities_Cache() cacheEntry.cachekey = key cacheEntry.value = pickle.dumps(value) cacheEntry.timeout = timeout try: cacheEntry.put() except: pass memcache_timeout = timeout - datetime.datetime.now() memcache.set('cache-'+key, value, int(memcache_timeout.seconds)) if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheSet') def _read(self, key = None): """ _read returns a cache object determined by the key. It's set to private because it returns a db.Model object, and also does not handle the unpickling of objects making it not the best candidate for use. The special method __getitem__ is the preferred access method for cache data. """ query = _AppEngineUtilities_Cache.all() query.filter('cachekey', key) query.filter('timeout > ', datetime.datetime.now()) results = query.fetch(1) if len(results) is 0: return None return results[0] if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheReadFromDatastore') if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheRead') def delete(self, key = None): """ Deletes a cache object determined by the key. """ memcache.delete('cache-'+key) result = self._read(key) if result: if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheDeleted') result.delete() def get(self, key): """ get is used to return the cache value associated with the key passed. """ mc = memcache.get('cache-'+key) if mc: if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheReadFromMemcache') if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('cacheRead') return mc result = self._read(key) if result: timeout = result.timeout - datetime.datetime.now() # print timeout.seconds memcache.set('cache-'+key, pickle.loads(result.value), int(timeout.seconds)) return pickle.loads(result.value) else: raise KeyError def get_many(self, keys): """ Returns a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the response dict. """ dict = {} for key in keys: value = self.get(key) if value is not None: dict[key] = val return dict def __getitem__(self, key): """ __getitem__ is necessary for this object to emulate a container. """ return self.get(key) def __setitem__(self, key, value): """ __setitem__ is necessary for this object to emulate a container. """ return self.set(key, value) def __delitem__(self, key): """ Implement the 'del' keyword """ return self.delete(key) def __contains__(self, key): """ Implements "in" operator """ try: r = self.__getitem__(key) except KeyError: return False return True def has_key(self, keyname): """ Equivalent to k in a, use that form in new code """ return self.__contains__(keyname)
Python
# -*- coding: utf-8 -*- """ Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ # main python imports import os import time import datetime import random import md5 import Cookie import pickle import __main__ from time import strftime import logging # google appengine imports from google.appengine.ext import db from google.appengine.api import memcache #django simplejson import, used for flash from django.utils import simplejson from rotmodel import ROTModel # settings, if you have these set elsewhere, such as your django settings file, # you'll need to adjust the values to pull from there. class _AppEngineUtilities_Session(db.Model): """ Model for the sessions in the datastore. This contains the identifier and validation information for the session. """ sid = db.StringListProperty() session_key = db.FloatProperty() ip = db.StringProperty() ua = db.StringProperty() last_activity = db.DateTimeProperty() dirty = db.BooleanProperty(default=False) working = db.BooleanProperty(default=False) deleted = db.BooleanProperty(default=False) # used for cases where # datastore delete doesn't # work def put(self): """ Extend put so that it writes vaules to memcache as well as the datastore, and keeps them in sync, even when datastore writes fails. """ if self.session_key: memcache.set("_AppEngineUtilities_Session_" + str(self.session_key), self) else: # new session, generate a new key, which will handle the put and set the memcache self.create_key() self.last_activity = datetime.datetime.now() try: self.dirty = False logging.info("doing a put") db.put(self) memcache.set("_AppEngineUtilities_Session_" + str(self.session_key), self) except: self.dirty = True memcache.set("_AppEngineUtilities_Session_" + str(self.session_key), self) return self @classmethod def get_session(cls, session_obj=None): """ Uses the passed sid to get a session object from memcache, or datastore if a valid one exists. """ if session_obj.sid == None: return None session_key = session_obj.sid.split('_')[0] session = memcache.get("_AppEngineUtilities_Session_" + str(session_key)) if session: if session.deleted == True: session.delete() return None if session.dirty == True and session.working != False: # the working bit is used to make sure multiple requests, which can happen # with ajax oriented sites, don't try to put at the same time session.working = True memcache.set("_AppEngineUtilities_Session_" + str(session_key), session) session.put() if session_obj.sid in session.sid: logging.info('grabbed session from memcache') sessionAge = datetime.datetime.now() - session.last_activity if sessionAge.seconds > session_obj.session_expire_time: session.delete() return None return session else: return None # Not in memcache, check datastore query = _AppEngineUtilities_Session.all() query.filter("sid = ", session_obj.sid) results = query.fetch(1) if len(results) > 0: sessionAge = datetime.datetime.now() - results[0].last_activity if sessionAge.seconds > self.session_expire_time: results[0].delete() return None memcache.set("_AppEngineUtilities_Session_" + str(session_key), results[0]) memcache.set("_AppEngineUtilities_SessionData_" + str(session_key), results[0].get_items_ds()) logging.info('grabbed session from datastore') return results[0] else: return None def get_items(self): """ Returns all the items stored in a session """ items = memcache.get("_AppEngineUtilities_SessionData_" + str(self.session_key)) if items: for item in items: if item.deleted == True: item.delete() items.remove(item) return items query = _AppEngineUtilities_SessionData.all() query.filter('session_key', self.session_key) results = query.fetch(1000) return results def get_item(self, keyname = None): """ Returns a single item from the memcache or datastore """ mc = memcache.get("_AppEngineUtilities_SessionData_" + str(self.session_key)) if mc: for item in mc: if item.keyname == keyname: if item.deleted == True: item.delete() return None return item query = _AppEngineUtilities_SessionData.all() query.filter("session_key = ", self.session_key) query.filter("keyname = ", keyname) results = query.fetch(1) if len(results) > 0: memcache.set("_AppEngineUtilities_SessionData_" + str(self.session_key), self.get_items_ds()) return results[0] return None def get_items_ds(self): """ This gets all the items straight from the datastore, does not interact with the memcache. """ query = _AppEngineUtilities_SessionData.all() query.filter('session_key', self.session_key) results = query.fetch(1000) return results def delete(self): try: query = _AppEngineUtilities_SessionData.all() query.filter("session_key = ", self.session_key) results = query.fetch(1000) db.delete(results) db.delete(self) memcache.delete_multi(["_AppEngineUtilities_Session_" + str(self.session_key), "_AppEngineUtilities_SessionData_" + str(self.session_key)]) except: mc = memcache.get("_AppEngineUtilities_Session_" + str(self.session_key)) mc.deleted = True memcache.set("_AppEngineUtilities_Session_" + str(self.session_key), mc) def create_key(self): """ Creates a unique key for the session. """ self.session_key = time.time() valid = False while valid == False: # verify session_key is unique if memcache.get("_AppEngineUtilities_Session_" + str(self.session_key)): self.session_key = self.session_key + 0.001 else: query = _AppEngineUtilities_Session.all() query.filter("session_key = ", self.session_key) results = query.fetch(1) if len(results) > 0: self.session_key = self.session_key + 0.001 else: try: self.put() memcache.set("_AppEngineUtilities_Session_" + str(self.session_key), self) except: self.dirty = True memcache.set("_AppEngineUtilities_Session_" + str(self.session_key), self) valid = True class _AppEngineUtilities_SessionData(db.Model): """ Model for the session data in the datastore. """ session_key = db.FloatProperty() keyname = db.StringProperty() content = db.BlobProperty() dirty = db.BooleanProperty(default=False) deleted = db.BooleanProperty(default=False) def put(self): """ Adds a keyname/value for session to the datastore and memcache """ # update or insert in datastore try: db.put(self) self.dirty = False except: self.dirty = True # update or insert in memcache mc_items = memcache.get("_AppEngineUtilities_SessionData_" + str(self.session_key)) if mc_items: value_updated = False for item in mc_items: if value_updated == True: break if item.keyname == self.keyname: logging.info("updating " + self.keyname) item.content = self.content memcache.set("_AppEngineUtilities_SessionData_" + str(self.session_key), mc_items) value_updated = True break if value_updated == False: #logging.info("adding " + self.keyname) mc_items.append(self) memcache.set("_AppEngineUtilities_SessionData_" + str(self.session_key), mc_items) def delete(self): """ Deletes an entity from the session in memcache and the datastore """ try: db.delete(self) except: self.deleted = True mc_items = memcache.get("_AppEngineUtilities_SessionData_" + str(self.session_key)) value_handled = False for item in mc_items: if value_handled == True: break if item.keyname == self.keyname: if self.deleted == True: item.deleted = True else: mc_items.remove(item) memcache.set("_AppEngineUtilities_SessionData_" + str(self.session_key), mc_items) class _DatastoreWriter(object): def put(self, keyname, value, session): """ Insert a keyname/value pair into the datastore for the session. Args: keyname: The keyname of the mapping. value: The value of the mapping. """ keyname = session._validate_key(keyname) if value is None: raise ValueError('You must pass a value to put.') # datestore write trumps cookie. If there is a cookie value # with this keyname, delete it so we don't have conflicting # entries. if session.cookie_vals.has_key(keyname): del(session.cookie_vals[keyname]) session.output_cookie[session.cookie_name + '_data'] = \ simplejson.dumps(session.cookie_vals) print session.output_cookie.output() sessdata = session._get(keyname=keyname) if sessdata is None: sessdata = _AppEngineUtilities_SessionData() sessdata.session_key = session.session.session_key sessdata.keyname = keyname sessdata.content = pickle.dumps(value) # UNPICKLING CACHE session.cache[keyname] = pickle.dumps(value) session.cache[keyname] = value sessdata.put() # todo _set_memcache() should be going away when this is done # session._set_memcache() class _CookieWriter(object): def put(self, keyname, value, session): """ Insert a keyname/value pair into the datastore for the session. Args: keyname: The keyname of the mapping. value: The value of the mapping. """ keyname = session._validate_key(keyname) if value is None: raise ValueError('You must pass a value to put.') # Use simplejson for cookies instead of pickle. session.cookie_vals[keyname] = value # update the requests session cache as well. session.cache[keyname] = value session.output_cookie[session.cookie_name + '_data'] = \ simplejson.dumps(session.cookie_vals) print session.output_cookie.output() class Session(object): """ Sessions used to maintain user presence between requests. Sessions store a unique id as a cookie in the browser and referenced in a datastore object. This maintains user presence by validating requests as visits from the same browser. You can add extra data to the session object by using it as a dictionary object. Values can be any python object that can be pickled. For extra performance, session objects are also store in memcache and kept consistent with the datastore. This increases the performance of read requests to session data. """ COOKIE_NAME = 'appengine-utilities-session-sid' # session token DEFAULT_COOKIE_PATH = '/' SESSION_EXPIRE_TIME = 7200 # sessions are valid for 7200 seconds (2 hours) CLEAN_CHECK_PERCENT = 50 # By default, 50% of all requests will clean the database INTEGRATE_FLASH = True # integrate functionality from flash module? CHECK_IP = True # validate sessions by IP CHECK_USER_AGENT = True # validate sessions by user agent SET_COOKIE_EXPIRES = True # Set to True to add expiration field to cookie SESSION_TOKEN_TTL = 5 # Number of seconds a session token is valid for. UPDATE_LAST_ACTIVITY = 60 # Number of seconds that may pass before # last_activity is updated WRITER = "datastore" # Use the datastore writer by default. cookie is the # other option. def __init__(self, cookie_path=DEFAULT_COOKIE_PATH, cookie_name=COOKIE_NAME, session_expire_time=SESSION_EXPIRE_TIME, clean_check_percent=CLEAN_CHECK_PERCENT, integrate_flash=INTEGRATE_FLASH, check_ip=CHECK_IP, check_user_agent=CHECK_USER_AGENT, set_cookie_expires=SET_COOKIE_EXPIRES, session_token_ttl=SESSION_TOKEN_TTL, last_activity_update=UPDATE_LAST_ACTIVITY, writer=WRITER): """ Initializer Args: cookie_name: The name for the session cookie stored in the browser. session_expire_time: The amount of time between requests before the session expires. clean_check_percent: The percentage of requests the will fire off a cleaning routine that deletes stale session data. integrate_flash: If appengine-utilities flash utility should be integrated into the session object. check_ip: If browser IP should be used for session validation check_user_agent: If the browser user agent should be used for sessoin validation. set_cookie_expires: True adds an expires field to the cookie so it saves even if the browser is closed. session_token_ttl: Number of sessions a session token is valid for before it should be regenerated. """ self.cookie_path = cookie_path self.cookie_name = cookie_name self.session_expire_time = session_expire_time self.integrate_flash = integrate_flash self.check_user_agent = check_user_agent self.check_ip = check_ip self.set_cookie_expires = set_cookie_expires self.session_token_ttl = session_token_ttl self.last_activity_update = last_activity_update self.writer = writer # make sure the page is not cached in the browser self.no_cache_headers() # Check the cookie and, if necessary, create a new one. self.cache = {} string_cookie = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.output_cookie = Cookie.SimpleCookie() self.cookie.load(string_cookie) try: self.cookie_vals = \ simplejson.loads(self.cookie[self.cookie_name + '_data'].value) # sync self.cache and self.cookie_vals which will make those # values available for all gets immediately. for k in self.cookie_vals: self.cache[k] = self.cookie_vals[k] self.output_cookie[self.cookie_name + '_data'] = self.cookie[self.cookie_name + '_data'] # sync the input cookie with the output cookie except: self.cookie_vals = {} if writer == "cookie": pass else: self.sid = None new_session = True # do_put is used to determine if a datastore write should # happen on this request. do_put = False # check for existing cookie if self.cookie.get(cookie_name): self.sid = self.cookie[cookie_name].value self.session = _AppEngineUtilities_Session.get_session(self) # will return None if # sid expired if self.session: new_session = False if new_session: # start a new session self.session = _AppEngineUtilities_Session() self.session.put() self.sid = self.new_sid() if 'HTTP_USER_AGENT' in os.environ: self.session.ua = os.environ['HTTP_USER_AGENT'] else: self.session.ua = None if 'REMOTE_ADDR' in os.environ: self.session.ip = os.environ['REMOTE_ADDR'] else: self.session.ip = None self.session.sid = [self.sid] # do put() here to get the session key self.session.put() else: # check the age of the token to determine if a new one # is required duration = datetime.timedelta(seconds=self.session_token_ttl) session_age_limit = datetime.datetime.now() - duration if self.session.last_activity < session_age_limit: logging.info("UPDATING SID LA = " + str(self.session.last_activity) + " - TL = " + str(session_age_limit)) self.sid = self.new_sid() if len(self.session.sid) > 2: self.session.sid.remove(self.session.sid[0]) self.session.sid.append(self.sid) do_put = True else: self.sid = self.session.sid[-1] # check if last_activity needs updated ula = datetime.timedelta(seconds=self.last_activity_update) if datetime.datetime.now() > self.session.last_activity + ula: do_put = True self.output_cookie[cookie_name] = self.sid self.output_cookie[cookie_name]['path'] = cookie_path # UNPICKLING CACHE self.cache['sid'] = pickle.dumps(self.sid) self.cache['sid'] = self.sid if do_put: if self.sid != None or self.sid != "": logging.info("doing put") self.session.put() if self.set_cookie_expires: if not self.output_cookie.has_key(cookie_name + '_data'): self.output_cookie[cookie_name + '_data'] = "" self.output_cookie[cookie_name + '_data']['expires'] = \ self.session_expire_time print self.output_cookie.output() # fire up a Flash object if integration is enabled if self.integrate_flash: import flash self.flash = flash.Flash(cookie=self.cookie) # randomly delete old stale sessions in the datastore (see # CLEAN_CHECK_PERCENT variable) if random.randint(1, 100) < clean_check_percent: self._clean_old_sessions() def new_sid(self): """ Create a new session id. """ sid = str(self.session.session_key) + "_" +md5.new(repr(time.time()) + \ str(random.random())).hexdigest() return sid ''' # removed as model now has get_session classmethod def _get_session(self): """ Get the user's session from the datastore """ query = _AppEngineUtilities_Session.all() query.filter('sid', self.sid) if self.check_user_agent: query.filter('ua', os.environ['HTTP_USER_AGENT']) if self.check_ip: query.filter('ip', os.environ['REMOTE_ADDR']) results = query.fetch(1) if len(results) is 0: return None else: sessionAge = datetime.datetime.now() - results[0].last_activity if sessionAge.seconds > self.session_expire_time: results[0].delete() return None return results[0] ''' def _get(self, keyname=None): """ Return all of the SessionData object data from the datastore onlye, unless keyname is specified, in which case only that instance of SessionData is returned. Important: This does not interact with memcache and pulls directly from the datastore. This also does not get items from the cookie store. Args: keyname: The keyname of the value you are trying to retrieve. """ if keyname != None: return self.session.get_item(keyname) return self.session.get_items() """ OLD query = _AppEngineUtilities_SessionData.all() query.filter('session', self.session) if keyname != None: query.filter('keyname =', keyname) results = query.fetch(1000) if len(results) is 0: return None if keyname != None: return results[0] return results """ def _validate_key(self, keyname): """ Validate the keyname, making sure it is set and not a reserved name. """ if keyname is None: raise ValueError('You must pass a keyname for the session' + \ ' data content.') elif keyname in ('sid', 'flash'): raise ValueError(keyname + ' is a reserved keyname.') if type(keyname) != type([str, unicode]): return str(keyname) return keyname def _put(self, keyname, value): """ Insert a keyname/value pair into the datastore for the session. Args: keyname: The keyname of the mapping. value: The value of the mapping. """ if self.writer == "datastore": writer = _DatastoreWriter() else: writer = _CookieWriter() writer.put(keyname, value, self) def _delete_session(self): """ Delete the session and all session data. """ if hasattr(self, "session"): self.session.delete() self.cookie_vals = {} self.cache = {} self.output_cookie[self.cookie_name + '_data'] = \ simplejson.dumps(self.cookie_vals) print self.output_cookie.output() """ OLD if hasattr(self, "session"): sessiondata = self._get() # delete from datastore if sessiondata is not None: for sd in sessiondata: sd.delete() # delete from memcache memcache.delete('sid-'+str(self.session.key())) # delete the session now that all items that reference it are deleted. self.session.delete() # unset any cookie values that may exist self.cookie_vals = {} self.cache = {} self.output_cookie[self.cookie_name + '_data'] = \ simplejson.dumps(self.cookie_vals) print self.output_cookie.output() """ # if the event class has been loaded, fire off the sessionDeleted event if 'AEU_Events' in __main__.__dict__: __main__.AEU_Events.fire_event('sessionDelete') def delete(self): """ Delete the current session and start a new one. This is useful for when you need to get rid of all data tied to a current session, such as when you are logging out a user. """ self._delete_session() @classmethod def delete_all_sessions(cls): """ Deletes all sessions and session data from the data store and memcache: NOTE: This is not fully developed. It also will not delete any cookie data as this does not work for each incoming request. Keep this in mind if you are using the cookie writer. """ all_sessions_deleted = False all_data_deleted = False while not all_sessions_deleted: query = _AppEngineUtilities_Session.all() results = query.fetch(75) if len(results) is 0: all_sessions_deleted = True else: for result in results: result.delete() def _clean_old_sessions(self): """ Delete expired sessions from the datastore. This is only called for CLEAN_CHECK_PERCENT percent of requests because it could be rather intensive. """ duration = datetime.timedelta(seconds=self.session_expire_time) session_age = datetime.datetime.now() - duration query = _AppEngineUtilities_Session.all() query.filter('last_activity <', session_age) results = query.fetch(50) for result in results: """ OLD data_query = _AppEngineUtilities_SessionData.all() data_query.filter('session', result) data_results = data_query.fetch(1000) for data_result in data_results: data_result.delete() memcache.delete('sid-'+str(result.key())) """ result.delete() # Implement Python container methods def __getitem__(self, keyname): """ Get item from session data. keyname: The keyname of the mapping. """ # flash messages don't go in the datastore if self.integrate_flash and (keyname == 'flash'): return self.flash.msg if keyname in self.cache: # UNPICKLING CACHE return pickle.loads(str(self.cache[keyname])) return self.cache[keyname] if keyname in self.cookie_vals: return self.cookie_vals[keyname] if hasattr(self, "session"): data = self._get(keyname) if data: #UNPICKLING CACHE self.cache[keyname] = data.content self.cache[keyname] = pickle.loads(data.content) return pickle.loads(data.content) else: raise KeyError(str(keyname)) raise KeyError(str(keyname)) def __setitem__(self, keyname, value): """ Set item in session data. Args: keyname: They keyname of the mapping. value: The value of mapping. """ if self.integrate_flash and (keyname == 'flash'): self.flash.msg = value else: keyname = self._validate_key(keyname) self.cache[keyname] = value # self._set_memcache() # commented out because this is done in the datestore put return self._put(keyname, value) def delete_item(self, keyname, throw_exception=False): """ Delete item from session data, ignoring exceptions if necessary. Args: keyname: The keyname of the object to delete. throw_exception: false if exceptions are to be ignored. Returns: Nothing. """ if throw_exception: self.__delitem__(keyname) return None else: try: self.__delitem__(keyname) except KeyError: return None def __delitem__(self, keyname): """ Delete item from session data. Args: keyname: The keyname of the object to delete. """ bad_key = False sessdata = self._get(keyname = keyname) if sessdata is None: bad_key = True else: sessdata.delete() if keyname in self.cookie_vals: del self.cookie_vals[keyname] bad_key = False self.output_cookie[self.cookie_name + '_data'] = \ simplejson.dumps(self.cookie_vals) print self.output_cookie.output() if bad_key: raise KeyError(str(keyname)) if keyname in self.cache: del self.cache[keyname] def __len__(self): """ Return size of session. """ # check memcache first if hasattr(self, "session"): results = self._get() if results is not None: return len(results) + len(self.cookie_vals) else: return 0 return len(self.cookie_vals) def __contains__(self, keyname): """ Check if an item is in the session data. Args: keyname: The keyname being searched. """ try: r = self.__getitem__(keyname) except KeyError: return False return True def __iter__(self): """ Iterate over the keys in the session data. """ # try memcache first if hasattr(self, "session"): for k in self._get(): yield k.keyname for k in self.cookie_vals: yield k def __str__(self): """ Return string representation. """ #if self._get(): return '{' + ', '.join(['"%s" = "%s"' % (k, self[k]) for k in self]) + '}' #else: # return [] ''' OLD def _set_memcache(self): """ Set a memcache object with all the session data. Optionally you can add a key and value to the memcache for put operations. """ # Pull directly from the datastore in order to ensure that the # information is as up to date as possible. if self.writer == "datastore": data = {} sessiondata = self._get() if sessiondata is not None: for sd in sessiondata: data[sd.keyname] = pickle.loads(sd.content) memcache.set('sid-'+str(self.session.key()), data, \ self.session_expire_time) ''' def cycle_key(self): """ Changes the session id. """ self.sid = self.new_sid() if len(self.session.sid) > 2: self.session.sid.remove(self.session.sid[0]) self.session.sid.append(self.sid) def flush(self): """ Delete's the current session, creating a new one. """ self._delete_session() self.__init__() def no_cache_headers(self): """ Adds headers, avoiding any page caching in the browser. Useful for highly dynamic sites. """ print "Expires: Tue, 03 Jul 2001 06:00:00 GMT" print strftime("Last-Modified: %a, %d %b %y %H:%M:%S %Z") print "Cache-Control: no-store, no-cache, must-revalidate, max-age=0" print "Cache-Control: post-check=0, pre-check=0" print "Pragma: no-cache" def clear(self): """ Remove all items """ sessiondata = self._get() # delete from datastore if sessiondata is not None: for sd in sessiondata: sd.delete() # delete from memcache self.cache = {} self.cookie_vals = {} self.output_cookie[self.cookie_name + '_data'] = \ simplejson.dumps(self.cookie_vals) print self.output_cookie.output() def has_key(self, keyname): """ Equivalent to k in a, use that form in new code """ return self.__contains__(keyname) def items(self): """ A copy of list of (key, value) pairs """ op = {} for k in self: op[k] = self[k] return op def keys(self): """ List of keys. """ l = [] for k in self: l.append(k) return l def update(*dicts): """ Updates with key/value pairs from b, overwriting existing keys, returns None """ for dict in dicts: for k in dict: self._put(k, dict[k]) return None def values(self): """ A copy list of values. """ v = [] for k in self: v.append(self[k]) return v def get(self, keyname, default = None): """ a[k] if k in a, else x """ try: return self.__getitem__(keyname) except KeyError: if default is not None: return default return None def setdefault(self, keyname, default = None): """ a[k] if k in a, else x (also setting it) """ try: return self.__getitem__(keyname) except KeyError: if default is not None: self.__setitem__(keyname, default) return default return None @classmethod def check_token(cls, cookie_name=COOKIE_NAME, delete_invalid=True): """ Retrieves the token from a cookie and validates that it is a valid token for an existing cookie. Cookie validation is based on the token existing on a session that has not expired. This is useful for determining if datastore or cookie writer should be used in hybrid implementations. Args: cookie_name: Name of the cookie to check for a token. delete_invalid: If the token is not valid, delete the session cookie, to avoid datastore queries on future requests. Returns True/False NOTE: TODO This currently only works when the datastore is working, which of course is pointless for applications using the django middleware. This needs to be resolved before merging back into the main project. """ string_cookie = os.environ.get('HTTP_COOKIE', '') cookie = Cookie.SimpleCookie() cookie.load(string_cookie) if cookie.has_key(cookie_name): query = _AppEngineUtilities_Session.all() query.filter('sid', cookie[cookie_name].value) results = query.fetch(1) if len(results) > 0: return True else: if delete_invalid: output_cookie = Cookie.SimpleCookie() output_cookie[cookie_name] = cookie[cookie_name] output_cookie[cookie_name]['expires'] = 0 print output_cookie.output() return False
Python
""" Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ from google.appengine.ext import db class ROTModel(db.Model): """ ROTModel overrides the db.Model put function, having it retry up to 3 times when it encounters a datastore timeout. This is to try an maximize the chance the data makes it into the datastore when attempted. If it fails, it raises the db.Timeout error and the calling application will need to handle that. """ def put(self): count = 0 while count < 3: try: return db.Model.put(self) except db.Timeout: count += 1 else: raise db.Timeout()
Python
""" Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import __main__ class Event(object): """ Event is a simple publish/subscribe based event dispatcher It sets itself to the __main__ function. In order to use it, you must import it and __main__ """ def __init__(self): self.events = [] def subscribe(self, event, callback, args = None): """ This method will subscribe a callback function to an event name. """ if not {"event": event, "callback": callback, "args": args, } \ in self.events: self.events.append({"event": event, "callback": callback, \ "args": args, }) def unsubscribe(self, event, callback, args = None): """ This method will unsubscribe a callback from an event. """ if {"event": event, "callback": callback, "args": args, }\ in self.events: self.events.remove({"event": event, "callback": callback,\ "args": args, }) def fire_event(self, event = None): """ This method is what a method uses to fire an event, initiating all registered callbacks """ for e in self.events: if e["event"] == event: if type(e["args"]) == type([]): e["callback"](*e["args"]) elif type(e["args"]) == type({}): e["callback"](**e["args"]) elif e["args"] == None: e["callback"]() else: e["callback"](e["args"]) """ Assign to the event class to __main__ """ __main__.AEU_Events = Event()
Python
""" Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import os import sys import Cookie import pickle from time import strftime from django.utils import simplejson COOKIE_NAME = 'appengine-utilities-flash' class Flash(object): """ Send messages to the user between pages. When you instantiate the class, the attribute 'msg' will be set from the cookie, and the cookie will be deleted. If there is no flash cookie, 'msg' will default to None. To set a flash message for the next page, simply set the 'msg' attribute. Example psuedocode: if new_entity.put(): flash = Flash() flash.msg = 'Your new entity has been created!' return redirect_to_entity_list() Then in the template on the next page: {% if flash.msg %} <div class="flash-msg">{{ flash.msg }}</div> {% endif %} """ def __init__(self, cookie=None): """ Load the flash message and clear the cookie. """ self.no_cache_headers() # load cookie if cookie is None: browser_cookie = os.environ.get('HTTP_COOKIE', '') self.cookie = Cookie.SimpleCookie() self.cookie.load(browser_cookie) else: self.cookie = cookie # check for flash data if self.cookie.get(COOKIE_NAME): # set 'msg' attribute cookie_val = self.cookie[COOKIE_NAME].value # we don't want to trigger __setattr__(), which creates a cookie try: self.__dict__['msg'] = simplejson.loads(cookie_val) except: # not able to load the json, so do not set message. This should # catch for when the browser doesn't delete the cookie in time for # the next request, and only blanks out the content. pass # clear the cookie self.cookie[COOKIE_NAME] = '' self.cookie[COOKIE_NAME]['path'] = '/' self.cookie[COOKIE_NAME]['expires'] = 0 print self.cookie[COOKIE_NAME] else: # default 'msg' attribute to None self.__dict__['msg'] = None def __setattr__(self, name, value): """ Create a cookie when setting the 'msg' attribute. """ if name == 'cookie': self.__dict__['cookie'] = value elif name == 'msg': self.__dict__['msg'] = value self.__dict__['cookie'][COOKIE_NAME] = simplejson.dumps(value) self.__dict__['cookie'][COOKIE_NAME]['path'] = '/' print self.cookie else: raise ValueError('You can only set the "msg" attribute.') def no_cache_headers(self): """ Adds headers, avoiding any page caching in the browser. Useful for highly dynamic sites. """ print "Expires: Tue, 03 Jul 2001 06:00:00 GMT" print strftime("Last-Modified: %a, %d %b %y %H:%M:%S %Z") print "Cache-Control: no-store, no-cache, must-revalidate, max-age=0" print "Cache-Control: post-check=0, pre-check=0" print "Pragma: no-cache"
Python
""" Copyright (c) 2008, appengine-utilities project All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the appengine-utilities project nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import os import cgi import re import datetime import pickle from google.appengine.ext import db from google.appengine.api import urlfetch from google.appengine.api import memcache APPLICATION_PORT = '8080' CRON_PORT = '8081' class _AppEngineUtilities_Cron(db.Model): """ Model for the tasks in the datastore. This contains the scheduling and url information, as well as a field that sets the next time the instance should run. """ cron_entry = db.StringProperty() next_run = db.DateTimeProperty() cron_compiled = db.BlobProperty() url = db.LinkProperty() class Cron(object): """ Cron is a scheduling utility built for appengine, modeled after crontab for unix systems. While true scheduled tasks are not possible within the Appengine environment currently, this is an attmempt to provide a request based alternate. You configure the tasks in an included interface, and the import the class on any request you want capable of running tasks. On each request where Cron is imported, the list of tasks that need to be run will be pulled and run. A task is a url within your application. It's important to make sure that these requests fun quickly, or you could risk timing out the actual request. See the documentation for more information on configuring your application to support Cron and setting up tasks. """ def __init__(self): # Check if any tasks need to be run query = _AppEngineUtilities_Cron.all() query.filter('next_run <= ', datetime.datetime.now()) results = query.fetch(1000) if len(results) > 0: one_second = datetime.timedelta(seconds = 1) before = datetime.datetime.now() for r in results: if re.search(':' + APPLICATION_PORT, r.url): r.url = re.sub(':' + APPLICATION_PORT, ':' + CRON_PORT, r.url) #result = urlfetch.fetch(r.url) diff = datetime.datetime.now() - before if int(diff.seconds) < 1: if memcache.add(str(r.key), "running"): result = urlfetch.fetch(r.url) r.next_run = self._get_next_run(pickle.loads(r.cron_compiled)) r.put() memcache.delete(str(r.key)) else: break def add_cron(self, cron_string): cron = cron_string.split(" ") if len(cron) is not 6: raise ValueError, 'Invalid cron string. Format: * * * * * url' cron = { 'min': cron[0], 'hour': cron[1], 'day': cron[2], 'mon': cron[3], 'dow': cron[4], 'url': cron[5], } cron_compiled = self._validate_cron(cron) next_run = self._get_next_run(cron_compiled) cron_entry = _AppEngineUtilities_Cron() cron_entry.cron_entry = cron_string cron_entry.next_run = next_run cron_entry.cron_compiled = pickle.dumps(cron_compiled) cron_entry.url = cron["url"] cron_entry.put() def _validate_cron(self, cron): """ Parse the field to determine whether it is an integer or lists, also converting strings to integers where necessary. If passed bad values, raises a ValueError. """ parsers = { 'dow': self._validate_dow, 'mon': self._validate_mon, 'day': self._validate_day, 'hour': self._validate_hour, 'min': self._validate_min, 'url': self. _validate_url, } for el in cron: parse = parsers[el] cron[el] = parse(cron[el]) return cron def _validate_type(self, v, t): """ Validates that the number (v) passed is in the correct range for the type (t). Raise ValueError, if validation fails. Valid ranges: day of week = 0-7 month = 1-12 day = 1-31 hour = 0-23 minute = 0-59 All can * which will then return the range for that entire type. """ if t == "dow": if v >= 0 and v <= 7: return [v] elif v == "*": return "*" else: raise ValueError, "Invalid day of week." elif t == "mon": if v >= 1 and v <= 12: return [v] elif v == "*": return range(1, 12) else: raise ValueError, "Invalid month." elif t == "day": if v >= 1 and v <= 31: return [v] elif v == "*": return range(1, 31) else: raise ValueError, "Invalid day." elif t == "hour": if v >= 0 and v <= 23: return [v] elif v == "*": return range(0, 23) else: raise ValueError, "Invalid hour." elif t == "min": if v >= 0 and v <= 59: return [v] elif v == "*": return range(0, 59) else: raise ValueError, "Invalid minute." def _validate_list(self, l, t): """ Validates a crontab list. Lists are numerical values seperated by a comma with no spaces. Ex: 0,5,10,15 Arguments: l: comma seperated list of numbers t: type used for validation, valid values are dow, mon, day, hour, min """ elements = l.split(",") return_list = [] # we have a list, validate all of them for e in elements: if "-" in e: return_list.extend(self._validate_range(e, t)) else: try: v = int(e) self._validate_type(v, t) return_list.append(v) except: raise ValueError, "Names are not allowed in lists." # return a list of integers return return_list def _validate_range(self, r, t): """ Validates a crontab range. Ranges are 2 numerical values seperated by a dash with no spaces. Ex: 0-10 Arguments: r: dash seperated list of 2 numbers t: type used for validation, valid values are dow, mon, day, hour, min """ elements = r.split('-') # a range should be 2 elements if len(elements) is not 2: raise ValueError, "Invalid range passed: " + str(r) # validate the minimum and maximum are valid for the type for e in elements: self._validate_type(int(e), t) # return a list of the numbers in the range. # +1 makes sure the end point is included in the return value return range(int(elements[0]), int(elements[1]) + 1) def _validate_step(self, s, t): """ Validates a crontab step. Steps are complicated. They can be based on a range 1-10/2 or just step through all valid */2. When parsing times you should always check for step first and see if it has a range or not, before checking for ranges because this will handle steps of ranges returning the final list. Steps of lists is not supported. Arguments: s: slash seperated string t: type used for validation, valid values are dow, mon, day, hour, min """ elements = s.split('/') # a range should be 2 elements if len(elements) is not 2: raise ValueError, "Invalid step passed: " + str(s) try: step = int(elements[1]) except: raise ValueError, "Invalid step provided " + str(s) r_list = [] # if the first element is *, use all valid numbers if elements[0] is "*" or elements[0] is "": r_list.extend(self._validate_type('*', t)) # check and see if there is a list of ranges elif "," in elements[0]: ranges = elements[0].split(",") for r in ranges: # if it's a range, we need to manage that if "-" in r: r_list.extend(self._validate_range(r, t)) else: try: r_list.extend(int(r)) except: raise ValueError, "Invalid step provided " + str(s) elif "-" in elements[0]: r_list.extend(self._validate_range(elements[0], t)) return range(r_list[0], r_list[-1] + 1, step) def _validate_dow(self, dow): """ """ # if dow is * return it. This is for date parsing where * does not mean # every day for crontab entries. if dow is "*": return dow days = { 'mon': 1, 'tue': 2, 'wed': 3, 'thu': 4, 'fri': 5, 'sat': 6, # per man crontab sunday can be 0 or 7. 'sun': [0, 7], } if dow in days: dow = days[dow] return [dow] # if dow is * return it. This is for date parsing where * does not mean # every day for crontab entries. elif dow is "*": return dow elif "/" in dow: return(self._validate_step(dow, "dow")) elif "," in dow: return(self._validate_list(dow, "dow")) elif "-" in dow: return(self._validate_range(dow, "dow")) else: valid_numbers = range(0, 8) if not int(dow) in valid_numbers: raise ValueError, "Invalid day of week " + str(dow) else: return [int(dow)] def _validate_mon(self, mon): months = { 'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12, } if mon in months: mon = months[mon] return [mon] elif mon is "*": return range(1, 13) elif "/" in mon: return(self._validate_step(mon, "mon")) elif "," in mon: return(self._validate_list(mon, "mon")) elif "-" in mon: return(self._validate_range(mon, "mon")) else: valid_numbers = range(1, 13) if not int(mon) in valid_numbers: raise ValueError, "Invalid month " + str(mon) else: return [int(mon)] def _validate_day(self, day): if day is "*": return range(1, 32) elif "/" in day: return(self._validate_step(day, "day")) elif "," in day: return(self._validate_list(day, "day")) elif "-" in day: return(self._validate_range(day, "day")) else: valid_numbers = range(1, 31) if not int(day) in valid_numbers: raise ValueError, "Invalid day " + str(day) else: return [int(day)] def _validate_hour(self, hour): if hour is "*": return range(0, 24) elif "/" in hour: return(self._validate_step(hour, "hour")) elif "," in hour: return(self._validate_list(hour, "hour")) elif "-" in hour: return(self._validate_range(hour, "hour")) else: valid_numbers = range(0, 23) if not int(hour) in valid_numbers: raise ValueError, "Invalid hour " + str(hour) else: return [int(hour)] def _validate_min(self, min): if min is "*": return range(0, 60) elif "/" in min: return(self._validate_step(min, "min")) elif "," in min: return(self._validate_list(min, "min")) elif "-" in min: return(self._validate_range(min, "min")) else: valid_numbers = range(0, 59) if not int(min) in valid_numbers: raise ValueError, "Invalid min " + str(min) else: return [int(min)] def _validate_url(self, url): # kludge for issue 842, right now we use request headers # to set the host. if url[0] is not "/": url = "/" + url url = 'http://' + str(os.environ['HTTP_HOST']) + url return url # content below is for when that issue gets fixed #regex = re.compile("^(http|https):\/\/([a-z0-9-]\.+)*", re.IGNORECASE) #if regex.match(url) is not None: # return url #else: # raise ValueError, "Invalid url " + url def _calc_month(self, next_run, cron): while True: if cron["mon"][-1] < next_run.month: next_run = next_run.replace(year=next_run.year+1, \ month=cron["mon"][0], \ day=1,hour=0,minute=0) else: if next_run.month in cron["mon"]: return next_run else: one_month = datetime.timedelta(months=1) next_run = next_run + one_month def _calc_day(self, next_run, cron): # start with dow as per cron if dow and day are set # then dow is used if it comes before day. If dow # is *, then ignore it. if str(cron["dow"]) != str("*"): # convert any integers to lists in order to easily compare values m = next_run.month while True: if next_run.month is not m: next_run = next_run.replace(hour=0, minute=0) next_run = self._calc_month(next_run, cron) if next_run.weekday() in cron["dow"] or next_run.day in cron["day"]: return next_run else: one_day = datetime.timedelta(days=1) next_run = next_run + one_day else: m = next_run.month while True: if next_run.month is not m: next_run = next_run.replace(hour=0, minute=0) next_run = self._calc_month(next_run, cron) # if cron["dow"] is next_run.weekday() or cron["day"] is next_run.day: if next_run.day in cron["day"]: return next_run else: one_day = datetime.timedelta(days=1) next_run = next_run + one_day def _calc_hour(self, next_run, cron): m = next_run.month d = next_run.day while True: if next_run.month is not m: next_run = next_run.replace(hour=0, minute=0) next_run = self._calc_month(next_run, cron) if next_run.day is not d: next_run = next_run.replace(hour=0) next_run = self._calc_day(next_run, cron) if next_run.hour in cron["hour"]: return next_run else: m = next_run.month d = next_run.day one_hour = datetime.timedelta(hours=1) next_run = next_run + one_hour def _calc_minute(self, next_run, cron): one_minute = datetime.timedelta(minutes=1) m = next_run.month d = next_run.day h = next_run.hour while True: if next_run.month is not m: next_run = next_run.replace(minute=0) next_run = self._calc_month(next_run, cron) if next_run.day is not d: next_run = next_run.replace(minute=0) next_run = self._calc_day(next_run, cron) if next_run.hour is not h: next_run = next_run.replace(minute=0) next_run = self._calc_day(next_run, cron) if next_run.minute in cron["min"]: return next_run else: m = next_run.month d = next_run.day h = next_run.hour next_run = next_run + one_minute def _get_next_run(self, cron): one_minute = datetime.timedelta(minutes=1) # go up 1 minute because it shouldn't happen right when added now = datetime.datetime.now() + one_minute next_run = now.replace(second=0, microsecond=0) # start with month, which will also help calculate year next_run = self._calc_month(next_run, cron) next_run = self._calc_day(next_run, cron) next_run = self._calc_hour(next_run, cron) next_run = self._calc_minute(next_run, cron) return next_run
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. __author__ = 'e.bidelman (Eric Bidelman)' import cgi import os import gdata.auth import gdata.docs import gdata.docs.service import gdata.alt.appengine from appengine_utilities.sessions import Session from django.utils import simplejson from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app SETTINGS = { 'APP_NAME': 'google-GDataOAuthAppEngine-v1', 'CONSUMER_KEY': 'YOUR_CONSUMER_KEY', 'SIG_METHOD': gdata.auth.OAuthSignatureMethod.RSA_SHA1, 'SCOPES': ['http://docs.google.com/feeds/', 'https://docs.google.com/feeds/'] } f = open('/path/to/your/rsa_private_key.pem') RSA_KEY = f.read() f.close() gdocs = gdata.docs.service.DocsService(source=SETTINGS['APP_NAME']) gdocs.SetOAuthInputParameters(SETTINGS['SIG_METHOD'], SETTINGS['CONSUMER_KEY'], rsa_key=RSA_KEY) gdata.alt.appengine.run_on_appengine(gdocs) class MainPage(webapp.RequestHandler): """Main page displayed to user.""" # GET / def get(self): if not users.get_current_user(): self.redirect(users.create_login_url(self.request.uri)) access_token = gdocs.token_store.find_token('%20'.join(SETTINGS['SCOPES'])) if isinstance(access_token, gdata.auth.OAuthToken): form_action = '/fetch_data' form_value = 'Now fetch my docs!' revoke_token_link = True else: form_action = '/get_oauth_token' form_value = 'Give this website access to my Google Docs' revoke_token_link = None template_values = { 'form_action': form_action, 'form_value': form_value, 'user': users.get_current_user(), 'revoke_token_link': revoke_token_link, 'oauth_token': access_token, 'consumer': gdocs.GetOAuthInputParameters().GetConsumer(), 'sig_method': gdocs.GetOAuthInputParameters().GetSignatureMethod().get_name() } path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) class OAuthDance(webapp.RequestHandler): """Handler for the 3 legged OAuth dance, v1.0a.""" """This handler is responsible for fetching an initial OAuth request token, redirecting the user to the approval page. When the user grants access, they will be redirected back to this GET handler and their authorized request token will be exchanged for a long-lived access token.""" # GET /get_oauth_token def get(self): """Invoked after we're redirected back from the approval page.""" self.session = Session() oauth_token = gdata.auth.OAuthTokenFromUrl(self.request.uri) if oauth_token: oauth_token.oauth_input_params = gdocs.GetOAuthInputParameters() gdocs.SetOAuthToken(oauth_token) # 3.) Exchange the authorized request token for an access token oauth_verifier = self.request.get('oauth_verifier', default_value='') access_token = gdocs.UpgradeToOAuthAccessToken( oauth_verifier=oauth_verifier) # Remember the access token in the current user's token store if access_token and users.get_current_user(): gdocs.token_store.add_token(access_token) elif access_token: gdocs.current_token = access_token gdocs.SetOAuthToken(access_token) self.redirect('/') # POST /get_oauth_token def post(self): """Fetches a request token and redirects the user to the approval page.""" self.session = Session() if users.get_current_user(): # 1.) REQUEST TOKEN STEP. Provide the data scope(s) and the page we'll # be redirected back to after the user grants access on the approval page. req_token = gdocs.FetchOAuthRequestToken( scopes=SETTINGS['SCOPES'], oauth_callback=self.request.uri) # Generate the URL to redirect the user to. Add the hd paramter for a # better user experience. Leaving it off will give the user the choice # of what account (Google vs. Google Apps) to login with. domain = self.request.get('domain', default_value='default') approval_page_url = gdocs.GenerateOAuthAuthorizationURL( extra_params={'hd': domain}) # 2.) APPROVAL STEP. Redirect to user to Google's OAuth approval page. self.redirect(approval_page_url) class FetchData(OAuthDance): """Fetches the user's data.""" """This class inherits from OAuthDance in order to utilize OAuthDance.post() in case of a request error (e.g. the user has a bad token).""" # GET /fetch_data def get(self): self.redirect('/') # POST /fetch_data def post(self): """Fetches the user's data.""" try: feed = gdocs.GetDocumentListFeed() json = [] for entry in feed.entry: if entry.lastModifiedBy is not None: last_modified_by = entry.lastModifiedBy.email.text else: last_modified_by = '' if entry.lastViewed is not None: last_viewed = entry.lastViewed.text else: last_viewed = '' json.append({'title': entry.title.text, 'links': {'alternate': entry.GetHtmlLink().href}, 'published': entry.published.text, 'updated': entry.updated.text, 'resourceId': entry.resourceId.text, 'type': entry.GetDocumentType(), 'lastModifiedBy': last_modified_by, 'lastViewed': last_viewed }) self.response.out.write(simplejson.dumps(json)) except gdata.service.RequestError, error: OAuthDance.post(self) class RevokeToken(webapp.RequestHandler): # GET /revoke_token def get(self): """Revokes the current user's OAuth access token.""" try: gdocs.RevokeOAuthToken() except gdata.service.RevokingOAuthTokenFailed: pass gdocs.token_store.remove_all_tokens() self.redirect('/') def main(): application = webapp.WSGIApplication([('/', MainPage), ('/get_oauth_token', OAuthDance), ('/fetch_data', FetchData), ('/revoke_token', RevokeToken)], debug=True) run_wsgi_app(application)
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. import gdata.base.service import gdata.service try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata.base import getpass # Demonstrates item insertion with a dry run insert operation. The item will # NOT be added to Google Base. gb_client = gdata.base.service.GBaseService() gb_client.email = raw_input('Please enter your username: ') gb_client.password = getpass.getpass() print 'Logging in' gb_client.ProgrammaticLogin() # Create a test item which will be used in a dry run insert item = gdata.base.GBaseItem() item.author.append(atom.Author(name=atom.Name(text='Mr. Smith'))) item.title = atom.Title(text='He Jingxian\'s chicken') item.link.append(atom.Link(rel='alternate', link_type='text/html', href='http://www.host.com/123456jsh9')) item.label.append(gdata.base.Label(text='kung pao chicken')) item.label.append(gdata.base.Label(text='chinese cuisine')) item.label.append(gdata.base.Label(text='testrecipes')) item.item_type = gdata.base.ItemType(text='recipes') item.AddItemAttribute(name='cooking_time', value_type='intUnit', value='30 minutes') item.AddItemAttribute(name='main_ingredient', value='chicken') item.AddItemAttribute(name='main_ingredient', value='chili') # Make an insert request with the dry run flag set so that the item will not # actually be created. result = gb_client.InsertItem(item, url_params={'dry-run': 'true'}) # Send the XML from the server to standard out. print 'Here\'s the XML from the server\'s simulated insert' print str(result) print 'Done'
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. import gdata.base.service import gdata.service try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata.base # Demonstrates queries to the snippets feed and stepping through the results. gb_client = gdata.base.service.GBaseService() q = gdata.base.service.BaseQuery() q.feed = '/base/feeds/snippets' q['start-index'] = '1' q['max-results'] = '10' q.bq = raw_input('Please enter your Google Base query: ') feed = gb_client.QuerySnippetsFeed(q.ToUri()) while(int(q['start-index']) < 989): # Display the titles of the snippets. print 'Snippet query results items %s to %s' % (q['start-index'], int(q['start-index'])+10) for entry in feed.entry: print ' ', entry.title.text # Show the next 10 results from the snippets feed when the user presses # enter. nothing = raw_input('Press enter to see the next 10 results') q['start-index'] = str(int(q['start-index']) + 10) feed = gb_client.QuerySnippetsFeed(q.ToUri()) print 'You\'ve reached the upper limit of 1000 items. Goodbye :)'
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. import gdata.base.service import gdata.service try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata.base # Demonstrates queries to the attributes feed gb_client = gdata.base.service.GBaseService() q = gdata.base.service.BaseQuery() q.feed = '/base/feeds/attributes' q.bq = raw_input('Please item type to query for (ex: housing): ') print q.ToUri() feed = gb_client.QueryAttributesFeed(q.ToUri()) print feed.title.text for entry in feed.entry: for attr in entry.attribute: display_str = 'attribute name:%s, type:%s' % (attr.name, attr.type) values = '' for value in attr.value: values += '(' + value.text + ',' + value.count + ')' if values != '': display_str += ', values: %s' % values print ' ' + display_str
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. import gdata.base.service import gdata.service try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata.base # Demonstrates queries to the itemtypes feed for specified locale. gb_client = gdata.base.service.GBaseService() locale = raw_input('Please enter locale (ex: en_US): ') q = gdata.base.service.BaseQuery() q.feed = '/base/feeds/itemtypes/%s' % locale print q.ToUri() feed = gb_client.QueryItemTypesFeed(q.ToUri()) print feed.title.text for entry in feed.entry: print '\t' + entry.title.text for attr in entry.attributes.attribute: print '\t\tAttr name:%s, type:%s' % (attr.name, attr.type)
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. import getpass from gdata.contentforshopping.data import build_entry from gdata.contentforshopping.client import ContentForShoppingClient # Gather merchant information account_id = raw_input('Merchant Account ID? ').strip() email = raw_input('Google Email Address? ').strip() # Create a client client = ContentForShoppingClient(account_id) # Perform programmatic login client.client_login(email, getpass.getpass('Google Password? '), 'Shopping API for Content sample', 'structuredcontent') # Generate a product entry product_entry = build_entry( product_id='ipod2', target_country = 'US', content_language = 'EN', title='iPod Nano 8GB', content='A nice small mp3 player', price='149', price_unit='USD', shipping_price = '5', shipping_price_unit = 'USD', tax_rate='17.5', condition = 'new', link = 'http://pseudoscience.co.uk/google4e823e35f032f011.html', ) # Post it to the service client.insert_product(product_entry)
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. import getpass from gdata.contentforshopping.data import build_entry from gdata.contentforshopping.client import ContentForShoppingClient # Gather merchant information account_id = raw_input('Merchant Account ID? ').strip() email = raw_input('Google Email Address? ').strip() # Create a client client = ContentForShoppingClient(account_id) # Perform programmatic login client.client_login(email, getpass.getpass('Google Password? '), 'Shopping API for Content sample', 'structuredcontent') products = [] for color in ['red', 'green', 'white', 'black', 'purple', 'brown', 'yellow', 'orange', 'magenta']: # Generate a product entry product_entry = build_entry( product_id='ipod%s' % color, target_country = 'US', content_language = 'EN', title='iPod Nano 8GB, %s' % color, content='A nice small mp3 player, in %s' % color, price='149', price_unit='USD', shipping_price = '5', shipping_price_unit = 'USD', tax_rate='17.5', condition = 'new', link = 'http://pseudoscience.co.uk/google4e823e35f032f011.html', color = color, ) products.append(product_entry) # Post it to the service client.insert_products(products)
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. import getpass from gdata.contentforshopping.client import ContentForShoppingClient # Gather merchant information account_id = raw_input('Merchant Account ID? ').strip() email = raw_input('Google Email Address? ').strip() # Create a client client = ContentForShoppingClient(account_id) # Perform programmatic login client.client_login(email, getpass.getpass('Google Password? '), 'Shopping API for Content sample', 'structuredcontent') # Get the products list from the products feed product_feed = client.get_products() print 'Listing: %s result(s)' % product_feed.total_results.text # Each product is an element in the feed's entry (a list) for product in product_feed.entry: print '- %s: %s' % (product.title.text, product.content.text)
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. import getpass from atom.data import Title from gdata.contentforshopping.client import ContentForShoppingClient from gdata.contentforshopping.data import ClientAccount, AdultContent # Gather merchant information account_id = raw_input('Merchant Account ID? ').strip() email = raw_input('Google Email Address? ').strip() # Create a client client = ContentForShoppingClient(account_id) # Perform programmatic login client.client_login(email, getpass.getpass('Google Password? '), 'Shopping API for Content sample', 'structuredcontent') # Create 10 accounts for i in range(10): client_account = ClientAccount() client_account.title = Title('Test Account %s' % (i + 1)) client_account.adult_content = AdultContent('no') # Insert the client account client.insert_client_account(client_account) # Display something to the user print i + 1, '/', 10
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. import getpass from gdata.contentforshopping.client import ContentForShoppingClient # Gather merchant information account_id = raw_input('Merchant Account ID? ').strip() email = raw_input('Google Email Address? ').strip() # Create a client client = ContentForShoppingClient(account_id) # Perform programmatic login client.client_login(email, getpass.getpass('Google Password? '), 'Shopping API for Content sample', 'structuredcontent') # Get the feed of client accounts client_account_feed = client.get_client_accounts() # Display the title and self link for each client account for client_account in client_account_feed.entry: print client_account.title.text, client_account.GetSelfLink().href
Python
#!/usr/bin/python # # Copyright 2008 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. """Sample to demonstrate using secure AuthSub in the Google Data Python client. This sample focuses on the Google Health Data API because it requires the use of secure tokens. This samples makes queries against the H9 Developer's Sandbox (https://www.google.com/h9). To run this sample: 1.) Use Apache's mod_python 2.) Run from your local webserver (e.g. http://localhost/...) 3.) You need to have entered medication data into H9 HealthAubSubHelper: Class to handle secure AuthSub tokens. GetMedicationHTML: Returns the user's medication formatted in HTML. index: Main entry point for the web app. """ __author__ = 'e.bidelman@google.com (Eric Bidelman)' import os import sys import urllib import gdata.auth import gdata.service H9_PROFILE_FEED_URL = 'https://www.google.com/h9/feeds/profile/default' class HealthAuthSubHelper(object): """A secure AuthSub helper to interact with the Google Health Data API""" H9_AUTHSUB_HANDLER = 'https://www.google.com/h9/authsub' H9_SCOPE = 'https://www.google.com/h9/feeds/' def GetNextUrl(self, req): """Computes the current URL the web app is running from. Args: req: mod_python mp_request instance to build the URL from. Returns: A string representing the web app's URL. """ if req.is_https(): next_url = 'https://' else: next_url = 'http://' next_url += req.hostname + req.unparsed_uri return next_url def GenerateAuthSubRequestUrl(self, next, scopes=[H9_SCOPE], secure=True, session=True, extra_params=None, include_scopes_in_next=True): """Constructs the URL to the AuthSub token handler. Args: next: string The URL AuthSub will redirect back to. Use self.GetNextUrl() to return that URL. scopes: (optional) string or list of scopes the token will be valid for. secure: (optional) boolean True if the token should be a secure one session: (optional) boolean True if the token will be exchanged for a session token. extra_params: (optional) dict of additional parameters to pass to AuthSub. include_scopes_in_next: (optional) boolean True if the scopes in the scopes should be passed to AuthSub. Returns: A string (as a URL) to use for the AuthSubRequest endpoint. """ auth_sub_url = gdata.service.GenerateAuthSubRequestUrl( next, scopes, hd='default', secure=secure, session=session, request_url=self.H9_AUTHSUB_HANDLER, include_scopes_in_next=include_scopes_in_next) if extra_params: auth_sub_url = '%s&%s' % (auth_sub_url, urllib.urlencode(extra_params)) return auth_sub_url def SetPrivateKey(self, filename): """Reads the private key from the specified file. See http://code.google.com/apis/gdata/authsub.html#Registered for\ information on how to create a RSA private key/public cert pair. Args: filename: string .pem file the key is stored in. Returns: The private key as a string. Raises: IOError: The file could not be read or does not exist. """ try: f = open(filename) rsa_private_key = f.read() f.close() except IOError, (errno, strerror): raise 'I/O error(%s): %s' % (errno, strerror) self.rsa_key = rsa_private_key return rsa_private_key def GetMedicationHTML(feed): """Prints out the user's medication to the console. Args: feed: A gdata.GDataFeed instance. Returns: An HTML formatted string containing the user's medication data. """ if not feed.entry: return '<b>No entries in feed</b><br>' html = [] for entry in feed.entry: try: ccr = entry.FindExtensions('ContinuityOfCareRecord')[0] body = ccr.FindChildren('Body')[0] meds = body.FindChildren('Medications')[0].FindChildren('Medication') for med in meds: name = med.FindChildren('Product')[0].FindChildren('ProductName')[0] html.append('<li>%s</li>' % name.FindChildren('Text')[0].text) except: html.append('<b>No medication data in this profile</b><br>') return '<ul>%s</ul>' % ''.join(html) def index(req): req.content_type = 'text/html' authsub = HealthAuthSubHelper() client = gdata.service.GDataService(service='weaver') current_url = authsub.GetNextUrl(req) rsa_key = authsub.SetPrivateKey('/path/to/yourRSAPrivateKey.pem') # Strip token query parameter's value from URL if it exists token = gdata.auth.extract_auth_sub_token_from_url(current_url, rsa_key=rsa_key) if not token: """STEP 1: No single use token in the URL or a saved session token. Generate the AuthSub URL to fetch a single use token.""" params = {'permission': 1} authsub_url = authsub.GenerateAuthSubRequestUrl(current_url, extra_params=params) req.write('<a href="%s">Link your Google Health Profile</a>' % authsub_url) else: """STEP 2: A single use token was extracted from the URL. Upgrade the one time token to a session token.""" req.write('<b>Single use token</b>: %s<br>' % str(token)) client.UpgradeToSessionToken(token) # calls gdata.service.SetAuthSubToken() """STEP 3: Done with AuthSub :) Save the token for subsequent requests. Query the Health Data API""" req.write('<b>Token info</b>: %s<br>' % client.AuthSubTokenInfo()) req.write('<b>Session token</b>: %s<br>' % client.GetAuthSubToken()) # Query the Health Data API params = {'digest': 'true', 'strict': 'true'} uri = '%s?%s' % (H9_PROFILE_FEED_URL, urllib.urlencode(params)) feed = client.GetFeed(uri) req.write('<h4>Listing medications</h4>') req.write(GetMedicationHTML(feed)) """STEP 4: Revoke the session token.""" req.write('Revoked session token') client.RevokeAuthSubToken()
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. """Sample Google Analytics Data Export API Data Feed application. This sample demonstrates how to make requests and retrieve the important information from the Google Analytics Data Export API Data Feed. This sample requires a Google Analytics username and password and uses the Client Login authorization routine. Class DataFeedDemo: Prints all the important Data Feed informantion. """ __author__ = 'api.nickm@google.com (Nick Mihailovski)' import gdata.analytics.client import gdata.sample_util def main(): """Main function for the sample.""" demo = DataFeedDemo() demo.PrintFeedDetails() demo.PrintDataSources() demo.PrintFeedAggregates() demo.PrintSegmentInfo() demo.PrintOneEntry() demo.PrintFeedTable() class DataFeedDemo(object): """Gets data from the Data Feed. Attributes: data_feed: Google Analytics AccountList returned form the API. """ def __init__(self): """Inits DataFeedDemo.""" SOURCE_APP_NAME = 'Google-dataFeedDemoPython-v2' my_client = gdata.analytics.client.AnalyticsClient(source=SOURCE_APP_NAME) try: gdata.sample_util.authorize_client( my_client, service=my_client.auth_service, source=SOURCE_APP_NAME, scopes=['https://www.google.com/analytics/feeds/']) except gdata.client.BadAuthentication: exit('Invalid user credentials given.') except gdata.client.Error: exit('Login Error') table_id = gdata.sample_util.get_param( name='table_id', prompt='Please enter your Google Analytics Table id (format ga:xxxx)') # DataFeedQuery simplifies constructing API queries and uri encodes params. data_query = gdata.analytics.client.DataFeedQuery({ 'ids': table_id, 'start-date': '2008-10-01', 'end-date': '2008-10-30', 'dimensions': 'ga:source,ga:medium', 'metrics': 'ga:visits', 'sort': '-ga:visits', 'filters': 'ga:medium==referral', 'max-results': '50'}) self.feed = my_client.GetDataFeed(data_query) def PrintFeedDetails(self): """Prints important Analytics related data found at the top of the feed.""" print '\n-------- Feed Data --------' print 'Feed Title = ' + self.feed.title.text print 'Feed Id = ' + self.feed.id.text print 'Total Results Found = ' + self.feed.total_results.text print 'Start Index = ' + self.feed.start_index.text print 'Results Returned = ' + self.feed.items_per_page.text print 'Start Date = ' + self.feed.start_date.text print 'End Date = ' + self.feed.end_date.text print 'Has Sampeld Data = ' + str(self.feed.HasSampledData()) def PrintDataSources(self): """Prints data found in the data source elements. This data has information about the Google Analytics account the referenced table ID belongs to. Note there is currently exactly one data source in the data feed. """ data_source = self.feed.data_source[0] print '\n-------- Data Source Data --------' print 'Table ID = ' + data_source.table_id.text print 'Table Name = ' + data_source.table_name.text print 'Web Property Id = ' + data_source.GetProperty('ga:webPropertyId').value print 'Profile Id = ' + data_source.GetProperty('ga:profileId').value print 'Account Name = ' + data_source.GetProperty('ga:accountName').value def PrintFeedAggregates(self): """Prints data found in the aggregates elements. This contains the sum of all the metrics defined in the query across. This sum spans all the rows matched in the feed.total_results property and not just the rows returned by the response. """ aggregates = self.feed.aggregates print '\n-------- Metric Aggregates --------' for met in aggregates.metric: print '' print 'Metric Name = ' + met.name print 'Metric Value = ' + met.value print 'Metric Type = ' + met.type print 'Metric CI = ' + met.confidence_interval def PrintSegmentInfo(self): """Prints segment information if the query has advanced segments defined.""" print '-------- Advanced Segments Information --------' if self.feed.segment: if segment.name: print 'Segment Name = ' + str(segment.name) if segment.id: print 'Segment Id = ' + str(segment.id) print 'Segment Definition = ' + segment.definition.text else: print 'No segments defined' def PrintOneEntry(self): """Prints all the important Google Analytics data found in an entry""" print '\n-------- One Entry --------' if len(self.feed.entry) == 0: print 'No entries found' return entry = self.feed.entry[0] print 'ID = ' + entry.id.text for dim in entry.dimension: print 'Dimension Name = ' + dim.name print 'Dimension Value = ' + dim.value for met in entry.metric: print 'Metric Name = ' + met.name print 'Metric Value = ' + met.value print 'Metric Type = ' + met.type print 'Metric CI = ' + met.confidence_interval def PrintFeedTable(self): """Prints all the entries as a table.""" print '\n-------- All Entries In a Table --------' for entry in self.feed.entry: for dim in entry.dimension: print ('Dimension Name = %s \t Dimension Value = %s' % (dim.name, dim.value)) for met in entry.metric: print ('Metric Name = %s \t Metric Value = %s' % (met.name, met.value)) print '---' if __name__ == '__main__': main()
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. """Google Analytics Management API Demo. This script demonstrates how to retrieve the important data from the Google Analytics Data Management API using the Python Client library. This example requires a Google Analytics account with data and a username and password. Each feed in the Management API is retrieved and printed using the respective print method in ManagementFeedDemo. To simplify setting filters and query parameters, each feed has it's own query class. Check the <code>gdata.analytics.client</code> module for more details on usage. main: The main method of this example. GetAnalyticsClient: Returns an authorized AnalyticsClient object. Class ManagementFeedDemo: Prints all the import Account Feed data. """ __author__ = 'api.nickm@google.com (Nick Mihailovski)' import gdata.analytics.client import gdata.sample_util ACCOUNT_ID = '~all' WEB_PROPERTY_ID = '~all' PROFILE_ID = '~all' def main(): """Main example script. Un-comment each method to print the feed.""" demo = ManagementFeedDemo(GetAnalyticsClient()) demo.PrintAccountFeed() # demo.PrintWebPropertyFeed() # demo.PrintProfileFeed() # demo.PrintGoalFeed() # demo.PrintSegmentFeed() def GetAnalyticsClient(): """Returns an authorized GoogleAnalayticsClient object. Uses the Google Data python samples wrapper to prompt the user for credentials then tries to authorize the client object with the Google Analytics API. Returns: An authorized GoogleAnalyticsClient object. """ SOURCE_APP_NAME = 'Analytics-ManagementAPI-Demo-v1' my_client = gdata.analytics.client.AnalyticsClient(source=SOURCE_APP_NAME) try: gdata.sample_util.authorize_client( my_client, service=my_client.auth_service, source=SOURCE_APP_NAME, scopes=['https://www.google.com/analytics/feeds/']) except gdata.client.BadAuthentication: exit('Invalid user credentials given.') except gdata.client.Error: exit('Login Error') return my_client class ManagementFeedDemo(object): """The main demo for the management feed. Attributes: my_client: gdata.analytics.client The AnalyticsClient object for this demo. """ def __init__(self, my_client): """Initializes the ManagementFeedDemo class. Args: my_client: gdata.analytics.client An authorized GoogleAnalyticsClient object. """ self.my_client = my_client def PrintAccountFeed(self): """Requests and prints the important data in the Account Feed. Note: AccountQuery is used for the ManagementAPI. AccountFeedQuery is used for the Data Export API. """ account_query = gdata.analytics.client.AccountQuery() results = self.my_client.GetManagementFeed(account_query) print '-------- Account Feed Data --------' if not results.entry: print 'no entries found' else: for entry in results.entry: print 'Account Name = ' + entry.GetProperty('ga:accountName').value print 'Account ID = ' + entry.GetProperty('ga:accountId').value print 'Child Feed Link = ' + entry.GetChildLink('analytics#webproperties').href print def PrintWebPropertyFeed(self): """Requests and prints the important data in the Web Property Feed.""" web_property_query = gdata.analytics.client.WebPropertyQuery( acct_id=ACCOUNT_ID) results = self.my_client.GetManagementFeed(web_property_query) print '-------- Web Property Feed Data --------' if not results.entry: print 'no entries found' else: for entry in results.entry: print 'Account ID = ' + entry.GetProperty('ga:accountId').value print 'Web Property ID = ' + entry.GetProperty('ga:webPropertyId').value print 'Child Feed Link = ' + entry.GetChildLink('analytics#profiles').href print def PrintProfileFeed(self): """Requests and prints the important data in the Profile Feed. Note: TableId has a different namespace (dxp:) than all the other properties (ga:). """ profile_query = gdata.analytics.client.ProfileQuery( acct_id=ACCOUNT_ID, web_prop_id=WEB_PROPERTY_ID) results = self.my_client.GetManagementFeed(profile_query) print '-------- Profile Feed Data --------' if not results.entry: print 'no entries found' else: for entry in results.entry: print 'Account ID = ' + entry.GetProperty('ga:accountId').value print 'Web Property ID = ' + entry.GetProperty('ga:webPropertyId').value print 'Profile ID = ' + entry.GetProperty('ga:profileId').value print 'Currency = ' + entry.GetProperty('ga:currency').value print 'Timezone = ' + entry.GetProperty('ga:timezone').value print 'TableId = ' + entry.GetProperty('dxp:tableId').value print 'Child Feed Link = ' + entry.GetChildLink('analytics#goals').href print def PrintGoalFeed(self): """Requests and prints the important data in the Goal Feed. Note: There are two types of goals, destination and engagement which need to be handled differently. """ goal_query = gdata.analytics.client.GoalQuery( acct_id=ACCOUNT_ID, web_prop_id=WEB_PROPERTY_ID, profile_id=PROFILE_ID) results = self.my_client.GetManagementFeed(goal_query) print '-------- Goal Feed Data --------' if not results.entry: print 'no entries found' else: for entry in results.entry: print 'Goal Number = ' + entry.goal.number print 'Goal Name = ' + entry.goal.name print 'Goal Value = ' + entry.goal.value print 'Goal Active = ' + entry.goal.active if entry.goal.destination: self.PrintDestinationGoal(entry.goal.destination) elif entry.goal.engagement: self.PrintEngagementGoal(entry.goal.engagement) def PrintDestinationGoal(self, destination): """Prints the important information for destination goals including all the configured steps if they exist. Args: destination: gdata.data.Destination The destination goal configuration. """ print '\t----- Destination Goal -----' print '\tExpression = ' + destination.expression print '\tMatch Type = ' + destination.match_type print '\tStep 1 Required = ' + destination.step1_required print '\tCase Sensitive = ' + destination.case_sensitive if destination.step: print '\t\t----- Destination Goal Steps -----' for step in destination.step: print '\t\tStep Number = ' + step.number print '\t\tStep Name = ' + step.name print '\t\tStep Path = ' + step.path print def PrintEngagementGoal(self, engagement): """Prints the important information for engagement goals. Args: engagement: gdata.data.Engagement The engagement goal configuration. """ print '\t----- Engagement Goal -----' print '\tGoal Type = ' + engagement.type print '\tGoal Engagement = ' + engagement.comparison print '\tGoal Threshold = ' + engagement.threshold_value print def PrintSegmentFeed(self): """Requests and prints the important data in the Profile Feed.""" adv_seg_query = gdata.analytics.client.AdvSegQuery() results = self.my_client.GetManagementFeed(adv_seg_query) print '-------- Advanced Segment Feed Data --------' if not results.entry: print 'no entries found' else: for entry in results.entry: print 'Segment ID = ' + entry.segment.id print 'Segment Name = ' + entry.segment.name print 'Segment Definition = ' + entry.segment.definition.text print if __name__ == '__main__': main()
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. """Sample Google Analytics Data Export API Account Feed application. This sample demonstrates how to retrieve the important data from the Google Analytics Data Export API Account feed using the Python Client library. This requires a Google Analytics username and password and uses the Client Login authorization routine. Class AccountFeedDemo: Prints all the import Account Feed data. """ __author__ = 'api.nickm@google.com (Nick Mihailovski)' import gdata.analytics.client import gdata.sample_util def main(): """Main fucntion for the sample.""" demo = AccountFeedDemo() demo.PrintFeedDetails() demo.PrintAdvancedSegments() demo.PrintCustomVarForOneEntry() demo.PrintGoalsForOneEntry() demo.PrintAccountEntries() class AccountFeedDemo(object): """Prints the Google Analytics account feed Attributes: account_feed: Google Analytics AccountList returned form the API. """ def __init__(self): """Inits AccountFeedDemo.""" SOURCE_APP_NAME = 'Google-accountFeedDemoPython-v1' my_client = gdata.analytics.client.AnalyticsClient(source=SOURCE_APP_NAME) try: gdata.sample_util.authorize_client( my_client, service=my_client.auth_service, source=SOURCE_APP_NAME, scopes=['https://www.google.com/analytics/feeds/']) except gdata.client.BadAuthentication: exit('Invalid user credentials given.') except gdata.client.Error: exit('Login Error') account_query = gdata.analytics.client.AccountFeedQuery() self.feed = my_client.GetAccountFeed(account_query) def PrintFeedDetails(self): """Prints important Analytics related data found at the top of the feed.""" print '-------- Important Feed Data --------' print 'Feed Title = ' + self.feed.title.text print 'Feed Id = ' + self.feed.id.text print 'Total Results Found = ' + self.feed.total_results.text print 'Start Index = ' + self.feed.start_index.text print 'Results Returned = ' + self.feed.items_per_page.text def PrintAdvancedSegments(self): """Prints the advanced segments for this user.""" print '-------- Advances Segments --------' if not self.feed.segment: print 'No advanced segments found' else: for segment in self.feed.segment: print 'Segment Name = ' + segment.name print 'Segment Id = ' + segment.id print 'Segment Definition = ' + segment.definition.text def PrintCustomVarForOneEntry(self): """Prints custom variable information for the first profile that has custom variable configured.""" print '-------- Custom Variables --------' if not self.feed.entry: print 'No entries found' else: for entry in self.feed.entry: if entry.custom_variable: for custom_variable in entry.custom_variable: print 'Custom Variable Index = ' + custom_variable.index print 'Custom Variable Name = ' + custom_variable.name print 'Custom Variable Scope = ' + custom_variable.scope return print 'No custom variables defined for this user' def PrintGoalsForOneEntry(self): """Prints All the goal information for one profile.""" print '-------- Goal Configuration --------' if not self.feed.entry: print 'No entries found' else: for entry in self.feed.entry: if entry.goal: for goal in entry.goal: print 'Goal Number = ' + goal.number print 'Goal Name = ' + goal.name print 'Goal Value = ' + goal.value print 'Goal Active = ' + goal.active if goal.destination: self.PrintDestinationGoal(goal.destination) elif goal.engagement: self.PrintEngagementGoal(goal.engagement) return def PrintDestinationGoal(self, destination): """Prints the important information for destination goals including all the configured steps if they exist. Args: destination: gdata.data.Destination The destination goal configuration. """ print '----- Destination Goal -----' print 'Expression = ' + destination.expression print 'Match Type = ' + destination.match_type print 'Step 1 Required = ' + destination.step1_required print 'Case Sensitive = ' + destination.case_sensitive # Print goal steps. if destination.step: print '----- Destination Goal Steps -----' for step in destination.step: print 'Step Number = ' + step.number print 'Step Name = ' + step.name print 'Step Path = ' + step.path def PrintEngagementGoal(self, engagement): """Prints the important information for engagement goals. Args: engagement: gdata.data.Engagement The engagement goal configuration. """ print '----- Engagement Goal -----' print 'Goal Type = ' + engagement.type print 'Goal Engagement = ' + engagement.comparison print 'Goal Threshold = ' + engagement.threshold_value def PrintAccountEntries(self): """Prints important Analytics data found in each account entry""" print '-------- First 1000 Profiles in Account Feed --------' if not self.feed.entry: print 'No entries found' else: for entry in self.feed.entry: print 'Web Property ID = ' + entry.GetProperty('ga:webPropertyId').value print 'Account Name = ' + entry.GetProperty('ga:accountName').value print 'Account Id = ' + entry.GetProperty('ga:accountId').value print 'Profile Name = ' + entry.title.text print 'Profile ID = ' + entry.GetProperty('ga:profileId').value print 'Table ID = ' + entry.table_id.text print 'Currency = ' + entry.GetProperty('ga:currency').value print 'TimeZone = ' + entry.GetProperty('ga:timezone').value if entry.custom_variable: print 'This profile has custom variables' if entry.goal: print 'This profile has goals' if __name__ == '__main__': main()
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. __author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)' try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import gdata.spreadsheet.service import gdata.service import atom.service import gdata.spreadsheet import atom import getopt import sys import string class SimpleCRUD: def __init__(self, email, password): self.gd_client = gdata.spreadsheet.service.SpreadsheetsService() self.gd_client.email = email self.gd_client.password = password self.gd_client.source = 'Spreadsheets GData Sample' self.gd_client.ProgrammaticLogin() self.curr_key = '' self.curr_wksht_id = '' self.list_feed = None def _PromptForSpreadsheet(self): # Get the list of spreadsheets feed = self.gd_client.GetSpreadsheetsFeed() self._PrintFeed(feed) input = raw_input('\nSelection: ') id_parts = feed.entry[string.atoi(input)].id.text.split('/') self.curr_key = id_parts[len(id_parts) - 1] def _PromptForWorksheet(self): # Get the list of worksheets feed = self.gd_client.GetWorksheetsFeed(self.curr_key) self._PrintFeed(feed) input = raw_input('\nSelection: ') id_parts = feed.entry[string.atoi(input)].id.text.split('/') self.curr_wksht_id = id_parts[len(id_parts) - 1] def _PromptForCellsAction(self): print ('dump\n' 'update {row} {col} {input_value}\n' '\n') input = raw_input('Command: ') command = input.split(' ', 1) if command[0] == 'dump': self._CellsGetAction() elif command[0] == 'update': parsed = command[1].split(' ', 2) if len(parsed) == 3: self._CellsUpdateAction(parsed[0], parsed[1], parsed[2]) else: self._CellsUpdateAction(parsed[0], parsed[1], '') else: self._InvalidCommandError(input) def _PromptForListAction(self): print ('dump\n' 'insert {row_data} (example: insert label=content)\n' 'update {row_index} {row_data}\n' 'delete {row_index}\n' 'Note: No uppercase letters in column names!\n' '\n') input = raw_input('Command: ') command = input.split(' ' , 1) if command[0] == 'dump': self._ListGetAction() elif command[0] == 'insert': self._ListInsertAction(command[1]) elif command[0] == 'update': parsed = command[1].split(' ', 1) self._ListUpdateAction(parsed[0], parsed[1]) elif command[0] == 'delete': self._ListDeleteAction(command[1]) else: self._InvalidCommandError(input) def _CellsGetAction(self): # Get the feed of cells feed = self.gd_client.GetCellsFeed(self.curr_key, self.curr_wksht_id) self._PrintFeed(feed) def _CellsUpdateAction(self, row, col, inputValue): entry = self.gd_client.UpdateCell(row=row, col=col, inputValue=inputValue, key=self.curr_key, wksht_id=self.curr_wksht_id) if isinstance(entry, gdata.spreadsheet.SpreadsheetsCell): print 'Updated!' def _ListGetAction(self): # Get the list feed self.list_feed = self.gd_client.GetListFeed(self.curr_key, self.curr_wksht_id) self._PrintFeed(self.list_feed) def _ListInsertAction(self, row_data): entry = self.gd_client.InsertRow(self._StringToDictionary(row_data), self.curr_key, self.curr_wksht_id) if isinstance(entry, gdata.spreadsheet.SpreadsheetsList): print 'Inserted!' def _ListUpdateAction(self, index, row_data): self.list_feed = self.gd_client.GetListFeed(self.curr_key, self.curr_wksht_id) entry = self.gd_client.UpdateRow( self.list_feed.entry[string.atoi(index)], self._StringToDictionary(row_data)) if isinstance(entry, gdata.spreadsheet.SpreadsheetsList): print 'Updated!' def _ListDeleteAction(self, index): self.list_feed = self.gd_client.GetListFeed(self.curr_key, self.curr_wksht_id) self.gd_client.DeleteRow(self.list_feed.entry[string.atoi(index)]) print 'Deleted!' def _StringToDictionary(self, row_data): dict = {} for param in row_data.split(): temp = param.split('=') dict[temp[0]] = temp[1] return dict def _PrintFeed(self, feed): for i, entry in enumerate(feed.entry): if isinstance(feed, gdata.spreadsheet.SpreadsheetsCellsFeed): print '%s %s\n' % (entry.title.text, entry.content.text) elif isinstance(feed, gdata.spreadsheet.SpreadsheetsListFeed): print '%s %s %s' % (i, entry.title.text, entry.content.text) # Print this row's value for each column (the custom dictionary is # built using the gsx: elements in the entry.) print 'Contents:' for key in entry.custom: print ' %s: %s' % (key, entry.custom[key].text) print '\n', else: print '%s %s\n' % (i, entry.title.text) def _InvalidCommandError(self, input): print 'Invalid input: %s\n' % (input) def Run(self): self._PromptForSpreadsheet() self._PromptForWorksheet() input = raw_input('cells or list? ') if input == 'cells': while True: self._PromptForCellsAction() elif input == 'list': while True: self._PromptForListAction() def main(): # parse command line options try: opts, args = getopt.getopt(sys.argv[1:], "", ["user=", "pw="]) except getopt.error, msg: print 'python spreadsheetExample.py --user [username] --pw [password] ' sys.exit(2) user = '' pw = '' key = '' # Process options for o, a in opts: if o == "--user": user = a elif o == "--pw": pw = a if user == '' or pw == '': print 'python spreadsheetExample.py --user [username] --pw [password] ' sys.exit(2) sample = SimpleCRUD(user, pw) sample.Run() if __name__ == '__main__': main()
Python
#!/usr/bin/env python # # 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. """Tool for uploading diffs from a version control system to the codereview app. Usage summary: upload.py [options] [-- diff_options] Diff options are passed to the diff command of the underlying system. Supported version control systems: Git Mercurial Subversion It is important for Git/Mercurial users to specify a tree/node/branch to diff against by using the '--rev' option. """ # This code is derived from appcfg.py in the App Engine SDK (open source), # and from ASPN recipe #146306. import ConfigParser import cookielib import fnmatch import getpass import logging import mimetypes import optparse import os import re import socket import subprocess import sys import urllib import urllib2 import urlparse # The md5 module was deprecated in Python 2.5. try: from hashlib import md5 except ImportError: from md5 import md5 try: import readline except ImportError: pass # The logging verbosity: # 0: Errors only. # 1: Status messages. # 2: Info logs. # 3: Debug logs. verbosity = 1 # Max size of patch or base file. MAX_UPLOAD_SIZE = 900 * 1024 # Constants for version control names. Used by GuessVCSName. VCS_GIT = "Git" VCS_MERCURIAL = "Mercurial" VCS_SUBVERSION = "Subversion" VCS_UNKNOWN = "Unknown" # whitelist for non-binary filetypes which do not start with "text/" # .mm (Objective-C) shows up as application/x-freemind on my Linux box. TEXT_MIMETYPES = ['application/javascript', 'application/x-javascript', 'application/x-freemind'] VCS_ABBREVIATIONS = { VCS_MERCURIAL.lower(): VCS_MERCURIAL, "hg": VCS_MERCURIAL, VCS_SUBVERSION.lower(): VCS_SUBVERSION, "svn": VCS_SUBVERSION, VCS_GIT.lower(): VCS_GIT, } # The result of parsing Subversion's [auto-props] setting. svn_auto_props_map = None def GetEmail(prompt): """Prompts the user for their email address and returns it. The last used email address is saved to a file and offered up as a suggestion to the user. If the user presses enter without typing in anything the last used email address is used. If the user enters a new address, it is saved for next time we prompt. """ last_email_file_name = os.path.expanduser("~/.last_codereview_email_address") last_email = "" if os.path.exists(last_email_file_name): try: last_email_file = open(last_email_file_name, "r") last_email = last_email_file.readline().strip("\n") last_email_file.close() prompt += " [%s]" % last_email except IOError, e: pass email = raw_input(prompt + ": ").strip() if email: try: last_email_file = open(last_email_file_name, "w") last_email_file.write(email) last_email_file.close() except IOError, e: pass else: email = last_email return email def StatusUpdate(msg): """Print a status message to stdout. If 'verbosity' is greater than 0, print the message. Args: msg: The string to print. """ if verbosity > 0: print msg def ErrorExit(msg): """Print an error message to stderr and exit.""" print >>sys.stderr, msg sys.exit(1) class ClientLoginError(urllib2.HTTPError): """Raised to indicate there was an error authenticating with ClientLogin.""" def __init__(self, url, code, msg, headers, args): urllib2.HTTPError.__init__(self, url, code, msg, headers, None) self.args = args self.reason = args["Error"] class AbstractRpcServer(object): """Provides a common interface for a simple RPC server.""" def __init__(self, host, auth_function, host_override=None, extra_headers={}, save_cookies=False): """Creates a new HttpRpcServer. Args: host: The host to send requests to. auth_function: A function that takes no arguments and returns an (email, password) tuple when called. Will be called if authentication is required. host_override: The host header to send to the server (defaults to host). extra_headers: A dict of extra headers to append to every request. save_cookies: If True, save the authentication cookies to local disk. If False, use an in-memory cookiejar instead. Subclasses must implement this functionality. Defaults to False. """ self.host = host self.host_override = host_override self.auth_function = auth_function self.authenticated = False self.extra_headers = extra_headers self.save_cookies = save_cookies self.opener = self._GetOpener() if self.host_override: logging.info("Server: %s; Host: %s", self.host, self.host_override) else: logging.info("Server: %s", self.host) def _GetOpener(self): """Returns an OpenerDirector for making HTTP requests. Returns: A urllib2.OpenerDirector object. """ raise NotImplementedError() def _CreateRequest(self, url, data=None): """Creates a new urllib request.""" logging.debug("Creating request for: '%s' with payload:\n%s", url, data) req = urllib2.Request(url, data=data) if self.host_override: req.add_header("Host", self.host_override) for key, value in self.extra_headers.iteritems(): req.add_header(key, value) return req def _GetAuthToken(self, email, password): """Uses ClientLogin to authenticate the user, returning an auth token. Args: email: The user's email address password: The user's password Raises: ClientLoginError: If there was an error authenticating with ClientLogin. HTTPError: If there was some other form of HTTP error. Returns: The authentication token returned by ClientLogin. """ account_type = "GOOGLE" if self.host.endswith(".google.com"): # Needed for use inside Google. account_type = "HOSTED" req = self._CreateRequest( url="https://www.google.com/accounts/ClientLogin", data=urllib.urlencode({ "Email": email, "Passwd": password, "service": "ah", "source": "rietveld-codereview-upload", "accountType": account_type, }), ) try: response = self.opener.open(req) response_body = response.read() response_dict = dict(x.split("=") for x in response_body.split("\n") if x) return response_dict["Auth"] except urllib2.HTTPError, e: if e.code == 403: body = e.read() response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) raise ClientLoginError(req.get_full_url(), e.code, e.msg, e.headers, response_dict) else: raise def _GetAuthCookie(self, auth_token): """Fetches authentication cookies for an authentication token. Args: auth_token: The authentication token returned by ClientLogin. Raises: HTTPError: If there was an error fetching the authentication cookies. """ # This is a dummy value to allow us to identify when we're successful. continue_location = "http://localhost/" args = {"continue": continue_location, "auth": auth_token} req = self._CreateRequest("http://%s/_ah/login?%s" % (self.host, urllib.urlencode(args))) try: response = self.opener.open(req) except urllib2.HTTPError, e: response = e if (response.code != 302 or response.info()["location"] != continue_location): raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp) self.authenticated = True def _Authenticate(self): """Authenticates the user. The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. If we attempt to access the upload API without first obtaining an authentication cookie, it returns a 401 response (or a 302) and directs us to authenticate ourselves with ClientLogin. """ for i in range(3): credentials = self.auth_function() try: auth_token = self._GetAuthToken(credentials[0], credentials[1]) except ClientLoginError, e: if e.reason == "BadAuthentication": print >>sys.stderr, "Invalid username or password." continue if e.reason == "CaptchaRequired": print >>sys.stderr, ( "Please go to\n" "https://www.google.com/accounts/DisplayUnlockCaptcha\n" "and verify you are a human. Then try again.") break if e.reason == "NotVerified": print >>sys.stderr, "Account not verified." break if e.reason == "TermsNotAgreed": print >>sys.stderr, "User has not agreed to TOS." break if e.reason == "AccountDeleted": print >>sys.stderr, "The user account has been deleted." break if e.reason == "AccountDisabled": print >>sys.stderr, "The user account has been disabled." break if e.reason == "ServiceDisabled": print >>sys.stderr, ("The user's access to the service has been " "disabled.") break if e.reason == "ServiceUnavailable": print >>sys.stderr, "The service is not available; try again later." break raise self._GetAuthCookie(auth_token) return def Send(self, request_path, payload=None, content_type="application/octet-stream", timeout=None, **kwargs): """Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: for large requests on OS X, the timeout doesn't work right.) kwargs: Any keyword arguments are converted into query string parameters. Returns: The response body, as a string. """ # TODO: Don't require authentication. Let the server say # whether it is necessary. if not self.authenticated: self._Authenticate() old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout) try: tries = 0 while True: tries += 1 args = dict(kwargs) url = "http://%s%s" % (self.host, request_path) if args: url += "?" + urllib.urlencode(args) req = self._CreateRequest(url=url, data=payload) req.add_header("Content-Type", content_type) try: f = self.opener.open(req) response = f.read() f.close() return response except urllib2.HTTPError, e: if tries > 3: raise elif e.code == 401 or e.code == 302: self._Authenticate() ## elif e.code >= 500 and e.code < 600: ## # Server Error - try again. ## continue else: raise finally: socket.setdefaulttimeout(old_timeout) class HttpRpcServer(AbstractRpcServer): """Provides a simplified RPC-style interface for HTTP requests.""" def _Authenticate(self): """Save the cookie jar after authentication.""" super(HttpRpcServer, self)._Authenticate() if self.save_cookies: StatusUpdate("Saving authentication cookies to %s" % self.cookie_file) self.cookie_jar.save() def _GetOpener(self): """Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object. """ opener = urllib2.OpenerDirector() opener.add_handler(urllib2.ProxyHandler()) opener.add_handler(urllib2.UnknownHandler()) opener.add_handler(urllib2.HTTPHandler()) opener.add_handler(urllib2.HTTPDefaultErrorHandler()) opener.add_handler(urllib2.HTTPSHandler()) opener.add_handler(urllib2.HTTPErrorProcessor()) if self.save_cookies: self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies") self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file) if os.path.exists(self.cookie_file): try: self.cookie_jar.load() self.authenticated = True StatusUpdate("Loaded authentication cookies from %s" % self.cookie_file) except (cookielib.LoadError, IOError): # Failed to load cookies - just ignore them. pass else: # Create an empty cookie file with mode 600 fd = os.open(self.cookie_file, os.O_CREAT, 0600) os.close(fd) # Always chmod the cookie file os.chmod(self.cookie_file, 0600) else: # Don't save cookies across runs of update.py. self.cookie_jar = cookielib.CookieJar() opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar)) return opener parser = optparse.OptionParser(usage="%prog [options] [-- diff_options]") parser.add_option("-y", "--assume_yes", action="store_true", dest="assume_yes", default=False, help="Assume that the answer to yes/no questions is 'yes'.") # Logging group = parser.add_option_group("Logging options") group.add_option("-q", "--quiet", action="store_const", const=0, dest="verbose", help="Print errors only.") group.add_option("-v", "--verbose", action="store_const", const=2, dest="verbose", default=1, help="Print info level logs (default).") group.add_option("--noisy", action="store_const", const=3, dest="verbose", help="Print all logs.") # Review server group = parser.add_option_group("Review server options") group.add_option("-s", "--server", action="store", dest="server", default="codereview.appspot.com", metavar="SERVER", help=("The server to upload to. The format is host[:port]. " "Defaults to '%default'.")) group.add_option("-e", "--email", action="store", dest="email", metavar="EMAIL", default=None, help="The username to use. Will prompt if omitted.") group.add_option("-H", "--host", action="store", dest="host", metavar="HOST", default=None, help="Overrides the Host header sent with all RPCs.") group.add_option("--no_cookies", action="store_false", dest="save_cookies", default=True, help="Do not save authentication cookies to local disk.") # Issue group = parser.add_option_group("Issue options") group.add_option("-d", "--description", action="store", dest="description", metavar="DESCRIPTION", default=None, help="Optional description when creating an issue.") group.add_option("-f", "--description_file", action="store", dest="description_file", metavar="DESCRIPTION_FILE", default=None, help="Optional path of a file that contains " "the description when creating an issue.") group.add_option("-r", "--reviewers", action="store", dest="reviewers", metavar="REVIEWERS", default=",joe.gregorio@gmail.com", help="Add reviewers (comma separated email addresses).") group.add_option("--cc", action="store", dest="cc", metavar="CC", default="gdata-python-client-library-contributors@googlegroups.com", help="Add CC (comma separated email addresses).") group.add_option("--private", action="store_true", dest="private", default=False, help="Make the issue restricted to reviewers and those CCed") # Upload options group = parser.add_option_group("Patch options") group.add_option("-m", "--message", action="store", dest="message", metavar="MESSAGE", default=None, help="A message to identify the patch. " "Will prompt if omitted.") group.add_option("-i", "--issue", type="int", action="store", metavar="ISSUE", default=None, help="Issue number to which to add. Defaults to new issue.") group.add_option("--base_url", action="store", dest="base_url", default=None, help="Base repository URL (listed as \"Base URL\" when " "viewing issue). If omitted, will be guessed automatically " "for SVN repos and left blank for others.") group.add_option("--download_base", action="store_true", dest="download_base", default=False, help="Base files will be downloaded by the server " "(side-by-side diffs may not work on files with CRs).") group.add_option("--rev", action="store", dest="revision", metavar="REV", default=None, help="Base revision/branch/tree to diff against. Use " "rev1:rev2 range to review already committed changeset.") group.add_option("--send_mail", action="store_true", dest="send_mail", default=True, help="Send notification email to reviewers.") group.add_option("--vcs", action="store", dest="vcs", metavar="VCS", default=None, help=("Version control system (optional, usually upload.py " "already guesses the right VCS).")) group.add_option("--emulate_svn_auto_props", action="store_true", dest="emulate_svn_auto_props", default=False, help=("Emulate Subversion's auto properties feature.")) def GetRpcServer(options): """Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made. """ rpc_server_class = HttpRpcServer def GetUserCredentials(): """Prompts the user for a username and password.""" email = options.email if email is None: email = GetEmail("Email (login for uploading to %s)" % options.server) password = getpass.getpass("Password for %s: " % email) return (email, password) # If this is the dev_appserver, use fake authentication. host = (options.host or options.server).lower() if host == "localhost" or host.startswith("localhost:"): email = options.email if email is None: email = "test@example.com" logging.info("Using debug user %s. Override with --email" % email) server = rpc_server_class( options.server, lambda: (email, "password"), host_override=options.host, extra_headers={"Cookie": 'dev_appserver_login="%s:False"' % email}, save_cookies=options.save_cookies) # Don't try to talk to ClientLogin. server.authenticated = True return server return rpc_server_class(options.server, GetUserCredentials, host_override=options.host, save_cookies=options.save_cookies) def EncodeMultipartFormData(fields, files): """Encode form fields for multipart/form-data. Args: fields: A sequence of (name, value) elements for regular form fields. files: A sequence of (name, filename, value) elements for data to be uploaded as files. Returns: (content_type, body) ready for httplib.HTTP instance. Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 """ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' lines = [] for (key, value) in fields: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"' % key) lines.append('') lines.append(value) for (key, filename, value) in files: lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) lines.append('Content-Type: %s' % GetContentType(filename)) lines.append('') lines.append(value) lines.append('--' + BOUNDARY + '--') lines.append('') body = CRLF.join(lines) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def GetContentType(filename): """Helper to guess the content-type from the filename.""" return mimetypes.guess_type(filename)[0] or 'application/octet-stream' # Use a shell for subcommands on Windows to get a PATH search. use_shell = sys.platform.startswith("win") def RunShellWithReturnCode(command, print_output=False, universal_newlines=True, env=os.environ): """Executes a command and returns the output from stdout and the return code. Args: command: Command to execute. print_output: If True, the output is printed to stdout. If False, both stdout and stderr are ignored. universal_newlines: Use universal_newlines flag (default: True). Returns: Tuple (output, return code) """ logging.info("Running %s", command) p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=use_shell, universal_newlines=universal_newlines, env=env) if print_output: output_array = [] while True: line = p.stdout.readline() if not line: break print line.strip("\n") output_array.append(line) output = "".join(output_array) else: output = p.stdout.read() p.wait() errout = p.stderr.read() if print_output and errout: print >>sys.stderr, errout p.stdout.close() p.stderr.close() return output, p.returncode def RunShell(command, silent_ok=False, universal_newlines=True, print_output=False, env=os.environ): data, retcode = RunShellWithReturnCode(command, print_output, universal_newlines, env) if retcode: ErrorExit("Got error status from %s:\n%s" % (command, data)) if not silent_ok and not data: ErrorExit("No output from %s" % command) return data class VersionControlSystem(object): """Abstract base class providing an interface to the VCS.""" def __init__(self, options): """Constructor. Args: options: Command line options. """ self.options = options def GenerateDiff(self, args): """Return the current diff as a string. Args: args: Extra arguments to pass to the diff command. """ raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def CheckForUnknownFiles(self): """Show an "are you sure?" prompt if there are unknown files.""" unknown_files = self.GetUnknownFiles() if unknown_files: print "The following files are not added to version control:" for line in unknown_files: print line prompt = "Are you sure to continue?(y/N) " answer = raw_input(prompt).strip() if answer != "y": ErrorExit("User aborted") def GetBaseFile(self, filename): """Get the content of the upstream version of a file. Returns: A tuple (base_content, new_content, is_binary, status) base_content: The contents of the base file. new_content: For text files, this is empty. For binary files, this is the contents of the new file, since the diff output won't contain information to reconstruct the current file. is_binary: True iff the file is binary. status: The status of the file. """ raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def GetBaseFiles(self, diff): """Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:". """ files = {} for line in diff.splitlines(True): if line.startswith('Index:') or line.startswith('Property changes on:'): unused, filename = line.split(':', 1) # On Windows if a file has property changes its filename uses '\' # instead of '/'. filename = filename.strip().replace('\\', '/') files[filename] = self.GetBaseFile(filename) return files def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options, files): """Uploads the base files (and if necessary, the current ones as well).""" def UploadFile(filename, file_id, content, is_binary, status, is_base): """Uploads a file to the server.""" file_too_large = False if is_base: type = "base" else: type = "current" if len(content) > MAX_UPLOAD_SIZE: print ("Not uploading the %s file for %s because it's too large." % (type, filename)) file_too_large = True content = "" checksum = md5(content).hexdigest() if options.verbose > 0 and not file_too_large: print "Uploading %s file for %s" % (type, filename) url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id) form_fields = [("filename", filename), ("status", status), ("checksum", checksum), ("is_binary", str(is_binary)), ("is_current", str(not is_base)), ] if file_too_large: form_fields.append(("file_too_large", "1")) if options.email: form_fields.append(("user", options.email)) ctype, body = EncodeMultipartFormData(form_fields, [("data", filename, content)]) response_body = rpc_server.Send(url, body, content_type=ctype) if not response_body.startswith("OK"): StatusUpdate(" --> %s" % response_body) sys.exit(1) patches = dict() [patches.setdefault(v, k) for k, v in patch_list] for filename in patches.keys(): base_content, new_content, is_binary, status = files[filename] file_id_str = patches.get(filename) if file_id_str.find("nobase") != -1: base_content = None file_id_str = file_id_str[file_id_str.rfind("_") + 1:] file_id = int(file_id_str) if base_content != None: UploadFile(filename, file_id, base_content, is_binary, status, True) if new_content != None: UploadFile(filename, file_id, new_content, is_binary, status, False) def IsImage(self, filename): """Returns true if the filename has an image extension.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False return mimetype.startswith("image/") def IsBinary(self, filename): """Returns true if the guessed mimetyped isnt't in text group.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False # e.g. README, "real" binaries usually have an extension # special case for text files which don't start with text/ if mimetype in TEXT_MIMETYPES: return False return not mimetype.startswith("text/") class SubversionVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Subversion.""" def __init__(self, options): super(SubversionVCS, self).__init__(options) if self.options.revision: match = re.match(r"(\d+)(:(\d+))?", self.options.revision) if not match: ErrorExit("Invalid Subversion revision %s." % self.options.revision) self.rev_start = match.group(1) self.rev_end = match.group(3) else: self.rev_start = self.rev_end = None # Cache output from "svn list -r REVNO dirname". # Keys: dirname, Values: 2-tuple (ouput for start rev and end rev). self.svnls_cache = {} # Base URL is required to fetch files deleted in an older revision. # Result is cached to not guess it over and over again in GetBaseFile(). required = self.options.download_base or self.options.revision is not None self.svn_base = self._GuessBase(required) def GuessBase(self, required): """Wrapper for _GuessBase.""" return self.svn_base def _GuessBase(self, required): """Returns the SVN base URL. Args: required: If true, exits if the url can't be guessed, otherwise None is returned. """ info = RunShell(["svn", "info"]) for line in info.splitlines(): words = line.split() if len(words) == 2 and words[0] == "URL:": url = words[1] scheme, netloc, path, params, query, fragment = urlparse.urlparse(url) username, netloc = urllib.splituser(netloc) if username: logging.info("Removed username from base URL") if netloc.endswith("svn.python.org"): if netloc == "svn.python.org": if path.startswith("/projects/"): path = path[9:] elif netloc != "pythondev@svn.python.org": ErrorExit("Unrecognized Python URL: %s" % url) base = "http://svn.python.org/view/*checkout*%s/" % path logging.info("Guessed Python base = %s", base) elif netloc.endswith("svn.collab.net"): if path.startswith("/repos/"): path = path[6:] base = "http://svn.collab.net/viewvc/*checkout*%s/" % path logging.info("Guessed CollabNet base = %s", base) elif netloc.endswith(".googlecode.com"): path = path + "/" base = urlparse.urlunparse(("http", netloc, path, params, query, fragment)) logging.info("Guessed Google Code base = %s", base) else: path = path + "/" base = urlparse.urlunparse((scheme, netloc, path, params, query, fragment)) logging.info("Guessed base = %s", base) return base if required: ErrorExit("Can't find URL in output from svn info") return None def GenerateDiff(self, args): cmd = ["svn", "diff"] if self.options.revision: cmd += ["-r", self.options.revision] cmd.extend(args) data = RunShell(cmd) count = 0 for line in data.splitlines(): if line.startswith("Index:") or line.startswith("Property changes on:"): count += 1 logging.info(line) if not count: ErrorExit("No valid patches found in output from svn diff") return data def _CollapseKeywords(self, content, keyword_str): """Collapses SVN keywords.""" # svn cat translates keywords but svn diff doesn't. As a result of this # behavior patching.PatchChunks() fails with a chunk mismatch error. # This part was originally written by the Review Board development team # who had the same problem (http://reviews.review-board.org/r/276/). # Mapping of keywords to known aliases svn_keywords = { # Standard keywords 'Date': ['Date', 'LastChangedDate'], 'Revision': ['Revision', 'LastChangedRevision', 'Rev'], 'Author': ['Author', 'LastChangedBy'], 'HeadURL': ['HeadURL', 'URL'], 'Id': ['Id'], # Aliases 'LastChangedDate': ['LastChangedDate', 'Date'], 'LastChangedRevision': ['LastChangedRevision', 'Rev', 'Revision'], 'LastChangedBy': ['LastChangedBy', 'Author'], 'URL': ['URL', 'HeadURL'], } def repl(m): if m.group(2): return "$%s::%s$" % (m.group(1), " " * len(m.group(3))) return "$%s$" % m.group(1) keywords = [keyword for name in keyword_str.split(" ") for keyword in svn_keywords.get(name, [])] return re.sub(r"\$(%s):(:?)([^\$]+)\$" % '|'.join(keywords), repl, content) def GetUnknownFiles(self): status = RunShell(["svn", "status", "--ignore-externals"], silent_ok=True) unknown_files = [] for line in status.split("\n"): if line and line[0] == "?": unknown_files.append(line) return unknown_files def ReadFile(self, filename): """Returns the contents of a file.""" file = open(filename, 'rb') result = "" try: result = file.read() finally: file.close() return result def GetStatus(self, filename): """Returns the status of a file.""" if not self.options.revision: status = RunShell(["svn", "status", "--ignore-externals", filename]) if not status: ErrorExit("svn status returned no output for %s" % filename) status_lines = status.splitlines() # If file is in a cl, the output will begin with # "\n--- Changelist 'cl_name':\n". See # http://svn.collab.net/repos/svn/trunk/notes/changelist-design.txt if (len(status_lines) == 3 and not status_lines[0] and status_lines[1].startswith("--- Changelist")): status = status_lines[2] else: status = status_lines[0] # If we have a revision to diff against we need to run "svn list" # for the old and the new revision and compare the results to get # the correct status for a file. else: dirname, relfilename = os.path.split(filename) if dirname not in self.svnls_cache: cmd = ["svn", "list", "-r", self.rev_start, dirname or "."] out, returncode = RunShellWithReturnCode(cmd) if returncode: ErrorExit("Failed to get status for %s." % filename) old_files = out.splitlines() args = ["svn", "list"] if self.rev_end: args += ["-r", self.rev_end] cmd = args + [dirname or "."] out, returncode = RunShellWithReturnCode(cmd) if returncode: ErrorExit("Failed to run command %s" % cmd) self.svnls_cache[dirname] = (old_files, out.splitlines()) old_files, new_files = self.svnls_cache[dirname] if relfilename in old_files and relfilename not in new_files: status = "D " elif relfilename in old_files and relfilename in new_files: status = "M " else: status = "A " return status def GetBaseFile(self, filename): status = self.GetStatus(filename) base_content = None new_content = None # If a file is copied its status will be "A +", which signifies # "addition-with-history". See "svn st" for more information. We need to # upload the original file or else diff parsing will fail if the file was # edited. if status[0] == "A" and status[3] != "+": # We'll need to upload the new content if we're adding a binary file # since diff's output won't contain it. mimetype = RunShell(["svn", "propget", "svn:mime-type", filename], silent_ok=True) base_content = "" is_binary = bool(mimetype) and not mimetype.startswith("text/") if is_binary and self.IsImage(filename): new_content = self.ReadFile(filename) elif (status[0] in ("M", "D", "R") or (status[0] == "A" and status[3] == "+") or # Copied file. (status[0] == " " and status[1] == "M")): # Property change. args = [] if self.options.revision: url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) else: # Don't change filename, it's needed later. url = filename args += ["-r", "BASE"] cmd = ["svn"] + args + ["propget", "svn:mime-type", url] mimetype, returncode = RunShellWithReturnCode(cmd) if returncode: # File does not exist in the requested revision. # Reset mimetype, it contains an error message. mimetype = "" get_base = False is_binary = bool(mimetype) and not mimetype.startswith("text/") if status[0] == " ": # Empty base content just to force an upload. base_content = "" elif is_binary: if self.IsImage(filename): get_base = True if status[0] == "M": if not self.rev_end: new_content = self.ReadFile(filename) else: url = "%s/%s@%s" % (self.svn_base, filename, self.rev_end) new_content = RunShell(["svn", "cat", url], universal_newlines=True, silent_ok=True) else: base_content = "" else: get_base = True if get_base: if is_binary: universal_newlines = False else: universal_newlines = True if self.rev_start: # "svn cat -r REV delete_file.txt" doesn't work. cat requires # the full URL with "@REV" appended instead of using "-r" option. url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) base_content = RunShell(["svn", "cat", url], universal_newlines=universal_newlines, silent_ok=True) else: base_content = RunShell(["svn", "cat", filename], universal_newlines=universal_newlines, silent_ok=True) if not is_binary: args = [] if self.rev_start: url = "%s/%s@%s" % (self.svn_base, filename, self.rev_start) else: url = filename args += ["-r", "BASE"] cmd = ["svn"] + args + ["propget", "svn:keywords", url] keywords, returncode = RunShellWithReturnCode(cmd) if keywords and not returncode: base_content = self._CollapseKeywords(base_content, keywords) else: StatusUpdate("svn status returned unexpected output: %s" % status) sys.exit(1) return base_content, new_content, is_binary, status[0:5] class GitVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Git.""" def __init__(self, options): super(GitVCS, self).__init__(options) # Map of filename -> (hash before, hash after) of base file. # Hashes for "no such file" are represented as None. self.hashes = {} # Map of new filename -> old filename for renames. self.renames = {} def GenerateDiff(self, extra_args): # This is more complicated than svn's GenerateDiff because we must convert # the diff output to include an svn-style "Index:" line as well as record # the hashes of the files, so we can upload them along with our diff. # Special used by git to indicate "no such content". NULL_HASH = "0"*40 extra_args = extra_args[:] if self.options.revision: extra_args = [self.options.revision] + extra_args # --no-ext-diff is broken in some versions of Git, so try to work around # this by overriding the environment (but there is still a problem if the # git config key "diff.external" is used). env = os.environ.copy() if 'GIT_EXTERNAL_DIFF' in env: del env['GIT_EXTERNAL_DIFF'] gitdiff = RunShell(["git", "diff", "--no-ext-diff", "--full-index", "-M"] + extra_args, env=env) def IsFileNew(filename): return filename in self.hashes and self.hashes[filename][0] is None def AddSubversionPropertyChange(filename): """Add svn's property change information into the patch if given file is new file. We use Subversion's auto-props setting to retrieve its property. See http://svnbook.red-bean.com/en/1.1/ch07.html#svn-ch-7-sect-1.3.2 for Subversion's [auto-props] setting. """ if self.options.emulate_svn_auto_props and IsFileNew(filename): svnprops = GetSubversionPropertyChanges(filename) if svnprops: svndiff.append("\n" + svnprops + "\n") svndiff = [] filecount = 0 filename = None for line in gitdiff.splitlines(): match = re.match(r"diff --git a/(.*) b/(.*)$", line) if match: # Add auto property here for previously seen file. if filename is not None: AddSubversionPropertyChange(filename) filecount += 1 # Intentionally use the "after" filename so we can show renames. filename = match.group(2) svndiff.append("Index: %s\n" % filename) if match.group(1) != match.group(2): self.renames[match.group(2)] = match.group(1) else: # The "index" line in a git diff looks like this (long hashes elided): # index 82c0d44..b2cee3f 100755 # We want to save the left hash, as that identifies the base file. match = re.match(r"index (\w+)\.\.(\w+)", line) if match: before, after = (match.group(1), match.group(2)) if before == NULL_HASH: before = None if after == NULL_HASH: after = None self.hashes[filename] = (before, after) svndiff.append(line + "\n") if not filecount: ErrorExit("No valid patches found in output from git diff") # Add auto property for the last seen file. assert filename is not None AddSubversionPropertyChange(filename) return "".join(svndiff) def GetUnknownFiles(self): status = RunShell(["git", "ls-files", "--exclude-standard", "--others"], silent_ok=True) return status.splitlines() def GetFileContent(self, file_hash, is_binary): """Returns the content of a file identified by its git hash.""" data, retcode = RunShellWithReturnCode(["git", "show", file_hash], universal_newlines=not is_binary) if retcode: ErrorExit("Got error status from 'git show %s'" % file_hash) return data def GetBaseFile(self, filename): hash_before, hash_after = self.hashes.get(filename, (None,None)) base_content = None new_content = None is_binary = self.IsBinary(filename) status = None if filename in self.renames: status = "A +" # Match svn attribute name for renames. if filename not in self.hashes: # If a rename doesn't change the content, we never get a hash. base_content = RunShell(["git", "show", "HEAD:" + filename]) elif not hash_before: status = "A" base_content = "" elif not hash_after: status = "D" else: status = "M" is_image = self.IsImage(filename) # Grab the before/after content if we need it. # We should include file contents if it's text or it's an image. if not is_binary or is_image: # Grab the base content if we don't have it already. if base_content is None and hash_before: base_content = self.GetFileContent(hash_before, is_binary) # Only include the "after" file if it's an image; otherwise it # it is reconstructed from the diff. if is_image and hash_after: new_content = self.GetFileContent(hash_after, is_binary) return (base_content, new_content, is_binary, status) class MercurialVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Mercurial.""" def __init__(self, options, repo_dir): super(MercurialVCS, self).__init__(options) # Absolute path to repository (we can be in a subdir) self.repo_dir = os.path.normpath(repo_dir) # Compute the subdir cwd = os.path.normpath(os.getcwd()) assert cwd.startswith(self.repo_dir) self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/") if self.options.revision: self.base_rev = self.options.revision else: self.base_rev = RunShell(["hg", "parent", "-q"]).split(':')[1].strip() def _GetRelPath(self, filename): """Get relative path of a file according to the current directory, given its logical path in the repo.""" assert filename.startswith(self.subdir), (filename, self.subdir) return filename[len(self.subdir):].lstrip(r"\/") def GenerateDiff(self, extra_args): # If no file specified, restrict to the current subdir extra_args = extra_args or ["."] cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args data = RunShell(cmd, silent_ok=True) svndiff = [] filecount = 0 for line in data.splitlines(): m = re.match("diff --git a/(\S+) b/(\S+)", line) if m: # Modify line to make it look like as it comes from svn diff. # With this modification no changes on the server side are required # to make upload.py work with Mercurial repos. # NOTE: for proper handling of moved/copied files, we have to use # the second filename. filename = m.group(2) svndiff.append("Index: %s" % filename) svndiff.append("=" * 67) filecount += 1 logging.info(line) else: svndiff.append(line) if not filecount: ErrorExit("No valid patches found in output from hg diff") return "\n".join(svndiff) + "\n" def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" args = [] status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."], silent_ok=True) unknown_files = [] for line in status.splitlines(): st, fn = line.split(" ", 1) if st == "?": unknown_files.append(fn) return unknown_files def GetBaseFile(self, filename): # "hg status" and "hg cat" both take a path relative to the current subdir # rather than to the repo root, but "hg diff" has given us the full path # to the repo root. base_content = "" new_content = None is_binary = False oldrelpath = relpath = self._GetRelPath(filename) # "hg status -C" returns two lines for moved/copied files, one otherwise out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath]) out = out.splitlines() # HACK: strip error message about missing file/directory if it isn't in # the working copy if out[0].startswith('%s: ' % relpath): out = out[1:] if len(out) > 1: # Moved/copied => considered as modified, use old filename to # retrieve base contents oldrelpath = out[1].strip() status = "M" else: status, _ = out[0].split(' ', 1) if ":" in self.base_rev: base_rev = self.base_rev.split(":", 1)[0] else: base_rev = self.base_rev if status != "A": base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath], silent_ok=True) is_binary = "\0" in base_content # Mercurial's heuristic if status != "R": new_content = open(relpath, "rb").read() is_binary = is_binary or "\0" in new_content if is_binary and base_content: # Fetch again without converting newlines base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath], silent_ok=True, universal_newlines=False) if not is_binary or not self.IsImage(relpath): new_content = None return base_content, new_content, is_binary, status # NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync. def SplitPatch(data): """Splits a patch into separate pieces for each file. Args: data: A string containing the output of svn diff. Returns: A list of 2-tuple (filename, text) where text is the svn diff output pertaining to filename. """ patches = [] filename = None diff = [] for line in data.splitlines(True): new_filename = None if line.startswith('Index:'): unused, new_filename = line.split(':', 1) new_filename = new_filename.strip() elif line.startswith('Property changes on:'): unused, temp_filename = line.split(':', 1) # When a file is modified, paths use '/' between directories, however # when a property is modified '\' is used on Windows. Make them the same # otherwise the file shows up twice. temp_filename = temp_filename.strip().replace('\\', '/') if temp_filename != filename: # File has property changes but no modifications, create a new diff. new_filename = temp_filename if new_filename: if filename and diff: patches.append((filename, ''.join(diff))) filename = new_filename diff = [line] continue if diff is not None: diff.append(line) if filename and diff: patches.append((filename, ''.join(diff))) return patches def UploadSeparatePatches(issue, rpc_server, patchset, data, options): """Uploads a separate patch for each file in the diff output. Returns a list of [patch_key, filename] for each file. """ patches = SplitPatch(data) rv = [] for patch in patches: if len(patch[1]) > MAX_UPLOAD_SIZE: print ("Not uploading the patch for " + patch[0] + " because the file is too large.") continue form_fields = [("filename", patch[0])] if not options.download_base: form_fields.append(("content_upload", "1")) files = [("data", "data.diff", patch[1])] ctype, body = EncodeMultipartFormData(form_fields, files) url = "/%d/upload_patch/%d" % (int(issue), int(patchset)) print "Uploading patch for " + patch[0] response_body = rpc_server.Send(url, body, content_type=ctype) lines = response_body.splitlines() if not lines or lines[0] != "OK": StatusUpdate(" --> %s" % response_body) sys.exit(1) rv.append([lines[1], patch[0]]) return rv def GuessVCSName(): """Helper to guess the version control system. This examines the current directory, guesses which VersionControlSystem we're using, and returns an string indicating which VCS is detected. Returns: A pair (vcs, output). vcs is a string indicating which VCS was detected and is one of VCS_GIT, VCS_MERCURIAL, VCS_SUBVERSION, or VCS_UNKNOWN. output is a string containing any interesting output from the vcs detection routine, or None if there is nothing interesting. """ # Mercurial has a command to get the base directory of a repository # Try running it, but don't die if we don't have hg installed. # NOTE: we try Mercurial first as it can sit on top of an SVN working copy. try: out, returncode = RunShellWithReturnCode(["hg", "root"]) if returncode == 0: return (VCS_MERCURIAL, out.strip()) except OSError, (errno, message): if errno != 2: # ENOENT -- they don't have hg installed. raise # Subversion has a .svn in all working directories. if os.path.isdir('.svn'): logging.info("Guessed VCS = Subversion") return (VCS_SUBVERSION, None) # Git has a command to test if you're in a git tree. # Try running it, but don't die if we don't have git installed. try: out, returncode = RunShellWithReturnCode(["git", "rev-parse", "--is-inside-work-tree"]) if returncode == 0: return (VCS_GIT, None) except OSError, (errno, message): if errno != 2: # ENOENT -- they don't have git installed. raise return (VCS_UNKNOWN, None) def GuessVCS(options): """Helper to guess the version control system. This verifies any user-specified VersionControlSystem (by command line or environment variable). If the user didn't specify one, this examines the current directory, guesses which VersionControlSystem we're using, and returns an instance of the appropriate class. Exit with an error if we can't figure it out. Returns: A VersionControlSystem instance. Exits if the VCS can't be guessed. """ vcs = options.vcs if not vcs: vcs = os.environ.get("CODEREVIEW_VCS") if vcs: v = VCS_ABBREVIATIONS.get(vcs.lower()) if v is None: ErrorExit("Unknown version control system %r specified." % vcs) (vcs, extra_output) = (v, None) else: (vcs, extra_output) = GuessVCSName() if vcs == VCS_MERCURIAL: if extra_output is None: extra_output = RunShell(["hg", "root"]).strip() return MercurialVCS(options, extra_output) elif vcs == VCS_SUBVERSION: return SubversionVCS(options) elif vcs == VCS_GIT: return GitVCS(options) ErrorExit(("Could not guess version control system. " "Are you in a working copy directory?")) def CheckReviewer(reviewer): """Validate a reviewer -- either a nickname or an email addres. Args: reviewer: A nickname or an email address. Calls ErrorExit() if it is an invalid email address. """ if "@" not in reviewer: return # Assume nickname parts = reviewer.split("@") if len(parts) > 2: ErrorExit("Invalid email address: %r" % reviewer) assert len(parts) == 2 if "." not in parts[1]: ErrorExit("Invalid email address: %r" % reviewer) def LoadSubversionAutoProperties(): """Returns the content of [auto-props] section of Subversion's config file as a dictionary. Returns: A dictionary whose key-value pair corresponds the [auto-props] section's key-value pair. In following cases, returns empty dictionary: - config file doesn't exist, or - 'enable-auto-props' is not set to 'true-like-value' in [miscellany]. """ # Todo(hayato): Windows users might use different path for configuration file. subversion_config = os.path.expanduser("~/.subversion/config") if not os.path.exists(subversion_config): return {} config = ConfigParser.ConfigParser() config.read(subversion_config) if (config.has_section("miscellany") and config.has_option("miscellany", "enable-auto-props") and config.getboolean("miscellany", "enable-auto-props") and config.has_section("auto-props")): props = {} for file_pattern in config.options("auto-props"): props[file_pattern] = ParseSubversionPropertyValues( config.get("auto-props", file_pattern)) return props else: return {} def ParseSubversionPropertyValues(props): """Parse the given property value which comes from [auto-props] section and returns a list whose element is a (svn_prop_key, svn_prop_value) pair. See the following doctest for example. >>> ParseSubversionPropertyValues('svn:eol-style=LF') [('svn:eol-style', 'LF')] >>> ParseSubversionPropertyValues('svn:mime-type=image/jpeg') [('svn:mime-type', 'image/jpeg')] >>> ParseSubversionPropertyValues('svn:eol-style=LF;svn:executable') [('svn:eol-style', 'LF'), ('svn:executable', '*')] """ key_value_pairs = [] for prop in props.split(";"): key_value = prop.split("=") assert len(key_value) <= 2 if len(key_value) == 1: # If value is not given, use '*' as a Subversion's convention. key_value_pairs.append((key_value[0], "*")) else: key_value_pairs.append((key_value[0], key_value[1])) return key_value_pairs def GetSubversionPropertyChanges(filename): """Return a Subversion's 'Property changes on ...' string, which is used in the patch file. Args: filename: filename whose property might be set by [auto-props] config. Returns: A string like 'Property changes on |filename| ...' if given |filename| matches any entries in [auto-props] section. None, otherwise. """ global svn_auto_props_map if svn_auto_props_map is None: svn_auto_props_map = LoadSubversionAutoProperties() all_props = [] for file_pattern, props in svn_auto_props_map.items(): if fnmatch.fnmatch(filename, file_pattern): all_props.extend(props) if all_props: return FormatSubversionPropertyChanges(filename, all_props) return None def FormatSubversionPropertyChanges(filename, props): """Returns Subversion's 'Property changes on ...' strings using given filename and properties. Args: filename: filename props: A list whose element is a (svn_prop_key, svn_prop_value) pair. Returns: A string which can be used in the patch file for Subversion. See the following doctest for example. >>> print FormatSubversionPropertyChanges('foo.cc', [('svn:eol-style', 'LF')]) Property changes on: foo.cc ___________________________________________________________________ Added: svn:eol-style + LF <BLANKLINE> """ prop_changes_lines = [ "Property changes on: %s" % filename, "___________________________________________________________________"] for key, value in props: prop_changes_lines.append("Added: " + key) prop_changes_lines.append(" + " + value) return "\n".join(prop_changes_lines) + "\n" def RealMain(argv, data=None): """The real main function. Args: argv: Command line arguments. data: Diff contents. If None (default) the diff is generated by the VersionControlSystem implementation returned by GuessVCS(). Returns: A 2-tuple (issue id, patchset id). The patchset id is None if the base files are not uploaded by this script (applies only to SVN checkouts). """ logging.basicConfig(format=("%(asctime).19s %(levelname)s %(filename)s:" "%(lineno)s %(message)s ")) os.environ['LC_ALL'] = 'C' options, args = parser.parse_args(argv[1:]) global verbosity verbosity = options.verbose if verbosity >= 3: logging.getLogger().setLevel(logging.DEBUG) elif verbosity >= 2: logging.getLogger().setLevel(logging.INFO) vcs = GuessVCS(options) base = options.base_url if isinstance(vcs, SubversionVCS): # Guessing the base field is only supported for Subversion. # Note: Fetching base files may become deprecated in future releases. guessed_base = vcs.GuessBase(options.download_base) if base: if guessed_base and base != guessed_base: print "Using base URL \"%s\" from --base_url instead of \"%s\"" % \ (base, guessed_base) else: base = guessed_base if not base and options.download_base: options.download_base = True logging.info("Enabled upload of base file") if not options.assume_yes: vcs.CheckForUnknownFiles() if data is None: data = vcs.GenerateDiff(args) files = vcs.GetBaseFiles(data) if verbosity >= 1: print "Upload server:", options.server, "(change with -s/--server)" if options.issue: prompt = "Message describing this patch set: " else: prompt = "New issue subject: " message = options.message or raw_input(prompt).strip() if not message: ErrorExit("A non-empty message is required") rpc_server = GetRpcServer(options) form_fields = [("subject", message)] if base: form_fields.append(("base", base)) if options.issue: form_fields.append(("issue", str(options.issue))) if options.email: form_fields.append(("user", options.email)) if options.reviewers: for reviewer in options.reviewers.split(','): CheckReviewer(reviewer) form_fields.append(("reviewers", options.reviewers)) if options.cc: for cc in options.cc.split(','): CheckReviewer(cc) form_fields.append(("cc", options.cc)) description = options.description if options.description_file: if options.description: ErrorExit("Can't specify description and description_file") file = open(options.description_file, 'r') description = file.read() file.close() if description: form_fields.append(("description", description)) # Send a hash of all the base file so the server can determine if a copy # already exists in an earlier patchset. base_hashes = "" for file, info in files.iteritems(): if not info[0] is None: checksum = md5(info[0]).hexdigest() if base_hashes: base_hashes += "|" base_hashes += checksum + ":" + file form_fields.append(("base_hashes", base_hashes)) if options.private: if options.issue: print "Warning: Private flag ignored when updating an existing issue." else: form_fields.append(("private", "1")) # If we're uploading base files, don't send the email before the uploads, so # that it contains the file status. if options.send_mail and options.download_base: form_fields.append(("send_mail", "1")) if not options.download_base: form_fields.append(("content_upload", "1")) if len(data) > MAX_UPLOAD_SIZE: print "Patch is large, so uploading file patches separately." uploaded_diff_file = [] form_fields.append(("separate_patches", "1")) else: uploaded_diff_file = [("data", "data.diff", data)] ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file) response_body = rpc_server.Send("/upload", body, content_type=ctype) patchset = None if not options.download_base or not uploaded_diff_file: lines = response_body.splitlines() if len(lines) >= 2: msg = lines[0] patchset = lines[1].strip() patches = [x.split(" ", 1) for x in lines[2:]] else: msg = response_body else: msg = response_body StatusUpdate(msg) if not response_body.startswith("Issue created.") and \ not response_body.startswith("Issue updated."): sys.exit(0) issue = msg[msg.rfind("/")+1:] if not uploaded_diff_file: result = UploadSeparatePatches(issue, rpc_server, patchset, data, options) if not options.download_base: patches = result if not options.download_base: vcs.UploadBaseFiles(issue, rpc_server, patches, patchset, options, files) if options.send_mail: rpc_server.Send("/" + issue + "/mail", payload="") return issue, patchset def main(): try: RealMain(sys.argv) except KeyboardInterrupt: print StatusUpdate("Interrupted.") sys.exit(1) if __name__ == "__main__": main()
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. import sys from distutils.core import setup required = [] if sys.version_info[:3] < (2, 5, 0): required.append('elementtree') setup( name='gdata', version='2.0.14', description='Python client library for Google data APIs', long_description = """\ The Google data Python client library makes it easy to interact with Google services through the Google Data APIs. This library provides data models and service modules for the the following Google data services: - Google Calendar data API - Google Contacts data API - Google Spreadsheets data API - Google Document List data APIs - Google Base data API - Google Apps Provisioning API - Google Apps Email Migration API - Google Apps Email Settings API - Picasa Web Albums Data API - Google Code Search Data API - YouTube Data API - Google Webmaster Tools Data API - Blogger Data API - Google Health API - Google Book Search API - Google Analytics API - Google Finance API - Google Sites Data API - Google Content API For Shopping - Google App Marketplace API - core Google data API functionality The core Google data code provides sufficient functionality to use this library with any Google data API (even if a module hasn't been written for it yet). For example, this client can be used with the Notebook API. This library may also be used with any Atom Publishing Protocol service (AtomPub). """, author='Jeffrey Scudder', author_email='j.s@google.com', license='Apache 2.0', url='http://code.google.com/p/gdata-python-client/', packages=[ 'atom', 'gdata', 'gdata.Crypto', 'gdata.Crypto.Cipher', 'gdata.Crypto.Hash', 'gdata.Crypto.Protocol', 'gdata.Crypto.PublicKey', 'gdata.Crypto.Util', 'gdata.acl', 'gdata.alt', 'gdata.analytics', 'gdata.apps', 'gdata.apps.adminsettings', 'gdata.apps.audit', 'gdata.apps.emailsettings', 'gdata.apps.groups', 'gdata.apps.migration', 'gdata.apps.organization', 'gdata.base', 'gdata.blogger', 'gdata.books', 'gdata.calendar', 'gdata.calendar_resource', 'gdata.codesearch', 'gdata.contacts', 'gdata.docs', 'gdata.dublincore', 'gdata.exif', 'gdata.finance', 'gdata.geo', 'gdata.health', 'gdata.media', 'gdata.notebook', 'gdata.oauth', 'gdata.opensearch', 'gdata.photos', 'gdata.projecthosting', 'gdata.sites', 'gdata.spreadsheet', 'gdata.spreadsheets', 'gdata.tlslite', 'gdata.tlslite.integration', 'gdata.tlslite.utils', 'gdata.webmastertools', 'gdata.youtube', ], package_dir = {'gdata':'src/gdata', 'atom':'src/atom'}, install_requires=required )
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. """Classes to interact with the Blogger server.""" __author__ = 'api.jscudder (Jeffrey Scudder)' import gdata.service import gdata.blogger class BloggerService(gdata.service.GDataService): def __init__(self, email=None, password=None, source=None, server='www.blogger.com', **kwargs): """Creates a client for the Blogger 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.blogger.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='blogger', source=source, server=server, **kwargs) def GetBlogFeed(self, uri=None): """Retrieve a list of the blogs to which the current user may manage.""" if not uri: uri = '/feeds/default/blogs' return self.Get(uri, converter=gdata.blogger.BlogFeedFromString) def GetBlogCommentFeed(self, blog_id=None, uri=None): """Retrieve a list of the comments for this blog.""" if blog_id: uri = '/feeds/%s/comments/default' % blog_id return self.Get(uri, converter=gdata.blogger.CommentFeedFromString) def GetBlogPostFeed(self, blog_id=None, uri=None): if blog_id: uri = '/feeds/%s/posts/default' % blog_id return self.Get(uri, converter=gdata.blogger.BlogPostFeedFromString) def GetPostCommentFeed(self, blog_id=None, post_id=None, uri=None): """Retrieve a list of the comments for this particular blog post.""" if blog_id and post_id: uri = '/feeds/%s/%s/comments/default' % (blog_id, post_id) return self.Get(uri, converter=gdata.blogger.CommentFeedFromString) def AddPost(self, entry, blog_id=None, uri=None): if blog_id: uri = '/feeds/%s/posts/default' % blog_id return self.Post(entry, uri, converter=gdata.blogger.BlogPostEntryFromString) def UpdatePost(self, entry, uri=None): if not uri: uri = entry.GetEditLink().href return self.Put(entry, uri, converter=gdata.blogger.BlogPostEntryFromString) def DeletePost(self, entry=None, uri=None): if not uri: uri = entry.GetEditLink().href return self.Delete(uri) def AddComment(self, comment_entry, blog_id=None, post_id=None, uri=None): """Adds a new comment to the specified blog post.""" if blog_id and post_id: uri = '/feeds/%s/%s/comments/default' % (blog_id, post_id) return self.Post(comment_entry, uri, converter=gdata.blogger.CommentEntryFromString) def DeleteComment(self, entry=None, uri=None): if not uri: uri = entry.GetEditLink().href return self.Delete(uri) class BlogQuery(gdata.service.Query): def __init__(self, feed=None, params=None, categories=None, blog_id=None): """Constructs a query object for the list of a user's Blogger blogs. Args: feed: str (optional) The beginning of the URL to be queried. If the feed is not set, and there is no blog_id passed in, the default value is used ('/feeds/default/blogs'). params: dict (optional) categories: list (optional) blog_id: str (optional) """ if not feed and blog_id: feed = '/feeds/default/blogs/%s' % blog_id elif not feed: feed = '/feeds/default/blogs' gdata.service.Query.__init__(self, feed=feed, params=params, categories=categories) class BlogPostQuery(gdata.service.Query): def __init__(self, feed=None, params=None, categories=None, blog_id=None, post_id=None): if not feed and blog_id and post_id: feed = '/feeds/%s/posts/default/%s' % (blog_id, post_id) elif not feed and blog_id: feed = '/feeds/%s/posts/default' % blog_id gdata.service.Query.__init__(self, feed=feed, params=params, categories=categories) class BlogCommentQuery(gdata.service.Query): def __init__(self, feed=None, params=None, categories=None, blog_id=None, post_id=None, comment_id=None): if not feed and blog_id and comment_id: feed = '/feeds/%s/comments/default/%s' % (blog_id, comment_id) elif not feed and blog_id and post_id: feed = '/feeds/%s/%s/comments/default' % (blog_id, post_id) elif not feed and blog_id: feed = '/feeds/%s/comments/default' % blog_id gdata.service.Query.__init__(self, feed=feed, 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. """Contains a client to communicate with the Blogger servers. For documentation on the Blogger API, see: http://code.google.com/apis/blogger/ """ __author__ = 'j.s@google.com (Jeff Scudder)' import gdata.client import gdata.gauth import gdata.blogger.data import atom.data import atom.http_core # List user's blogs, takes a user ID, or 'default'. BLOGS_URL = 'http://www.blogger.com/feeds/%s/blogs' # Takes a blog ID. BLOG_POST_URL = 'http://www.blogger.com/feeds/%s/posts/default' # Takes a blog ID. BLOG_PAGE_URL = 'http://www.blogger.com/feeds/%s/pages/default' # Takes a blog ID and post ID. BLOG_POST_COMMENTS_URL = 'http://www.blogger.com/feeds/%s/%s/comments/default' # Takes a blog ID. BLOG_COMMENTS_URL = 'http://www.blogger.com/feeds/%s/comments/default' # Takes a blog ID. BLOG_ARCHIVE_URL = 'http://www.blogger.com/feeds/%s/archive/full' class BloggerClient(gdata.client.GDClient): api_version = '2' auth_service = 'blogger' auth_scopes = gdata.gauth.AUTH_SCOPES['blogger'] def get_blogs(self, user_id='default', auth_token=None, desired_class=gdata.blogger.data.BlogFeed, **kwargs): return self.get_feed(BLOGS_URL % user_id, auth_token=auth_token, desired_class=desired_class, **kwargs) GetBlogs = get_blogs def get_posts(self, blog_id, auth_token=None, desired_class=gdata.blogger.data.BlogPostFeed, query=None, **kwargs): return self.get_feed(BLOG_POST_URL % blog_id, auth_token=auth_token, desired_class=desired_class, query=query, **kwargs) GetPosts = get_posts def get_pages(self, blog_id, auth_token=None, desired_class=gdata.blogger.data.BlogPageFeed, query=None, **kwargs): return self.get_feed(BLOG_PAGE_URL % blog_id, auth_token=auth_token, desired_class=desired_class, query=query, **kwargs) GetPages = get_pages def get_post_comments(self, blog_id, post_id, auth_token=None, desired_class=gdata.blogger.data.CommentFeed, query=None, **kwargs): return self.get_feed(BLOG_POST_COMMENTS_URL % (blog_id, post_id), auth_token=auth_token, desired_class=desired_class, query=query, **kwargs) GetPostComments = get_post_comments def get_blog_comments(self, blog_id, auth_token=None, desired_class=gdata.blogger.data.CommentFeed, query=None, **kwargs): return self.get_feed(BLOG_COMMENTS_URL % blog_id, auth_token=auth_token, desired_class=desired_class, query=query, **kwargs) GetBlogComments = get_blog_comments def get_blog_archive(self, blog_id, auth_token=None, **kwargs): return self.get_feed(BLOG_ARCHIVE_URL % blog_id, auth_token=auth_token, **kwargs) GetBlogArchive = get_blog_archive def add_post(self, blog_id, title, body, labels=None, draft=False, auth_token=None, title_type='text', body_type='html', **kwargs): # Construct an atom Entry for the blog post to be sent to the server. new_entry = gdata.blogger.data.BlogPost( title=atom.data.Title(text=title, type=title_type), content=atom.data.Content(text=body, type=body_type)) if labels: for label in labels: new_entry.add_label(label) if draft: new_entry.control = atom.data.Control(draft=atom.data.Draft(text='yes')) return self.post(new_entry, BLOG_POST_URL % blog_id, auth_token=auth_token, **kwargs) AddPost = add_post def add_page(self, blog_id, title, body, draft=False, auth_token=None, title_type='text', body_type='html', **kwargs): new_entry = gdata.blogger.data.BlogPage( title=atom.data.Title(text=title, type=title_type), content=atom.data.Content(text=body, type=body_type)) if draft: new_entry.control = atom.data.Control(draft=atom.data.Draft(text='yes')) return self.post(new_entry, BLOG_PAGE_URL % blog_id, auth_token=auth_token, **kwargs) AddPage = add_page def add_comment(self, blog_id, post_id, body, auth_token=None, title_type='text', body_type='html', **kwargs): new_entry = gdata.blogger.data.Comment( content=atom.data.Content(text=body, type=body_type)) return self.post(new_entry, BLOG_POST_COMMENTS_URL % (blog_id, post_id), auth_token=auth_token, **kwargs) AddComment = add_comment def update(self, entry, auth_token=None, **kwargs): # The Blogger API does not currently support ETags, so for now remove # the ETag before performing an update. old_etag = entry.etag entry.etag = None response = gdata.client.GDClient.update(self, entry, auth_token=auth_token, **kwargs) entry.etag = old_etag return response Update = update def delete(self, entry_or_uri, auth_token=None, **kwargs): if isinstance(entry_or_uri, (str, unicode, atom.http_core.Uri)): return gdata.client.GDClient.delete(self, entry_or_uri, auth_token=auth_token, **kwargs) # The Blogger API does not currently support ETags, so for now remove # the ETag before performing a delete. old_etag = entry_or_uri.etag entry_or_uri.etag = None response = gdata.client.GDClient.delete(self, entry_or_uri, auth_token=auth_token, **kwargs) # TODO: if GDClient.delete raises and exception, the entry's etag may be # left as None. Should revisit this logic. entry_or_uri.etag = old_etag return response Delete = delete class Query(gdata.client.Query): def __init__(self, order_by=None, **kwargs): gdata.client.Query.__init__(self, **kwargs) self.order_by = order_by def modify_request(self, http_request): gdata.client._add_query_param('orderby', self.order_by, http_request) gdata.client.Query.modify_request(self, http_request) ModifyRequest = modify_request
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 Blogger API.""" __author__ = 'j.s@google.com (Jeff Scudder)' import re import urlparse import atom.core import gdata.data LABEL_SCHEME = 'http://www.blogger.com/atom/ns#' THR_TEMPLATE = '{http://purl.org/syndication/thread/1.0}%s' BLOG_NAME_PATTERN = re.compile('(http://)(\w*)') BLOG_ID_PATTERN = re.compile('(tag:blogger.com,1999:blog-)(\w*)') BLOG_ID2_PATTERN = re.compile('tag:blogger.com,1999:user-(\d+)\.blog-(\d+)') POST_ID_PATTERN = re.compile( '(tag:blogger.com,1999:blog-)(\w*)(.post-)(\w*)') PAGE_ID_PATTERN = re.compile( '(tag:blogger.com,1999:blog-)(\w*)(.page-)(\w*)') COMMENT_ID_PATTERN = re.compile('.*-(\w*)$') class BloggerEntry(gdata.data.GDEntry): """Adds convenience methods inherited by all Blogger entries.""" def get_blog_id(self): """Extracts the Blogger id of this blog. This method is useful when contructing URLs by hand. The blog id is often used in blogger operation URLs. This should not be confused with the id member of a BloggerBlog. The id element is the Atom id XML element. The blog id which this method returns is a part of the Atom id. Returns: The blog's unique id as a string. """ if self.id.text: match = BLOG_ID_PATTERN.match(self.id.text) if match: return match.group(2) else: return BLOG_ID2_PATTERN.match(self.id.text).group(2) return None GetBlogId = get_blog_id def get_blog_name(self): """Finds the name of this blog as used in the 'alternate' URL. An alternate URL is in the form 'http://blogName.blogspot.com/'. For an entry representing the above example, this method would return 'blogName'. Returns: The blog's URL name component as a string. """ for link in self.link: if link.rel == 'alternate': return urlparse.urlparse(link.href)[1].split(".", 1)[0] return None GetBlogName = get_blog_name class Blog(BloggerEntry): """Represents a blog which belongs to the user.""" class BlogFeed(gdata.data.GDFeed): entry = [Blog] class BlogPost(BloggerEntry): """Represents a single post on a blog.""" def add_label(self, label): """Adds a label to the blog post. The label is represented by an Atom category element, so this method is shorthand for appending a new atom.Category object. Args: label: str """ self.category.append(atom.data.Category(scheme=LABEL_SCHEME, term=label)) AddLabel = add_label def get_post_id(self): """Extracts the postID string from the entry's Atom id. Returns: A string of digits which identify this post within the blog. """ if self.id.text: return POST_ID_PATTERN.match(self.id.text).group(4) return None GetPostId = get_post_id class BlogPostFeed(gdata.data.GDFeed): entry = [BlogPost] class BlogPage(BloggerEntry): """Represents a single page on a blog.""" def get_page_id(self): """Extracts the pageID string from entry's Atom id. Returns: A string of digits which identify this post within the blog. """ if self.id.text: return PAGE_ID_PATTERN.match(self.id.text).group(4) return None GetPageId = get_page_id class BlogPageFeed(gdata.data.GDFeed): entry = [BlogPage] class InReplyTo(atom.core.XmlElement): _qname = THR_TEMPLATE % 'in-reply-to' href = 'href' ref = 'ref' source = 'source' type = 'type' class Comment(BloggerEntry): """Blog post comment entry in a feed listing comments on a post or blog.""" in_reply_to = InReplyTo def get_comment_id(self): """Extracts the commentID string from the entry's Atom id. Returns: A string of digits which identify this post within the blog. """ if self.id.text: return COMMENT_ID_PATTERN.match(self.id.text).group(1) return None GetCommentId = get_comment_id class CommentFeed(gdata.data.GDFeed): entry = [Comment]
Python
#!/usr/bin/python # # Copyright (C) 2007, 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. """Contains extensions to Atom objects used with Blogger.""" __author__ = 'api.jscudder (Jeffrey Scudder)' import atom import gdata import re LABEL_SCHEME = 'http://www.blogger.com/atom/ns#' THR_NAMESPACE = 'http://purl.org/syndication/thread/1.0' class BloggerEntry(gdata.GDataEntry): """Adds convenience methods inherited by all Blogger entries.""" blog_name_pattern = re.compile('(http://)(\w*)') blog_id_pattern = re.compile('(tag:blogger.com,1999:blog-)(\w*)') blog_id2_pattern = re.compile('tag:blogger.com,1999:user-(\d+)\.blog-(\d+)') def GetBlogId(self): """Extracts the Blogger id of this blog. This method is useful when contructing URLs by hand. The blog id is often used in blogger operation URLs. This should not be confused with the id member of a BloggerBlog. The id element is the Atom id XML element. The blog id which this method returns is a part of the Atom id. Returns: The blog's unique id as a string. """ if self.id.text: match = self.blog_id_pattern.match(self.id.text) if match: return match.group(2) else: return self.blog_id2_pattern.match(self.id.text).group(2) return None def GetBlogName(self): """Finds the name of this blog as used in the 'alternate' URL. An alternate URL is in the form 'http://blogName.blogspot.com/'. For an entry representing the above example, this method would return 'blogName'. Returns: The blog's URL name component as a string. """ for link in self.link: if link.rel == 'alternate': return self.blog_name_pattern.match(link.href).group(2) return None class BlogEntry(BloggerEntry): """Describes a blog entry in the feed listing a user's blogs.""" def BlogEntryFromString(xml_string): return atom.CreateClassFromXMLString(BlogEntry, xml_string) class BlogFeed(gdata.GDataFeed): """Describes a feed of a user's blogs.""" _children = gdata.GDataFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BlogEntry]) def BlogFeedFromString(xml_string): return atom.CreateClassFromXMLString(BlogFeed, xml_string) class BlogPostEntry(BloggerEntry): """Describes a blog post entry in the feed of a blog's posts.""" post_id_pattern = re.compile('(tag:blogger.com,1999:blog-)(\w*)(.post-)(\w*)') def AddLabel(self, label): """Adds a label to the blog post. The label is represented by an Atom category element, so this method is shorthand for appending a new atom.Category object. Args: label: str """ self.category.append(atom.Category(scheme=LABEL_SCHEME, term=label)) def GetPostId(self): """Extracts the postID string from the entry's Atom id. Returns: A string of digits which identify this post within the blog. """ if self.id.text: return self.post_id_pattern.match(self.id.text).group(4) return None def BlogPostEntryFromString(xml_string): return atom.CreateClassFromXMLString(BlogPostEntry, xml_string) class BlogPostFeed(gdata.GDataFeed): """Describes a feed of a blog's posts.""" _children = gdata.GDataFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BlogPostEntry]) def BlogPostFeedFromString(xml_string): return atom.CreateClassFromXMLString(BlogPostFeed, xml_string) class InReplyTo(atom.AtomBase): _tag = 'in-reply-to' _namespace = THR_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['href'] = 'href' _attributes['ref'] = 'ref' _attributes['source'] = 'source' _attributes['type'] = 'type' def __init__(self, href=None, ref=None, source=None, type=None, extension_elements=None, extension_attributes=None, text=None): self.href = href self.ref = ref self.source = source self.type = type self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text def InReplyToFromString(xml_string): return atom.CreateClassFromXMLString(InReplyTo, xml_string) class CommentEntry(BloggerEntry): """Describes a blog post comment entry in the feed of a blog post's comments.""" _children = BloggerEntry._children.copy() _children['{%s}in-reply-to' % THR_NAMESPACE] = ('in_reply_to', InReplyTo) comment_id_pattern = re.compile('.*-(\w*)$') 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, in_reply_to=None, extension_elements=None, extension_attributes=None, text=None): BloggerEntry.__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) self.in_reply_to = in_reply_to def GetCommentId(self): """Extracts the commentID string from the entry's Atom id. Returns: A string of digits which identify this post within the blog. """ if self.id.text: return self.comment_id_pattern.match(self.id.text).group(1) return None def CommentEntryFromString(xml_string): return atom.CreateClassFromXMLString(CommentEntry, xml_string) class CommentFeed(gdata.GDataFeed): """Describes a feed of a blog post's comments.""" _children = gdata.GDataFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CommentEntry]) def CommentFeedFromString(xml_string): return atom.CreateClassFromXMLString(CommentFeed, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 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. """Allow Google Apps domain administrators to manage groups, group members and group owners. GroupsService: Provides methods to manage groups, members and owners. """ __author__ = 'google-apps-apis@googlegroups.com' import urllib import gdata.apps import gdata.apps.service import gdata.service API_VER = '2.0' BASE_URL = '/a/feeds/group/' + API_VER + '/%s' GROUP_MEMBER_URL = BASE_URL + '?member=%s' GROUP_MEMBER_DIRECT_URL = GROUP_MEMBER_URL + '&directOnly=%s' GROUP_ID_URL = BASE_URL + '/%s' MEMBER_URL = BASE_URL + '/%s/member' MEMBER_WITH_SUSPENDED_URL = MEMBER_URL + '?includeSuspendedUsers=%s' MEMBER_ID_URL = MEMBER_URL + '/%s' OWNER_URL = BASE_URL + '/%s/owner' OWNER_WITH_SUSPENDED_URL = OWNER_URL + '?includeSuspendedUsers=%s' OWNER_ID_URL = OWNER_URL + '/%s' PERMISSION_OWNER = 'Owner' PERMISSION_MEMBER = 'Member' PERMISSION_DOMAIN = 'Domain' PERMISSION_ANYONE = 'Anyone' class GroupsService(gdata.apps.service.PropertyService): """Client for the Google Apps Groups service.""" def _ServiceUrl(self, service_type, is_existed, group_id, member_id, owner_email, direct_only=False, domain=None, suspended_users=False): if domain is None: domain = self.domain if service_type == 'group': if group_id != '' and is_existed: return GROUP_ID_URL % (domain, group_id) elif member_id != '': if direct_only: return GROUP_MEMBER_DIRECT_URL % (domain, urllib.quote_plus(member_id), self._Bool2Str(direct_only)) else: return GROUP_MEMBER_URL % (domain, urllib.quote_plus(member_id)) else: return BASE_URL % (domain) if service_type == 'member': if member_id != '' and is_existed: return MEMBER_ID_URL % (domain, group_id, urllib.quote_plus(member_id)) elif suspended_users: return MEMBER_WITH_SUSPENDED_URL % (domain, group_id, self._Bool2Str(suspended_users)) else: return MEMBER_URL % (domain, group_id) if service_type == 'owner': if owner_email != '' and is_existed: return OWNER_ID_URL % (domain, group_id, urllib.quote_plus(owner_email)) elif suspended_users: return OWNER_WITH_SUSPENDED_URL % (domain, group_id, self._Bool2Str(suspended_users)) else: return OWNER_URL % (domain, group_id) def _Bool2Str(self, b): if b is None: return None return str(b is True).lower() def _IsExisted(self, uri): try: self._GetProperties(uri) return True except gdata.apps.service.AppsForYourDomainException, e: if e.error_code == gdata.apps.service.ENTITY_DOES_NOT_EXIST: return False else: raise e def CreateGroup(self, group_id, group_name, description, email_permission): """Create a group. Args: group_id: The ID of the group (e.g. us-sales). group_name: The name of the group. description: A description of the group email_permission: The subscription permission of the group. Returns: A dict containing the result of the create operation. """ uri = self._ServiceUrl('group', False, group_id, '', '') properties = {} properties['groupId'] = group_id properties['groupName'] = group_name properties['description'] = description properties['emailPermission'] = email_permission return self._PostProperties(uri, properties) def UpdateGroup(self, group_id, group_name, description, email_permission): """Update a group's name, description and/or permission. Args: group_id: The ID of the group (e.g. us-sales). group_name: The name of the group. description: A description of the group email_permission: The subscription permission of the group. Returns: A dict containing the result of the update operation. """ uri = self._ServiceUrl('group', True, group_id, '', '') properties = {} properties['groupId'] = group_id properties['groupName'] = group_name properties['description'] = description properties['emailPermission'] = email_permission return self._PutProperties(uri, properties) def RetrieveGroup(self, group_id): """Retrieve a group based on its ID. Args: group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the retrieve operation. """ uri = self._ServiceUrl('group', True, group_id, '', '') return self._GetProperties(uri) def RetrieveAllGroups(self): """Retrieve all groups in the domain. Args: None Returns: A list containing the result of the retrieve operation. """ uri = self._ServiceUrl('group', True, '', '', '') return self._GetPropertiesList(uri) def RetrievePageOfGroups(self, start_group=None): """Retrieve one page of groups in the domain. Args: start_group: The key to continue for pagination through all groups. Returns: A feed object containing the result of the retrieve operation. """ uri = self._ServiceUrl('group', True, '', '', '') if start_group is not None: uri += "?start="+start_group property_feed = self._GetPropertyFeed(uri) return property_feed def RetrieveGroups(self, member_id, direct_only=False): """Retrieve all groups that belong to the given member_id. Args: member_id: The member's email address (e.g. member@example.com). direct_only: Boolean whether only return groups that this member directly belongs to. Returns: A list containing the result of the retrieve operation. """ uri = self._ServiceUrl('group', True, '', member_id, '', direct_only=direct_only) return self._GetPropertiesList(uri) def DeleteGroup(self, group_id): """Delete a group based on its ID. Args: group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the delete operation. """ uri = self._ServiceUrl('group', True, group_id, '', '') return self._DeleteProperties(uri) def AddMemberToGroup(self, member_id, group_id): """Add a member to a group. Args: member_id: The member's email address (e.g. member@example.com). group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the add operation. """ uri = self._ServiceUrl('member', False, group_id, member_id, '') properties = {} properties['memberId'] = member_id return self._PostProperties(uri, properties) def IsMember(self, member_id, group_id): """Check whether the given member already exists in the given group. Args: member_id: The member's email address (e.g. member@example.com). group_id: The ID of the group (e.g. us-sales). Returns: True if the member exists in the group. False otherwise. """ uri = self._ServiceUrl('member', True, group_id, member_id, '') return self._IsExisted(uri) def RetrieveMember(self, member_id, group_id): """Retrieve the given member in the given group. Args: member_id: The member's email address (e.g. member@example.com). group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the retrieve operation. """ uri = self._ServiceUrl('member', True, group_id, member_id, '') return self._GetProperties(uri) def RetrieveAllMembers(self, group_id, suspended_users=False): """Retrieve all members in the given group. Args: group_id: The ID of the group (e.g. us-sales). suspended_users: A boolean; should we include any suspended users in the membership list returned? Returns: A list containing the result of the retrieve operation. """ uri = self._ServiceUrl('member', True, group_id, '', '', suspended_users=suspended_users) return self._GetPropertiesList(uri) def RetrievePageOfMembers(self, group_id, suspended_users=False, start=None): """Retrieve one page of members of a given group. Args: group_id: The ID of the group (e.g. us-sales). suspended_users: A boolean; should we include any suspended users in the membership list returned? start: The key to continue for pagination through all members. Returns: A feed object containing the result of the retrieve operation. """ uri = self._ServiceUrl('member', True, group_id, '', '', suspended_users=suspended_users) if start is not None: if suspended_users: uri += "&start="+start else: uri += "?start="+start property_feed = self._GetPropertyFeed(uri) return property_feed def RemoveMemberFromGroup(self, member_id, group_id): """Remove the given member from the given group. Args: member_id: The member's email address (e.g. member@example.com). group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the remove operation. """ uri = self._ServiceUrl('member', True, group_id, member_id, '') return self._DeleteProperties(uri) def AddOwnerToGroup(self, owner_email, group_id): """Add an owner to a group. Args: owner_email: The email address of a group owner. group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the add operation. """ uri = self._ServiceUrl('owner', False, group_id, '', owner_email) properties = {} properties['email'] = owner_email return self._PostProperties(uri, properties) def IsOwner(self, owner_email, group_id): """Check whether the given member an owner of the given group. Args: owner_email: The email address of a group owner. group_id: The ID of the group (e.g. us-sales). Returns: True if the member is an owner of the given group. False otherwise. """ uri = self._ServiceUrl('owner', True, group_id, '', owner_email) return self._IsExisted(uri) def RetrieveOwner(self, owner_email, group_id): """Retrieve the given owner in the given group. Args: owner_email: The email address of a group owner. group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the retrieve operation. """ uri = self._ServiceUrl('owner', True, group_id, '', owner_email) return self._GetProperties(uri) def RetrieveAllOwners(self, group_id, suspended_users=False): """Retrieve all owners of the given group. Args: group_id: The ID of the group (e.g. us-sales). suspended_users: A boolean; should we include any suspended users in the ownership list returned? Returns: A list containing the result of the retrieve operation. """ uri = self._ServiceUrl('owner', True, group_id, '', '', suspended_users=suspended_users) return self._GetPropertiesList(uri) def RetrievePageOfOwners(self, group_id, suspended_users=False, start=None): """Retrieve one page of owners of the given group. Args: group_id: The ID of the group (e.g. us-sales). suspended_users: A boolean; should we include any suspended users in the ownership list returned? start: The key to continue for pagination through all owners. Returns: A feed object containing the result of the retrieve operation. """ uri = self._ServiceUrl('owner', True, group_id, '', '', suspended_users=suspended_users) if start is not None: if suspended_users: uri += "&start="+start else: uri += "?start="+start property_feed = self._GetPropertyFeed(uri) return property_feed def RemoveOwnerFromGroup(self, owner_email, group_id): """Remove the given owner from the given group. Args: owner_email: The email address of a group owner. group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the remove operation. """ uri = self._ServiceUrl('owner', True, group_id, '', owner_email) return self._DeleteProperties(uri)
Python
#!/usr/bin/python # # Copyright (C) 2008 Google. # # 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 methods to import mail via Google Apps Email Migration API. MigrationService: Provides methids to import mail. """ __author__ = 'google-apps-apis@googlegroups.com' import base64 import gdata import gdata.apps.service import gdata.service from gdata.apps import migration API_VER = '2.0' class MigrationService(gdata.apps.service.AppsService): """Client for the EMAPI migration service. Use either ImportMail to import one message at a time, or AddBatchEntry and SubmitBatch to import a batch of messages at a time. """ def __init__(self, email=None, password=None, domain=None, source=None, server='apps-apis.google.com', additional_headers=None): gdata.apps.service.AppsService.__init__( self, email=email, password=password, domain=domain, source=source, server=server, additional_headers=additional_headers) self.mail_batch = migration.BatchMailEventFeed() def _BaseURL(self): return '/a/feeds/migration/%s/%s' % (API_VER, self.domain) def ImportMail(self, user_name, mail_message, mail_item_properties, mail_labels): """Import a single mail message. Args: user_name: The username to import messages to. mail_message: An RFC822 format email message. mail_item_properties: A list of Gmail properties to apply to the message. mail_labels: A list of labels to apply to the message. Returns: A MailEntry representing the successfully imported message. Raises: AppsForYourDomainException: An error occurred importing the message. """ uri = '%s/%s/mail' % (self._BaseURL(), user_name) mail_entry = migration.MailEntry() mail_entry.rfc822_msg = migration.Rfc822Msg(text=(base64.b64encode( mail_message))) mail_entry.rfc822_msg.encoding = 'base64' mail_entry.mail_item_property = map( lambda x: migration.MailItemProperty(value=x), mail_item_properties) mail_entry.label = map(lambda x: migration.Label(label_name=x), mail_labels) try: return migration.MailEntryFromString(str(self.Post(mail_entry, uri))) except gdata.service.RequestError, e: raise gdata.apps.service.AppsForYourDomainException(e.args[0]) def AddBatchEntry(self, mail_message, mail_item_properties, mail_labels): """Add a message to the current batch that you later will submit. Args: mail_message: An RFC822 format email message. mail_item_properties: A list of Gmail properties to apply to the message. mail_labels: A list of labels to apply to the message. Returns: The length of the MailEntry representing the message. """ mail_entry = migration.BatchMailEntry() mail_entry.rfc822_msg = migration.Rfc822Msg(text=(base64.b64encode( mail_message))) mail_entry.rfc822_msg.encoding = 'base64' mail_entry.mail_item_property = map( lambda x: migration.MailItemProperty(value=x), mail_item_properties) mail_entry.label = map(lambda x: migration.Label(label_name=x), mail_labels) self.mail_batch.AddBatchEntry(mail_entry) return len(str(mail_entry)) def SubmitBatch(self, user_name): """Send a all the mail items you have added to the batch to the server. Args: user_name: The username to import messages to. Returns: A HTTPResponse from the web service call. Raises: AppsForYourDomainException: An error occurred importing the batch. """ uri = '%s/%s/mail/batch' % (self._BaseURL(), user_name) try: self.result = self.Post(self.mail_batch, uri, converter=migration.BatchMailEventFeedFromString) except gdata.service.RequestError, e: raise gdata.apps.service.AppsForYourDomainException(e.args[0]) self.mail_batch = migration.BatchMailEventFeed() return self.result
Python
#!/usr/bin/python # # Copyright (C) 2008 Google # # 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 objects used with Google Apps.""" __author__ = 'google-apps-apis@googlegroups.com' import atom import gdata # XML namespaces which are often used in Google Apps entity. APPS_NAMESPACE = 'http://schemas.google.com/apps/2006' APPS_TEMPLATE = '{http://schemas.google.com/apps/2006}%s' class Rfc822Msg(atom.AtomBase): """The Migration rfc822Msg element.""" _tag = 'rfc822Msg' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['encoding'] = 'encoding' def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.text = text self.encoding = 'base64' self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def Rfc822MsgFromString(xml_string): """Parse in the Rrc822 message from the XML definition.""" return atom.CreateClassFromXMLString(Rfc822Msg, xml_string) class MailItemProperty(atom.AtomBase): """The Migration mailItemProperty element.""" _tag = 'mailItemProperty' _namespace = APPS_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 {} def MailItemPropertyFromString(xml_string): """Parse in the MailItemProperiy from the XML definition.""" return atom.CreateClassFromXMLString(MailItemProperty, xml_string) class Label(atom.AtomBase): """The Migration label element.""" _tag = 'label' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['labelName'] = 'label_name' def __init__(self, label_name=None, extension_elements=None, extension_attributes=None, text=None): self.label_name = label_name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def LabelFromString(xml_string): """Parse in the mailItemProperty from the XML definition.""" return atom.CreateClassFromXMLString(Label, xml_string) class MailEntry(gdata.GDataEntry): """A Google Migration flavor of an Atom Entry.""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}rfc822Msg' % APPS_NAMESPACE] = ('rfc822_msg', Rfc822Msg) _children['{%s}mailItemProperty' % APPS_NAMESPACE] = ('mail_item_property', [MailItemProperty]) _children['{%s}label' % APPS_NAMESPACE] = ('label', [Label]) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, rfc822_msg=None, mail_item_property=None, label=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) self.rfc822_msg = rfc822_msg self.mail_item_property = mail_item_property self.label = label self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def MailEntryFromString(xml_string): """Parse in the MailEntry from the XML definition.""" return atom.CreateClassFromXMLString(MailEntry, xml_string) class BatchMailEntry(gdata.BatchEntry): """A Google Migration flavor of an Atom Entry.""" _tag = gdata.BatchEntry._tag _namespace = gdata.BatchEntry._namespace _children = gdata.BatchEntry._children.copy() _attributes = gdata.BatchEntry._attributes.copy() _children['{%s}rfc822Msg' % APPS_NAMESPACE] = ('rfc822_msg', Rfc822Msg) _children['{%s}mailItemProperty' % APPS_NAMESPACE] = ('mail_item_property', [MailItemProperty]) _children['{%s}label' % APPS_NAMESPACE] = ('label', [Label]) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, rfc822_msg=None, mail_item_property=None, label=None, batch_operation=None, batch_id=None, batch_status=None, extended_property=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.rfc822_msg = rfc822_msg or None self.mail_item_property = mail_item_property or [] self.label = label or [] self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def BatchMailEntryFromString(xml_string): """Parse in the BatchMailEntry from the XML definition.""" return atom.CreateClassFromXMLString(BatchMailEntry, xml_string) class BatchMailEventFeed(gdata.BatchFeed): """A Migration 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', [BatchMailEntry]) 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): 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) def BatchMailEventFeedFromString(xml_string): """Parse in the BatchMailEventFeed from the XML definition.""" return atom.CreateClassFromXMLString(BatchMailEventFeed, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2007 SIOS Technology, 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. __author__ = 'tmatsuo@sios.com (Takashi MATSUO)' 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 urllib import gdata import atom.service import gdata.service import gdata.apps import atom API_VER="2.0" HTTP_OK=200 UNKOWN_ERROR=1000 USER_DELETED_RECENTLY=1100 USER_SUSPENDED=1101 DOMAIN_USER_LIMIT_EXCEEDED=1200 DOMAIN_ALIAS_LIMIT_EXCEEDED=1201 DOMAIN_SUSPENDED=1202 DOMAIN_FEATURE_UNAVAILABLE=1203 ENTITY_EXISTS=1300 ENTITY_DOES_NOT_EXIST=1301 ENTITY_NAME_IS_RESERVED=1302 ENTITY_NAME_NOT_VALID=1303 INVALID_GIVEN_NAME=1400 INVALID_FAMILY_NAME=1401 INVALID_PASSWORD=1402 INVALID_USERNAME=1403 INVALID_HASH_FUNCTION_NAME=1404 INVALID_HASH_DIGGEST_LENGTH=1405 INVALID_EMAIL_ADDRESS=1406 INVALID_QUERY_PARAMETER_VALUE=1407 TOO_MANY_RECIPIENTS_ON_EMAIL_LIST=1500 DEFAULT_QUOTA_LIMIT='2048' class Error(Exception): pass class AppsForYourDomainException(Error): def __init__(self, response): Error.__init__(self, response) try: self.element_tree = ElementTree.fromstring(response['body']) self.error_code = int(self.element_tree[0].attrib['errorCode']) self.reason = self.element_tree[0].attrib['reason'] self.invalidInput = self.element_tree[0].attrib['invalidInput'] except: self.error_code = UNKOWN_ERROR class AppsService(gdata.service.GDataService): """Client for the Google Apps Provisioning service.""" def __init__(self, email=None, password=None, domain=None, source=None, server='apps-apis.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Apps Provisioning service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. domain: string (optional) The Google Apps domain name. 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: 'apps-apis.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='apps', source=source, server=server, additional_headers=additional_headers, **kwargs) self.ssl = True self.port = 443 self.domain = domain def _baseURL(self): return "/a/feeds/%s" % self.domain def AddAllElementsFromAllPages(self, link_finder, func): """retrieve all pages and add all elements""" next = link_finder.GetNextLink() while next is not None: next_feed = self.Get(next.href, converter=func) for a_entry in next_feed.entry: link_finder.entry.append(a_entry) next = next_feed.GetNextLink() return link_finder def RetrievePageOfEmailLists(self, start_email_list_name=None, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve one page of email list""" uri = "%s/emailList/%s" % (self._baseURL(), API_VER) if start_email_list_name is not None: uri += "?startEmailListName=%s" % start_email_list_name try: return gdata.apps.EmailListFeedFromString(str(self.GetWithRetries( uri, num_retries=num_retries, delay=delay, backoff=backoff))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def GetGeneratorForAllEmailLists( self, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve a generator for all emaillists in this domain.""" first_page = self.RetrievePageOfEmailLists(num_retries=num_retries, delay=delay, backoff=backoff) return self.GetGeneratorFromLinkFinder( first_page, gdata.apps.EmailListRecipientFeedFromString, num_retries=num_retries, delay=delay, backoff=backoff) def RetrieveAllEmailLists(self): """Retrieve all email list of a domain.""" ret = self.RetrievePageOfEmailLists() # pagination return self.AddAllElementsFromAllPages( ret, gdata.apps.EmailListFeedFromString) def RetrieveEmailList(self, list_name): """Retreive a single email list by the list's name.""" uri = "%s/emailList/%s/%s" % ( self._baseURL(), API_VER, list_name) try: return self.Get(uri, converter=gdata.apps.EmailListEntryFromString) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def RetrieveEmailLists(self, recipient): """Retrieve All Email List Subscriptions for an Email Address.""" uri = "%s/emailList/%s?recipient=%s" % ( self._baseURL(), API_VER, recipient) try: ret = gdata.apps.EmailListFeedFromString(str(self.Get(uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) # pagination return self.AddAllElementsFromAllPages( ret, gdata.apps.EmailListFeedFromString) def RemoveRecipientFromEmailList(self, recipient, list_name): """Remove recipient from email list.""" uri = "%s/emailList/%s/%s/recipient/%s" % ( self._baseURL(), API_VER, list_name, recipient) try: self.Delete(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def RetrievePageOfRecipients(self, list_name, start_recipient=None, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve one page of recipient of an email list. """ uri = "%s/emailList/%s/%s/recipient" % ( self._baseURL(), API_VER, list_name) if start_recipient is not None: uri += "?startRecipient=%s" % start_recipient try: return gdata.apps.EmailListRecipientFeedFromString(str( self.GetWithRetries( uri, num_retries=num_retries, delay=delay, backoff=backoff))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def GetGeneratorForAllRecipients( self, list_name, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve a generator for all recipients of a particular emaillist.""" first_page = self.RetrievePageOfRecipients(list_name, num_retries=num_retries, delay=delay, backoff=backoff) return self.GetGeneratorFromLinkFinder( first_page, gdata.apps.EmailListRecipientFeedFromString, num_retries=num_retries, delay=delay, backoff=backoff) def RetrieveAllRecipients(self, list_name): """Retrieve all recipient of an email list.""" ret = self.RetrievePageOfRecipients(list_name) # pagination return self.AddAllElementsFromAllPages( ret, gdata.apps.EmailListRecipientFeedFromString) def AddRecipientToEmailList(self, recipient, list_name): """Add a recipient to a email list.""" uri = "%s/emailList/%s/%s/recipient" % ( self._baseURL(), API_VER, list_name) recipient_entry = gdata.apps.EmailListRecipientEntry() recipient_entry.who = gdata.apps.Who(email=recipient) try: return gdata.apps.EmailListRecipientEntryFromString( str(self.Post(recipient_entry, uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def DeleteEmailList(self, list_name): """Delete a email list""" uri = "%s/emailList/%s/%s" % (self._baseURL(), API_VER, list_name) try: self.Delete(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def CreateEmailList(self, list_name): """Create a email list. """ uri = "%s/emailList/%s" % (self._baseURL(), API_VER) email_list_entry = gdata.apps.EmailListEntry() email_list_entry.email_list = gdata.apps.EmailList(name=list_name) try: return gdata.apps.EmailListEntryFromString( str(self.Post(email_list_entry, uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def DeleteNickname(self, nickname): """Delete a nickname""" uri = "%s/nickname/%s/%s" % (self._baseURL(), API_VER, nickname) try: self.Delete(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def RetrievePageOfNicknames(self, start_nickname=None, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve one page of nicknames in the domain""" uri = "%s/nickname/%s" % (self._baseURL(), API_VER) if start_nickname is not None: uri += "?startNickname=%s" % start_nickname try: return gdata.apps.NicknameFeedFromString(str(self.GetWithRetries( uri, num_retries=num_retries, delay=delay, backoff=backoff))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def GetGeneratorForAllNicknames( self, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve a generator for all nicknames in this domain.""" first_page = self.RetrievePageOfNicknames(num_retries=num_retries, delay=delay, backoff=backoff) return self.GetGeneratorFromLinkFinder( first_page, gdata.apps.NicknameFeedFromString, num_retries=num_retries, delay=delay, backoff=backoff) def RetrieveAllNicknames(self): """Retrieve all nicknames in the domain""" ret = self.RetrievePageOfNicknames() # pagination return self.AddAllElementsFromAllPages( ret, gdata.apps.NicknameFeedFromString) def GetGeneratorForAllNicknamesOfAUser( self, user_name, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve a generator for all nicknames of a particular user.""" uri = "%s/nickname/%s?username=%s" % (self._baseURL(), API_VER, user_name) try: first_page = gdata.apps.NicknameFeedFromString(str(self.GetWithRetries( uri, num_retries=num_retries, delay=delay, backoff=backoff))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) return self.GetGeneratorFromLinkFinder( first_page, gdata.apps.NicknameFeedFromString, num_retries=num_retries, delay=delay, backoff=backoff) def RetrieveNicknames(self, user_name): """Retrieve nicknames of the user""" uri = "%s/nickname/%s?username=%s" % (self._baseURL(), API_VER, user_name) try: ret = gdata.apps.NicknameFeedFromString(str(self.Get(uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) # pagination return self.AddAllElementsFromAllPages( ret, gdata.apps.NicknameFeedFromString) def RetrieveNickname(self, nickname): """Retrieve a nickname. Args: nickname: string The nickname to retrieve Returns: gdata.apps.NicknameEntry """ uri = "%s/nickname/%s/%s" % (self._baseURL(), API_VER, nickname) try: return gdata.apps.NicknameEntryFromString(str(self.Get(uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def CreateNickname(self, user_name, nickname): """Create a nickname""" uri = "%s/nickname/%s" % (self._baseURL(), API_VER) nickname_entry = gdata.apps.NicknameEntry() nickname_entry.login = gdata.apps.Login(user_name=user_name) nickname_entry.nickname = gdata.apps.Nickname(name=nickname) try: return gdata.apps.NicknameEntryFromString( str(self.Post(nickname_entry, uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def DeleteUser(self, user_name): """Delete a user account""" uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name) try: return self.Delete(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def UpdateUser(self, user_name, user_entry): """Update a user account.""" uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name) try: return gdata.apps.UserEntryFromString(str(self.Put(user_entry, uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def CreateUser(self, user_name, family_name, given_name, password, suspended='false', quota_limit=None, password_hash_function=None, change_password=None): """Create a user account. """ uri = "%s/user/%s" % (self._baseURL(), API_VER) user_entry = gdata.apps.UserEntry() user_entry.login = gdata.apps.Login( user_name=user_name, password=password, suspended=suspended, hash_function_name=password_hash_function, change_password=change_password) user_entry.name = gdata.apps.Name(family_name=family_name, given_name=given_name) if quota_limit is not None: user_entry.quota = gdata.apps.Quota(limit=str(quota_limit)) try: return gdata.apps.UserEntryFromString(str(self.Post(user_entry, uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def SuspendUser(self, user_name): user_entry = self.RetrieveUser(user_name) if user_entry.login.suspended != 'true': user_entry.login.suspended = 'true' user_entry = self.UpdateUser(user_name, user_entry) return user_entry def RestoreUser(self, user_name): user_entry = self.RetrieveUser(user_name) if user_entry.login.suspended != 'false': user_entry.login.suspended = 'false' user_entry = self.UpdateUser(user_name, user_entry) return user_entry def RetrieveUser(self, user_name): """Retrieve an user account. Args: user_name: string The user name to retrieve Returns: gdata.apps.UserEntry """ uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name) try: return gdata.apps.UserEntryFromString(str(self.Get(uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def RetrievePageOfUsers(self, start_username=None, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve one page of users in this domain.""" uri = "%s/user/%s" % (self._baseURL(), API_VER) if start_username is not None: uri += "?startUsername=%s" % start_username try: return gdata.apps.UserFeedFromString(str(self.GetWithRetries( uri, num_retries=num_retries, delay=delay, backoff=backoff))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def GetGeneratorForAllUsers(self, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve a generator for all users in this domain.""" first_page = self.RetrievePageOfUsers(num_retries=num_retries, delay=delay, backoff=backoff) return self.GetGeneratorFromLinkFinder( first_page, gdata.apps.UserFeedFromString, num_retries=num_retries, delay=delay, backoff=backoff) def RetrieveAllUsers(self): """Retrieve all users in this domain. OBSOLETE""" ret = self.RetrievePageOfUsers() # pagination return self.AddAllElementsFromAllPages( ret, gdata.apps.UserFeedFromString) class PropertyService(gdata.service.GDataService): """Client for the Google Apps Property service.""" def __init__(self, email=None, password=None, domain=None, source=None, server='apps-apis.google.com', additional_headers=None): gdata.service.GDataService.__init__(self, email=email, password=password, service='apps', source=source, server=server, additional_headers=additional_headers) self.ssl = True self.port = 443 self.domain = domain def AddAllElementsFromAllPages(self, link_finder, func): """retrieve all pages and add all elements""" next = link_finder.GetNextLink() while next is not None: next_feed = self.Get(next.href, converter=func) for a_entry in next_feed.entry: link_finder.entry.append(a_entry) next = next_feed.GetNextLink() return link_finder def _GetPropertyEntry(self, properties): property_entry = gdata.apps.PropertyEntry() property = [] for name, value in properties.iteritems(): if name is not None and value is not None: property.append(gdata.apps.Property(name=name, value=value)) property_entry.property = property return property_entry def _PropertyEntry2Dict(self, property_entry): properties = {} for i, property in enumerate(property_entry.property): properties[property.name] = property.value return properties def _GetPropertyFeed(self, uri): try: return gdata.apps.PropertyFeedFromString(str(self.Get(uri))) except gdata.service.RequestError, e: raise gdata.apps.service.AppsForYourDomainException(e.args[0]) def _GetPropertiesList(self, uri): property_feed = self._GetPropertyFeed(uri) # pagination property_feed = self.AddAllElementsFromAllPages( property_feed, gdata.apps.PropertyFeedFromString) properties_list = [] for property_entry in property_feed.entry: properties_list.append(self._PropertyEntry2Dict(property_entry)) return properties_list def _GetProperties(self, uri): try: return self._PropertyEntry2Dict(gdata.apps.PropertyEntryFromString( str(self.Get(uri)))) except gdata.service.RequestError, e: raise gdata.apps.service.AppsForYourDomainException(e.args[0]) def _PostProperties(self, uri, properties): property_entry = self._GetPropertyEntry(properties) try: return self._PropertyEntry2Dict(gdata.apps.PropertyEntryFromString( str(self.Post(property_entry, uri)))) except gdata.service.RequestError, e: raise gdata.apps.service.AppsForYourDomainException(e.args[0]) def _PutProperties(self, uri, properties): property_entry = self._GetPropertyEntry(properties) try: return self._PropertyEntry2Dict(gdata.apps.PropertyEntryFromString( str(self.Put(property_entry, uri)))) except gdata.service.RequestError, e: raise gdata.apps.service.AppsForYourDomainException(e.args[0]) def _DeleteProperties(self, uri): try: self.Delete(uri) except gdata.service.RequestError, e: raise gdata.apps.service.AppsForYourDomainException(e.args[0]) def _bool2str(b): if b is None: return None return str(b is True).lower()
Python
#!/usr/bin/python # # Copyright (C) 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. """Allow Google Apps domain administrators to set users' email settings. EmailSettingsService: Set various email settings. """ __author__ = 'google-apps-apis@googlegroups.com' import gdata.apps import gdata.apps.service import gdata.service API_VER='2.0' # Forwarding and POP3 options KEEP='KEEP' ARCHIVE='ARCHIVE' DELETE='DELETE' ALL_MAIL='ALL_MAIL' MAIL_FROM_NOW_ON='MAIL_FROM_NOW_ON' class EmailSettingsService(gdata.apps.service.PropertyService): """Client for the Google Apps Email Settings service.""" def _serviceUrl(self, setting_id, username, domain=None): if domain is None: domain = self.domain return '/a/feeds/emailsettings/%s/%s/%s/%s' % (API_VER, domain, username, setting_id) def CreateLabel(self, username, label): """Create a label. Args: username: User to create label for. label: Label to create. Returns: A dict containing the result of the create operation. """ uri = self._serviceUrl('label', username) properties = {'label': label} return self._PostProperties(uri, properties) def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None): """Create a filter. Args: username: User to create filter for. from_: Filter from string. to: Filter to string. subject: Filter subject. has_the_word: Words to filter in. does_not_have_the_word: Words to filter out. has_attachment: Boolean for message having attachment. label: Label to apply. should_mark_as_read: Boolean for marking message as read. should_archive: Boolean for archiving message. Returns: A dict containing the result of the create operation. """ uri = self._serviceUrl('filter', username) properties = {} properties['from'] = from_ properties['to'] = to properties['subject'] = subject properties['hasTheWord'] = has_the_word properties['doesNotHaveTheWord'] = does_not_have_the_word properties['hasAttachment'] = gdata.apps.service._bool2str(has_attachment) properties['label'] = label properties['shouldMarkAsRead'] = gdata.apps.service._bool2str(should_mark_as_read) properties['shouldArchive'] = gdata.apps.service._bool2str(should_archive) return self._PostProperties(uri, properties) def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None): """Create alias to send mail as. Args: username: User to create alias for. name: Name of alias. address: Email address to send from. reply_to: Email address to reply to. make_default: Boolean for whether this is the new default sending alias. Returns: A dict containing the result of the create operation. """ uri = self._serviceUrl('sendas', username) properties = {} properties['name'] = name properties['address'] = address properties['replyTo'] = reply_to properties['makeDefault'] = gdata.apps.service._bool2str(make_default) return self._PostProperties(uri, properties) def UpdateWebClipSettings(self, username, enable): """Update WebClip Settings Args: username: User to update forwarding for. enable: Boolean whether to enable Web Clip. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('webclip', username) properties = {} properties['enable'] = gdata.apps.service._bool2str(enable) return self._PutProperties(uri, properties) def UpdateForwarding(self, username, enable, forward_to=None, action=None): """Update forwarding settings. Args: username: User to update forwarding for. enable: Boolean whether to enable this forwarding rule. forward_to: Email address to forward to. action: Action to take after forwarding. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('forwarding', username) properties = {} properties['enable'] = gdata.apps.service._bool2str(enable) if enable is True: properties['forwardTo'] = forward_to properties['action'] = action return self._PutProperties(uri, properties) def UpdatePop(self, username, enable, enable_for=None, action=None): """Update POP3 settings. Args: username: User to update POP3 settings for. enable: Boolean whether to enable POP3. enable_for: Which messages to make available via POP3. action: Action to take after user retrieves email via POP3. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('pop', username) properties = {} properties['enable'] = gdata.apps.service._bool2str(enable) if enable is True: properties['enableFor'] = enable_for properties['action'] = action return self._PutProperties(uri, properties) def UpdateImap(self, username, enable): """Update IMAP settings. Args: username: User to update IMAP settings for. enable: Boolean whether to enable IMAP. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('imap', username) properties = {'enable': gdata.apps.service._bool2str(enable)} return self._PutProperties(uri, properties) def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None): """Update vacation settings. Args: username: User to update vacation settings for. enable: Boolean whether to enable vacation responses. subject: Vacation message subject. message: Vacation message body. contacts_only: Boolean whether to send message only to contacts. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('vacation', username) properties = {} properties['enable'] = gdata.apps.service._bool2str(enable) if enable is True: properties['subject'] = subject properties['message'] = message properties['contactsOnly'] = gdata.apps.service._bool2str(contacts_only) return self._PutProperties(uri, properties) def UpdateSignature(self, username, signature): """Update signature. Args: username: User to update signature for. signature: Signature string. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('signature', username) properties = {'signature': signature} return self._PutProperties(uri, properties) def UpdateLanguage(self, username, language): """Update user interface language. Args: username: User to update language for. language: Language code. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('language', username) properties = {'language': language} return self._PutProperties(uri, properties) def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None): """Update general settings. Args: username: User to update general settings for. page_size: Number of messages to show. shortcuts: Boolean whether shortcuts are enabled. arrows: Boolean whether arrows are enabled. snippets: Boolean whether snippets are enabled. unicode: Wheter unicode is enabled. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('general', username) properties = {} if page_size != None: properties['pageSize'] = str(page_size) if shortcuts != None: properties['shortcuts'] = gdata.apps.service._bool2str(shortcuts) if arrows != None: properties['arrows'] = gdata.apps.service._bool2str(arrows) if snippets != None: properties['snippets'] = gdata.apps.service._bool2str(snippets) if unicode != None: properties['unicode'] = gdata.apps.service._bool2str(unicode) return self._PutProperties(uri, properties)
Python
#!/usr/bin/python2.4 # # 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. """EmailSettingsClient simplifies Email Settings API calls. EmailSettingsClient extends gdata.client.GDClient to ease interaction with the Google Apps Email Settings API. These interactions include the ability to create labels, filters, aliases, and update web-clip, forwarding, POP, IMAP, vacation-responder, signature, language, and general settings. """ __author__ = 'Claudio Cherubino <ccherubino@google.com>' import gdata.apps.emailsettings.data import gdata.client # Email Settings URI template # The strings in this template are eventually replaced with the API version, # Google Apps domain name, username, and settingID, respectively. EMAIL_SETTINGS_URI_TEMPLATE = '/a/feeds/emailsettings/%s/%s/%s/%s' # The settingID value for the label requests SETTING_ID_LABEL = 'label' # The settingID value for the filter requests SETTING_ID_FILTER = 'filter' # The settingID value for the send-as requests SETTING_ID_SENDAS = 'sendas' # The settingID value for the webclip requests SETTING_ID_WEBCLIP = 'webclip' # The settingID value for the forwarding requests SETTING_ID_FORWARDING = 'forwarding' # The settingID value for the POP requests SETTING_ID_POP = 'pop' # The settingID value for the IMAP requests SETTING_ID_IMAP = 'imap' # The settingID value for the vacation responder requests SETTING_ID_VACATION_RESPONDER = 'vacation' # The settingID value for the signature requests SETTING_ID_SIGNATURE = 'signature' # The settingID value for the language requests SETTING_ID_LANGUAGE = 'language' # The settingID value for the general requests SETTING_ID_GENERAL = 'general' # The KEEP action for the email settings ACTION_KEEP = 'KEEP' # The ARCHIVE action for the email settings ACTION_ARCHIVE = 'ARCHIVE' # The DELETE action for the email settings ACTION_DELETE = 'DELETE' # The ALL_MAIL setting for POP enable_for property POP_ENABLE_FOR_ALL_MAIL = 'ALL_MAIL' # The MAIL_FROM_NOW_ON setting for POP enable_for property POP_ENABLE_FOR_MAIL_FROM_NOW_ON = 'MAIL_FROM_NOW_ON' class EmailSettingsClient(gdata.client.GDClient): """Client extension for the Google Email Settings API service. Attributes: host: string The hostname for the Email Settings API service. api_version: string The version of the Email Settings 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 Email Settings API. Args: domain: string The Google Apps domain with Email Settings. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the email settings. 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_email_settings_uri(self, username, setting_id): """Creates the URI for the Email Settings API call. Using this client's Google Apps domain, create the URI to setup email settings for the given user in that domain. If params are provided, append them as GET params. Args: username: string The name of the user affected by this setting. setting_id: string The key of the setting to be configured. Returns: A string giving the URI for Email Settings API calls for this client's Google Apps domain. """ uri = EMAIL_SETTINGS_URI_TEMPLATE % (self.api_version, self.domain, username, setting_id) return uri MakeEmailSettingsUri = make_email_settings_uri def create_label(self, username, name, **kwargs): """Creates a label with the given properties. Args: username: string The name of the user. name: string The name of the label. kwargs: The other parameters to pass to gdata.client.GDClient.post(). Returns: gdata.apps.emailsettings.data.EmailSettingsLabel of the new resource. """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_LABEL) new_label = gdata.apps.emailsettings.data.EmailSettingsLabel( uri=uri, name=name) return self.post(new_label, uri, **kwargs) CreateLabel = create_label def create_filter(self, username, from_address=None, to_address=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachments=None, label=None, mark_as_read=None, archive=None, **kwargs): """Creates a filter with the given properties. Args: username: string The name of the user. from_address: string The source email address for the filter. to_address: string (optional) The destination email address for the filter. subject: string (optional) The value the email must have in its subject to be filtered. has_the_word: string (optional) The value the email must have in its subject or body to be filtered. does_not_have_the_word: string (optional) The value the email cannot have in its subject or body to be filtered. has_attachments: string (optional) A boolean string representing whether the email must have an attachment to be filtered. label: string (optional) The name of the label to apply to messages matching the filter criteria. mark_as_read: Boolean (optional) Whether or not to mark messages matching the filter criteria as read. archive: Boolean (optional) Whether or not to move messages matching to Archived state. kwargs: The other parameters to pass to gdata.client.GDClient.post(). Returns: gdata.apps.emailsettings.data.EmailSettingsFilter of the new resource. """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_FILTER) new_filter = gdata.apps.emailsettings.data.EmailSettingsFilter( uri=uri, from_address=from_address, to_address=to_address, subject=subject, has_the_word=has_the_word, does_not_have_the_word=does_not_have_the_word, has_attachments=has_attachments, label=label, mark_as_read=mark_as_read, archive=archive) return self.post(new_filter, uri, **kwargs) CreateFilter = create_filter def create_send_as(self, username, name, address, reply_to=None, make_default=None, **kwargs): """Creates a send-as alias with the given properties. Args: username: string The name of the user. name: string The name that will appear in the "From" field. address: string The email address that appears as the origination address for emails sent by this user. reply_to: string (optional) The address to be used as the reply-to address in email sent using the alias. make_default: Boolean (optional) Whether or not this alias should become the default alias for this user. kwargs: The other parameters to pass to gdata.client.GDClient.post(). Returns: gdata.apps.emailsettings.data.EmailSettingsSendAsAlias of the new resource. """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_SENDAS) new_alias = gdata.apps.emailsettings.data.EmailSettingsSendAsAlias( uri=uri, name=name, address=address, reply_to=reply_to, make_default=make_default) return self.post(new_alias, uri, **kwargs) CreateSendAs = create_send_as def update_webclip(self, username, enable, **kwargs): """Enable/Disable Google Mail web clip. Args: username: string The name of the user. enable: Boolean Whether to enable showing Web clips. kwargs: The other parameters to pass to the update method. Returns: gdata.apps.emailsettings.data.EmailSettingsWebClip of the updated resource. """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_WEBCLIP) new_webclip = gdata.apps.emailsettings.data.EmailSettingsWebClip( uri=uri, enable=enable) return self.update(new_webclip, **kwargs) UpdateWebclip = update_webclip def update_forwarding(self, username, enable, forward_to=None, action=None, **kwargs): """Update Google Mail Forwarding settings. Args: username: string The name of the user. enable: Boolean Whether to enable incoming email forwarding. forward_to: (optional) string The address email will be forwarded to. action: string (optional) The action to perform after forwarding an email (ACTION_KEEP, ACTION_ARCHIVE, ACTION_DELETE). kwargs: The other parameters to pass to the update method. Returns: gdata.apps.emailsettings.data.EmailSettingsForwarding of the updated resource """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_FORWARDING) new_forwarding = gdata.apps.emailsettings.data.EmailSettingsForwarding( uri=uri, enable=enable, forward_to=forward_to, action=action) return self.update(new_forwarding, **kwargs) UpdateForwarding = update_forwarding def update_pop(self, username, enable, enable_for=None, action=None, **kwargs): """Update Google Mail POP settings. Args: username: string The name of the user. enable: Boolean Whether to enable incoming POP3 access. enable_for: string (optional) Whether to enable POP3 for all mail (POP_ENABLE_FOR_ALL_MAIL), or mail from now on (POP_ENABLE_FOR_MAIL_FROM_NOW_ON). action: string (optional) What Google Mail should do with its copy of the email after it is retrieved using POP (ACTION_KEEP, ACTION_ARCHIVE, ACTION_DELETE). kwargs: The other parameters to pass to the update method. Returns: gdata.apps.emailsettings.data.EmailSettingsPop of the updated resource. """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_POP) new_pop = gdata.apps.emailsettings.data.EmailSettingsPop( uri=uri, enable=enable, enable_for=enable_for, action=action) return self.update(new_pop, **kwargs) UpdatePop = update_pop def update_imap(self, username, enable, **kwargs): """Update Google Mail IMAP settings. Args: username: string The name of the user. enable: Boolean Whether to enable IMAP access.language kwargs: The other parameters to pass to the update method. Returns: gdata.apps.emailsettings.data.EmailSettingsImap of the updated resource. """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_IMAP) new_imap = gdata.apps.emailsettings.data.EmailSettingsImap( uri=uri, enable=enable) return self.update(new_imap, **kwargs) UpdateImap = update_imap def update_vacation(self, username, enable, subject=None, message=None, contacts_only=None, **kwargs): """Update Google Mail vacation-responder settings. Args: username: string The name of the user. enable: Boolean Whether to enable the vacation responder. subject: string (optional) The subject line of the vacation responder autoresponse. message: string (optional) The message body of the vacation responder autoresponse. contacts_only: Boolean (optional) Whether to only send autoresponses to known contacts. kwargs: The other parameters to pass to the update method. Returns: gdata.apps.emailsettings.data.EmailSettingsVacationResponder of the updated resource. """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_VACATION_RESPONDER) new_vacation = gdata.apps.emailsettings.data.EmailSettingsVacationResponder( uri=uri, enable=enable, subject=subject, message=message, contacts_only=contacts_only) return self.update(new_vacation, **kwargs) UpdateVacation = update_vacation def update_signature(self, username, signature, **kwargs): """Update Google Mail signature. Args: username: string The name of the user. signature: string The signature to be appended to outgoing messages. kwargs: The other parameters to pass to the update method. Returns: gdata.apps.emailsettings.data.EmailSettingsSignature of the updated resource. """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_SIGNATURE) new_signature = gdata.apps.emailsettings.data.EmailSettingsSignature( uri=uri, signature=signature) return self.update(new_signature, **kwargs) UpdateSignature = update_signature def update_language(self, username, language, **kwargs): """Update Google Mail language settings. Args: username: string The name of the user. language: string The language tag for Google Mail's display language. kwargs: The other parameters to pass to the update method. Returns: gdata.apps.emailsettings.data.EmailSettingsLanguage of the updated resource. """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_LANGUAGE) new_language = gdata.apps.emailsettings.data.EmailSettingsLanguage( uri=uri, language=language) return self.update(new_language, **kwargs) UpdateLanguage = update_language def update_general_settings(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, use_unicode=None, **kwargs): """Update Google Mail general settings. Args: username: string The name of the user. page_size: int (optional) The number of conversations to be shown per page. shortcuts: Boolean (optional) Whether to enable keyboard shortcuts. arrows: Boolean (optional) Whether to display arrow-shaped personal indicators next to email sent specifically to the user. snippets: Boolean (optional) Whether to display snippets of the messages in the inbox and when searching. use_unicode: Boolean (optional) Whether to use UTF-8 (unicode) encoding for all outgoing messages. kwargs: The other parameters to pass to the update method. Returns: gdata.apps.emailsettings.data.EmailSettingsGeneral of the updated resource. """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_GENERAL) new_general = gdata.apps.emailsettings.data.EmailSettingsGeneral( uri=uri, page_size=page_size, shortcuts=shortcuts, arrows=arrows, snippets=snippets, use_unicode=use_unicode) return self.update(new_general, **kwargs) UpdateGeneralSettings = update_general_settings
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 the Email Settings API.""" __author__ = 'Claudio Cherubino <ccherubino@google.com>' 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 label of the label property LABEL_NAME = 'label' # The apps:property from of the filter property FILTER_FROM_NAME = 'from' # The apps:property to of the filter property FILTER_TO_NAME = 'to' # The apps:property subject of the filter property FILTER_SUBJECT_NAME = 'subject' # The apps:property hasTheWord of the filter property FILTER_HAS_THE_WORD_NAME = 'hasTheWord' # The apps:property doesNotHaveTheWord of the filter property FILTER_DOES_NOT_HAVE_THE_WORD_NAME = 'doesNotHaveTheWord' # The apps:property hasAttachment of the filter property FILTER_HAS_ATTACHMENTS_NAME = 'hasAttachment' # The apps:property label of the filter action property FILTER_LABEL = 'label' # The apps:property shouldMarkAsRead of the filter action property FILTER_MARK_AS_READ = 'shouldMarkAsRead' # The apps:property shouldArchive of the filter action propertylabel FILTER_ARCHIVE = 'shouldArchive' # The apps:property name of the send-as alias property SENDAS_ALIAS_NAME = 'name' # The apps:property address of theAPPS_TEMPLATE send-as alias property SENDAS_ALIAS_ADDRESS = 'address' # The apps:property replyTo of the send-as alias property SENDAS_ALIAS_REPLY_TO = 'replyTo' # The apps:property makeDefault of the send-as alias property SENDAS_ALIAS_MAKE_DEFAULT = 'makeDefault' # The apps:property enable of the webclip property WEBCLIP_ENABLE = 'enable' # The apps:property enable of the forwarding property FORWARDING_ENABLE = 'enable' # The apps:property forwardTo of the forwarding property FORWARDING_TO = 'forwardTo' # The apps:property action of the forwarding property FORWARDING_ACTION = 'action' # The apps:property enable of the POP property POP_ENABLE = 'enable' # The apps:property enableFor of the POP propertyACTION POP_ENABLE_FOR = 'enableFor' # The apps:property action of the POP property POP_ACTION = 'action' # The apps:property enable of the IMAP property IMAP_ENABLE = 'enable' # The apps:property enable of the vacation responder property VACATION_RESPONDER_ENABLE = 'enable' # The apps:property subject of the vacation responder property VACATION_RESPONDER_SUBJECT = 'subject' # The apps:property message of the vacation responder property VACATION_RESPONDER_MESSAGE = 'message' # The apps:property contactsOnly of the vacation responder property VACATION_RESPONDER_CONTACTS_ONLY = 'contactsOnly' # The apps:property signature of the signature property SIGNATURE_VALUE = 'signature' # The apps:property language of the language property LANGUAGE_TAG = 'language' # The apps:property pageSize of the general settings property GENERAL_PAGE_SIZE = 'pageSize' # The apps:property shortcuts of the general settings property GENERAL_SHORTCUTS = 'shortcuts' # The apps:property arrows of the general settings property GENERAL_ARROWS = 'arrows' # The apps:prgdata.appsoperty snippets of the general settings property GENERAL_SNIPPETS = 'snippets' # The apps:property uniAppsProcode of the general settings property GENERAL_UNICODE = 'unicode' class EmailSettingsEntry(gdata.data.GDEntry): """Represents an Email Settings 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. """ value = None for p in self.property: if p.name == name: value = p.value break return value 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. """ found = False for i in range(len(self.property)): if self.property[i].name == name: self.property[i].value = value found = True break if not found: self.property.append(gdata.apps_property.AppsProperty(name=name, value=value)) def find_edit_link(self): return self.uri class EmailSettingsLabel(EmailSettingsEntry): """Represents a Label in object form.""" def GetName(self): """Get the name of the Label object. Returns: The name of this Label object as a string or None. """ return self._GetProperty(LABEL_NAME) def SetName(self, value): """Set the name of this Label object. Args: value: string The new label name to give this object. """ self._SetProperty(LABEL_NAME, value) name = pyproperty(GetName, SetName) def __init__(self, uri=None, name=None, *args, **kwargs): """Constructs a new EmailSettingsLabel object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. name: string (optional) The name 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(EmailSettingsLabel, self).__init__(*args, **kwargs) if uri: self.uri = uri if name: self.name = name class EmailSettingsFilter(EmailSettingsEntry): """Represents an Email Settings Filter in object form.""" def GetFrom(self): """Get the From value of the Filter object. Returns: The From value of this Filter object as a string or None. """ return self._GetProperty(FILTER_FROM_NAME) def SetFrom(self, value): """Set the From value of this Filter object. Args: value: string The new From value to give this object. """ self._SetProperty(FILTER_FROM_NAME, value) from_address = pyproperty(GetFrom, SetFrom) def GetTo(self): """Get the To value of the Filter object. Returns: The To value of this Filter object as a string or None. """ return self._GetProperty(FILTER_TO_NAME) def SetTo(self, value): """Set the To value of this Filter object. Args: value: string The new To value to give this object. """ self._SetProperty(FILTER_TO_NAME, value) to_address = pyproperty(GetTo, SetTo) def GetSubject(self): """Get the Subject value of the Filter object. Returns: The Subject value of this Filter object as a string or None. """ return self._GetProperty(FILTER_SUBJECT_NAME) def SetSubject(self, value): """Set the Subject value of this Filter object. Args: value: string The new Subject value to give this object. """ self._SetProperty(FILTER_SUBJECT_NAME, value) subject = pyproperty(GetSubject, SetSubject) def GetHasTheWord(self): """Get the HasTheWord value of the Filter object. Returns: The HasTheWord value of this Filter object as a string or None. """ return self._GetProperty(FILTER_HAS_THE_WORD_NAME) def SetHasTheWord(self, value): """Set the HasTheWord value of this Filter object. Args: value: string The new HasTheWord value to give this object. """ self._SetProperty(FILTER_HAS_THE_WORD_NAME, value) has_the_word = pyproperty(GetHasTheWord, SetHasTheWord) def GetDoesNotHaveTheWord(self): """Get the DoesNotHaveTheWord value of the Filter object. Returns: The DoesNotHaveTheWord value of this Filter object as a string or None. """ return self._GetProperty(FILTER_DOES_NOT_HAVE_THE_WORD_NAME) def SetDoesNotHaveTheWord(self, value): """Set the DoesNotHaveTheWord value of this Filter object. Args: value: string The new DoesNotHaveTheWord value to give this object. """ self._SetProperty(FILTER_DOES_NOT_HAVE_THE_WORD_NAME, value) does_not_have_the_word = pyproperty(GetDoesNotHaveTheWord, SetDoesNotHaveTheWord) def GetHasAttachments(self): """Get the HasAttachments value of the Filter object. Returns: The HasAttachments value of this Filter object as a string or None. """ return self._GetProperty(FILTER_HAS_ATTACHMENTS_NAME) def SetHasAttachments(self, value): """Set the HasAttachments value of this Filter object. Args: value: string The new HasAttachments value to give this object. """ self._SetProperty(FILTER_HAS_ATTACHMENTS_NAME, value) has_attachments = pyproperty(GetHasAttachments, SetHasAttachments) def GetLabel(self): """Get the Label value of the Filter object. Returns: The Label value of this Filter object as a string or None. """ return self._GetProperty(FILTER_LABEL) def SetLabel(self, value): """Set the Label value of this Filter object. Args: value: string The new Label value to give this object. """ self._SetProperty(FILTER_LABEL, value) label = pyproperty(GetLabel, SetLabel) def GetMarkAsRead(self): """Get the MarkAsRead value of the Filter object. Returns: The MarkAsRead value of this Filter object as a string or None. """ return self._GetProperty(FILTER_MARK_AS_READ) def SetMarkAsRead(self, value): """Set the MarkAsRead value of this Filter object. Args: value: string The new MarkAsRead value to give this object. """ self._SetProperty(FILTER_MARK_AS_READ, value) mark_as_read = pyproperty(GetMarkAsRead, SetMarkAsRead) def GetArchive(self): """Get the Archive value of the Filter object. Returns: The Archive value of this Filter object as a string or None. """ return self._GetProperty(FILTER_ARCHIVE) def SetArchive(self, value): """Set the Archive value of this Filter object. Args: value: string The new Archive value to give this object. """ self._SetProperty(FILTER_ARCHIVE, value) archive = pyproperty(GetArchive, SetArchive) def __init__(self, uri=None, from_address=None, to_address=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachments=None, label=None, mark_as_read=None, archive=None, *args, **kwargs): """Constructs a new EmailSettingsFilter object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. from_address: string (optional) The source email address for the filter. to_address: string (optional) The destination email address for the filter. subject: string (optional) The value the email must have in its subject to be filtered. has_the_word: string (optional) The value the email must have in its subject or body to be filtered. does_not_have_the_word: string (optional) The value the email cannot have in its subject or body to be filtered. has_attachments: Boolean (optional) Whether or not the email must have an attachment to be filtered. label: string (optional) The name of the label to apply to messages matching the filter criteria. mark_as_read: Boolean (optional) Whether or not to mark messages matching the filter criteria as read. archive: Boolean (optional) Whether or not to move messages matching to Archived state. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsFilter, self).__init__(*args, **kwargs) if uri: self.uri = uri if from_address: self.from_address = from_address if to_address: self.to_address = to_address if subject: self.subject = subject if has_the_word: self.has_the_word = has_the_word if does_not_have_the_word: self.does_not_have_the_word = does_not_have_the_word if has_attachments is not None: self.has_attachments = str(has_attachments) if label: self.label = label if mark_as_read is not None: self.mark_as_read = str(mark_as_read) if archive is not None: self.archive = str(archive) class EmailSettingsSendAsAlias(EmailSettingsEntry): """Represents an Email Settings send-as Alias in object form.""" def GetName(self): """Get the Name of the send-as Alias object. Returns: The Name of this send-as Alias object as a string or None. """ return self._GetProperty(SENDAS_ALIAS_NAME) def SetName(self, value): """Set the Name of this send-as Alias object. Args: value: string The new Name to give this object. """ self._SetProperty(SENDAS_ALIAS_NAME, value) name = pyproperty(GetName, SetName) def GetAddress(self): """Get the Address of the send-as Alias object. Returns: The Address of this send-as Alias object as a string or None. """ return self._GetProperty(SENDAS_ALIAS_ADDRESS) def SetAddress(self, value): """Set the Address of this send-as Alias object. Args: value: string The new Address to give this object. """ self._SetProperty(SENDAS_ALIAS_ADDRESS, value) address = pyproperty(GetAddress, SetAddress) def GetReplyTo(self): """Get the ReplyTo address of the send-as Alias object. Returns: The ReplyTo address of this send-as Alias object as a string or None. """ return self._GetProperty(SENDAS_ALIAS_REPLY_TO) def SetReplyTo(self, value): """Set the ReplyTo address of this send-as Alias object. Args: value: string The new ReplyTo address to give this object. """ self._SetProperty(SENDAS_ALIAS_REPLY_TO, value) reply_to = pyproperty(GetReplyTo, SetReplyTo) def GetMakeDefault(self): """Get the MakeDefault value of the send-as Alias object. Returns: The MakeDefault value of this send-as Alias object as a string or None. """ return self._GetProperty(SENDAS_ALIAS_MAKE_DEFAULT) def SetMakeDefault(self, value): """Set the MakeDefault value of this send-as Alias object. Args: value: string The new MakeDefault valueto give this object.WebClip """ self._SetProperty(SENDAS_ALIAS_MAKE_DEFAULT, value) make_default = pyproperty(GetMakeDefault, SetMakeDefault) def __init__(self, uri=None, name=None, address=None, reply_to=None, make_default=None, *args, **kwargs): """Constructs a new EmailSettingsSendAsAlias object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. name: string (optional) The name that will appear in the "From" field for this user. address: string (optional) The email address that appears as the origination address for emails sent by this user. reply_to: string (optional) The address to be used as the reply-to address in email sent using the alias. make_default: Boolean (optional) Whether or not this alias should become the default alias for this user. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsSendAsAlias, self).__init__(*args, **kwargs) if uri: self.uri = uri if name: self.name = name if address: self.address = address if reply_to: self.reply_to = reply_to if make_default is not None: self.make_default = str(make_default) class EmailSettingsWebClip(EmailSettingsEntry): """Represents a WebClip in object form.""" def GetEnable(self): """Get the Enable value of the WebClip object. Returns: The Enable value of this WebClip object as a string or None. """ return self._GetProperty(WEBCLIP_ENABLE) def SetEnable(self, value): """Set the Enable value of this WebClip object. Args: value: string The new Enable value to give this object. """ self._SetProperty(WEBCLIP_ENABLE, value) enable = pyproperty(GetEnable, SetEnable) def __init__(self, uri=None, enable=None, *args, **kwargs): """Constructs a new EmailSettingsWebClip object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. enable: Boolean (optional) Whether to enable showing Web clips. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsWebClip, self).__init__(*args, **kwargs) if uri: self.uri = uri if enable is not None: self.enable = str(enable) class EmailSettingsForwarding(EmailSettingsEntry): """Represents Forwarding settings in object form.""" def GetEnable(self): """Get the Enable value of the Forwarding object. Returns: The Enable value of this Forwarding object as a string or None. """ return self._GetProperty(FORWARDING_ENABLE) def SetEnable(self, value): """Set the Enable value of this Forwarding object. Args: value: string The new Enable value to give this object. """ self._SetProperty(FORWARDING_ENABLE, value) enable = pyproperty(GetEnable, SetEnable) def GetForwardTo(self): """Get the ForwardTo value of the Forwarding object. Returns: The ForwardTo value of this Forwarding object as a string or None. """ return self._GetProperty(FORWARDING_TO) def SetForwardTo(self, value): """Set the ForwardTo value of this Forwarding object. Args: value: string The new ForwardTo value to give this object. """ self._SetProperty(FORWARDING_TO, value) forward_to = pyproperty(GetForwardTo, SetForwardTo) def GetAction(self): """Get the Action value of the Forwarding object. Returns: The Action value of this Forwarding object as a string or None. """ return self._GetProperty(FORWARDING_ACTION) def SetAction(self, value): """Set the Action value of this Forwarding object. Args: value: string The new Action value to give this object. """ self._SetProperty(FORWARDING_ACTION, value) action = pyproperty(GetAction, SetAction) def __init__(self, uri=None, enable=None, forward_to=None, action=None, *args, **kwargs): """Constructs a new EmailSettingsForwarding object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. enable: Boolean (optional) Whether to enable incoming email forwarding. forward_to: string (optional) The address email will be forwarded to. action: string (optional) The action to perform after forwarding an email ("KEEP", "ARCHIVE", "DELETE"). args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsForwarding, self).__init__(*args, **kwargs) if uri: self.uri = uri if enable is not None: self.enable = str(enable) if forward_to: self.forward_to = forward_to if action: self.action = action class EmailSettingsPop(EmailSettingsEntry): """Represents POP settings in object form.""" def GetEnable(self): """Get the Enable value of the POP object. Returns: The Enable value of this POP object as a string or None. """ return self._GetProperty(POP_ENABLE) def SetEnable(self, value): """Set the Enable value of this POP object. Args: value: string The new Enable value to give this object. """ self._SetProperty(POP_ENABLE, value) enable = pyproperty(GetEnable, SetEnable) def GetEnableFor(self): """Get the EnableFor value of the POP object. Returns: The EnableFor value of this POP object as a string or None. """ return self._GetProperty(POP_ENABLE_FOR) def SetEnableFor(self, value): """Set the EnableFor value of this POP object. Args: value: string The new EnableFor value to give this object. """ self._SetProperty(POP_ENABLE_FOR, value) enable_for = pyproperty(GetEnableFor, SetEnableFor) def GetPopAction(self): """Get the Action value of the POP object. Returns: The Action value of this POP object as a string or None. """ return self._GetProperty(POP_ACTION) def SetPopAction(self, value): """Set the Action value of this POP object. Args: value: string The new Action value to give this object. """ self._SetProperty(POP_ACTION, value) action = pyproperty(GetPopAction, SetPopAction) def __init__(self, uri=None, enable=None, enable_for=None, action=None, *args, **kwargs): """Constructs a new EmailSettingsPOP object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. enable: Boolean (optional) Whether to enable incoming POP3 access. enable_for: string (optional) Whether to enable POP3 for all mail ("ALL_MAIL"), or mail from now on ("MAIL_FROM_NOW_ON"). action: string (optional) What Google Mail should do with its copy of the email after it is retrieved using POP ("KEEP", "ARCHIVE", or "DELETE"). args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsPop, self).__init__(*args, **kwargs) if uri: self.uri = uri if enable is not None: self.enable = str(enable) if enable_for: self.enable_for = enable_for if action: self.action = action class EmailSettingsImap(EmailSettingsEntry): """Represents IMAP settings in object form.""" def GetEnable(self): """Get the Enable value of the IMAP object. Returns: The Enable value of this IMAP object as a string or None. """ return self._GetProperty(IMAP_ENABLE) def SetEnable(self, value): """Set the Enable value of this IMAP object. Args: value: string The new Enable value to give this object. """ self._SetProperty(IMAP_ENABLE, value) enable = pyproperty(GetEnable, SetEnable) def __init__(self, uri=None, enable=None, *args, **kwargs): """Constructs a new EmailSettingsImap object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. enable: Boolean (optional) Whether to enable IMAP access. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsImap, self).__init__(*args, **kwargs) if uri: self.uri = uri if enable is not None: self.enable = str(enable) class EmailSettingsVacationResponder(EmailSettingsEntry): """Represents Vacation Responder settings in object form.""" def GetEnable(self): """Get the Enable value of the Vacation Responder object. Returns: The Enable value of this Vacation Responder object as a string or None. """ return self._GetProperty(VACATION_RESPONDER_ENABLE) def SetEnable(self, value): """Set the Enable value of this Vacation Responder object. Args: value: string The new Enable value to give this object. """ self._SetProperty(VACATION_RESPONDER_ENABLE, value) enable = pyproperty(GetEnable, SetEnable) def GetSubject(self): """Get the Subject value of the Vacation Responder object. Returns: The Subject value of this Vacation Responder object as a string or None. """ return self._GetProperty(VACATION_RESPONDER_SUBJECT) def SetSubject(self, value): """Set the Subject value of this Vacation Responder object. Args: value: string The new Subject value to give this object. """ self._SetProperty(VACATION_RESPONDER_SUBJECT, value) subject = pyproperty(GetSubject, SetSubject) def GetMessage(self): """Get the Message value of the Vacation Responder object. Returns: The Message value of this Vacation Responder object as a string or None. """ return self._GetProperty(VACATION_RESPONDER_MESSAGE) def SetMessage(self, value): """Set the Message value of this Vacation Responder object. Args: value: string The new Message value to give this object. """ self._SetProperty(VACATION_RESPONDER_MESSAGE, value) message = pyproperty(GetMessage, SetMessage) def GetContactsOnly(self): """Get the ContactsOnly value of the Vacation Responder object. Returns: The ContactsOnly value of this Vacation Responder object as a string or None. """ return self._GetProperty(VACATION_RESPONDER_CONTACTS_ONLY) def SetContactsOnly(self, value): """Set the ContactsOnly value of this Vacation Responder object. Args: value: string The new ContactsOnly value to give this object. """ self._SetProperty(VACATION_RESPONDER_CONTACTS_ONLY, value) contacts_only = pyproperty(GetContactsOnly, SetContactsOnly) def __init__(self, uri=None, enable=None, subject=None, message=None, contacts_only=None, *args, **kwargs): """Constructs a new EmailSettingsVacationResponder object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. enable: Boolean (optional) Whether to enable the vacation responder. subject: string (optional) The subject line of the vacation responder autoresponse. message: string (optional) The message body of the vacation responder autoresponse. contacts_only: Boolean (optional) Whether to only send autoresponses to known contacts. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsVacationResponder, self).__init__(*args, **kwargs) if uri: self.uri = uri if enable is not None: self.enable = str(enable) if subject: self.subject = subject if message: self.message = message if contacts_only is not None: self.contacts_only = str(contacts_only) class EmailSettingsSignature(EmailSettingsEntry): """Represents a Signature in object form.""" def GetValue(self): """Get the value of the Signature object. Returns: The value of this Signature object as a string or None. """ value = self._GetProperty(SIGNATURE_VALUE) if value == ' ': # hack to support empty signature return '' else: return value def SetValue(self, value): """Set the name of this Signature object. Args: value: string The new signature value to give this object. """ if value == '': # hack to support empty signature value = ' ' self._SetProperty(SIGNATURE_VALUE, value) signature_value = pyproperty(GetValue, SetValue) def __init__(self, uri=None, signature=None, *args, **kwargs): """Constructs a new EmailSettingsSignature object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. signature: string (optional) The signature to be appended to outgoing messages. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsSignature, self).__init__(*args, **kwargs) if uri: self.uri = uri if signature is not None: self.signature_value = signature class EmailSettingsLanguage(EmailSettingsEntry): """Represents Language Settings in object form.""" def GetLanguage(self): """Get the tag of the Language object. Returns: The tag of this Language object as a string or None. """ return self._GetProperty(LANGUAGE_TAG) def SetLanguage(self, value): """Set the tag of this Language object. Args: value: string The new tag value to give this object. """ self._SetProperty(LANGUAGE_TAG, value) language_tag = pyproperty(GetLanguage, SetLanguage) def __init__(self, uri=None, language=None, *args, **kwargs): """Constructs a new EmailSettingsLanguage object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. language: string (optional) The language tag for Google Mail's display language. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsLanguage, self).__init__(*args, **kwargs) if uri: self.uri = uri if language: self.language_tag = language class EmailSettingsGeneral(EmailSettingsEntry): """Represents General Settings in object form.""" def GetPageSize(self): """Get the Page Size value of the General Settings object. Returns: The Page Size value of this General Settings object as a string or None. """ return self._GetProperty(GENERAL_PAGE_SIZE) def SetPageSize(self, value): """Set the Page Size value of this General Settings object. Args: value: string The new Page Size value to give this object. """ self._SetProperty(GENERAL_PAGE_SIZE, value) page_size = pyproperty(GetPageSize, SetPageSize) def GetShortcuts(self): """Get the Shortcuts value of the General Settings object. Returns: The Shortcuts value of this General Settings object as a string or None. """ return self._GetProperty(GENERAL_SHORTCUTS) def SetShortcuts(self, value): """Set the Shortcuts value of this General Settings object. Args: value: string The new Shortcuts value to give this object. """ self._SetProperty(GENERAL_SHORTCUTS, value) shortcuts = pyproperty(GetShortcuts, SetShortcuts) def GetArrows(self): """Get the Arrows value of the General Settings object. Returns: The Arrows value of this General Settings object as a string or None. """ return self._GetProperty(GENERAL_ARROWS) def SetArrows(self, value): """Set the Arrows value of this General Settings object. Args: value: string The new Arrows value to give this object. """ self._SetProperty(GENERAL_ARROWS, value) arrows = pyproperty(GetArrows, SetArrows) def GetSnippets(self): """Get the Snippets value of the General Settings object. Returns: The Snippets value of this General Settings object as a string or None. """ return self._GetProperty(GENERAL_SNIPPETS) def SetSnippets(self, value): """Set the Snippets value of this General Settings object. Args: value: string The new Snippets value to give this object. """ self._SetProperty(GENERAL_SNIPPETS, value) snippets = pyproperty(GetSnippets, SetSnippets) def GetUnicode(self): """Get the Unicode value of the General Settings object. Returns: The Unicode value of this General Settings object as a string or None. """ return self._GetProperty(GENERAL_UNICODE) def SetUnicode(self, value): """Set the Unicode value of this General Settings object. Args: value: string The new Unicode value to give this object. """ self._SetProperty(GENERAL_UNICODE, value) use_unicode = pyproperty(GetUnicode, SetUnicode) def __init__(self, uri=None, page_size=None, shortcuts=None, arrows=None, snippets=None, use_unicode=None, *args, **kwargs): """Constructs a new EmailSettingsGeneral object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. page_size: int (optional) The number of conversations to be shown per page. shortcuts: Boolean (optional) Whether to enable keyboard shortcuts. arrows: Boolean (optional) Whether to display arrow-shaped personal indicators next to email sent specifically to the user. snippets: Boolean (optional) Whether to display snippets of the messages in the inbox and when searching. use_unicode: Boolean (optional) Whether to use UTF-8 (unicode) encoding for all outgoing messages. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsGeneral, self).__init__(*args, **kwargs) if uri: self.uri = uri if page_size is not None: self.page_size = str(page_size) if shortcuts is not None: self.shortcuts = str(shortcuts) if arrows is not None: self.arrows = str(arrows) if snippets is not None: self.snippets = str(snippets) if use_unicode is not None: self.use_unicode = str(use_unicode)
Python
#!/usr/bin/python # # Copyright (C) 2008 Google # # 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) 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. """Allow Google Apps domain administrators to manage organization unit and organization user. OrganizationService: Provides methods to manage organization unit and organization user. """ __author__ = 'Alexandre Vivien (alex@simplecode.fr)' import gdata.apps import gdata.apps.service import gdata.service API_VER = '2.0' CUSTOMER_BASE_URL = '/a/feeds/customer/2.0/customerId' BASE_UNIT_URL = '/a/feeds/orgunit/' + API_VER + '/%s' UNIT_URL = BASE_UNIT_URL + '/%s' UNIT_ALL_URL = BASE_UNIT_URL + '?get=all' UNIT_CHILD_URL = BASE_UNIT_URL + '?get=children&orgUnitPath=%s' BASE_USER_URL = '/a/feeds/orguser/' + API_VER + '/%s' USER_URL = BASE_USER_URL + '/%s' USER_ALL_URL = BASE_USER_URL + '?get=all' USER_CHILD_URL = BASE_USER_URL + '?get=children&orgUnitPath=%s' class OrganizationService(gdata.apps.service.PropertyService): """Client for the Google Apps Organizations service.""" def _Bool2Str(self, b): if b is None: return None return str(b is True).lower() def RetrieveCustomerId(self): """Retrieve the Customer ID for the account of the authenticated administrator making this request. Args: None. Returns: A dict containing the result of the retrieve operation. """ uri = CUSTOMER_BASE_URL return self._GetProperties(uri) def CreateOrgUnit(self, customer_id, name, parent_org_unit_path='/', description='', block_inheritance=False): """Create a Organization Unit. Args: customer_id: The ID of the Google Apps customer. name: The simple organization unit text name, not the full path name. parent_org_unit_path: The full path of the parental tree to this organization unit (default: '/'). Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) description: The human readable text description of the organization unit (optional). block_inheritance: This parameter blocks policy setting inheritance from organization units higher in the organization tree (default: False). Returns: A dict containing the result of the create operation. """ uri = BASE_UNIT_URL % (customer_id) properties = {} properties['name'] = name properties['parentOrgUnitPath'] = parent_org_unit_path properties['description'] = description properties['blockInheritance'] = self._Bool2Str(block_inheritance) return self._PostProperties(uri, properties) def UpdateOrgUnit(self, customer_id, org_unit_path, name=None, parent_org_unit_path=None, description=None, block_inheritance=None): """Update a Organization Unit. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) name: The simple organization unit text name, not the full path name. parent_org_unit_path: The full path of the parental tree to this organization unit. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) description: The human readable text description of the organization unit. block_inheritance: This parameter blocks policy setting inheritance from organization units higher in the organization tree. Returns: A dict containing the result of the update operation. """ uri = UNIT_URL % (customer_id, org_unit_path) properties = {} if name: properties['name'] = name if parent_org_unit_path: properties['parentOrgUnitPath'] = parent_org_unit_path if description: properties['description'] = description if block_inheritance: properties['blockInheritance'] = self._Bool2Str(block_inheritance) return self._PutProperties(uri, properties) def MoveUserToOrgUnit(self, customer_id, org_unit_path, users_to_move): """Move a user to an Organization Unit. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) users_to_move: Email addresses list of users to move. Note: You can move a maximum of 25 users at one time. Returns: A dict containing the result of the update operation. """ uri = UNIT_URL % (customer_id, org_unit_path) properties = {} if users_to_move and isinstance(users_to_move, list): properties['usersToMove'] = ', '.join(users_to_move) return self._PutProperties(uri, properties) def RetrieveOrgUnit(self, customer_id, org_unit_path): """Retrieve a Orgunit based on its path. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) Returns: A dict containing the result of the retrieve operation. """ uri = UNIT_URL % (customer_id, org_unit_path) return self._GetProperties(uri) def DeleteOrgUnit(self, customer_id, org_unit_path): """Delete a Orgunit based on its path. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) Returns: A dict containing the result of the delete operation. """ uri = UNIT_URL % (customer_id, org_unit_path) return self._DeleteProperties(uri) def RetrieveAllOrgUnits(self, customer_id): """Retrieve all OrgUnits in the customer's domain. Args: customer_id: The ID of the Google Apps customer. Returns: A list containing the result of the retrieve operation. """ uri = UNIT_ALL_URL % (customer_id) return self._GetPropertiesList(uri) def RetrievePageOfOrgUnits(self, customer_id, startKey=None): """Retrieve one page of OrgUnits in the customer's domain. Args: customer_id: The ID of the Google Apps customer. startKey: The key to continue for pagination through all OrgUnits. Returns: A feed object containing the result of the retrieve operation. """ uri = UNIT_ALL_URL % (customer_id) if startKey is not None: uri += "&startKey=" + startKey property_feed = self._GetPropertyFeed(uri) return property_feed def RetrieveSubOrgUnits(self, customer_id, org_unit_path): """Retrieve all Sub-OrgUnits of the provided OrgUnit. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) Returns: A list containing the result of the retrieve operation. """ uri = UNIT_CHILD_URL % (customer_id, org_unit_path) return self._GetPropertiesList(uri) def RetrieveOrgUser(self, customer_id, user_email): """Retrieve the OrgUnit of the user. Args: customer_id: The ID of the Google Apps customer. user_email: The email address of the user. Returns: A dict containing the result of the retrieve operation. """ uri = USER_URL % (customer_id, user_email) return self._GetProperties(uri) def UpdateOrgUser(self, customer_id, user_email, org_unit_path): """Update the OrgUnit of a OrgUser. Args: customer_id: The ID of the Google Apps customer. user_email: The email address of the user. org_unit_path: The new organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) Returns: A dict containing the result of the update operation. """ uri = USER_URL % (customer_id, user_email) properties = {} if org_unit_path: properties['orgUnitPath'] = org_unit_path return self._PutProperties(uri, properties) def RetrieveAllOrgUsers(self, customer_id): """Retrieve all OrgUsers in the customer's domain. Args: customer_id: The ID of the Google Apps customer. Returns: A list containing the result of the retrieve operation. """ uri = USER_ALL_URL % (customer_id) return self._GetPropertiesList(uri) def RetrievePageOfOrgUsers(self, customer_id, startKey=None): """Retrieve one page of OrgUsers in the customer's domain. Args: customer_id: The ID of the Google Apps customer. startKey: The key to continue for pagination through all OrgUnits. Returns: A feed object containing the result of the retrieve operation. """ uri = USER_ALL_URL % (customer_id) if startKey is not None: uri += "&startKey=" + startKey property_feed = self._GetPropertyFeed(uri) return property_feed def RetrieveOrgUnitUsers(self, customer_id, org_unit_path): """Retrieve all OrgUsers of the provided OrgUnit. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) Returns: A list containing the result of the retrieve operation. """ uri = USER_CHILD_URL % (customer_id, org_unit_path) return self._GetPropertiesList(uri) def RetrieveOrgUnitPageOfUsers(self, customer_id, org_unit_path, startKey=None): """Retrieve one page of OrgUsers of the provided OrgUnit. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) startKey: The key to continue for pagination through all OrgUsers. Returns: A feed object containing the result of the retrieve operation. """ uri = USER_CHILD_URL % (customer_id, org_unit_path) if startKey is not None: uri += "&startKey=" + startKey property_feed = self._GetPropertyFeed(uri) return property_feed
Python
#!/usr/bin/python # # Copyright (C) 2007 SIOS Technology, 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 objects used with Google Apps.""" __author__ = 'tmatsuo@sios.com (Takashi MATSUO)' import atom import gdata # XML namespaces which are often used in Google Apps entity. APPS_NAMESPACE = 'http://schemas.google.com/apps/2006' APPS_TEMPLATE = '{http://schemas.google.com/apps/2006}%s' class EmailList(atom.AtomBase): """The Google Apps EmailList element""" _tag = 'emailList' _namespace = APPS_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.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailListFromString(xml_string): return atom.CreateClassFromXMLString(EmailList, xml_string) class Who(atom.AtomBase): """The Google Apps Who element""" _tag = 'who' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['email'] = 'email' def __init__(self, rel=None, email=None, extension_elements=None, extension_attributes=None, text=None): self.rel = rel self.email = email self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def WhoFromString(xml_string): return atom.CreateClassFromXMLString(Who, xml_string) class Login(atom.AtomBase): """The Google Apps Login element""" _tag = 'login' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['userName'] = 'user_name' _attributes['password'] = 'password' _attributes['suspended'] = 'suspended' _attributes['admin'] = 'admin' _attributes['changePasswordAtNextLogin'] = 'change_password' _attributes['agreedToTerms'] = 'agreed_to_terms' _attributes['ipWhitelisted'] = 'ip_whitelisted' _attributes['hashFunctionName'] = 'hash_function_name' def __init__(self, user_name=None, password=None, suspended=None, ip_whitelisted=None, hash_function_name=None, admin=None, change_password=None, agreed_to_terms=None, extension_elements=None, extension_attributes=None, text=None): self.user_name = user_name self.password = password self.suspended = suspended self.admin = admin self.change_password = change_password self.agreed_to_terms = agreed_to_terms self.ip_whitelisted = ip_whitelisted self.hash_function_name = hash_function_name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def LoginFromString(xml_string): return atom.CreateClassFromXMLString(Login, xml_string) class Quota(atom.AtomBase): """The Google Apps Quota element""" _tag = 'quota' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['limit'] = 'limit' def __init__(self, limit=None, extension_elements=None, extension_attributes=None, text=None): self.limit = limit self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def QuotaFromString(xml_string): return atom.CreateClassFromXMLString(Quota, xml_string) class Name(atom.AtomBase): """The Google Apps Name element""" _tag = 'name' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['familyName'] = 'family_name' _attributes['givenName'] = 'given_name' def __init__(self, family_name=None, given_name=None, extension_elements=None, extension_attributes=None, text=None): self.family_name = family_name self.given_name = given_name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NameFromString(xml_string): return atom.CreateClassFromXMLString(Name, xml_string) class Nickname(atom.AtomBase): """The Google Apps Nickname element""" _tag = 'nickname' _namespace = APPS_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.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NicknameFromString(xml_string): return atom.CreateClassFromXMLString(Nickname, xml_string) class NicknameEntry(gdata.GDataEntry): """A Google Apps flavor of an Atom Entry for Nickname""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}login' % APPS_NAMESPACE] = ('login', Login) _children['{%s}nickname' % APPS_NAMESPACE] = ('nickname', Nickname) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, login=None, nickname=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) self.login = login self.nickname = nickname self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NicknameEntryFromString(xml_string): return atom.CreateClassFromXMLString(NicknameEntry, xml_string) class NicknameFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps Nickname feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [NicknameEntry]) 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 NicknameFeedFromString(xml_string): return atom.CreateClassFromXMLString(NicknameFeed, xml_string) class UserEntry(gdata.GDataEntry): """A Google Apps flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}login' % APPS_NAMESPACE] = ('login', Login) _children['{%s}name' % APPS_NAMESPACE] = ('name', Name) _children['{%s}quota' % APPS_NAMESPACE] = ('quota', Quota) # This child may already be defined in GDataEntry, confirm before removing. _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', [gdata.FeedLink]) _children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, login=None, name=None, quota=None, who=None, feed_link=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) self.login = login self.name = name self.quota = quota self.who = who self.feed_link = feed_link or [] self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def UserEntryFromString(xml_string): return atom.CreateClassFromXMLString(UserEntry, xml_string) class UserFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps User feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [UserEntry]) 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 UserFeedFromString(xml_string): return atom.CreateClassFromXMLString(UserFeed, xml_string) class EmailListEntry(gdata.GDataEntry): """A Google Apps EmailList flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}emailList' % APPS_NAMESPACE] = ('email_list', EmailList) # Might be able to remove this _children entry. _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', [gdata.FeedLink]) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, email_list=None, feed_link=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) self.email_list = email_list self.feed_link = feed_link or [] self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailListEntryFromString(xml_string): return atom.CreateClassFromXMLString(EmailListEntry, xml_string) class EmailListFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps EmailList feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [EmailListEntry]) 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 EmailListFeedFromString(xml_string): return atom.CreateClassFromXMLString(EmailListFeed, xml_string) class EmailListRecipientEntry(gdata.GDataEntry): """A Google Apps EmailListRecipient flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, who=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) self.who = who self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailListRecipientEntryFromString(xml_string): return atom.CreateClassFromXMLString(EmailListRecipientEntry, xml_string) class EmailListRecipientFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps EmailListRecipient feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [EmailListRecipientEntry]) 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 EmailListRecipientFeedFromString(xml_string): return atom.CreateClassFromXMLString(EmailListRecipientFeed, xml_string) class Property(atom.AtomBase): """The Google Apps Property element""" _tag = 'property' _namespace = APPS_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 PropertyFromString(xml_string): return atom.CreateClassFromXMLString(Property, xml_string) class PropertyEntry(gdata.GDataEntry): """A Google Apps Property flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}property' % APPS_NAMESPACE] = ('property', [Property]) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, property=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) self.property = property self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def PropertyEntryFromString(xml_string): return atom.CreateClassFromXMLString(PropertyEntry, xml_string) class PropertyFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps Property feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [PropertyEntry]) 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 PropertyFeedFromString(xml_string): return atom.CreateClassFromXMLString(PropertyFeed, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 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. """Allow Google Apps domain administrators to set domain admin settings. AdminSettingsService: Set admin settings.""" __author__ = 'jlee@pbu.edu' import gdata.apps import gdata.apps.service import gdata.service API_VER='2.0' class AdminSettingsService(gdata.apps.service.PropertyService): """Client for the Google Apps Admin Settings service.""" def _serviceUrl(self, setting_id, domain=None): if domain is None: domain = self.domain return '/a/feeds/domain/%s/%s/%s' % (API_VER, domain, setting_id) def genericGet(self, location): """Generic HTTP Get Wrapper Args: location: relative uri to Get Returns: A dict containing the result of the get operation.""" uri = self._serviceUrl(location) try: return self._GetProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def GetDefaultLanguage(self): """Gets Domain Default Language Args: None Returns: Default Language as a string. All possible values are listed at: http://code.google.com/apis/apps/email_settings/developers_guide_protocol.html#GA_email_language_tags""" result = self.genericGet('general/defaultLanguage') return result['defaultLanguage'] def UpdateDefaultLanguage(self, defaultLanguage): """Updates Domain Default Language Args: defaultLanguage: Domain Language to set possible values are at: http://code.google.com/apis/apps/email_settings/developers_guide_protocol.html#GA_email_language_tags Returns: A dict containing the result of the put operation""" uri = self._serviceUrl('general/defaultLanguage') properties = {'defaultLanguage': defaultLanguage} return self._PutProperties(uri, properties) def GetOrganizationName(self): """Gets Domain Default Language Args: None Returns: Organization Name as a string.""" result = self.genericGet('general/organizationName') return result['organizationName'] def UpdateOrganizationName(self, organizationName): """Updates Organization Name Args: organizationName: Name of organization Returns: A dict containing the result of the put operation""" uri = self._serviceUrl('general/organizationName') properties = {'organizationName': organizationName} return self._PutProperties(uri, properties) def GetMaximumNumberOfUsers(self): """Gets Maximum Number of Users Allowed Args: None Returns: An integer, the maximum number of users""" result = self.genericGet('general/maximumNumberOfUsers') return int(result['maximumNumberOfUsers']) def GetCurrentNumberOfUsers(self): """Gets Current Number of Users Args: None Returns: An integer, the current number of users""" result = self.genericGet('general/currentNumberOfUsers') return int(result['currentNumberOfUsers']) def IsDomainVerified(self): """Is the domain verified Args: None Returns: Boolean, is domain verified""" result = self.genericGet('accountInformation/isVerified') if result['isVerified'] == 'true': return True else: return False def GetSupportPIN(self): """Gets Support PIN Args: None Returns: A string, the Support PIN""" result = self.genericGet('accountInformation/supportPIN') return result['supportPIN'] def GetEdition(self): """Gets Google Apps Domain Edition Args: None Returns: A string, the domain's edition (premier, education, partner)""" result = self.genericGet('accountInformation/edition') return result['edition'] def GetCustomerPIN(self): """Gets Customer PIN Args: None Returns: A string, the customer PIN""" result = self.genericGet('accountInformation/customerPIN') return result['customerPIN'] def GetCreationTime(self): """Gets Domain Creation Time Args: None Returns: A string, the domain's creation time""" result = self.genericGet('accountInformation/creationTime') return result['creationTime'] def GetCountryCode(self): """Gets Domain Country Code Args: None Returns: A string, the domain's country code. Possible values at: http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm""" result = self.genericGet('accountInformation/countryCode') return result['countryCode'] def GetAdminSecondaryEmail(self): """Gets Domain Admin Secondary Email Address Args: None Returns: A string, the secondary email address for domain admin""" result = self.genericGet('accountInformation/adminSecondaryEmail') return result['adminSecondaryEmail'] def UpdateAdminSecondaryEmail(self, adminSecondaryEmail): """Gets Domain Creation Time Args: adminSecondaryEmail: string, secondary email address of admin Returns: A dict containing the result of the put operation""" uri = self._serviceUrl('accountInformation/adminSecondaryEmail') properties = {'adminSecondaryEmail': adminSecondaryEmail} return self._PutProperties(uri, properties) def GetDomainLogo(self): """Gets Domain Logo This function does not make use of the Google Apps Admin Settings API, it does an HTTP Get of a url specific to the Google Apps domain. It is included for completeness sake. Args: None Returns: binary image file""" import urllib url = 'http://www.google.com/a/cpanel/'+self.domain+'/images/logo.gif' response = urllib.urlopen(url) return response.read() def UpdateDomainLogo(self, logoImage): """Update Domain's Custom Logo Args: logoImage: binary image data Returns: A dict containing the result of the put operation""" from base64 import base64encode uri = self._serviceUrl('appearance/customLogo') properties = {'logoImage': base64encode(logoImage)} return self._PutProperties(uri, properties) def GetCNAMEVerificationStatus(self): """Gets Domain CNAME Verification Status Args: None Returns: A dict {recordName, verified, verifiedMethod}""" return self.genericGet('verification/cname') def UpdateCNAMEVerificationStatus(self, verified): """Updates CNAME Verification Status Args: verified: boolean, True will retry verification process Returns: A dict containing the result of the put operation""" uri = self._serviceUrl('verification/cname') properties = self.GetCNAMEVerificationStatus() properties['verified'] = verified return self._PutProperties(uri, properties) def GetMXVerificationStatus(self): """Gets Domain MX Verification Status Args: None Returns: A dict {verified, verifiedMethod}""" return self.genericGet('verification/mx') def UpdateMXVerificationStatus(self, verified): """Updates MX Verification Status Args: verified: boolean, True will retry verification process Returns: A dict containing the result of the put operation""" uri = self._serviceUrl('verification/mx') properties = self.GetMXVerificationStatus() properties['verified'] = verified return self._PutProperties(uri, properties) def GetSSOSettings(self): """Gets Domain Single Sign-On Settings Args: None Returns: A dict {samlSignonUri, samlLogoutUri, changePasswordUri, enableSSO, ssoWhitelist, useDomainSpecificIssuer}""" return self.genericGet('sso/general') def UpdateSSOSettings(self, enableSSO=None, samlSignonUri=None, samlLogoutUri=None, changePasswordUri=None, ssoWhitelist=None, useDomainSpecificIssuer=None): """Update SSO Settings. Args: enableSSO: boolean, SSO Master on/off switch samlSignonUri: string, SSO Login Page samlLogoutUri: string, SSO Logout Page samlPasswordUri: string, SSO Password Change Page ssoWhitelist: string, Range of IP Addresses which will see SSO useDomainSpecificIssuer: boolean, Include Google Apps Domain in Issuer Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('sso/general') #Get current settings, replace Nones with '' properties = self.GetSSOSettings() if properties['samlSignonUri'] == None: properties['samlSignonUri'] = '' if properties['samlLogoutUri'] == None: properties['samlLogoutUri'] = '' if properties['changePasswordUri'] == None: properties['changePasswordUri'] = '' if properties['ssoWhitelist'] == None: properties['ssoWhitelist'] = '' #update only the values we were passed if enableSSO != None: properties['enableSSO'] = gdata.apps.service._bool2str(enableSSO) if samlSignonUri != None: properties['samlSignonUri'] = samlSignonUri if samlLogoutUri != None: properties['samlLogoutUri'] = samlLogoutUri if changePasswordUri != None: properties['changePasswordUri'] = changePasswordUri if ssoWhitelist != None: properties['ssoWhitelist'] = ssoWhitelist if useDomainSpecificIssuer != None: properties['useDomainSpecificIssuer'] = gdata.apps.service._bool2str(useDomainSpecificIssuer) return self._PutProperties(uri, properties) def GetSSOKey(self): """Gets Domain Single Sign-On Signing Key Args: None Returns: A dict {modulus, exponent, algorithm, format}""" return self.genericGet('sso/signingkey') def UpdateSSOKey(self, signingKey): """Update SSO Settings. Args: signingKey: string, public key to be uploaded Returns: A dict containing the result of the update operation.""" uri = self._serviceUrl('sso/signingkey') properties = {'signingKey': signingKey} return self._PutProperties(uri, properties) def IsUserMigrationEnabled(self): """Is User Migration Enabled Args: None Returns: boolean, is user migration enabled""" result = self.genericGet('email/migration') if result['enableUserMigration'] == 'true': return True else: return False def UpdateUserMigrationStatus(self, enableUserMigration): """Update User Migration Status Args: enableUserMigration: boolean, user migration enable/disable Returns: A dict containing the result of the update operation.""" uri = self._serviceUrl('email/migration') properties = {'enableUserMigration': enableUserMigration} return self._PutProperties(uri, properties) def GetOutboundGatewaySettings(self): """Get Outbound Gateway Settings Args: None Returns: A dict {smartHost, smtpMode}""" uri = self._serviceUrl('email/gateway') try: return self._GetProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) except TypeError: #if no outbound gateway is set, we get a TypeError, #catch it and return nothing... return {'smartHost': None, 'smtpMode': None} def UpdateOutboundGatewaySettings(self, smartHost=None, smtpMode=None): """Update Outbound Gateway Settings Args: smartHost: string, ip address or hostname of outbound gateway smtpMode: string, SMTP or SMTP_TLS Returns: A dict containing the result of the update operation.""" uri = self._serviceUrl('email/gateway') #Get current settings, replace Nones with '' properties = GetOutboundGatewaySettings() if properties['smartHost'] == None: properties['smartHost'] = '' if properties['smtpMode'] == None: properties['smtpMode'] = '' #If we were passed new values for smartHost or smtpMode, update them if smartHost != None: properties['smartHost'] = smartHost if smtpMode != None: properties['smtpMode'] = smtpMode return self._PutProperties(uri, properties) def AddEmailRoute(self, routeDestination, routeRewriteTo, routeEnabled, bounceNotifications, accountHandling): """Adds Domain Email Route Args: routeDestination: string, destination ip address or hostname routeRewriteTo: boolean, rewrite smtp envelop To: routeEnabled: boolean, enable disable email routing bounceNotifications: boolean, send bound notificiations to sender accountHandling: string, which to route, "allAccounts", "provisionedAccounts", "unknownAccounts" Returns: A dict containing the result of the update operation.""" uri = self._serviceUrl('emailrouting') properties = {} properties['routeDestination'] = routeDestination properties['routeRewriteTo'] = gdata.apps.service._bool2str(routeRewriteTo) properties['routeEnabled'] = gdata.apps.service._bool2str(routeEnabled) properties['bounceNotifications'] = gdata.apps.service._bool2str(bounceNotifications) properties['accountHandling'] = accountHandling return self._PostProperties(uri, properties)
Python
#!/usr/bin/python # # Copyright (C) 2008 Google # # 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
# Copyright (C) 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. """Allow Google Apps domain administrators to audit user data. AuditService: Set auditing.""" __author__ = 'jlee@pbu.edu' from base64 import b64encode import gdata.apps import gdata.apps.service import gdata.service class AuditService(gdata.apps.service.PropertyService): """Client for the Google Apps Audit service.""" def _serviceUrl(self, setting_id, domain=None, user=None): if domain is None: domain = self.domain if user is None: return '/a/feeds/compliance/audit/%s/%s' % (setting_id, domain) else: return '/a/feeds/compliance/audit/%s/%s/%s' % (setting_id, domain, user) def updatePGPKey(self, pgpkey): """Updates Public PGP Key Google uses to encrypt audit data Args: pgpkey: string, ASCII text of PGP Public Key to be used Returns: A dict containing the result of the POST operation.""" uri = self._serviceUrl('publickey') b64pgpkey = b64encode(pgpkey) properties = {} properties['publicKey'] = b64pgpkey return self._PostProperties(uri, properties) def createEmailMonitor(self, source_user, destination_user, end_date, begin_date=None, incoming_headers_only=False, outgoing_headers_only=False, drafts=False, drafts_headers_only=False, chats=False, chats_headers_only=False): """Creates a email monitor, forwarding the source_users emails/chats Args: source_user: string, the user whose email will be audited destination_user: string, the user to receive the audited email end_date: string, the date the audit will end in "yyyy-MM-dd HH:mm" format, required begin_date: string, the date the audit will start in "yyyy-MM-dd HH:mm" format, leave blank to use current time incoming_headers_only: boolean, whether to audit only the headers of mail delivered to source user outgoing_headers_only: boolean, whether to audit only the headers of mail sent from the source user drafts: boolean, whether to audit draft messages of the source user drafts_headers_only: boolean, whether to audit only the headers of mail drafts saved by the user chats: boolean, whether to audit archived chats of the source user chats_headers_only: boolean, whether to audit only the headers of archived chats of the source user Returns: A dict containing the result of the POST operation.""" uri = self._serviceUrl('mail/monitor', user=source_user) properties = {} properties['destUserName'] = destination_user if begin_date is not None: properties['beginDate'] = begin_date properties['endDate'] = end_date if incoming_headers_only: properties['incomingEmailMonitorLevel'] = 'HEADER_ONLY' else: properties['incomingEmailMonitorLevel'] = 'FULL_MESSAGE' if outgoing_headers_only: properties['outgoingEmailMonitorLevel'] = 'HEADER_ONLY' else: properties['outgoingEmailMonitorLevel'] = 'FULL_MESSAGE' if drafts: if drafts_headers_only: properties['draftMonitorLevel'] = 'HEADER_ONLY' else: properties['draftMonitorLevel'] = 'FULL_MESSAGE' if chats: if chats_headers_only: properties['chatMonitorLevel'] = 'HEADER_ONLY' else: properties['chatMonitorLevel'] = 'FULL_MESSAGE' return self._PostProperties(uri, properties) def getEmailMonitors(self, user): """"Gets the email monitors for the given user Args: user: string, the user to retrieve email monitors for Returns: list results of the POST operation """ uri = self._serviceUrl('mail/monitor', user=user) return self._GetPropertiesList(uri) def deleteEmailMonitor(self, source_user, destination_user): """Deletes the email monitor for the given user Args: source_user: string, the user who is being monitored destination_user: string, theuser who recieves the monitored emails Returns: Nothing """ uri = self._serviceUrl('mail/monitor', user=source_user+'/'+destination_user) try: return self._DeleteProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def createAccountInformationRequest(self, user): """Creates a request for account auditing details Args: user: string, the user to request account information for Returns: A dict containing the result of the post operation.""" uri = self._serviceUrl('account', user=user) properties = {} #XML Body is left empty try: return self._PostProperties(uri, properties) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def getAccountInformationRequestStatus(self, user, request_id): """Gets the status of an account auditing request Args: user: string, the user whose account auditing details were requested request_id: string, the request_id Returns: A dict containing the result of the get operation.""" uri = self._serviceUrl('account', user=user+'/'+request_id) try: return self._GetProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def getAllAccountInformationRequestsStatus(self): """Gets the status of all account auditing requests for the domain Args: None Returns: list results of the POST operation """ uri = self._serviceUrl('account') return self._GetPropertiesList(uri) def deleteAccountInformationRequest(self, user, request_id): """Deletes the request for account auditing information Args: user: string, the user whose account auditing details were requested request_id: string, the request_id Returns: Nothing """ uri = self._serviceUrl('account', user=user+'/'+request_id) try: return self._DeleteProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def createMailboxExportRequest(self, user, begin_date=None, end_date=None, include_deleted=False, search_query=None, headers_only=False): """Creates a mailbox export request Args: user: string, the user whose mailbox export is being requested begin_date: string, date of earliest emails to export, optional, defaults to date of account creation format is 'yyyy-MM-dd HH:mm' end_date: string, date of latest emails to export, optional, defaults to current date format is 'yyyy-MM-dd HH:mm' include_deleted: boolean, whether to include deleted emails in export, mutually exclusive with search_query search_query: string, gmail style search query, matched emails will be exported, mutually exclusive with include_deleted Returns: A dict containing the result of the post operation.""" uri = self._serviceUrl('mail/export', user=user) properties = {} if begin_date is not None: properties['beginDate'] = begin_date if end_date is not None: properties['endDate'] = end_date if include_deleted is not None: properties['includeDeleted'] = gdata.apps.service._bool2str(include_deleted) if search_query is not None: properties['searchQuery'] = search_query if headers_only is True: properties['packageContent'] = 'HEADER_ONLY' else: properties['packageContent'] = 'FULL_MESSAGE' return self._PostProperties(uri, properties) def getMailboxExportRequestStatus(self, user, request_id): """Gets the status of an mailbox export request Args: user: string, the user whose mailbox were requested request_id: string, the request_id Returns: A dict containing the result of the get operation.""" uri = self._serviceUrl('mail/export', user=user+'/'+request_id) try: return self._GetProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def getAllMailboxExportRequestsStatus(self): """Gets the status of all mailbox export requests for the domain Args: None Returns: list results of the POST operation """ uri = self._serviceUrl('mail/export') return self._GetPropertiesList(uri) def deleteMailboxExportRequest(self, user, request_id): """Deletes the request for mailbox export Args: user: string, the user whose mailbox were requested request_id: string, the request_id Returns: Nothing """ uri = self._serviceUrl('mail/export', user=user+'/'+request_id) try: return self._DeleteProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0])
Python
#!/usr/bin/python # # Copyright (C) 2007 - 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. import cgi import math import random import re import time import types import urllib import atom.http_interface import atom.token_store import atom.url import gdata.oauth as oauth import gdata.oauth.rsa as oauth_rsa import gdata.tlslite.utils.keyfactory as keyfactory import gdata.tlslite.utils.cryptomath as cryptomath import gdata.gauth __author__ = 'api.jscudder (Jeff Scudder)' PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth=' AUTHSUB_AUTH_LABEL = 'AuthSub token=' """This module provides functions and objects used with Google authentication. Details on Google authorization mechanisms used with the Google Data APIs can be found here: http://code.google.com/apis/gdata/auth.html http://code.google.com/apis/accounts/ The essential functions are the following. Related to ClientLogin: generate_client_login_request_body: Constructs the body of an HTTP request to obtain a ClientLogin token for a specific service. extract_client_login_token: Creates a ClientLoginToken with the token from a success response to a ClientLogin request. get_captcha_challenge: If the server responded to the ClientLogin request with a CAPTCHA challenge, this method extracts the CAPTCHA URL and identifying CAPTCHA token. Related to AuthSub: generate_auth_sub_url: Constructs a full URL for a AuthSub request. The user's browser must be sent to this Google Accounts URL and redirected back to the app to obtain the AuthSub token. extract_auth_sub_token_from_url: Once the user's browser has been redirected back to the web app, use this function to create an AuthSubToken with the correct authorization token and scope. token_from_http_body: Extracts the AuthSubToken value string from the server's response to an AuthSub session token upgrade request. """ def generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): """Creates the body of the autentication request See http://code.google.com/apis/accounts/AuthForInstalledApps.html#Request for more details. Args: email: str password: str service: str source: str account_type: str (optional) Defaul is 'HOSTED_OR_GOOGLE', other valid values are 'GOOGLE' and 'HOSTED' captcha_token: str (optional) captcha_response: str (optional) Returns: The HTTP body to send in a request for a client login token. """ return gdata.gauth.generate_client_login_request_body(email, password, service, source, account_type, captcha_token, captcha_response) GenerateClientLoginRequestBody = generate_client_login_request_body def GenerateClientLoginAuthToken(http_body): """Returns the token value to use in Authorization headers. Reads the token from the server's response to a Client Login request and creates header value to use in requests. Args: http_body: str The body of the server's HTTP response to a Client Login request Returns: The value half of an Authorization header. """ token = get_client_login_token(http_body) if token: return 'GoogleLogin auth=%s' % token return None def get_client_login_token(http_body): """Returns the token value for a ClientLoginToken. Reads the token from the server's response to a Client Login request and creates the token value string to use in requests. Args: http_body: str The body of the server's HTTP response to a Client Login request Returns: The token value string for a ClientLoginToken. """ return gdata.gauth.get_client_login_token_string(http_body) def extract_client_login_token(http_body, scopes): """Parses the server's response and returns a ClientLoginToken. Args: http_body: str The body of the server's HTTP response to a Client Login request. It is assumed that the login request was successful. scopes: list containing atom.url.Urls or strs. The scopes list contains all of the partial URLs under which the client login token is valid. For example, if scopes contains ['http://example.com/foo'] then the client login token would be valid for http://example.com/foo/bar/baz Returns: A ClientLoginToken which is valid for the specified scopes. """ token_string = get_client_login_token(http_body) token = ClientLoginToken(scopes=scopes) token.set_token_string(token_string) return token def get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): """Returns the URL and token for a CAPTCHA challenge issued by the server. Args: http_body: str The body of the HTTP response from the server which contains the CAPTCHA challenge. captcha_base_url: str This function returns a full URL for viewing the challenge image which is built from the server's response. This base_url is used as the beginning of the URL because the server only provides the end of the URL. For example the server provides 'Captcha?ctoken=Hi...N' and the URL for the image is 'http://www.google.com/accounts/Captcha?ctoken=Hi...N' Returns: A dictionary containing the information needed to repond to the CAPTCHA challenge, the image URL and the ID token of the challenge. The dictionary is in the form: {'token': string identifying the CAPTCHA image, 'url': string containing the URL of the image} Returns None if there was no CAPTCHA challenge in the response. """ return gdata.gauth.get_captcha_challenge(http_body, captcha_base_url) GetCaptchaChallenge = get_captcha_challenge def GenerateOAuthRequestTokenUrl( oauth_input_params, scopes, request_token_url='https://www.google.com/accounts/OAuthGetRequestToken', extra_parameters=None): """Generate a URL at which a request for OAuth request token is to be sent. Args: oauth_input_params: OAuthInputParams OAuth input parameters. scopes: list of strings The URLs of the services to be accessed. request_token_url: string The beginning of the request token URL. This is normally 'https://www.google.com/accounts/OAuthGetRequestToken' or '/accounts/OAuthGetRequestToken' 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'} Returns: atom.url.Url OAuth request token URL. """ scopes_string = ' '.join([str(scope) for scope in scopes]) parameters = {'scope': scopes_string} if extra_parameters: parameters.update(extra_parameters) oauth_request = oauth.OAuthRequest.from_consumer_and_token( oauth_input_params.GetConsumer(), http_url=request_token_url, parameters=parameters) oauth_request.sign_request(oauth_input_params.GetSignatureMethod(), oauth_input_params.GetConsumer(), None) return atom.url.parse_url(oauth_request.to_url()) def GenerateOAuthAuthorizationUrl( request_token, authorization_url='https://www.google.com/accounts/OAuthAuthorizeToken', callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix='oauth_token_scope'): """Generates URL at which user will login to authorize the request token. Args: request_token: gdata.auth.OAuthToken OAuth request token. authorization_url: string The beginning of the authorization URL. This is normally 'https://www.google.com/accounts/OAuthAuthorizeToken' or '/accounts/OAuthAuthorizeToken' 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. Returns: atom.url.Url OAuth authorization URL. """ scopes = request_token.scopes if isinstance(scopes, list): scopes = ' '.join(scopes) if include_scopes_in_callback and callback_url: if callback_url.find('?') > -1: callback_url += '&' else: callback_url += '?' callback_url += urllib.urlencode({scopes_param_prefix:scopes}) oauth_token = oauth.OAuthToken(request_token.key, request_token.secret) oauth_request = oauth.OAuthRequest.from_token_and_callback( token=oauth_token, callback=callback_url, http_url=authorization_url, parameters=extra_params) return atom.url.parse_url(oauth_request.to_url()) def GenerateOAuthAccessTokenUrl( authorized_request_token, oauth_input_params, access_token_url='https://www.google.com/accounts/OAuthGetAccessToken', oauth_version='1.0', oauth_verifier=None): """Generates URL at which user will login to authorize the request token. Args: authorized_request_token: gdata.auth.OAuthToken OAuth authorized request token. oauth_input_params: OAuthInputParams OAuth input parameters. access_token_url: string The beginning of the authorization URL. This is normally 'https://www.google.com/accounts/OAuthGetAccessToken' or '/accounts/OAuthGetAccessToken' oauth_version: str (default='1.0') oauth_version parameter. 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: atom.url.Url OAuth access token URL. """ oauth_token = oauth.OAuthToken(authorized_request_token.key, authorized_request_token.secret) parameters = {'oauth_version': oauth_version} if oauth_verifier is not None: parameters['oauth_verifier'] = oauth_verifier oauth_request = oauth.OAuthRequest.from_consumer_and_token( oauth_input_params.GetConsumer(), token=oauth_token, http_url=access_token_url, parameters=parameters) oauth_request.sign_request(oauth_input_params.GetSignatureMethod(), oauth_input_params.GetConsumer(), oauth_token) return atom.url.parse_url(oauth_request.to_url()) def GenerateAuthSubUrl(next, scope, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', 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/AuthForWebApps.html Args: request_url: str The beginning of the request URL. This is normally 'http://www.google.com/accounts/AuthSubRequest' or '/accounts/AuthSubRequest' next: string The URL user will be sent to after logging in. scope: string The URL of the service 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. domain: str (optional) The Google Apps domain for this account. If this is not a Google Apps account, use 'default' which is the default value. """ # Translate True/False values for parameters into numeric values acceoted # by the AuthSub service. if secure: secure = 1 else: secure = 0 if session: session = 1 else: session = 0 request_params = urllib.urlencode({'next': next, 'scope': scope, 'secure': secure, 'session': session, 'hd': domain}) if request_url.find('?') == -1: return '%s?%s' % (request_url, request_params) else: # The request URL already contained url parameters so we should add # the parameters using the & seperator return '%s&%s' % (request_url, request_params) def generate_auth_sub_url(next, scopes, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default', scopes_param_prefix='auth_sub_scopes'): """Constructs a URL string for requesting a multiscope AuthSub token. The generated token will contain a URL parameter to pass along the requested scopes to the next URL. When the Google Accounts page redirects the broswser to the 'next' URL, it appends the single use AuthSub token value to the URL as a URL parameter with the key 'token'. However, the information about which scopes were requested is not included by Google Accounts. This method adds the scopes to the next URL before making the request so that the redirect will be sent to a page, and both the token value and the list of scopes can be extracted from the request URL. Args: next: atom.url.URL or string The URL user will be sent to after authorizing this web application to access their data. scopes: list containint 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. request_url: atom.url.Url or str The beginning of the request URL. This is normally 'http://www.google.com/accounts/AuthSubRequest' or '/accounts/AuthSubRequest' domain: The domain which the account is part of. This is used for Google Apps accounts, the default value is 'default' which means that the requested account is a Google Account (@gmail.com for example) scopes_param_prefix: str (optional) The requested scopes are added as a URL parameter to the next URL so that the page at the 'next' URL can extract the token value and the valid scopes from the URL. The key for the URL parameter defaults to 'auth_sub_scopes' Returns: An atom.url.Url which the user's browser should be directed to in order to authorize this application to access their information. """ if isinstance(next, (str, unicode)): next = atom.url.parse_url(next) scopes_string = ' '.join([str(scope) for scope in scopes]) next.params[scopes_param_prefix] = scopes_string if isinstance(request_url, (str, unicode)): request_url = atom.url.parse_url(request_url) request_url.params['next'] = str(next) request_url.params['scope'] = scopes_string if session: request_url.params['session'] = 1 else: request_url.params['session'] = 0 if secure: request_url.params['secure'] = 1 else: request_url.params['secure'] = 0 request_url.params['hd'] = domain return request_url def AuthSubTokenFromUrl(url): """Extracts the AuthSub token from the URL. Used after the AuthSub redirect has sent the user to the 'next' page and appended the token to the URL. This function returns the value to be used in the Authorization header. Args: url: str The URL of the current page which contains the AuthSub token as a URL parameter. """ token = TokenFromUrl(url) if token: return 'AuthSub token=%s' % token return None def TokenFromUrl(url): """Extracts the AuthSub token from the URL. Returns the raw token value. Args: url: str The URL or the query portion of the URL string (after the ?) of the current page which contains the AuthSub token as a URL parameter. """ if url.find('?') > -1: query_params = url.split('?')[1] else: query_params = url for pair in query_params.split('&'): if pair.startswith('token='): return pair[6:] return None def extract_auth_sub_token_from_url(url, scopes_param_prefix='auth_sub_scopes', rsa_key=None): """Creates an AuthSubToken and sets the token value and scopes from the URL. After the Google Accounts AuthSub pages redirect the user's broswer back to the web application (using the 'next' URL from the request) the web app must extract the token from the current page's URL. The token is provided as a URL parameter named 'token' and if generate_auth_sub_url was used to create the request, the token's valid scopes are included in a URL parameter whose name is specified in scopes_param_prefix. Args: url: atom.url.Url or str representing the current URL. The token value and valid scopes should be included as URL parameters. scopes_param_prefix: str (optional) The URL parameter key which maps to the list of valid scopes for the token. Returns: An AuthSubToken with the token value from the URL and set to be valid for the scopes passed in on the URL. If no scopes were included in the URL, the AuthSubToken defaults to being valid for no scopes. If there was no 'token' parameter in the URL, this function returns None. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) if 'token' not in url.params: return None scopes = [] if scopes_param_prefix in url.params: scopes = url.params[scopes_param_prefix].split(' ') token_value = url.params['token'] if rsa_key: token = SecureAuthSubToken(rsa_key, scopes=scopes) else: token = AuthSubToken(scopes=scopes) token.set_token_string(token_value) return token def AuthSubTokenFromHttpBody(http_body): """Extracts the AuthSub token from an HTTP body string. Used to find the new session token after making a request to upgrade a single use AuthSub token. Args: http_body: str The repsonse from the server which contains the AuthSub key. For example, this function would find the new session token from the server's response to an upgrade token request. Returns: The header value to use for Authorization which contains the AuthSub token. """ token_value = token_from_http_body(http_body) if token_value: return '%s%s' % (AUTHSUB_AUTH_LABEL, token_value) return None def token_from_http_body(http_body): """Extracts the AuthSub token from an HTTP body string. Used to find the new session token after making a request to upgrade a single use AuthSub token. Args: http_body: str The repsonse from the server which contains the AuthSub key. For example, this function would find the new session token from the server's response to an upgrade token request. Returns: The raw token value to use in an AuthSubToken object. """ for response_line in http_body.splitlines(): if response_line.startswith('Token='): # Strip off Token= and return the token value string. return response_line[6:] return None TokenFromHttpBody = token_from_http_body def OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'): """Creates an OAuthToken and sets token key and scopes (if present) from URL. After the Google Accounts OAuth pages redirect the user's broswer back to the web application (using the 'callback' URL from the request) the web app can extract the token from the current page's URL. The token is same as the request token, but it is either authorized (if user grants access) or unauthorized (if user denies access). The token is provided as a URL parameter named 'oauth_token' and if it was chosen to use GenerateOAuthAuthorizationUrl with include_scopes_in_param=True, the token's valid scopes are included in a URL parameter whose name is specified in scopes_param_prefix. Args: url: atom.url.Url or str representing the current URL. The token value and valid scopes should be included as URL parameters. scopes_param_prefix: str (optional) The URL parameter key which maps to the list of valid scopes for the token. Returns: An OAuthToken with the token key from the URL and set to be valid for the scopes passed in on the URL. If no scopes were included in the URL, the OAuthToken defaults to being valid for no scopes. If there was no 'oauth_token' parameter in the URL, this function returns None. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) if 'oauth_token' not in url.params: return None scopes = [] if scopes_param_prefix in url.params: scopes = url.params[scopes_param_prefix].split(' ') token_key = url.params['oauth_token'] token = OAuthToken(key=token_key, scopes=scopes) return token def OAuthTokenFromHttpBody(http_body): """Parses the HTTP response body and returns an OAuth token. The returned OAuth token will just have key and secret parameters set. It won't have any knowledge about the scopes or oauth_input_params. It is your responsibility to make it aware of the remaining parameters. Returns: OAuthToken OAuth token. """ token = oauth.OAuthToken.from_string(http_body) oauth_token = OAuthToken(key=token.key, secret=token.secret) return oauth_token class OAuthSignatureMethod(object): """Holds valid OAuth signature methods. RSA_SHA1: Class to build signature according to RSA-SHA1 algorithm. HMAC_SHA1: Class to build signature according to HMAC-SHA1 algorithm. """ HMAC_SHA1 = oauth.OAuthSignatureMethod_HMAC_SHA1 class RSA_SHA1(oauth_rsa.OAuthSignatureMethod_RSA_SHA1): """Provides implementation for abstract methods to return RSA certs.""" def __init__(self, private_key, public_cert): self.private_key = private_key self.public_cert = public_cert def _fetch_public_cert(self, unused_oauth_request): return self.public_cert def _fetch_private_cert(self, unused_oauth_request): return self.private_key class OAuthInputParams(object): """Stores OAuth input parameters. This class is a store for OAuth input parameters viz. consumer key and secret, signature method and RSA key. """ def __init__(self, signature_method, consumer_key, consumer_secret=None, rsa_key=None, requestor_id=None): """Initializes object with parameters required for using OAuth 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. Instead of passing in the strategy class, you may pass in a string for 'RSA_SHA1' or 'HMAC_SHA1'. If you plan to use OAuth on App Engine (or another WSGI environment) I recommend specifying signature method using a string (the only options are 'RSA_SHA1' and 'HMAC_SHA1'). In these environments there are sometimes issues with pickling an object in which a member references a class or function. Storing a string to refer to the signature method mitigates complications when pickling. 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. requestor_id: string (optional) User email adress to make requests on their behalf. This parameter should only be set when performing 2 legged OAuth requests. """ if (signature_method == OAuthSignatureMethod.RSA_SHA1 or signature_method == 'RSA_SHA1'): self.__signature_strategy = 'RSA_SHA1' elif (signature_method == OAuthSignatureMethod.HMAC_SHA1 or signature_method == 'HMAC_SHA1'): self.__signature_strategy = 'HMAC_SHA1' else: self.__signature_strategy = signature_method self.rsa_key = rsa_key self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) self.requestor_id = requestor_id def __get_signature_method(self): if self.__signature_strategy == 'RSA_SHA1': return OAuthSignatureMethod.RSA_SHA1(self.rsa_key, None) elif self.__signature_strategy == 'HMAC_SHA1': return OAuthSignatureMethod.HMAC_SHA1() else: return self.__signature_strategy() def __set_signature_method(self, signature_method): if (signature_method == OAuthSignatureMethod.RSA_SHA1 or signature_method == 'RSA_SHA1'): self.__signature_strategy = 'RSA_SHA1' elif (signature_method == OAuthSignatureMethod.HMAC_SHA1 or signature_method == 'HMAC_SHA1'): self.__signature_strategy = 'HMAC_SHA1' else: self.__signature_strategy = signature_method _signature_method = property(__get_signature_method, __set_signature_method, doc="""Returns object capable of signing the request using RSA of HMAC. Replaces the _signature_method member to avoid pickle errors.""") def GetSignatureMethod(self): """Gets the OAuth signature method. Returns: object of supertype <oauth.oauth.OAuthSignatureMethod> """ return self._signature_method def GetConsumer(self): """Gets the OAuth consumer. Returns: object of type <oauth.oauth.Consumer> """ return self._consumer class ClientLoginToken(atom.http_interface.GenericToken): """Stores the Authorization header in auth_header and adds to requests. This token will add it's Authorization header to an HTTP request as it is made. Ths token class is simple but some Token classes must calculate portions of the Authorization header based on the request being made, which is why the token is responsible for making requests via an http_client parameter. Args: auth_header: str The value for the Authorization header. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' """ def __init__(self, auth_header=None, scopes=None): self.auth_header = auth_header self.scopes = scopes or [] def __str__(self): return self.auth_header def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header and makes the HTTP request.""" if headers is None: headers = {'Authorization':self.auth_header} else: headers['Authorization'] = self.auth_header return http_client.request(operation, url, data=data, headers=headers) def get_token_string(self): """Removes PROGRAMMATIC_AUTH_LABEL to give just the token value.""" return self.auth_header[len(PROGRAMMATIC_AUTH_LABEL):] def set_token_string(self, token_string): self.auth_header = '%s%s' % (PROGRAMMATIC_AUTH_LABEL, token_string) def valid_for_scope(self, url): """Tells the caller if the token authorizes access to the desired URL. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) for scope in self.scopes: if scope == atom.token_store.SCOPE_ALL: return True if isinstance(scope, (str, unicode)): scope = atom.url.parse_url(scope) if scope == url: return True # Check the host and the path, but ignore the port and protocol. elif scope.host == url.host and not scope.path: return True elif scope.host == url.host and scope.path and not url.path: continue elif scope.host == url.host and url.path.startswith(scope.path): return True return False class AuthSubToken(ClientLoginToken): def get_token_string(self): """Removes AUTHSUB_AUTH_LABEL to give just the token value.""" return self.auth_header[len(AUTHSUB_AUTH_LABEL):] def set_token_string(self, token_string): self.auth_header = '%s%s' % (AUTHSUB_AUTH_LABEL, token_string) class OAuthToken(atom.http_interface.GenericToken): """Stores the token key, token secret and scopes for which token is valid. This token adds the authorization header to each request made. It re-calculates authorization header for every request since the OAuth signature to be added to the authorization header is dependent on the request parameters. Attributes: key: str The value for the OAuth token i.e. token key. secret: str The value for the OAuth token secret. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' oauth_input_params: OAuthInputParams OAuth input parameters. """ def __init__(self, key=None, secret=None, scopes=None, oauth_input_params=None): self.key = key self.secret = secret self.scopes = scopes or [] self.oauth_input_params = oauth_input_params def __str__(self): return self.get_token_string() def get_token_string(self): """Returns the token string. The token string returned is of format oauth_token=[0]&oauth_token_secret=[1], where [0] and [1] are some strings. Returns: A token string of format oauth_token=[0]&oauth_token_secret=[1], where [0] and [1] are some strings. If self.secret is absent, it just returns oauth_token=[0]. If self.key is absent, it just returns oauth_token_secret=[1]. If both are absent, it returns None. """ if self.key and self.secret: return urllib.urlencode({'oauth_token': self.key, 'oauth_token_secret': self.secret}) elif self.key: return 'oauth_token=%s' % self.key elif self.secret: return 'oauth_token_secret=%s' % self.secret else: return None def set_token_string(self, token_string): """Sets the token key and secret from the token string. Args: token_string: str Token string of form oauth_token=[0]&oauth_token_secret=[1]. If oauth_token is not present, self.key will be None. If oauth_token_secret is not present, self.secret will be None. """ token_params = cgi.parse_qs(token_string, keep_blank_values=False) if 'oauth_token' in token_params: self.key = token_params['oauth_token'][0] if 'oauth_token_secret' in token_params: self.secret = token_params['oauth_token_secret'][0] def GetAuthHeader(self, http_method, http_url, realm=''): """Get the authentication header. Args: http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc. http_url: string or atom.url.Url HTTP URL to which request is made. realm: string (default='') realm parameter to be included in the authorization header. Returns: dict Header to be sent with every subsequent request after authentication. """ if isinstance(http_url, types.StringTypes): http_url = atom.url.parse_url(http_url) header = None token = None if self.key or self.secret: token = oauth.OAuthToken(self.key, self.secret) oauth_request = oauth.OAuthRequest.from_consumer_and_token( self.oauth_input_params.GetConsumer(), token=token, http_url=str(http_url), http_method=http_method, parameters=http_url.params) oauth_request.sign_request(self.oauth_input_params.GetSignatureMethod(), self.oauth_input_params.GetConsumer(), token) header = oauth_request.to_header(realm=realm) header['Authorization'] = header['Authorization'].replace('+', '%2B') return header def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header and makes the HTTP request.""" if not headers: headers = {} if self.oauth_input_params.requestor_id: url.params['xoauth_requestor_id'] = self.oauth_input_params.requestor_id headers.update(self.GetAuthHeader(operation, url)) return http_client.request(operation, url, data=data, headers=headers) def valid_for_scope(self, url): if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) for scope in self.scopes: if scope == atom.token_store.SCOPE_ALL: return True if isinstance(scope, (str, unicode)): scope = atom.url.parse_url(scope) if scope == url: return True # Check the host and the path, but ignore the port and protocol. elif scope.host == url.host and not scope.path: return True elif scope.host == url.host and scope.path and not url.path: continue elif scope.host == url.host and url.path.startswith(scope.path): return True return False class SecureAuthSubToken(AuthSubToken): """Stores the rsa private key, token, and scopes for the secure AuthSub token. This token adds the authorization header to each request made. It re-calculates authorization header for every request since the secure AuthSub signature to be added to the authorization header is dependent on the request parameters. Attributes: rsa_key: string The RSA private key in PEM format that the token will use to sign requests token_string: string (optional) The value for the AuthSub token. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' """ def __init__(self, rsa_key, token_string=None, scopes=None): self.rsa_key = keyfactory.parsePEMKey(rsa_key) self.token_string = token_string or '' self.scopes = scopes or [] def __str__(self): return self.get_token_string() def get_token_string(self): return str(self.token_string) def set_token_string(self, token_string): self.token_string = token_string def GetAuthHeader(self, http_method, http_url): """Generates the Authorization header. The form of the secure AuthSub Authorization header is Authorization: AuthSub token="token" sigalg="sigalg" data="data" sig="sig" and data represents a string in the form data = http_method http_url timestamp nonce Args: http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc. http_url: string or atom.url.Url HTTP URL to which request is made. Returns: dict Header to be sent with every subsequent request after authentication. """ timestamp = int(math.floor(time.time())) nonce = '%lu' % random.randrange(1, 2**64) data = '%s %s %d %s' % (http_method, str(http_url), timestamp, nonce) sig = cryptomath.bytesToBase64(self.rsa_key.hashAndSign(data)) header = {'Authorization': '%s"%s" data="%s" sig="%s" sigalg="rsa-sha1"' % (AUTHSUB_AUTH_LABEL, self.token_string, data, sig)} return header def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header and makes the HTTP request.""" if not headers: headers = {} headers.update(self.GetAuthHeader(operation, url)) return http_client.request(operation, url, data=data, headers=headers)
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 Access Control List (ACL) Extension""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import atom.data import gdata.data import gdata.opensearch.data GACL_TEMPLATE = '{http://schemas.google.com/acl/2007}%s' class AclRole(atom.core.XmlElement): """Describes the role of an entry in an access control list.""" _qname = GACL_TEMPLATE % 'role' value = 'value' class AclScope(atom.core.XmlElement): """Describes the scope of an entry in an access control list.""" _qname = GACL_TEMPLATE % 'scope' type = 'type' value = 'value' class AclWithKey(atom.core.XmlElement): """Describes a key that can be used to access a document.""" _qname = GACL_TEMPLATE % 'withKey' key = 'key' role = AclRole class AclEntry(gdata.data.GDEntry): """Describes an entry in a feed of an access control list (ACL).""" scope = AclScope role = AclRole with_key = AclWithKey class AclFeed(gdata.data.GDFeed): """Describes a feed of an access control list (ACL).""" entry = [AclEntry]
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 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. """SitesClient extends gdata.client.GDClient to streamline Sites API calls.""" __author__ = 'e.bidelman (Eric Bidelman)' import atom.data import gdata.client import gdata.sites.data import gdata.gauth # Feed URI templates CONTENT_FEED_TEMPLATE = '/feeds/content/%s/%s/' REVISION_FEED_TEMPLATE = '/feeds/revision/%s/%s/' ACTIVITY_FEED_TEMPLATE = '/feeds/activity/%s/%s/' SITE_FEED_TEMPLATE = '/feeds/site/%s/' ACL_FEED_TEMPLATE = '/feeds/acl/site/%s/%s/' class SitesClient(gdata.client.GDClient): """Client extension for the Google Sites API service.""" host = 'sites.google.com' # default server for the API domain = 'site' # default site domain name api_version = '1.1' # default major version for the service. auth_service = 'jotspot' auth_scopes = gdata.gauth.AUTH_SCOPES['jotspot'] ssl = True def __init__(self, site=None, domain=None, auth_token=None, **kwargs): """Constructs a new client for the Sites API. Args: site: string (optional) Name (webspace) of the Google Site domain: string (optional) Domain of the (Google Apps hosted) Site. If no domain is given, the Site is assumed to be a consumer Google Site, in which case the value 'site' is used. 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) self.site = site if domain is not None: self.domain = domain def __make_kind_category(self, label): if label is None: return None return atom.data.Category( scheme=gdata.sites.data.SITES_KIND_SCHEME, term='%s#%s' % (gdata.sites.data.SITES_NAMESPACE, label), label=label) __MakeKindCategory = __make_kind_category def __upload(self, entry, media_source, auth_token=None, **kwargs): """Uploads an attachment file to the Sites API. Args: entry: gdata.sites.data.ContentEntry The Atom XML to include. media_source: gdata.data.MediaSource The file payload to be uploaded. 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 gdata.client.post(). Returns: The created entry. """ uri = self.make_content_feed_uri() return self.post(entry, uri, media_source=media_source, auth_token=auth_token, **kwargs) def _get_file_content(self, uri): """Fetches the file content from the specified URI. Args: uri: string The full URL to fetch the file contents from. Returns: The binary file content. Raises: gdata.client.RequestError: on error response from server. """ server_response = self.request('GET', uri) 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 make_content_feed_uri(self): return CONTENT_FEED_TEMPLATE % (self.domain, self.site) MakeContentFeedUri = make_content_feed_uri def make_revision_feed_uri(self): return REVISION_FEED_TEMPLATE % (self.domain, self.site) MakeRevisionFeedUri = make_revision_feed_uri def make_activity_feed_uri(self): return ACTIVITY_FEED_TEMPLATE % (self.domain, self.site) MakeActivityFeedUri = make_activity_feed_uri def make_site_feed_uri(self, site_name=None): if site_name is not None: return (SITE_FEED_TEMPLATE % self.domain) + site_name else: return SITE_FEED_TEMPLATE % self.domain MakeSiteFeedUri = make_site_feed_uri def make_acl_feed_uri(self): return ACL_FEED_TEMPLATE % (self.domain, self.site) MakeAclFeedUri = make_acl_feed_uri def get_content_feed(self, uri=None, auth_token=None, **kwargs): """Retrieves the content feed containing the current state of site. Args: uri: string (optional) A full URI to query the Content 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.get_feed(). Returns: gdata.sites.data.ContentFeed """ if uri is None: uri = self.make_content_feed_uri() return self.get_feed(uri, desired_class=gdata.sites.data.ContentFeed, auth_token=auth_token, **kwargs) GetContentFeed = get_content_feed def get_revision_feed(self, entry_or_uri_or_id, auth_token=None, **kwargs): """Retrieves the revision feed containing the revision history for a node. Args: entry_or_uri_or_id: string or gdata.sites.data.ContentEntry A full URI, content entry node ID, or a content entry object of the entry to retrieve revision information for. 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.sites.data.RevisionFeed """ uri = self.make_revision_feed_uri() if isinstance(entry_or_uri_or_id, gdata.sites.data.ContentEntry): uri = entry_or_uri_or_id.FindRevisionLink() elif entry_or_uri_or_id.find('/') == -1: uri += entry_or_uri_or_id else: uri = entry_or_uri_or_id return self.get_feed(uri, desired_class=gdata.sites.data.RevisionFeed, auth_token=auth_token, **kwargs) GetRevisionFeed = get_revision_feed def get_activity_feed(self, uri=None, auth_token=None, **kwargs): """Retrieves the activity feed containing recent Site activity. Args: uri: string (optional) A full URI to query the Activity feed. 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.sites.data.ActivityFeed """ if uri is None: uri = self.make_activity_feed_uri() return self.get_feed(uri, desired_class=gdata.sites.data.ActivityFeed, auth_token=auth_token, **kwargs) GetActivityFeed = get_activity_feed def get_site_feed(self, uri=None, auth_token=None, **kwargs): """Retrieves the site feed containing a list of sites a user has access to. Args: uri: string (optional) A full URI to query the site feed. 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.sites.data.SiteFeed """ if uri is None: uri = self.make_site_feed_uri() return self.get_feed(uri, desired_class=gdata.sites.data.SiteFeed, auth_token=auth_token, **kwargs) GetSiteFeed = get_site_feed def get_acl_feed(self, uri=None, auth_token=None, **kwargs): """Retrieves the acl feed containing a site's sharing permissions. Args: uri: string (optional) A full URI to query the acl feed. 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.sites.data.AclFeed """ if uri is None: uri = self.make_acl_feed_uri() return self.get_feed(uri, desired_class=gdata.sites.data.AclFeed, auth_token=auth_token, **kwargs) GetAclFeed = get_acl_feed def create_site(self, title, description=None, source_site=None, theme=None, uri=None, auth_token=None, **kwargs): """Creates a new Google Site. Note: This feature is only available to Google Apps domains. Args: title: string Title for the site. description: string (optional) A description/summary for the site. source_site: string (optional) The site feed URI of the site to copy. This parameter should only be specified when copying a site. theme: string (optional) The name of the theme to create the site with. uri: string (optional) A full site feed URI to override where the site is created/copied. By default, the site will be created under the currently set domain (e.g. self.domain). 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 gdata.client.post(). Returns: gdata.sites.data.SiteEntry of the created site. """ new_entry = gdata.sites.data.SiteEntry(title=atom.data.Title(text=title)) if description is not None: new_entry.summary = gdata.sites.data.Summary(text=description) # Add the source link if we're making a copy of a site. if source_site is not None: source_link = atom.data.Link(rel=gdata.sites.data.SITES_SOURCE_LINK_REL, type='application/atom+xml', href=source_site) new_entry.link.append(source_link) if theme is not None: new_entry.theme = gdata.sites.data.Theme(text=theme) if uri is None: uri = self.make_site_feed_uri() return self.post(new_entry, uri, auth_token=auth_token, **kwargs) CreateSite = create_site def create_page(self, kind, title, html='', page_name=None, parent=None, auth_token=None, **kwargs): """Creates a new page (specified by kind) on a Google Site. Args: kind: string The type of page/item to create. For example, webpage, listpage, comment, announcementspage, filecabinet, etc. The full list of supported kinds can be found in gdata.sites.gdata.SUPPORT_KINDS. title: string Title for the page. html: string (optional) XHTML for the page's content body. page_name: string (optional) The URL page name to set. If not set, the title will be normalized and used as the page's URL path. parent: string or gdata.sites.data.ContentEntry (optional) The parent entry or parent link url to create the page under. 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 gdata.client.post(). Returns: gdata.sites.data.ContentEntry of the created page. """ new_entry = gdata.sites.data.ContentEntry( title=atom.data.Title(text=title), kind=kind, content=gdata.sites.data.Content(text=html)) if page_name is not None: new_entry.page_name = gdata.sites.data.PageName(text=page_name) # Add parent link to entry if it should be uploaded as a subpage. if isinstance(parent, gdata.sites.data.ContentEntry): parent_link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent.GetSelfLink().href) new_entry.link.append(parent_link) elif parent is not None: parent_link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent) new_entry.link.append(parent_link) return self.post(new_entry, self.make_content_feed_uri(), auth_token=auth_token, **kwargs) CreatePage = create_page def create_webattachment(self, src, content_type, title, parent, description=None, auth_token=None, **kwargs): """Creates a new webattachment within a filecabinet. Args: src: string The url of the web attachment. content_type: string The MIME type of the web attachment. title: string The title to name the web attachment. parent: string or gdata.sites.data.ContentEntry (optional) The parent entry or url of the filecabinet to create the attachment under. description: string (optional) A summary/description for the attachment. 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 gdata.client.post(). Returns: gdata.sites.data.ContentEntry of the created page. """ new_entry = gdata.sites.data.ContentEntry( title=atom.data.Title(text=title), kind='webattachment', content=gdata.sites.data.Content(src=src, type=content_type)) if isinstance(parent, gdata.sites.data.ContentEntry): link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent.GetSelfLink().href) elif parent is not None: link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent) new_entry.link.append(link) # Add file decription if it was specified if description is not None: new_entry.summary = gdata.sites.data.Summary(type='text', text=description) return self.post(new_entry, self.make_content_feed_uri(), auth_token=auth_token, **kwargs) CreateWebAttachment = create_webattachment def upload_attachment(self, file_handle, parent, content_type=None, title=None, description=None, folder_name=None, auth_token=None, **kwargs): """Uploads an attachment to a parent page. Args: file_handle: MediaSource or string A gdata.data.MediaSource object containing the file to be uploaded or the full path name to the file on disk. parent: gdata.sites.data.ContentEntry or string The parent page to upload the file to or the full URI of the entry's self link. content_type: string (optional) The MIME type of the file (e.g 'application/pdf'). This should be provided if file is not a MediaSource object. title: string (optional) The title to name the attachment. If not included, the filepath or media source's filename is used. description: string (optional) A summary/description for the attachment. folder_name: string (optional) The name of an existing folder to upload the attachment to. This only applies when the parent parameter points to a filecabinet entry. 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.__upload(). Returns: A gdata.sites.data.ContentEntry containing information about the created attachment. """ if isinstance(parent, gdata.sites.data.ContentEntry): link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent.GetSelfLink().href) else: link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent) if not isinstance(file_handle, gdata.data.MediaSource): ms = gdata.data.MediaSource(file_path=file_handle, content_type=content_type) else: ms = file_handle # If no title specified, use the file name if title is None: title = ms.file_name new_entry = gdata.sites.data.ContentEntry(kind='attachment') new_entry.title = atom.data.Title(text=title) new_entry.link.append(link) # Add file decription if it was specified if description is not None: new_entry.summary = gdata.sites.data.Summary(type='text', text=description) # Upload the attachment to a filecabinet folder? if parent.Kind() == 'filecabinet' and folder_name is not None: folder_category = atom.data.Category( scheme=gdata.sites.data.FOLDER_KIND_TERM, term=folder_name) new_entry.category.append(folder_category) return self.__upload(new_entry, ms, auth_token=auth_token, **kwargs) UploadAttachment = upload_attachment def download_attachment(self, uri_or_entry, file_path): """Downloads an attachment file to disk. Args: uri_or_entry: string The full URL to download the file from. file_path: string The full path to save the file to. Raises: gdata.client.RequestError: on error response from server. """ uri = uri_or_entry if isinstance(uri_or_entry, gdata.sites.data.ContentEntry): uri = uri_or_entry.content.src f = open(file_path, 'wb') try: f.write(self._get_file_content(uri)) except gdata.client.RequestError, e: f.close() raise e f.flush() f.close() DownloadAttachment = download_attachment
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 Sites Data API.""" __author__ = 'e.bidelman (Eric Bidelman)' import atom.core import atom.data import gdata.acl.data import gdata.data # XML Namespaces used in Google Sites entities. SITES_NAMESPACE = 'http://schemas.google.com/sites/2008' SITES_TEMPLATE = '{http://schemas.google.com/sites/2008}%s' SPREADSHEETS_NAMESPACE = 'http://schemas.google.com/spreadsheets/2006' SPREADSHEETS_TEMPLATE = '{http://schemas.google.com/spreadsheets/2006}%s' DC_TERMS_TEMPLATE = '{http://purl.org/dc/terms}%s' THR_TERMS_TEMPLATE = '{http://purl.org/syndication/thread/1.0}%s' XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml' XHTML_TEMPLATE = '{http://www.w3.org/1999/xhtml}%s' SITES_PARENT_LINK_REL = SITES_NAMESPACE + '#parent' SITES_REVISION_LINK_REL = SITES_NAMESPACE + '#revision' SITES_SOURCE_LINK_REL = SITES_NAMESPACE + '#source' SITES_KIND_SCHEME = 'http://schemas.google.com/g/2005#kind' ANNOUNCEMENT_KIND_TERM = SITES_NAMESPACE + '#announcement' ANNOUNCEMENT_PAGE_KIND_TERM = SITES_NAMESPACE + '#announcementspage' ATTACHMENT_KIND_TERM = SITES_NAMESPACE + '#attachment' COMMENT_KIND_TERM = SITES_NAMESPACE + '#comment' FILECABINET_KIND_TERM = SITES_NAMESPACE + '#filecabinet' LISTITEM_KIND_TERM = SITES_NAMESPACE + '#listitem' LISTPAGE_KIND_TERM = SITES_NAMESPACE + '#listpage' WEBPAGE_KIND_TERM = SITES_NAMESPACE + '#webpage' WEBATTACHMENT_KIND_TERM = SITES_NAMESPACE + '#webattachment' FOLDER_KIND_TERM = SITES_NAMESPACE + '#folder' SUPPORT_KINDS = [ 'announcement', 'announcementspage', 'attachment', 'comment', 'filecabinet', 'listitem', 'listpage', 'webpage', 'webattachment' ] class Revision(atom.core.XmlElement): """Google Sites <sites:revision>.""" _qname = SITES_TEMPLATE % 'revision' class PageName(atom.core.XmlElement): """Google Sites <sites:pageName>.""" _qname = SITES_TEMPLATE % 'pageName' class SiteName(atom.core.XmlElement): """Google Sites <sites:siteName>.""" _qname = SITES_TEMPLATE % 'siteName' class Theme(atom.core.XmlElement): """Google Sites <sites:theme>.""" _qname = SITES_TEMPLATE % 'theme' class Deleted(atom.core.XmlElement): """Google Sites <gd:deleted>.""" _qname = gdata.data.GDATA_TEMPLATE % 'deleted' class Publisher(atom.core.XmlElement): """Google Sites <dc:pulisher>.""" _qname = DC_TERMS_TEMPLATE % 'publisher' class Worksheet(atom.core.XmlElement): """Google Sites List Page <gs:worksheet>.""" _qname = SPREADSHEETS_TEMPLATE % 'worksheet' name = 'name' class Header(atom.core.XmlElement): """Google Sites List Page <gs:header>.""" _qname = SPREADSHEETS_TEMPLATE % 'header' row = 'row' class Column(atom.core.XmlElement): """Google Sites List Page <gs:column>.""" _qname = SPREADSHEETS_TEMPLATE % 'column' index = 'index' name = 'name' class Data(atom.core.XmlElement): """Google Sites List Page <gs:data>.""" _qname = SPREADSHEETS_TEMPLATE % 'data' startRow = 'startRow' column = [Column] class Field(atom.core.XmlElement): """Google Sites List Item <gs:field>.""" _qname = SPREADSHEETS_TEMPLATE % 'field' index = 'index' name = 'name' class InReplyTo(atom.core.XmlElement): """Google Sites List Item <thr:in-reply-to>.""" _qname = THR_TERMS_TEMPLATE % 'in-reply-to' href = 'href' ref = 'ref' source = 'source' type = 'type' class Content(atom.data.Content): """Google Sites version of <atom:content> that encapsulates XHTML.""" def __init__(self, html=None, type=None, **kwargs): if type is None and html: type = 'xhtml' super(Content, self).__init__(type=type, **kwargs) if html is not None: self.html = html def _get_html(self): if self.children: return self.children[0] else: return '' def _set_html(self, html): if not html: self.children = [] return if type(html) == str: html = atom.core.parse(html) if not html.namespace: html.namespace = XHTML_NAMESPACE self.children = [html] html = property(_get_html, _set_html) class Summary(atom.data.Summary): """Google Sites version of <atom:summary>.""" def __init__(self, html=None, type=None, text=None, **kwargs): if type is None and html: type = 'xhtml' super(Summary, self).__init__(type=type, text=text, **kwargs) if html is not None: self.html = html def _get_html(self): if self.children: return self.children[0] else: return '' def _set_html(self, html): if not html: self.children = [] return if type(html) == str: html = atom.core.parse(html) if not html.namespace: html.namespace = XHTML_NAMESPACE self.children = [html] html = property(_get_html, _set_html) class BaseSiteEntry(gdata.data.GDEntry): """Google Sites Entry.""" def __init__(self, kind=None, **kwargs): super(BaseSiteEntry, self).__init__(**kwargs) if kind is not None: self.category.append( atom.data.Category(scheme=SITES_KIND_SCHEME, term='%s#%s' % (SITES_NAMESPACE, kind), label=kind)) def __find_category_scheme(self, scheme): for category in self.category: if category.scheme == scheme: return category return None def kind(self): kind = self.__find_category_scheme(SITES_KIND_SCHEME) if kind is not None: return kind.term[len(SITES_NAMESPACE) + 1:] else: return None Kind = kind def get_node_id(self): return self.id.text[self.id.text.rfind('/') + 1:] GetNodeId = get_node_id def find_parent_link(self): return self.find_url(SITES_PARENT_LINK_REL) FindParentLink = find_parent_link def is_deleted(self): return self.deleted is not None IsDeleted = is_deleted class ContentEntry(BaseSiteEntry): """Google Sites Content Entry.""" content = Content deleted = Deleted publisher = Publisher in_reply_to = InReplyTo worksheet = Worksheet header = Header data = Data field = [Field] revision = Revision page_name = PageName feed_link = gdata.data.FeedLink def find_revison_link(self): return self.find_url(SITES_REVISION_LINK_REL) FindRevisionLink = find_revison_link class ContentFeed(gdata.data.GDFeed): """Google Sites Content Feed. The Content feed is a feed containing the current, editable site content. """ entry = [ContentEntry] def __get_entry_type(self, kind): matches = [] for entry in self.entry: if entry.Kind() == kind: matches.append(entry) return matches def get_announcements(self): return self.__get_entry_type('announcement') GetAnnouncements = get_announcements def get_announcement_pages(self): return self.__get_entry_type('announcementspage') GetAnnouncementPages = get_announcement_pages def get_attachments(self): return self.__get_entry_type('attachment') GetAttachments = get_attachments def get_comments(self): return self.__get_entry_type('comment') GetComments = get_comments def get_file_cabinets(self): return self.__get_entry_type('filecabinet') GetFileCabinets = get_file_cabinets def get_list_items(self): return self.__get_entry_type('listitem') GetListItems = get_list_items def get_list_pages(self): return self.__get_entry_type('listpage') GetListPages = get_list_pages def get_webpages(self): return self.__get_entry_type('webpage') GetWebpages = get_webpages def get_webattachments(self): return self.__get_entry_type('webattachment') GetWebattachments = get_webattachments class ActivityEntry(BaseSiteEntry): """Google Sites Activity Entry.""" summary = Summary class ActivityFeed(gdata.data.GDFeed): """Google Sites Activity Feed. The Activity feed is a feed containing recent Site activity. """ entry = [ActivityEntry] class RevisionEntry(BaseSiteEntry): """Google Sites Revision Entry.""" content = Content class RevisionFeed(gdata.data.GDFeed): """Google Sites Revision Feed. The Activity feed is a feed containing recent Site activity. """ entry = [RevisionEntry] class SiteEntry(gdata.data.GDEntry): """Google Sites Site Feed Entry.""" site_name = SiteName theme = Theme def find_source_link(self): return self.find_url(SITES_SOURCE_LINK_REL) FindSourceLink = find_source_link class SiteFeed(gdata.data.GDFeed): """Google Sites Site Feed. The Site feed can be used to list a user's sites and create new sites. """ entry = [SiteEntry] class AclEntry(gdata.acl.data.AclEntry): """Google Sites ACL Entry.""" class AclFeed(gdata.acl.data.AclFeed): """Google Sites ACL Feed. The ACL feed can be used to modify the sharing permissions of a Site. """ entry = [AclEntry]
Python
#!/usr/bin/python """ Extend gdata.service.GDataService to support authenticated CRUD ops on Books API http://code.google.com/apis/books/docs/getting-started.html http://code.google.com/apis/books/docs/gdata/developers_guide_protocol.html TODO: (here and __init__) * search based on label, review, or other annotations (possible?) * edit (specifically, Put requests) seem to fail effect a change Problems With API: * Adding a book with a review to the library adds a note, not a review. This does not get included in the returned item. You see this by looking at My Library through the website. * Editing a review never edits a review (unless it is freshly added, but see above). More generally, * a Put request with changed annotations (label/rating/review) does NOT change the data. Note: Put requests only work on the href from GetEditLink (as per the spec). Do not try to PUT to the annotate or library feeds, this will cause a 400 Invalid URI Bad Request response. Attempting to Post to one of the feeds with the updated annotations does not update them. See the following for (hopefully) a follow up: google.com/support/forum/p/booksearch-apis/thread?tid=27fd7f68de438fc8 * Attempts to workaround the edit problem continue to fail. For example, removing the item, editing the data, readding the item, gives us only our originally added data (annotations). This occurs even if we completely shut python down, refetch the book from the public feed, and re-add it. There is some kind of persistence going on that I cannot change. This is likely due to the annotations being cached in the annotation feed and the inability to edit (see Put, above) * GetAnnotationLink has www.books.... as the server, but hitting www... results in a bad URI error. * Spec indicates there may be multiple labels, but there does not seem to be a way to get the server to accept multiple labels, nor does the web interface have an obvious way to have multiple labels. Multiple labels are never returned. """ __author__ = "James Sams <sams.james@gmail.com>" __copyright__ = "Apache License v2.0" from shlex import split import gdata.service try: import books except ImportError: import gdata.books as books BOOK_SERVER = "books.google.com" GENERAL_FEED = "/books/feeds/volumes" ITEM_FEED = "/books/feeds/volumes/" LIBRARY_FEED = "/books/feeds/users/%s/collections/library/volumes" ANNOTATION_FEED = "/books/feeds/users/%s/volumes" PARTNER_FEED = "/books/feeds/p/%s/volumes" BOOK_SERVICE = "print" ACCOUNT_TYPE = "HOSTED_OR_GOOGLE" class BookService(gdata.service.GDataService): def __init__(self, email=None, password=None, source=None, server=BOOK_SERVER, account_type=ACCOUNT_TYPE, exception_handlers=tuple(), **kwargs): """source should be of form 'ProgramCompany - ProgramName - Version'""" gdata.service.GDataService.__init__(self, email=email, password=password, service=BOOK_SERVICE, source=source, server=server, **kwargs) self.exception_handlers = exception_handlers def search(self, q, start_index="1", max_results="10", min_viewability="none", feed=GENERAL_FEED, converter=books.BookFeed.FromString): """ Query the Public search feed. q is either a search string or a gdata.service.Query instance with a query set. min_viewability must be "none", "partial", or "full". If you change the feed to a single item feed, note that you will probably need to change the converter to be Book.FromString """ if not isinstance(q, gdata.service.Query): q = gdata.service.Query(text_query=q) if feed: q.feed = feed q['start-index'] = start_index q['max-results'] = max_results q['min-viewability'] = min_viewability return self.Get(uri=q.ToUri(),converter=converter) def search_by_keyword(self, q='', feed=GENERAL_FEED, start_index="1", max_results="10", min_viewability="none", **kwargs): """ Query the Public Search Feed by keyword. Non-keyword strings can be set in q. This is quite fragile. Is there a function somewhere in the Google library that will parse a query the same way that Google does? Legal Identifiers are listed below and correspond to their meaning at http://books.google.com/advanced_book_search: all_words exact_phrase at_least_one without_words title author publisher subject isbn lccn oclc seemingly unsupported: publication_date: a sequence of two, two tuples: ((min_month,min_year),(max_month,max_year)) where month is one/two digit month, year is 4 digit, eg: (('1','2000'),('10','2003')). Lower bound is inclusive, upper bound is exclusive """ for k, v in kwargs.items(): if not v: continue k = k.lower() if k == 'all_words': q = "%s %s" % (q, v) elif k == 'exact_phrase': q = '%s "%s"' % (q, v.strip('"')) elif k == 'at_least_one': q = '%s %s' % (q, ' '.join(['OR "%s"' % x for x in split(v)])) elif k == 'without_words': q = '%s %s' % (q, ' '.join(['-"%s"' % x for x in split(v)])) elif k in ('author','title', 'publisher'): q = '%s %s' % (q, ' '.join(['in%s:"%s"'%(k,x) for x in split(v)])) elif k == 'subject': q = '%s %s' % (q, ' '.join(['%s:"%s"' % (k,x) for x in split(v)])) elif k == 'isbn': q = '%s ISBN%s' % (q, v) elif k == 'issn': q = '%s ISSN%s' % (q,v) elif k == 'oclc': q = '%s OCLC%s' % (q,v) else: raise ValueError("Unsupported search keyword") return self.search(q.strip(),start_index=start_index, feed=feed, max_results=max_results, min_viewability=min_viewability) def search_library(self, q, id='me', **kwargs): """Like search, but in a library feed. Default is the authenticated user's feed. Change by setting id.""" if 'feed' in kwargs: raise ValueError("kwarg 'feed' conflicts with library_id") feed = LIBRARY_FEED % id return self.search(q, feed=feed, **kwargs) def search_library_by_keyword(self, id='me', **kwargs): """Hybrid of search_by_keyword and search_library """ if 'feed' in kwargs: raise ValueError("kwarg 'feed' conflicts with library_id") feed = LIBRARY_FEED % id return self.search_by_keyword(feed=feed,**kwargs) def search_annotations(self, q, id='me', **kwargs): """Like search, but in an annotation feed. Default is the authenticated user's feed. Change by setting id.""" if 'feed' in kwargs: raise ValueError("kwarg 'feed' conflicts with library_id") feed = ANNOTATION_FEED % id return self.search(q, feed=feed, **kwargs) def search_annotations_by_keyword(self, id='me', **kwargs): """Hybrid of search_by_keyword and search_annotations """ if 'feed' in kwargs: raise ValueError("kwarg 'feed' conflicts with library_id") feed = ANNOTATION_FEED % id return self.search_by_keyword(feed=feed,**kwargs) def add_item_to_library(self, item): """Add the item, either an XML string or books.Book instance, to the user's library feed""" feed = LIBRARY_FEED % 'me' return self.Post(data=item, uri=feed, converter=books.Book.FromString) def remove_item_from_library(self, item): """ Remove the item, a books.Book instance, from the authenticated user's library feed. Using an item retrieved from a public search will fail. """ return self.Delete(item.GetEditLink().href) def add_annotation(self, item): """ Add the item, either an XML string or books.Book instance, to the user's annotation feed. """ # do not use GetAnnotationLink, results in 400 Bad URI due to www return self.Post(data=item, uri=ANNOTATION_FEED % 'me', converter=books.Book.FromString) def edit_annotation(self, item): """ Send an edited item, a books.Book instance, to the user's annotation feed. Note that whereas extra annotations in add_annotations, minus ratings which are immutable once set, are simply added to the item in the annotation feed, if an annotation has been removed from the item, sending an edit request will remove that annotation. This should not happen with add_annotation. """ return self.Put(data=item, uri=item.GetEditLink().href, converter=books.Book.FromString) def get_by_google_id(self, id): return self.Get(ITEM_FEED + id, converter=books.Book.FromString) def get_library(self, id='me',feed=LIBRARY_FEED, start_index="1", max_results="100", min_viewability="none", converter=books.BookFeed.FromString): """ Return a generator object that will return gbook.Book instances until the search feed no longer returns an item from the GetNextLink method. Thus max_results is not the maximum number of items that will be returned, but rather the number of items per page of searches. This has been set high to reduce the required number of network requests. """ q = gdata.service.Query() q.feed = feed % id q['start-index'] = start_index q['max-results'] = max_results q['min-viewability'] = min_viewability x = self.Get(uri=q.ToUri(), converter=converter) while 1: for entry in x.entry: yield entry else: l = x.GetNextLink() if l: # hope the server preserves our preferences x = self.Get(uri=l.href, converter=converter) else: break def get_annotations(self, id='me', start_index="1", max_results="100", min_viewability="none", converter=books.BookFeed.FromString): """ Like get_library, but for the annotation feed """ return self.get_library(id=id, feed=ANNOTATION_FEED, max_results=max_results, min_viewability = min_viewability, converter=converter)
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 Book Search Data API""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import atom.data import gdata.data import gdata.dublincore.data import gdata.opensearch.data GBS_TEMPLATE = '{http://schemas.google.com/books/2008/}%s' class CollectionEntry(gdata.data.GDEntry): """Describes an entry in a feed of collections.""" class CollectionFeed(gdata.data.BatchFeed): """Describes a Book Search collection feed.""" entry = [CollectionEntry] class Embeddability(atom.core.XmlElement): """Describes an embeddability.""" _qname = GBS_TEMPLATE % 'embeddability' value = 'value' class OpenAccess(atom.core.XmlElement): """Describes an open access.""" _qname = GBS_TEMPLATE % 'openAccess' value = 'value' class Review(atom.core.XmlElement): """User-provided review.""" _qname = GBS_TEMPLATE % 'review' lang = 'lang' type = 'type' class Viewability(atom.core.XmlElement): """Describes a viewability.""" _qname = GBS_TEMPLATE % 'viewability' value = 'value' class VolumeEntry(gdata.data.GDEntry): """Describes an entry in a feed of Book Search volumes.""" comments = gdata.data.Comments language = [gdata.dublincore.data.Language] open_access = OpenAccess format = [gdata.dublincore.data.Format] dc_title = [gdata.dublincore.data.Title] viewability = Viewability embeddability = Embeddability creator = [gdata.dublincore.data.Creator] rating = gdata.data.Rating description = [gdata.dublincore.data.Description] publisher = [gdata.dublincore.data.Publisher] date = [gdata.dublincore.data.Date] subject = [gdata.dublincore.data.Subject] identifier = [gdata.dublincore.data.Identifier] review = Review class VolumeFeed(gdata.data.BatchFeed): """Describes a Book Search volume feed.""" entry = [VolumeEntry]
Python
#!/usr/bin/python """ Data Models for books.service All classes can be instantiated from an xml string using their FromString class method. Notes: * Book.title displays the first dc:title because the returned XML repeats that datum as atom:title. There is an undocumented gbs:openAccess element that is not parsed. """ __author__ = "James Sams <sams.james@gmail.com>" __copyright__ = "Apache License v2.0" import atom import gdata BOOK_SEARCH_NAMESPACE = 'http://schemas.google.com/books/2008' DC_NAMESPACE = 'http://purl.org/dc/terms' ANNOTATION_REL = "http://schemas.google.com/books/2008/annotation" INFO_REL = "http://schemas.google.com/books/2008/info" LABEL_SCHEME = "http://schemas.google.com/books/2008/labels" PREVIEW_REL = "http://schemas.google.com/books/2008/preview" THUMBNAIL_REL = "http://schemas.google.com/books/2008/thumbnail" FULL_VIEW = "http://schemas.google.com/books/2008#view_all_pages" PARTIAL_VIEW = "http://schemas.google.com/books/2008#view_partial" NO_VIEW = "http://schemas.google.com/books/2008#view_no_pages" UNKNOWN_VIEW = "http://schemas.google.com/books/2008#view_unknown" EMBEDDABLE = "http://schemas.google.com/books/2008#embeddable" NOT_EMBEDDABLE = "http://schemas.google.com/books/2008#not_embeddable" class _AtomFromString(atom.AtomBase): #@classmethod def FromString(cls, s): return atom.CreateClassFromXMLString(cls, s) FromString = classmethod(FromString) class Creator(_AtomFromString): """ The <dc:creator> element identifies an author-or more generally, an entity responsible for creating the volume in question. Examples of a creator include a person, an organization, or a service. In the case of anthologies, proceedings, or other edited works, this field may be used to indicate editors or other entities responsible for collecting the volume's contents. This element appears as a child of <entry>. If there are multiple authors or contributors to the book, there may be multiple <dc:creator> elements in the volume entry (one for each creator or contributor). """ _tag = 'creator' _namespace = DC_NAMESPACE class Date(_AtomFromString): #iso 8601 / W3CDTF profile """ The <dc:date> element indicates the publication date of the specific volume in question. If the book is a reprint, this is the reprint date, not the original publication date. The date is encoded according to the ISO-8601 standard (and more specifically, the W3CDTF profile). The <dc:date> element can appear only as a child of <entry>. Usually only the year or the year and the month are given. YYYY-MM-DDThh:mm:ssTZD TZD = -hh:mm or +hh:mm """ _tag = 'date' _namespace = DC_NAMESPACE class Description(_AtomFromString): """ The <dc:description> element includes text that describes a book or book result. In a search result feed, this may be a search result "snippet" that contains the words around the user's search term. For a single volume feed, this element may contain a synopsis of the book. The <dc:description> element can appear only as a child of <entry> """ _tag = 'description' _namespace = DC_NAMESPACE class Format(_AtomFromString): """ The <dc:format> element describes the physical properties of the volume. Currently, it indicates the number of pages in the book, but more information may be added to this field in the future. This element can appear only as a child of <entry>. """ _tag = 'format' _namespace = DC_NAMESPACE class Identifier(_AtomFromString): """ The <dc:identifier> element provides an unambiguous reference to a particular book. * Every <entry> contains at least one <dc:identifier> child. * The first identifier is always the unique string Book Search has assigned to the volume (such as s1gVAAAAYAAJ). This is the ID that appears in the book's URL in the Book Search GUI, as well as in the URL of that book's single item feed. * Many books contain additional <dc:identifier> elements. These provide alternate, external identifiers to the volume. Such identifiers may include the ISBNs, ISSNs, Library of Congress Control Numbers (LCCNs), and OCLC numbers; they are prepended with a corresponding namespace prefix (such as "ISBN:"). * Any <dc:identifier> can be passed to the Dynamic Links, used to instantiate an Embedded Viewer, or even used to construct static links to Book Search. The <dc:identifier> element can appear only as a child of <entry>. """ _tag = 'identifier' _namespace = DC_NAMESPACE class Publisher(_AtomFromString): """ The <dc:publisher> element contains the name of the entity responsible for producing and distributing the volume (usually the specific edition of this book). Examples of a publisher include a person, an organization, or a service. This element can appear only as a child of <entry>. If there is more than one publisher, multiple <dc:publisher> elements may appear. """ _tag = 'publisher' _namespace = DC_NAMESPACE class Subject(_AtomFromString): """ The <dc:subject> element identifies the topic of the book. Usually this is a Library of Congress Subject Heading (LCSH) or Book Industry Standards and Communications Subject Heading (BISAC). The <dc:subject> element can appear only as a child of <entry>. There may be multiple <dc:subject> elements per entry. """ _tag = 'subject' _namespace = DC_NAMESPACE class Title(_AtomFromString): """ The <dc:title> element contains the title of a book as it was published. If a book has a subtitle, it appears as a second <dc:title> element in the book result's <entry>. """ _tag = 'title' _namespace = DC_NAMESPACE class Viewability(_AtomFromString): """ Google Book Search respects the user's local copyright restrictions. As a result, previews or full views of some books are not available in all locations. The <gbs:viewability> element indicates whether a book is fully viewable, can be previewed, or only has "about the book" information. These three "viewability modes" are the same ones returned by the Dynamic Links API. The <gbs:viewability> element can appear only as a child of <entry>. The value attribute will take the form of the following URIs to represent the relevant viewing capability: Full View: http://schemas.google.com/books/2008#view_all_pages Limited Preview: http://schemas.google.com/books/2008#view_partial Snippet View/No Preview: http://schemas.google.com/books/2008#view_no_pages Unknown view: http://schemas.google.com/books/2008#view_unknown """ _tag = 'viewability' _namespace = BOOK_SEARCH_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, text=None, extension_elements=None, extension_attributes=None): self.value = value _AtomFromString.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Embeddability(_AtomFromString): """ Many of the books found on Google Book Search can be embedded on third-party sites using the Embedded Viewer. The <gbs:embeddability> element indicates whether a particular book result is available for embedding. By definition, a book that cannot be previewed on Book Search cannot be embedded on third- party sites. The <gbs:embeddability> element can appear only as a child of <entry>. The value attribute will take on one of the following URIs: embeddable: http://schemas.google.com/books/2008#embeddable not embeddable: http://schemas.google.com/books/2008#not_embeddable """ _tag = 'embeddability' _namespace = BOOK_SEARCH_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, text=None, extension_elements=None, extension_attributes=None): self.value = value _AtomFromString.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Review(_AtomFromString): """ When present, the <gbs:review> element contains a user-generated review for a given book. This element currently appears only in the user library and user annotation feeds, as a child of <entry>. type: text, html, xhtml xml:lang: id of the language, a guess, (always two letters?) """ _tag = 'review' _namespace = BOOK_SEARCH_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' _attributes['{http://www.w3.org/XML/1998/namespace}lang'] = 'lang' def __init__(self, type=None, lang=None, text=None, extension_elements=None, extension_attributes=None): self.type = type self.lang = lang _AtomFromString.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Rating(_AtomFromString): """All attributes must take an integral string between 1 and 5. The min, max, and average attributes represent 'community' ratings. The value attribute is the user's (of the feed from which the item is fetched, not necessarily the authenticated user) rating of the book. """ _tag = 'rating' _namespace = gdata.GDATA_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['min'] = 'min' _attributes['max'] = 'max' _attributes['average'] = 'average' _attributes['value'] = 'value' def __init__(self, min=None, max=None, average=None, value=None, text=None, extension_elements=None, extension_attributes=None): self.min = min self.max = max self.average = average self.value = value _AtomFromString.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Book(_AtomFromString, gdata.GDataEntry): """ Represents an <entry> from either a search, annotation, library, or single item feed. Note that dc_title attribute is the proper title of the volume, title is an atom element and may not represent the full title. """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() for i in (Creator, Identifier, Publisher, Subject,): _children['{%s}%s' % (i._namespace, i._tag)] = (i._tag, [i]) for i in (Date, Description, Format, Viewability, Embeddability, Review, Rating): # Review, Rating maybe only in anno/lib entrys _children['{%s}%s' % (i._namespace, i._tag)] = (i._tag, i) # there is an atom title as well, should we clobber that? del(i) _children['{%s}%s' % (Title._namespace, Title._tag)] = ('dc_title', [Title]) def to_dict(self): """Returns a dictionary of the book's available metadata. If the data cannot be discovered, it is not included as a key in the returned dict. The possible keys are: authors, embeddability, date, description, format, identifiers, publishers, rating, review, subjects, title, and viewability. Notes: * Plural keys will be lists * Singular keys will be strings * Title, despite usually being a list, joins the title and subtitle with a space as a single string. * embeddability and viewability only return the portion of the URI after # * identifiers is a list of tuples, where the first item of each tuple is the type of identifier and the second item is the identifying string. Note that while doing dict() on this tuple may be possible, some items may have multiple of the same identifier and converting to a dict may resulted in collisions/dropped data. * Rating returns only the user's rating. See Rating class for precise definition. """ d = {} if self.GetAnnotationLink(): d['annotation'] = self.GetAnnotationLink().href if self.creator: d['authors'] = [x.text for x in self.creator] if self.embeddability: d['embeddability'] = self.embeddability.value.split('#')[-1] if self.date: d['date'] = self.date.text if self.description: d['description'] = self.description.text if self.format: d['format'] = self.format.text if self.identifier: d['identifiers'] = [('google_id', self.identifier[0].text)] for x in self.identifier[1:]: l = x.text.split(':') # should we lower the case of the ids? d['identifiers'].append((l[0], ':'.join(l[1:]))) if self.GetInfoLink(): d['info'] = self.GetInfoLink().href if self.GetPreviewLink(): d['preview'] = self.GetPreviewLink().href if self.publisher: d['publishers'] = [x.text for x in self.publisher] if self.rating: d['rating'] = self.rating.value if self.review: d['review'] = self.review.text if self.subject: d['subjects'] = [x.text for x in self.subject] if self.GetThumbnailLink(): d['thumbnail'] = self.GetThumbnailLink().href if self.dc_title: d['title'] = ' '.join([x.text for x in self.dc_title]) if self.viewability: d['viewability'] = self.viewability.value.split('#')[-1] return d def __init__(self, creator=None, date=None, description=None, format=None, author=None, identifier=None, publisher=None, subject=None, dc_title=None, viewability=None, embeddability=None, review=None, rating=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.creator = creator self.date = date self.description = description self.format = format self.identifier = identifier self.publisher = publisher self.subject = subject self.dc_title = dc_title or [] self.viewability = viewability self.embeddability = embeddability self.review = review self.rating = rating gdata.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, title=title, control=control, updated=updated, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) def GetThumbnailLink(self): """Returns the atom.Link object representing the thumbnail URI.""" for i in self.link: if i.rel == THUMBNAIL_REL: return i def GetInfoLink(self): """ Returns the atom.Link object representing the human-readable info URI. """ for i in self.link: if i.rel == INFO_REL: return i def GetPreviewLink(self): """Returns the atom.Link object representing the preview URI.""" for i in self.link: if i.rel == PREVIEW_REL: return i def GetAnnotationLink(self): """ Returns the atom.Link object representing the Annotation URI. Note that the use of www.books in the href of this link seems to make this information useless. Using books.service.ANNOTATION_FEED and BOOK_SERVER to construct your URI seems to work better. """ for i in self.link: if i.rel == ANNOTATION_REL: return i def set_rating(self, value): """Set user's rating. Must be an integral string between 1 nad 5""" assert (value in ('1','2','3','4','5')) if not isinstance(self.rating, Rating): self.rating = Rating() self.rating.value = value def set_review(self, text, type='text', lang='en'): """Set user's review text""" self.review = Review(text=text, type=type, lang=lang) def get_label(self): """Get users label for the item as a string""" for i in self.category: if i.scheme == LABEL_SCHEME: return i.term def set_label(self, term): """Clear pre-existing label for the item and set term as the label.""" self.remove_label() self.category.append(atom.Category(term=term, scheme=LABEL_SCHEME)) def remove_label(self): """Clear the user's label for the item""" ln = len(self.category) for i, j in enumerate(self.category[::-1]): if j.scheme == LABEL_SCHEME: del(self.category[ln-1-i]) def clean_annotations(self): """Clear all annotations from an item. Useful for taking an item from another user's library/annotation feed and adding it to the authenticated user's library without adopting annotations.""" self.remove_label() self.review = None self.rating = None def get_google_id(self): """Get Google's ID of the item.""" return self.id.text.split('/')[-1] class BookFeed(_AtomFromString, gdata.GDataFeed): """Represents a feed of entries from a search.""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _children['{%s}%s' % (Book._namespace, Book._tag)] = (Book._tag, [Book]) if __name__ == '__main__': import doctest doctest.testfile('datamodels.txt')
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 auth related token classes and functions for Google Data APIs. Token classes represent a user's authorization of this app to access their data. Usually these are not created directly but by a GDClient object. ClientLoginToken AuthSubToken SecureAuthSubToken OAuthHmacToken OAuthRsaToken TwoLeggedOAuthHmacToken TwoLeggedOAuthRsaToken Functions which are often used in application code (as opposed to just within the gdata-python-client library) are the following: generate_auth_sub_url authorize_request_token The following are helper functions which are used to save and load auth token objects in the App Engine datastore. These should only be used if you are using this library within App Engine: ae_load ae_save """ import time import random import urllib import atom.http_core __author__ = 'j.s@google.com (Jeff Scudder)' PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth=' AUTHSUB_AUTH_LABEL = 'AuthSub token=' # This dict provides the AuthSub and OAuth scopes for all services by service # name. The service name (key) is used in ClientLogin requests. AUTH_SCOPES = { 'cl': ( # Google Calendar API 'https://www.google.com/calendar/feeds/', 'http://www.google.com/calendar/feeds/'), 'gbase': ( # Google Base API 'http://base.google.com/base/feeds/', 'http://www.google.com/base/feeds/'), 'blogger': ( # Blogger API 'http://www.blogger.com/feeds/',), 'codesearch': ( # Google Code Search API 'http://www.google.com/codesearch/feeds/',), 'cp': ( # Contacts API 'https://www.google.com/m8/feeds/', 'http://www.google.com/m8/feeds/'), 'finance': ( # Google Finance API 'http://finance.google.com/finance/feeds/',), 'health': ( # Google Health API 'https://www.google.com/health/feeds/',), 'writely': ( # Documents List API 'https://docs.google.com/feeds/', 'http://docs.google.com/feeds/'), 'lh2': ( # Picasa Web Albums API 'http://picasaweb.google.com/data/',), 'apps': ( # Google Apps Provisioning API 'http://www.google.com/a/feeds/', 'https://www.google.com/a/feeds/', 'http://apps-apis.google.com/a/feeds/', 'https://apps-apis.google.com/a/feeds/'), 'weaver': ( # Health H9 Sandbox 'https://www.google.com/h9/feeds/',), 'wise': ( # Spreadsheets Data API 'https://spreadsheets.google.com/feeds/', 'http://spreadsheets.google.com/feeds/'), 'sitemaps': ( # Google Webmaster Tools API 'https://www.google.com/webmasters/tools/feeds/',), 'youtube': ( # YouTube API 'http://gdata.youtube.com/feeds/api/', 'http://uploads.gdata.youtube.com/feeds/api', 'http://gdata.youtube.com/action/GetUploadToken'), 'books': ( # Google Books API 'http://www.google.com/books/feeds/',), 'analytics': ( # Google Analytics API 'https://www.google.com/analytics/feeds/',), 'jotspot': ( # Google Sites API 'http://sites.google.com/feeds/', 'https://sites.google.com/feeds/'), 'local': ( # Google Maps Data API 'http://maps.google.com/maps/feeds/',), 'code': ( # Project Hosting Data API 'http://code.google.com/feeds/issues',)} class Error(Exception): pass class UnsupportedTokenType(Error): """Raised when token to or from blob is unable to convert the token.""" pass # ClientLogin functions and classes. def generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): """Creates the body of the autentication request See http://code.google.com/apis/accounts/AuthForInstalledApps.html#Request for more details. Args: email: str password: str service: str source: str account_type: str (optional) Defaul is 'HOSTED_OR_GOOGLE', other valid values are 'GOOGLE' and 'HOSTED' captcha_token: str (optional) captcha_response: str (optional) Returns: The HTTP body to send in a request for a client login token. """ # Create a POST body containing the user's credentials. request_fields = {'Email': email, 'Passwd': password, 'accountType': account_type, 'service': service, 'source': source} if captcha_token and captcha_response: # Send the captcha token and response as part of the POST body if the # user is responding to a captch challenge. request_fields['logintoken'] = captcha_token request_fields['logincaptcha'] = captcha_response return urllib.urlencode(request_fields) GenerateClientLoginRequestBody = generate_client_login_request_body def get_client_login_token_string(http_body): """Returns the token value for a ClientLoginToken. Reads the token from the server's response to a Client Login request and creates the token value string to use in requests. Args: http_body: str The body of the server's HTTP response to a Client Login request Returns: The token value string for a ClientLoginToken. """ for response_line in http_body.splitlines(): if response_line.startswith('Auth='): # Strip off the leading Auth= and return the Authorization value. return response_line[5:] return None GetClientLoginTokenString = get_client_login_token_string def get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): """Returns the URL and token for a CAPTCHA challenge issued by the server. Args: http_body: str The body of the HTTP response from the server which contains the CAPTCHA challenge. captcha_base_url: str This function returns a full URL for viewing the challenge image which is built from the server's response. This base_url is used as the beginning of the URL because the server only provides the end of the URL. For example the server provides 'Captcha?ctoken=Hi...N' and the URL for the image is 'http://www.google.com/accounts/Captcha?ctoken=Hi...N' Returns: A dictionary containing the information needed to repond to the CAPTCHA challenge, the image URL and the ID token of the challenge. The dictionary is in the form: {'token': string identifying the CAPTCHA image, 'url': string containing the URL of the image} Returns None if there was no CAPTCHA challenge in the response. """ contains_captcha_challenge = False captcha_parameters = {} for response_line in http_body.splitlines(): if response_line.startswith('Error=CaptchaRequired'): contains_captcha_challenge = True elif response_line.startswith('CaptchaToken='): # Strip off the leading CaptchaToken= captcha_parameters['token'] = response_line[13:] elif response_line.startswith('CaptchaUrl='): captcha_parameters['url'] = '%s%s' % (captcha_base_url, response_line[11:]) if contains_captcha_challenge: return captcha_parameters else: return None GetCaptchaChallenge = get_captcha_challenge class ClientLoginToken(object): def __init__(self, token_string): self.token_string = token_string def modify_request(self, http_request): http_request.headers['Authorization'] = '%s%s' % (PROGRAMMATIC_AUTH_LABEL, self.token_string) ModifyRequest = modify_request # AuthSub functions and classes. def _to_uri(str_or_uri): if isinstance(str_or_uri, (str, unicode)): return atom.http_core.Uri.parse_uri(str_or_uri) return str_or_uri def generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri( 'https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): """Constructs a URI for requesting a multiscope AuthSub token. The generated token will contain a URL parameter to pass along the requested scopes to the next URL. When the Google Accounts page redirects the broswser to the 'next' URL, it appends the single use AuthSub token value to the URL as a URL parameter with the key 'token'. However, the information about which scopes were requested is not included by Google Accounts. This method adds the scopes to the next URL before making the request so that the redirect will be sent to a page, and both the token value and the list of scopes for which the token was requested. Args: next: atom.http_core.Uri or string The URL user will be sent to after authorizing this web application to access their data. scopes: list containint strings or atom.http_core.Uri objects. The URLs of the services to be accessed. Could also be a single string or single atom.http_core.Uri for requesting just one scope. 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. request_url: atom.http_core.Uri or str The beginning of the request URL. This is normally 'http://www.google.com/accounts/AuthSubRequest' or '/accounts/AuthSubRequest' domain: The domain which the account is part of. This is used for Google Apps accounts, the default value is 'default' which means that the requested account is a Google Account (@gmail.com for example) scopes_param_prefix: str (optional) The requested scopes are added as a URL parameter to the next URL so that the page at the 'next' URL can extract the token value and the valid scopes from the URL. The key for the URL parameter defaults to 'auth_sub_scopes' Returns: An atom.http_core.Uri which the user's browser should be directed to in order to authorize this application to access their information. """ if isinstance(next, (str, unicode)): next = atom.http_core.Uri.parse_uri(next) # If the user passed in a string instead of a list for scopes, convert to # a single item tuple. if isinstance(scopes, (str, unicode, atom.http_core.Uri)): scopes = (scopes,) scopes_string = ' '.join([str(scope) for scope in scopes]) next.query[scopes_param_prefix] = scopes_string if isinstance(request_url, (str, unicode)): request_url = atom.http_core.Uri.parse_uri(request_url) request_url.query['next'] = str(next) request_url.query['scope'] = scopes_string if session: request_url.query['session'] = '1' else: request_url.query['session'] = '0' if secure: request_url.query['secure'] = '1' else: request_url.query['secure'] = '0' request_url.query['hd'] = domain return request_url def auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): """Finds the token string (and scopes) after the browser is redirected. After the Google Accounts AuthSub pages redirect the user's broswer back to the web application (using the 'next' URL from the request) the web app must extract the token from the current page's URL. The token is provided as a URL parameter named 'token' and if generate_auth_sub_url was used to create the request, the token's valid scopes are included in a URL parameter whose name is specified in scopes_param_prefix. Args: url: atom.url.Url or str representing the current URL. The token value and valid scopes should be included as URL parameters. scopes_param_prefix: str (optional) The URL parameter key which maps to the list of valid scopes for the token. Returns: A tuple containing the token value as a string, and a tuple of scopes (as atom.http_core.Uri objects) which are URL prefixes under which this token grants permission to read and write user data. (token_string, (scope_uri, scope_uri, scope_uri, ...)) If no scopes were included in the URL, the second value in the tuple is None. If there was no token param in the url, the tuple returned is (None, None) """ if isinstance(url, (str, unicode)): url = atom.http_core.Uri.parse_uri(url) if 'token' not in url.query: return (None, None) token = url.query['token'] # TODO: decide whether no scopes should be None or (). scopes = None # Default to None for no scopes. if scopes_param_prefix in url.query: scopes = tuple(url.query[scopes_param_prefix].split(' ')) return (token, scopes) AuthSubStringFromUrl = auth_sub_string_from_url def auth_sub_string_from_body(http_body): """Extracts the AuthSub token from an HTTP body string. Used to find the new session token after making a request to upgrade a single use AuthSub token. Args: http_body: str The repsonse from the server which contains the AuthSub key. For example, this function would find the new session token from the server's response to an upgrade token request. Returns: The raw token value string to use in an AuthSubToken object. """ for response_line in http_body.splitlines(): if response_line.startswith('Token='): # Strip off Token= and return the token value string. return response_line[6:] return None class AuthSubToken(object): def __init__(self, token_string, scopes=None): self.token_string = token_string self.scopes = scopes or [] def modify_request(self, http_request): """Sets Authorization header, allows app to act on the user's behalf.""" http_request.headers['Authorization'] = '%s%s' % (AUTHSUB_AUTH_LABEL, self.token_string) ModifyRequest = modify_request def from_url(str_or_uri): """Creates a new AuthSubToken using information in the URL. Uses auth_sub_string_from_url. Args: str_or_uri: The current page's URL (as a str or atom.http_core.Uri) which should contain a token query parameter since the Google auth server redirected the user's browser to this URL. """ token_and_scopes = auth_sub_string_from_url(str_or_uri) return AuthSubToken(token_and_scopes[0], token_and_scopes[1]) from_url = staticmethod(from_url) FromUrl = from_url def _upgrade_token(self, http_body): """Replaces the token value with a session token from the auth server. Uses the response of a token upgrade request to modify this token. Uses auth_sub_string_from_body. """ self.token_string = auth_sub_string_from_body(http_body) # Functions and classes for Secure-mode AuthSub def build_auth_sub_data(http_request, timestamp, nonce): """Creates the data string which must be RSA-signed in secure requests. For more details see the documenation on secure AuthSub requests: http://code.google.com/apis/accounts/docs/AuthSub.html#signingrequests Args: http_request: The request being made to the server. The Request's URL must be complete before this signature is calculated as any changes to the URL will invalidate the signature. nonce: str Random 64-bit, unsigned number encoded as an ASCII string in decimal format. The nonce/timestamp pair should always be unique to prevent replay attacks. timestamp: Integer representing the time the request is sent. The timestamp should be expressed in number of seconds after January 1, 1970 00:00:00 GMT. """ return '%s %s %s %s' % (http_request.method, str(http_request.uri), str(timestamp), nonce) def generate_signature(data, rsa_key): """Signs the data string for a secure AuthSub request.""" import base64 try: from tlslite.utils import keyfactory except ImportError: from gdata.tlslite.utils import keyfactory private_key = keyfactory.parsePrivateKey(rsa_key) signed = private_key.hashAndSign(data) # Python2.3 and lower does not have the base64.b64encode function. if hasattr(base64, 'b64encode'): return base64.b64encode(signed) else: return base64.encodestring(signed).replace('\n', '') class SecureAuthSubToken(AuthSubToken): def __init__(self, token_string, rsa_private_key, scopes=None): self.token_string = token_string self.scopes = scopes or [] self.rsa_private_key = rsa_private_key def from_url(str_or_uri, rsa_private_key): """Creates a new SecureAuthSubToken using information in the URL. Uses auth_sub_string_from_url. Args: str_or_uri: The current page's URL (as a str or atom.http_core.Uri) which should contain a token query parameter since the Google auth server redirected the user's browser to this URL. rsa_private_key: str the private RSA key cert used to sign all requests made with this token. """ token_and_scopes = auth_sub_string_from_url(str_or_uri) return SecureAuthSubToken(token_and_scopes[0], rsa_private_key, token_and_scopes[1]) from_url = staticmethod(from_url) FromUrl = from_url def modify_request(self, http_request): """Sets the Authorization header and includes a digital signature. Calculates a digital signature using the private RSA key, a timestamp (uses now at the time this method is called) and a random nonce. Args: http_request: The atom.http_core.HttpRequest which contains all of the information needed to send a request to the remote server. The URL and the method of the request must be already set and cannot be changed after this token signs the request, or the signature will not be valid. """ timestamp = str(int(time.time())) nonce = ''.join([str(random.randint(0, 9)) for i in xrange(15)]) data = build_auth_sub_data(http_request, timestamp, nonce) signature = generate_signature(data, self.rsa_private_key) http_request.headers['Authorization'] = ( '%s%s sigalg="rsa-sha1" data="%s" sig="%s"' % (AUTHSUB_AUTH_LABEL, self.token_string, data, signature)) ModifyRequest = modify_request # OAuth functions and classes. RSA_SHA1 = 'RSA-SHA1' HMAC_SHA1 = 'HMAC-SHA1' def build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): """Generates the base string to be signed in the OAuth request. Args: http_request: The request being made to the server. The Request's URL must be complete before this signature is calculated as any changes to the URL will invalidate the signature. consumer_key: Domain identifying the third-party web application. This is the domain used when registering the application with Google. It identifies who is making the request on behalf of the user. nonce: Random 64-bit, unsigned number encoded as an ASCII string in decimal format. The nonce/timestamp pair should always be unique to prevent replay attacks. signaure_type: either RSA_SHA1 or HMAC_SHA1 timestamp: Integer representing the time the request is sent. The timestamp should be expressed in number of seconds after January 1, 1970 00:00:00 GMT. version: The OAuth version used by the requesting web application. This value must be '1.0' or '1.0a'. If not provided, Google assumes version 1.0 is in use. next: The URL the user should be redirected to after granting access to a Google service(s). It can include url-encoded query parameters. The default value is 'oob'. (This is the oauth_callback.) token: The string for the OAuth request token or OAuth access token. verifier: str Sent as the oauth_verifier and required when upgrading a request token to an access token. """ # First we must build the canonical base string for the request. params = http_request.uri.query.copy() params['oauth_consumer_key'] = consumer_key params['oauth_nonce'] = nonce params['oauth_signature_method'] = signaure_type params['oauth_timestamp'] = str(timestamp) if next is not None: params['oauth_callback'] = str(next) if token is not None: params['oauth_token'] = token if version is not None: params['oauth_version'] = version if verifier is not None: params['oauth_verifier'] = verifier # We need to get the key value pairs in lexigraphically sorted order. sorted_keys = None try: sorted_keys = sorted(params.keys()) # The sorted function is not available in Python2.3 and lower except NameError: sorted_keys = params.keys() sorted_keys.sort() pairs = [] for key in sorted_keys: pairs.append('%s=%s' % (urllib.quote(key, safe='~'), urllib.quote(params[key], safe='~'))) # We want to escape /'s too, so use safe='~' all_parameters = urllib.quote('&'.join(pairs), safe='~') normailzed_host = http_request.uri.host.lower() normalized_scheme = (http_request.uri.scheme or 'http').lower() non_default_port = None if (http_request.uri.port is not None and ((normalized_scheme == 'https' and http_request.uri.port != 443) or (normalized_scheme == 'http' and http_request.uri.port != 80))): non_default_port = http_request.uri.port path = http_request.uri.path or '/' request_path = None if not path.startswith('/'): path = '/%s' % path if non_default_port is not None: # Set the only safe char in url encoding to ~ since we want to escape / # as well. request_path = urllib.quote('%s://%s:%s%s' % ( normalized_scheme, normailzed_host, non_default_port, path), safe='~') else: # Set the only safe char in url encoding to ~ since we want to escape / # as well. request_path = urllib.quote('%s://%s%s' % ( normalized_scheme, normailzed_host, path), safe='~') # TODO: ensure that token escaping logic is correct, not sure if the token # value should be double escaped instead of single. base_string = '&'.join((http_request.method.upper(), request_path, all_parameters)) # Now we have the base string, we can calculate the oauth_signature. return base_string def generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): import hmac import base64 base_string = build_oauth_base_string( http_request, consumer_key, nonce, HMAC_SHA1, timestamp, version, next, token, verifier=verifier) hash_key = None hashed = None if token_secret is not None: hash_key = '%s&%s' % (urllib.quote(consumer_secret, safe='~'), urllib.quote(token_secret, safe='~')) else: hash_key = '%s&' % urllib.quote(consumer_secret, safe='~') try: import hashlib hashed = hmac.new(hash_key, base_string, hashlib.sha1) except ImportError: import sha hashed = hmac.new(hash_key, base_string, sha) # Python2.3 does not have base64.b64encode. if hasattr(base64, 'b64encode'): return base64.b64encode(hashed.digest()) else: return base64.encodestring(hashed.digest()).replace('\n', '') def generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): import base64 try: from tlslite.utils import keyfactory except ImportError: from gdata.tlslite.utils import keyfactory base_string = build_oauth_base_string( http_request, consumer_key, nonce, RSA_SHA1, timestamp, version, next, token, verifier=verifier) private_key = keyfactory.parsePrivateKey(rsa_key) # Sign using the key signed = private_key.hashAndSign(base_string) # Python2.3 does not have base64.b64encode. if hasattr(base64, 'b64encode'): return base64.b64encode(signed) else: return base64.encodestring(signed).replace('\n', '') def generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): """Builds the Authorization header to be sent in the request. Args: consumer_key: Identifies the application making the request (str). timestamp: nonce: signature_type: One of either HMAC_SHA1 or RSA_SHA1 signature: The HMAC or RSA signature for the request as a base64 encoded string. version: The version of the OAuth protocol that this request is using. Default is '1.0' next: The URL of the page that the user's browser should be sent to after they authorize the token. (Optional) token: str The OAuth token value to be used in the oauth_token parameter of the header. verifier: str The OAuth verifier which must be included when you are upgrading a request token to an access token. """ params = { 'oauth_consumer_key': consumer_key, 'oauth_version': version, 'oauth_nonce': nonce, 'oauth_timestamp': str(timestamp), 'oauth_signature_method': signature_type, 'oauth_signature': signature} if next is not None: params['oauth_callback'] = str(next) if token is not None: params['oauth_token'] = token if verifier is not None: params['oauth_verifier'] = verifier pairs = [ '%s="%s"' % ( k, urllib.quote(v, safe='~')) for k, v in params.iteritems()] return 'OAuth %s' % (', '.join(pairs)) REQUEST_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetRequestToken' ACCESS_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetAccessToken' def generate_request_for_request_token( consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): """Creates request to be sent to auth server to get an OAuth request token. Args: consumer_key: signature_type: either RSA_SHA1 or HMAC_SHA1. The rsa_key must be provided if the signature type is RSA but if the signature method is HMAC, the consumer_secret must be used. scopes: List of URL prefixes for the data which we want to access. For example, to request access to the user's Blogger and Google Calendar data, we would request ['http://www.blogger.com/feeds/', 'https://www.google.com/calendar/feeds/', 'http://www.google.com/calendar/feeds/'] rsa_key: Only used if the signature method is RSA_SHA1. consumer_secret: Only used if the signature method is HMAC_SHA1. auth_server_url: The URL to which the token request should be directed. Defaults to 'https://www.google.com/accounts/OAuthGetRequestToken'. next: The URL of the page that the user's browser should be sent to after they authorize the token. (Optional) version: The OAuth version used by the requesting web application. Defaults to '1.0a' Returns: An atom.http_core.HttpRequest object with the URL, Authorization header and body filled in. """ request = atom.http_core.HttpRequest(auth_server_url, 'POST') # Add the requested auth scopes to the Auth request URL. if scopes: request.uri.query['scope'] = ' '.join(scopes) timestamp = str(int(time.time())) nonce = ''.join([str(random.randint(0, 9)) for i in xrange(15)]) signature = None if signature_type == HMAC_SHA1: signature = generate_hmac_signature( request, consumer_key, consumer_secret, timestamp, nonce, version, next=next) elif signature_type == RSA_SHA1: signature = generate_rsa_signature( request, consumer_key, rsa_key, timestamp, nonce, version, next=next) else: return None request.headers['Authorization'] = generate_auth_header( consumer_key, timestamp, nonce, signature_type, signature, version, next) request.headers['Content-Length'] = '0' return request def generate_request_for_access_token( request_token, auth_server_url=ACCESS_TOKEN_URL): """Creates a request to ask the OAuth server for an access token. Requires a request token which the user has authorized. See the documentation on OAuth with Google Data for more details: http://code.google.com/apis/accounts/docs/OAuth.html#AccessToken Args: request_token: An OAuthHmacToken or OAuthRsaToken which the user has approved using their browser. auth_server_url: (optional) The URL at which the OAuth access token is requested. Defaults to https://www.google.com/accounts/OAuthGetAccessToken Returns: A new HttpRequest object which can be sent to the OAuth server to request an OAuth Access Token. """ http_request = atom.http_core.HttpRequest(auth_server_url, 'POST') http_request.headers['Content-Length'] = '0' return request_token.modify_request(http_request) def oauth_token_info_from_body(http_body): """Exracts an OAuth request token from the server's response. Returns: A tuple of strings containing the OAuth token and token secret. If neither of these are present in the body, returns (None, None) """ token = None token_secret = None for pair in http_body.split('&'): if pair.startswith('oauth_token='): token = urllib.unquote(pair[len('oauth_token='):]) if pair.startswith('oauth_token_secret='): token_secret = urllib.unquote(pair[len('oauth_token_secret='):]) return (token, token_secret) def hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): token_value, token_secret = oauth_token_info_from_body(http_body) token = OAuthHmacToken(consumer_key, consumer_secret, token_value, token_secret, auth_state) return token def rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): token_value, token_secret = oauth_token_info_from_body(http_body) token = OAuthRsaToken(consumer_key, rsa_private_key, token_value, token_secret, auth_state) return token DEFAULT_DOMAIN = 'default' OAUTH_AUTHORIZE_URL = 'https://www.google.com/accounts/OAuthAuthorizeToken' def generate_oauth_authorization_url( token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): """Creates a URL for the page where the request token can be authorized. Args: token: str The request token from the OAuth server. next: str (optional) URL the user should be redirected to after granting access to a Google service(s). It can include url-encoded query parameters. hd: str (optional) Identifies a particular hosted domain account to be accessed (for example, 'mycollege.edu'). Uses 'default' to specify a regular Google account ('username@gmail.com'). hl: str (optional) An ISO 639 country code identifying what language the approval page should be translated in (for example, 'hl=en' for English). The default is the user's selected language. btmpl: str (optional) Forces a mobile version of the approval page. The only accepted value is 'mobile'. auth_server: str (optional) The start of the token authorization web page. Defaults to 'https://www.google.com/accounts/OAuthAuthorizeToken' Returns: An atom.http_core.Uri pointing to the token authorization page where the user may allow or deny this app to access their Google data. """ uri = atom.http_core.Uri.parse_uri(auth_server) uri.query['oauth_token'] = token uri.query['hd'] = hd if next is not None: uri.query['oauth_callback'] = str(next) if hl is not None: uri.query['hl'] = hl if btmpl is not None: uri.query['btmpl'] = btmpl return uri def oauth_token_info_from_url(url): """Exracts an OAuth access token from the redirected page's URL. Returns: A tuple of strings containing the OAuth token and the OAuth verifier which need to sent when upgrading a request token to an access token. """ if isinstance(url, (str, unicode)): url = atom.http_core.Uri.parse_uri(url) token = None verifier = None if 'oauth_token' in url.query: token = urllib.unquote(url.query['oauth_token']) if 'oauth_verifier' in url.query: verifier = urllib.unquote(url.query['oauth_verifier']) return (token, verifier) def authorize_request_token(request_token, url): """Adds information to request token to allow it to become an access token. Modifies the request_token object passed in by setting and unsetting the necessary fields to allow this token to form a valid upgrade request. Args: request_token: The OAuth request token which has been authorized by the user. In order for this token to be upgraded to an access token, certain fields must be extracted from the URL and added to the token so that they can be passed in an upgrade-token request. url: The URL of the current page which the user's browser was redirected to after they authorized access for the app. This function extracts information from the URL which is needed to upgraded the token from a request token to an access token. Returns: The same token object which was passed in. """ token, verifier = oauth_token_info_from_url(url) request_token.token = token request_token.verifier = verifier request_token.auth_state = AUTHORIZED_REQUEST_TOKEN return request_token AuthorizeRequestToken = authorize_request_token def upgrade_to_access_token(request_token, server_response_body): """Extracts access token information from response to an upgrade request. Once the server has responded with the new token info for the OAuth access token, this method modifies the request_token to set and unset necessary fields to create valid OAuth authorization headers for requests. Args: request_token: An OAuth token which this function modifies to allow it to be used as an access token. server_response_body: str The server's response to an OAuthAuthorizeToken request. This should contain the new token and token_secret which are used to generate the signature and parameters of the Authorization header in subsequent requests to Google Data APIs. Returns: The same token object which was passed in. """ token, token_secret = oauth_token_info_from_body(server_response_body) request_token.token = token request_token.token_secret = token_secret request_token.auth_state = ACCESS_TOKEN request_token.next = None request_token.verifier = None return request_token UpgradeToAccessToken = upgrade_to_access_token REQUEST_TOKEN = 1 AUTHORIZED_REQUEST_TOKEN = 2 ACCESS_TOKEN = 3 class OAuthHmacToken(object): SIGNATURE_METHOD = HMAC_SHA1 def __init__(self, consumer_key, consumer_secret, token, token_secret, auth_state, next=None, verifier=None): self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.token = token self.token_secret = token_secret self.auth_state = auth_state self.next = next self.verifier = verifier # Used to convert request token to access token. def generate_authorization_url( self, google_apps_domain=DEFAULT_DOMAIN, language=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): """Creates the URL at which the user can authorize this app to access. Args: google_apps_domain: str (optional) If the user should be signing in using an account under a known Google Apps domain, provide the domain name ('example.com') here. If not provided, 'default' will be used, and the user will be prompted to select an account if they are signed in with a Google Account and Google Apps accounts. language: str (optional) An ISO 639 country code identifying what language the approval page should be translated in (for example, 'en' for English). The default is the user's selected language. btmpl: str (optional) Forces a mobile version of the approval page. The only accepted value is 'mobile'. auth_server: str (optional) The start of the token authorization web page. Defaults to 'https://www.google.com/accounts/OAuthAuthorizeToken' """ return generate_oauth_authorization_url( self.token, hd=google_apps_domain, hl=language, btmpl=btmpl, auth_server=auth_server) GenerateAuthorizationUrl = generate_authorization_url def modify_request(self, http_request): """Sets the Authorization header in the HTTP request using the token. Calculates an HMAC signature using the information in the token to indicate that the request came from this application and that this application has permission to access a particular user's data. Returns: The same HTTP request object which was passed in. """ timestamp = str(int(time.time())) nonce = ''.join([str(random.randint(0, 9)) for i in xrange(15)]) signature = generate_hmac_signature( http_request, self.consumer_key, self.consumer_secret, timestamp, nonce, version='1.0', next=self.next, token=self.token, token_secret=self.token_secret, verifier=self.verifier) http_request.headers['Authorization'] = generate_auth_header( self.consumer_key, timestamp, nonce, HMAC_SHA1, signature, version='1.0', next=self.next, token=self.token, verifier=self.verifier) return http_request ModifyRequest = modify_request class OAuthRsaToken(OAuthHmacToken): SIGNATURE_METHOD = RSA_SHA1 def __init__(self, consumer_key, rsa_private_key, token, token_secret, auth_state, next=None, verifier=None): self.consumer_key = consumer_key self.rsa_private_key = rsa_private_key self.token = token self.token_secret = token_secret self.auth_state = auth_state self.next = next self.verifier = verifier # Used to convert request token to access token. def modify_request(self, http_request): """Sets the Authorization header in the HTTP request using the token. Calculates an RSA signature using the information in the token to indicate that the request came from this application and that this application has permission to access a particular user's data. Returns: The same HTTP request object which was passed in. """ timestamp = str(int(time.time())) nonce = ''.join([str(random.randint(0, 9)) for i in xrange(15)]) signature = generate_rsa_signature( http_request, self.consumer_key, self.rsa_private_key, timestamp, nonce, version='1.0', next=self.next, token=self.token, token_secret=self.token_secret, verifier=self.verifier) http_request.headers['Authorization'] = generate_auth_header( self.consumer_key, timestamp, nonce, RSA_SHA1, signature, version='1.0', next=self.next, token=self.token, verifier=self.verifier) return http_request ModifyRequest = modify_request class TwoLeggedOAuthHmacToken(OAuthHmacToken): def __init__(self, consumer_key, consumer_secret, requestor_id): self.requestor_id = requestor_id OAuthHmacToken.__init__( self, consumer_key, consumer_secret, None, None, ACCESS_TOKEN, next=None, verifier=None) def modify_request(self, http_request): """Sets the Authorization header in the HTTP request using the token. Calculates an HMAC signature using the information in the token to indicate that the request came from this application and that this application has permission to access a particular user's data using 2LO. Returns: The same HTTP request object which was passed in. """ http_request.uri.query['xoauth_requestor_id'] = self.requestor_id return OAuthHmacToken.modify_request(self, http_request) ModifyRequest = modify_request class TwoLeggedOAuthRsaToken(OAuthRsaToken): def __init__(self, consumer_key, rsa_private_key, requestor_id): self.requestor_id = requestor_id OAuthRsaToken.__init__( self, consumer_key, rsa_private_key, None, None, ACCESS_TOKEN, next=None, verifier=None) def modify_request(self, http_request): """Sets the Authorization header in the HTTP request using the token. Calculates an RSA signature using the information in the token to indicate that the request came from this application and that this application has permission to access a particular user's data using 2LO. Returns: The same HTTP request object which was passed in. """ http_request.uri.query['xoauth_requestor_id'] = self.requestor_id return OAuthRsaToken.modify_request(self, http_request) ModifyRequest = modify_request def _join_token_parts(*args): """"Escapes and combines all strings passed in. Used to convert a token object's members into a string instead of using pickle. Note: A None value will be converted to an empty string. Returns: A string in the form 1x|member1|member2|member3... """ return '|'.join([urllib.quote_plus(a or '') for a in args]) def _split_token_parts(blob): """Extracts and unescapes fields from the provided binary string. Reverses the packing performed by _join_token_parts. Used to extract the members of a token object. Note: An empty string from the blob will be interpreted as None. Args: blob: str A string of the form 1x|member1|member2|member3 as created by _join_token_parts Returns: A list of unescaped strings. """ return [urllib.unquote_plus(part) or None for part in blob.split('|')] def token_to_blob(token): """Serializes the token data as a string for storage in a datastore. Supported token classes: ClientLoginToken, AuthSubToken, SecureAuthSubToken, OAuthRsaToken, and OAuthHmacToken, TwoLeggedOAuthRsaToken, TwoLeggedOAuthHmacToken. Args: token: A token object which must be of one of the supported token classes. Raises: UnsupportedTokenType if the token is not one of the supported token classes listed above. Returns: A string represenging this token. The string can be converted back into an equivalent token object using token_from_blob. Note that any members which are set to '' will be set to None when the token is deserialized by token_from_blob. """ if isinstance(token, ClientLoginToken): return _join_token_parts('1c', token.token_string) # Check for secure auth sub type first since it is a subclass of # AuthSubToken. elif isinstance(token, SecureAuthSubToken): return _join_token_parts('1s', token.token_string, token.rsa_private_key, *token.scopes) elif isinstance(token, AuthSubToken): return _join_token_parts('1a', token.token_string, *token.scopes) elif isinstance(token, TwoLeggedOAuthRsaToken): return _join_token_parts( '1rtl', token.consumer_key, token.rsa_private_key, token.requestor_id) elif isinstance(token, TwoLeggedOAuthHmacToken): return _join_token_parts( '1htl', token.consumer_key, token.consumer_secret, token.requestor_id) # Check RSA OAuth token first since the OAuthRsaToken is a subclass of # OAuthHmacToken. elif isinstance(token, OAuthRsaToken): return _join_token_parts( '1r', token.consumer_key, token.rsa_private_key, token.token, token.token_secret, str(token.auth_state), token.next, token.verifier) elif isinstance(token, OAuthHmacToken): return _join_token_parts( '1h', token.consumer_key, token.consumer_secret, token.token, token.token_secret, str(token.auth_state), token.next, token.verifier) else: raise UnsupportedTokenType( 'Unable to serialize token of type %s' % type(token)) TokenToBlob = token_to_blob def token_from_blob(blob): """Deserializes a token string from the datastore back into a token object. Supported token classes: ClientLoginToken, AuthSubToken, SecureAuthSubToken, OAuthRsaToken, and OAuthHmacToken, TwoLeggedOAuthRsaToken, TwoLeggedOAuthHmacToken. Args: blob: string created by token_to_blob. Raises: UnsupportedTokenType if the token is not one of the supported token classes listed above. Returns: A new token object with members set to the values serialized in the blob string. Note that any members which were set to '' in the original token will now be None. """ parts = _split_token_parts(blob) if parts[0] == '1c': return ClientLoginToken(parts[1]) elif parts[0] == '1a': return AuthSubToken(parts[1], parts[2:]) elif parts[0] == '1s': return SecureAuthSubToken(parts[1], parts[2], parts[3:]) elif parts[0] == '1rtl': return TwoLeggedOAuthRsaToken(parts[1], parts[2], parts[3]) elif parts[0] == '1htl': return TwoLeggedOAuthHmacToken(parts[1], parts[2], parts[3]) elif parts[0] == '1r': auth_state = int(parts[5]) return OAuthRsaToken(parts[1], parts[2], parts[3], parts[4], auth_state, parts[6], parts[7]) elif parts[0] == '1h': auth_state = int(parts[5]) return OAuthHmacToken(parts[1], parts[2], parts[3], parts[4], auth_state, parts[6], parts[7]) else: raise UnsupportedTokenType( 'Unable to deserialize token with type marker of %s' % parts[0]) TokenFromBlob = token_from_blob def dump_tokens(tokens): return ','.join([token_to_blob(t) for t in tokens]) def load_tokens(blob): return [token_from_blob(s) for s in blob.split(',')] def find_scopes_for_services(service_names=None): """Creates a combined list of scope URLs for the desired services. This method searches the AUTH_SCOPES dictionary. Args: service_names: list of strings (optional) Each name must be a key in the AUTH_SCOPES dictionary. If no list is provided (None) then the resulting list will contain all scope URLs in the AUTH_SCOPES dict. Returns: A list of URL strings which are the scopes needed to access these services when requesting a token using AuthSub or OAuth. """ result_scopes = [] if service_names is None: for service_name, scopes in AUTH_SCOPES.iteritems(): result_scopes.extend(scopes) else: for service_name in service_names: result_scopes.extend(AUTH_SCOPES[service_name]) return result_scopes FindScopesForServices = find_scopes_for_services def ae_save(token, token_key): """Stores an auth token in the App Engine datastore. This is a convenience method for using the library with App Engine. Recommended usage is to associate the auth token with the current_user. If a user is signed in to the app using the App Engine users API, you can use gdata.gauth.ae_save(some_token, users.get_current_user().user_id()) If you are not using the Users API you are free to choose whatever string you would like for a token_string. Args: token: an auth token object. Must be one of ClientLoginToken, AuthSubToken, SecureAuthSubToken, OAuthRsaToken, or OAuthHmacToken (see token_to_blob). token_key: str A unique identified to be used when you want to retrieve the token. If the user is signed in to App Engine using the users API, I recommend using the user ID for the token_key: users.get_current_user().user_id() """ import gdata.alt.app_engine key_name = ''.join(('gd_auth_token', token_key)) return gdata.alt.app_engine.set_token(key_name, token_to_blob(token)) AeSave = ae_save def ae_load(token_key): """Retrieves a token object from the App Engine datastore. This is a convenience method for using the library with App Engine. See also ae_save. Args: token_key: str The unique key associated with the desired token when it was saved using ae_save. Returns: A token object if there was a token associated with the token_key or None if the key could not be found. """ import gdata.alt.app_engine key_name = ''.join(('gd_auth_token', token_key)) token_string = gdata.alt.app_engine.get_token(key_name) if token_string is not None: return token_from_blob(token_string) else: return None AeLoad = ae_load def ae_delete(token_key): """Removes the token object from the App Engine datastore.""" import gdata.alt.app_engine key_name = ''.join(('gd_auth_token', token_key)) gdata.alt.app_engine.delete_token(key_name) AeDelete = ae_delete
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. """HealthService extends GDataService to streamline Google Health API access. HealthService: Provides methods to interact with the profile, profile list, and register/notices feeds. Extends GDataService. HealthProfileQuery: Queries the Google Health Profile feed. HealthProfileListQuery: Queries the Google Health Profile list feed. """ __author__ = 'api.eric@google.com (Eric Bidelman)' import atom import gdata.health import gdata.service class HealthService(gdata.service.GDataService): """Client extension for the Google Health service Document List feed.""" def __init__(self, email=None, password=None, source=None, use_h9_sandbox=False, server='www.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Health 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. use_h9_sandbox: boolean (optional) True to issue requests against the /h9 developer's sandbox. server: string (optional) The name of the server to which a connection will be opened. additional_headers: dictionary (optional) Any additional headers which should be included with CRUD operations. kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ service = use_h9_sandbox and 'weaver' or 'health' gdata.service.GDataService.__init__( self, email=email, password=password, service=service, source=source, server=server, additional_headers=additional_headers, **kwargs) self.ssl = True self.use_h9_sandbox = use_h9_sandbox def __get_service(self): return self.use_h9_sandbox and 'h9' or 'health' def GetProfileFeed(self, query=None, profile_id=None): """Fetches the users Google Health profile feed. Args: query: HealthProfileQuery or string (optional) A query to use on the profile feed. If None, a HealthProfileQuery is constructed. profile_id: string (optional) The profile id to query the profile feed with when using ClientLogin. Note: this parameter is ignored if query is set. Returns: A gdata.health.ProfileFeed object containing the user's Health profile. """ if query is None: projection = profile_id and 'ui' or 'default' uri = HealthProfileQuery( service=self.__get_service(), projection=projection, profile_id=profile_id).ToUri() elif isinstance(query, HealthProfileQuery): uri = query.ToUri() else: uri = query return self.GetFeed(uri, converter=gdata.health.ProfileFeedFromString) def GetProfileListFeed(self, query=None): """Fetches the users Google Health profile feed. Args: query: HealthProfileListQuery or string (optional) A query to use on the profile list feed. If None, a HealthProfileListQuery is constructed to /health/feeds/profile/list or /h9/feeds/profile/list. Returns: A gdata.health.ProfileListFeed object containing the user's list of profiles. """ if not query: uri = HealthProfileListQuery(service=self.__get_service()).ToUri() elif isinstance(query, HealthProfileListQuery): uri = query.ToUri() else: uri = query return self.GetFeed(uri, converter=gdata.health.ProfileListFeedFromString) def SendNotice(self, subject, body=None, content_type='html', ccr=None, profile_id=None): """Sends (posts) a notice to the user's Google Health profile. Args: subject: A string representing the message's subject line. body: string (optional) The message body. content_type: string (optional) The content type of the notice message body. This parameter is only honored when a message body is specified. ccr: string (optional) The CCR XML document to reconcile into the user's profile. profile_id: string (optional) The profile id to work with when using ClientLogin. Note: this parameter is ignored if query is set. Returns: A gdata.health.ProfileEntry object of the posted entry. """ if body: content = atom.Content(content_type=content_type, text=body) else: content = body entry = gdata.GDataEntry( title=atom.Title(text=subject), content=content, extension_elements=[atom.ExtensionElementFromString(ccr)]) projection = profile_id and 'ui' or 'default' query = HealthRegisterQuery(service=self.__get_service(), projection=projection, profile_id=profile_id) return self.Post(entry, query.ToUri(), converter=gdata.health.ProfileEntryFromString) class HealthProfileQuery(gdata.service.Query): """Object used to construct a URI to query the Google Health profile feed.""" def __init__(self, service='health', feed='feeds/profile', projection='default', profile_id=None, text_query=None, params=None, categories=None): """Constructor for Health profile feed query. Args: service: string (optional) The service to query. Either 'health' or 'h9'. feed: string (optional) The path for the feed. The default value is 'feeds/profile'. projection: string (optional) The visibility of the data. Possible values are 'default' for AuthSub and 'ui' for ClientLogin. If this value is set to 'ui', the profile_id parameter should also be set. profile_id: string (optional) The profile id to query. This should only be used when using ClientLogin. 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. Note: this parameter can only be used on the register feed using ClientLogin. 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. """ self.service = service self.profile_id = profile_id self.projection = projection gdata.service.Query.__init__(self, feed=feed, text_query=text_query, params=params, categories=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 Health profile feed. """ old_feed = self.feed self.feed = '/'.join([self.service, old_feed, self.projection]) if self.profile_id: self.feed += '/' + self.profile_id self.feed = '/%s' % (self.feed,) new_feed = gdata.service.Query.ToUri(self) self.feed = old_feed return new_feed class HealthProfileListQuery(gdata.service.Query): """Object used to construct a URI to query a Health profile list feed.""" def __init__(self, service='health', feed='feeds/profile/list'): """Constructor for Health profile list feed query. Args: service: string (optional) The service to query. Either 'health' or 'h9'. feed: string (optional) The path for the feed. The default value is 'feeds/profile/list'. """ gdata.service.Query.__init__(self, feed) self.service = service 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 profile list feed. """ return '/%s' % ('/'.join([self.service, self.feed]),) class HealthRegisterQuery(gdata.service.Query): """Object used to construct a URI to query a Health register/notice feed.""" def __init__(self, service='health', feed='feeds/register', projection='default', profile_id=None): """Constructor for Health profile list feed query. Args: service: string (optional) The service to query. Either 'health' or 'h9'. feed: string (optional) The path for the feed. The default value is 'feeds/register'. projection: string (optional) The visibility of the data. Possible values are 'default' for AuthSub and 'ui' for ClientLogin. If this value is set to 'ui', the profile_id parameter should also be set. profile_id: string (optional) The profile id to query. This should only be used when using ClientLogin. """ gdata.service.Query.__init__(self, feed) self.service = service self.projection = projection self.profile_id = profile_id def ToUri(self): """Generates a URI from the query parameters set in the object. Returns: A string containing the URI needed to interact with the register feed. """ old_feed = self.feed self.feed = '/'.join([self.service, old_feed, self.projection]) new_feed = gdata.service.Query.ToUri(self) self.feed = old_feed if self.profile_id: new_feed += '/' + self.profile_id return '/%s' % (new_feed,)
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 Health.""" __author__ = 'api.eric@google.com (Eric Bidelman)' import atom import gdata CCR_NAMESPACE = 'urn:astm-org:CCR' METADATA_NAMESPACE = 'http://schemas.google.com/health/metadata' class Ccr(atom.AtomBase): """Represents a Google Health <ContinuityOfCareRecord>.""" _tag = 'ContinuityOfCareRecord' _namespace = CCR_NAMESPACE _children = atom.AtomBase._children.copy() def __init__(self, extension_elements=None, extension_attributes=None, text=None): atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def GetAlerts(self): """Helper for extracting Alert/Allergy data from the CCR. Returns: A list of ExtensionElements (one for each allergy found) or None if no allergies where found in this CCR. """ try: body = self.FindExtensions('Body')[0] return body.FindChildren('Alerts')[0].FindChildren('Alert') except: return None def GetAllergies(self): """Alias for GetAlerts().""" return self.GetAlerts() def GetProblems(self): """Helper for extracting Problem/Condition data from the CCR. Returns: A list of ExtensionElements (one for each problem found) or None if no problems where found in this CCR. """ try: body = self.FindExtensions('Body')[0] return body.FindChildren('Problems')[0].FindChildren('Problem') except: return None def GetConditions(self): """Alias for GetProblems().""" return self.GetProblems() def GetProcedures(self): """Helper for extracting Procedure data from the CCR. Returns: A list of ExtensionElements (one for each procedure found) or None if no procedures where found in this CCR. """ try: body = self.FindExtensions('Body')[0] return body.FindChildren('Procedures')[0].FindChildren('Procedure') except: return None def GetImmunizations(self): """Helper for extracting Immunization data from the CCR. Returns: A list of ExtensionElements (one for each immunization found) or None if no immunizations where found in this CCR. """ try: body = self.FindExtensions('Body')[0] return body.FindChildren('Immunizations')[0].FindChildren('Immunization') except: return None def GetMedications(self): """Helper for extracting Medication data from the CCR. Returns: A list of ExtensionElements (one for each medication found) or None if no medications where found in this CCR. """ try: body = self.FindExtensions('Body')[0] return body.FindChildren('Medications')[0].FindChildren('Medication') except: return None def GetResults(self): """Helper for extracting Results/Labresults data from the CCR. Returns: A list of ExtensionElements (one for each result found) or None if no results where found in this CCR. """ try: body = self.FindExtensions('Body')[0] return body.FindChildren('Results')[0].FindChildren('Result') except: return None class ProfileEntry(gdata.GDataEntry): """The Google Health 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}ContinuityOfCareRecord' % CCR_NAMESPACE] = ('ccr', Ccr) def __init__(self, ccr=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.ccr = ccr 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) class ProfileFeed(gdata.GDataFeed): """A feed containing a list of Google Health profile entries.""" _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', [ProfileEntry]) class ProfileListEntry(gdata.GDataEntry): """The Atom Entry in the Google Health profile list feed.""" _tag = gdata.GDataEntry._tag _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() def GetProfileId(self): return self.content.text def GetProfileName(self): return self.title.text class ProfileListFeed(gdata.GDataFeed): """A feed containing a list of Google Health profile list entries.""" _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', [ProfileListEntry]) def ProfileEntryFromString(xml_string): """Converts an XML string into a ProfileEntry object. Args: xml_string: string The XML describing a Health profile feed entry. Returns: A ProfileEntry object corresponding to the given XML. """ return atom.CreateClassFromXMLString(ProfileEntry, xml_string) def ProfileListEntryFromString(xml_string): """Converts an XML string into a ProfileListEntry object. Args: xml_string: string The XML describing a Health profile list feed entry. Returns: A ProfileListEntry object corresponding to the given XML. """ return atom.CreateClassFromXMLString(ProfileListEntry, xml_string) def ProfileFeedFromString(xml_string): """Converts an XML string into a ProfileFeed object. Args: xml_string: string The XML describing a ProfileFeed feed. Returns: A ProfileFeed object corresponding to the given XML. """ return atom.CreateClassFromXMLString(ProfileFeed, xml_string) def ProfileListFeedFromString(xml_string): """Converts an XML string into a ProfileListFeed object. Args: xml_string: string The XML describing a ProfileListFeed feed. Returns: A ProfileListFeed object corresponding to the given XML. """ return atom.CreateClassFromXMLString(ProfileListFeed, xml_string)
Python
"""This file implements the chaffing algorithm. Winnowing and chaffing is a technique for enhancing privacy without requiring strong encryption. In short, the technique takes a set of authenticated message blocks (the wheat) and adds a number of chaff blocks which have randomly chosen data and MAC fields. This means that to an adversary, the chaff blocks look as valid as the wheat blocks, and so the authentication would have to be performed on every block. By tailoring the number of chaff blocks added to the message, the sender can make breaking the message computationally infeasible. There are many other interesting properties of the winnow/chaff technique. For example, say Alice is sending a message to Bob. She packetizes the message and performs an all-or-nothing transformation on the packets. Then she authenticates each packet with a message authentication code (MAC). The MAC is a hash of the data packet, and there is a secret key which she must share with Bob (key distribution is an exercise left to the reader). She then adds a serial number to each packet, and sends the packets to Bob. Bob receives the packets, and using the shared secret authentication key, authenticates the MACs for each packet. Those packets that have bad MACs are simply discarded. The remainder are sorted by serial number, and passed through the reverse all-or-nothing transform. The transform means that an eavesdropper (say Eve) must acquire all the packets before any of the data can be read. If even one packet is missing, the data is useless. There's one twist: by adding chaff packets, Alice and Bob can make Eve's job much harder, since Eve now has to break the shared secret key, or try every combination of wheat and chaff packet to read any of the message. The cool thing is that Bob doesn't need to add any additional code; the chaff packets are already filtered out because their MACs don't match (in all likelihood -- since the data and MACs for the chaff packets are randomly chosen it is possible, but very unlikely that a chaff MAC will match the chaff data). And Alice need not even be the party adding the chaff! She could be completely unaware that a third party, say Charles, is adding chaff packets to her messages as they are transmitted. For more information on winnowing and chaffing see this paper: Ronald L. Rivest, "Chaffing and Winnowing: Confidentiality without Encryption" http://theory.lcs.mit.edu/~rivest/chaffing.txt """ __revision__ = "$Id: Chaffing.py,v 1.7 2003/02/28 15:23:21 akuchling Exp $" from Crypto.Util.number import bytes_to_long class Chaff: """Class implementing the chaff adding algorithm. Methods for subclasses: _randnum(size): Returns a randomly generated number with a byte-length equal to size. Subclasses can use this to implement better random data and MAC generating algorithms. The default algorithm is probably not very cryptographically secure. It is most important that the chaff data does not contain any patterns that can be used to discern it from wheat data without running the MAC. """ def __init__(self, factor=1.0, blocksper=1): """Chaff(factor:float, blocksper:int) factor is the number of message blocks to add chaff to, expressed as a percentage between 0.0 and 1.0. blocksper is the number of chaff blocks to include for each block being chaffed. Thus the defaults add one chaff block to every message block. By changing the defaults, you can adjust how computationally difficult it could be for an adversary to brute-force crack the message. The difficulty is expressed as: pow(blocksper, int(factor * number-of-blocks)) For ease of implementation, when factor < 1.0, only the first int(factor*number-of-blocks) message blocks are chaffed. """ if not (0.0<=factor<=1.0): raise ValueError, "'factor' must be between 0.0 and 1.0" if blocksper < 0: raise ValueError, "'blocksper' must be zero or more" self.__factor = factor self.__blocksper = blocksper def chaff(self, blocks): """chaff( [(serial-number:int, data:string, MAC:string)] ) : [(int, string, string)] Add chaff to message blocks. blocks is a list of 3-tuples of the form (serial-number, data, MAC). Chaff is created by choosing a random number of the same byte-length as data, and another random number of the same byte-length as MAC. The message block's serial number is placed on the chaff block and all the packet's chaff blocks are randomly interspersed with the single wheat block. This method then returns a list of 3-tuples of the same form. Chaffed blocks will contain multiple instances of 3-tuples with the same serial number, but the only way to figure out which blocks are wheat and which are chaff is to perform the MAC hash and compare values. """ chaffedblocks = [] # count is the number of blocks to add chaff to. blocksper is the # number of chaff blocks to add per message block that is being # chaffed. count = len(blocks) * self.__factor blocksper = range(self.__blocksper) for i, wheat in map(None, range(len(blocks)), blocks): # it shouldn't matter which of the n blocks we add chaff to, so for # ease of implementation, we'll just add them to the first count # blocks if i < count: serial, data, mac = wheat datasize = len(data) macsize = len(mac) addwheat = 1 # add chaff to this block for j in blocksper: import sys chaffdata = self._randnum(datasize) chaffmac = self._randnum(macsize) chaff = (serial, chaffdata, chaffmac) # mix up the order, if the 5th bit is on then put the # wheat on the list if addwheat and bytes_to_long(self._randnum(16)) & 0x40: chaffedblocks.append(wheat) addwheat = 0 chaffedblocks.append(chaff) if addwheat: chaffedblocks.append(wheat) else: # just add the wheat chaffedblocks.append(wheat) return chaffedblocks def _randnum(self, size): # TBD: Not a very secure algorithm. # TBD: size * 2 to work around possible bug in RandomPool from Crypto.Util import randpool import time pool = randpool.RandomPool(size * 2) while size > pool.entropy: pass # we now have enough entropy in the pool to get size bytes of random # data... well, probably return pool.get_bytes(size) if __name__ == '__main__': text = """\ We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty, and the pursuit of Happiness. That to secure these rights, Governments are instituted among Men, deriving their just powers from the consent of the governed. That whenever any Form of Government becomes destructive of these ends, it is the Right of the People to alter or to abolish it, and to institute new Government, laying its foundation on such principles and organizing its powers in such form, as to them shall seem most likely to effect their Safety and Happiness. """ print 'Original text:\n==========' print text print '==========' # first transform the text into packets blocks = [] ; size = 40 for i in range(0, len(text), size): blocks.append( text[i:i+size] ) # now get MACs for all the text blocks. The key is obvious... print 'Calculating MACs...' from Crypto.Hash import HMAC, SHA key = 'Jefferson' macs = [HMAC.new(key, block, digestmod=SHA).digest() for block in blocks] assert len(blocks) == len(macs) # put these into a form acceptable as input to the chaffing procedure source = [] m = map(None, range(len(blocks)), blocks, macs) print m for i, data, mac in m: source.append((i, data, mac)) # now chaff these print 'Adding chaff...' c = Chaff(factor=0.5, blocksper=2) chaffed = c.chaff(source) from base64 import encodestring # print the chaffed message blocks. meanwhile, separate the wheat from # the chaff wheat = [] print 'chaffed message blocks:' for i, data, mac in chaffed: # do the authentication h = HMAC.new(key, data, digestmod=SHA) pmac = h.digest() if pmac == mac: tag = '-->' wheat.append(data) else: tag = ' ' # base64 adds a trailing newline print tag, '%3d' % i, \ repr(data), encodestring(mac)[:-1] # now decode the message packets and check it against the original text print 'Undigesting wheat...' newtext = "".join(wheat) if newtext == text: print 'They match!' else: print 'They differ!'
Python
"""This file implements all-or-nothing package transformations. An all-or-nothing package transformation is one in which some text is transformed into message blocks, such that all blocks must be obtained before the reverse transformation can be applied. Thus, if any blocks are corrupted or lost, the original message cannot be reproduced. An all-or-nothing package transformation is not encryption, although a block cipher algorithm is used. The encryption key is randomly generated and is extractable from the message blocks. This class implements the All-Or-Nothing package transformation algorithm described in: Ronald L. Rivest. "All-Or-Nothing Encryption and The Package Transform" http://theory.lcs.mit.edu/~rivest/fusion.pdf """ __revision__ = "$Id: AllOrNothing.py,v 1.8 2003/02/28 15:23:20 akuchling Exp $" import operator import string from Crypto.Util.number import bytes_to_long, long_to_bytes class AllOrNothing: """Class implementing the All-or-Nothing package transform. Methods for subclassing: _inventkey(key_size): Returns a randomly generated key. Subclasses can use this to implement better random key generating algorithms. The default algorithm is probably not very cryptographically secure. """ def __init__(self, ciphermodule, mode=None, IV=None): """AllOrNothing(ciphermodule, mode=None, IV=None) ciphermodule is a module implementing the cipher algorithm to use. It must provide the PEP272 interface. Note that the encryption key is randomly generated automatically when needed. Optional arguments mode and IV are passed directly through to the ciphermodule.new() method; they are the feedback mode and initialization vector to use. All three arguments must be the same for the object used to create the digest, and to undigest'ify the message blocks. """ self.__ciphermodule = ciphermodule self.__mode = mode self.__IV = IV self.__key_size = ciphermodule.key_size if self.__key_size == 0: self.__key_size = 16 __K0digit = chr(0x69) def digest(self, text): """digest(text:string) : [string] Perform the All-or-Nothing package transform on the given string. Output is a list of message blocks describing the transformed text, where each block is a string of bit length equal to the ciphermodule's block_size. """ # generate a random session key and K0, the key used to encrypt the # hash blocks. Rivest calls this a fixed, publically-known encryption # key, but says nothing about the security implications of this key or # how to choose it. key = self._inventkey(self.__key_size) K0 = self.__K0digit * self.__key_size # we need two cipher objects here, one that is used to encrypt the # message blocks and one that is used to encrypt the hashes. The # former uses the randomly generated key, while the latter uses the # well-known key. mcipher = self.__newcipher(key) hcipher = self.__newcipher(K0) # Pad the text so that its length is a multiple of the cipher's # block_size. Pad with trailing spaces, which will be eliminated in # the undigest() step. block_size = self.__ciphermodule.block_size padbytes = block_size - (len(text) % block_size) text = text + ' ' * padbytes # Run through the algorithm: # s: number of message blocks (size of text / block_size) # input sequence: m1, m2, ... ms # random key K' (`key' in the code) # Compute output sequence: m'1, m'2, ... m's' for s' = s + 1 # Let m'i = mi ^ E(K', i) for i = 1, 2, 3, ..., s # Let m's' = K' ^ h1 ^ h2 ^ ... hs # where hi = E(K0, m'i ^ i) for i = 1, 2, ... s # # The one complication I add is that the last message block is hard # coded to the number of padbytes added, so that these can be stripped # during the undigest() step s = len(text) / block_size blocks = [] hashes = [] for i in range(1, s+1): start = (i-1) * block_size end = start + block_size mi = text[start:end] assert len(mi) == block_size cipherblock = mcipher.encrypt(long_to_bytes(i, block_size)) mticki = bytes_to_long(mi) ^ bytes_to_long(cipherblock) blocks.append(mticki) # calculate the hash block for this block hi = hcipher.encrypt(long_to_bytes(mticki ^ i, block_size)) hashes.append(bytes_to_long(hi)) # Add the padbytes length as a message block i = i + 1 cipherblock = mcipher.encrypt(long_to_bytes(i, block_size)) mticki = padbytes ^ bytes_to_long(cipherblock) blocks.append(mticki) # calculate this block's hash hi = hcipher.encrypt(long_to_bytes(mticki ^ i, block_size)) hashes.append(bytes_to_long(hi)) # Now calculate the last message block of the sequence 1..s'. This # will contain the random session key XOR'd with all the hash blocks, # so that for undigest(), once all the hash blocks are calculated, the # session key can be trivially extracted. Calculating all the hash # blocks requires that all the message blocks be received, thus the # All-or-Nothing algorithm succeeds. mtick_stick = bytes_to_long(key) ^ reduce(operator.xor, hashes) blocks.append(mtick_stick) # we convert the blocks to strings since in Python, byte sequences are # always represented as strings. This is more consistent with the # model that encryption and hash algorithms always operate on strings. return map(long_to_bytes, blocks) def undigest(self, blocks): """undigest(blocks : [string]) : string Perform the reverse package transformation on a list of message blocks. Note that the ciphermodule used for both transformations must be the same. blocks is a list of strings of bit length equal to the ciphermodule's block_size. """ # better have at least 2 blocks, for the padbytes package and the hash # block accumulator if len(blocks) < 2: raise ValueError, "List must be at least length 2." # blocks is a list of strings. We need to deal with them as long # integers blocks = map(bytes_to_long, blocks) # Calculate the well-known key, to which the hash blocks are # encrypted, and create the hash cipher. K0 = self.__K0digit * self.__key_size hcipher = self.__newcipher(K0) # Since we have all the blocks (or this method would have been called # prematurely), we can calcualte all the hash blocks. hashes = [] for i in range(1, len(blocks)): mticki = blocks[i-1] ^ i hi = hcipher.encrypt(long_to_bytes(mticki)) hashes.append(bytes_to_long(hi)) # now we can calculate K' (key). remember the last block contains # m's' which we don't include here key = blocks[-1] ^ reduce(operator.xor, hashes) # and now we can create the cipher object mcipher = self.__newcipher(long_to_bytes(key)) block_size = self.__ciphermodule.block_size # And we can now decode the original message blocks parts = [] for i in range(1, len(blocks)): cipherblock = mcipher.encrypt(long_to_bytes(i, block_size)) mi = blocks[i-1] ^ bytes_to_long(cipherblock) parts.append(mi) # The last message block contains the number of pad bytes appended to # the original text string, such that its length was an even multiple # of the cipher's block_size. This number should be small enough that # the conversion from long integer to integer should never overflow padbytes = int(parts[-1]) text = string.join(map(long_to_bytes, parts[:-1]), '') return text[:-padbytes] def _inventkey(self, key_size): # TBD: Not a very secure algorithm. Eventually, I'd like to use JHy's # kernelrand module import time from Crypto.Util import randpool # TBD: key_size * 2 to work around possible bug in RandomPool? pool = randpool.RandomPool(key_size * 2) while key_size > pool.entropy: pool.add_event() # we now have enough entropy in the pool to get a key_size'd key return pool.get_bytes(key_size) def __newcipher(self, key): if self.__mode is None and self.__IV is None: return self.__ciphermodule.new(key) elif self.__IV is None: return self.__ciphermodule.new(key, self.__mode) else: return self.__ciphermodule.new(key, self.__mode, self.__IV) if __name__ == '__main__': import sys import getopt import base64 usagemsg = '''\ Test module usage: %(program)s [-c cipher] [-l] [-h] Where: --cipher module -c module Cipher module to use. Default: %(ciphermodule)s --aslong -l Print the encoded message blocks as long integers instead of base64 encoded strings --help -h Print this help message ''' ciphermodule = 'AES' aslong = 0 def usage(code, msg=None): if msg: print msg print usagemsg % {'program': sys.argv[0], 'ciphermodule': ciphermodule} sys.exit(code) try: opts, args = getopt.getopt(sys.argv[1:], 'c:l', ['cipher=', 'aslong']) except getopt.error, msg: usage(1, msg) if args: usage(1, 'Too many arguments') for opt, arg in opts: if opt in ('-h', '--help'): usage(0) elif opt in ('-c', '--cipher'): ciphermodule = arg elif opt in ('-l', '--aslong'): aslong = 1 # ugly hack to force __import__ to give us the end-path module module = __import__('Crypto.Cipher.'+ciphermodule, None, None, ['new']) a = AllOrNothing(module) print 'Original text:\n==========' print __doc__ print '==========' msgblocks = a.digest(__doc__) print 'message blocks:' for i, blk in map(None, range(len(msgblocks)), msgblocks): # base64 adds a trailing newline print ' %3d' % i, if aslong: print bytes_to_long(blk) else: print base64.encodestring(blk)[:-1] # # get a new undigest-only object so there's no leakage b = AllOrNothing(module) text = b.undigest(msgblocks) if text == __doc__: print 'They match!' else: print 'They differ!'
Python
"""Cryptographic protocols Implements various cryptographic protocols. (Don't expect to find network protocols here.) Crypto.Protocol.AllOrNothing Transforms a message into a set of message blocks, such that the blocks can be recombined to get the message back. Crypto.Protocol.Chaffing Takes a set of authenticated message blocks (the wheat) and adds a number of randomly generated blocks (the chaff). """ __all__ = ['AllOrNothing', 'Chaffing'] __revision__ = "$Id: __init__.py,v 1.4 2003/02/28 15:23:21 akuchling Exp $"
Python
# # DSA.py : Digital Signature Algorithm # # Part of the Python Cryptography Toolkit # # Distribute and use freely; there are no restrictions on further # dissemination and usage except those imposed by the laws of your # country of residence. This software is provided "as is" without # warranty of fitness for use or suitability for any purpose, express # or implied. Use at your own risk or not at all. # __revision__ = "$Id: DSA.py,v 1.16 2004/05/06 12:52:54 akuchling Exp $" from Crypto.PublicKey.pubkey import * from Crypto.Util import number from Crypto.Util.number import bytes_to_long, long_to_bytes from Crypto.Hash import SHA try: from Crypto.PublicKey import _fastmath except ImportError: _fastmath = None class error (Exception): pass def generateQ(randfunc): S=randfunc(20) hash1=SHA.new(S).digest() hash2=SHA.new(long_to_bytes(bytes_to_long(S)+1)).digest() q = bignum(0) for i in range(0,20): c=ord(hash1[i])^ord(hash2[i]) if i==0: c=c | 128 if i==19: c= c | 1 q=q*256+c while (not isPrime(q)): q=q+2 if pow(2,159L) < q < pow(2,160L): return S, q raise error, 'Bad q value generated' def generate(bits, randfunc, progress_func=None): """generate(bits:int, randfunc:callable, progress_func:callable) Generate a DSA key of length 'bits', using 'randfunc' to get random data and 'progress_func', if present, to display the progress of the key generation. """ if bits<160: raise error, 'Key length <160 bits' obj=DSAobj() # Generate string S and prime q if progress_func: progress_func('p,q\n') while (1): S, obj.q = generateQ(randfunc) n=(bits-1)/160 C, N, V = 0, 2, {} b=(obj.q >> 5) & 15 powb=pow(bignum(2), b) powL1=pow(bignum(2), bits-1) while C<4096: for k in range(0, n+1): V[k]=bytes_to_long(SHA.new(S+str(N)+str(k)).digest()) W=V[n] % powb for k in range(n-1, -1, -1): W=(W<<160L)+V[k] X=W+powL1 p=X-(X%(2*obj.q)-1) if powL1<=p and isPrime(p): break C, N = C+1, N+n+1 if C<4096: break if progress_func: progress_func('4096 multiples failed\n') obj.p = p power=(p-1)/obj.q if progress_func: progress_func('h,g\n') while (1): h=bytes_to_long(randfunc(bits)) % (p-1) g=pow(h, power, p) if 1<h<p-1 and g>1: break obj.g=g if progress_func: progress_func('x,y\n') while (1): x=bytes_to_long(randfunc(20)) if 0 < x < obj.q: break obj.x, obj.y = x, pow(g, x, p) return obj def construct(tuple): """construct(tuple:(long,long,long,long)|(long,long,long,long,long)):DSAobj Construct a DSA object from a 4- or 5-tuple of numbers. """ obj=DSAobj() if len(tuple) not in [4,5]: raise error, 'argument for construct() wrong length' for i in range(len(tuple)): field = obj.keydata[i] setattr(obj, field, tuple[i]) return obj class DSAobj(pubkey): keydata=['y', 'g', 'p', 'q', 'x'] def _encrypt(self, s, Kstr): raise error, 'DSA algorithm cannot encrypt data' def _decrypt(self, s): raise error, 'DSA algorithm cannot decrypt data' def _sign(self, M, K): if (K<2 or self.q<=K): raise error, 'K is not between 2 and q' r=pow(self.g, K, self.p) % self.q s=(inverse(K, self.q)*(M+self.x*r)) % self.q return (r,s) def _verify(self, M, sig): r, s = sig if r<=0 or r>=self.q or s<=0 or s>=self.q: return 0 w=inverse(s, self.q) u1, u2 = (M*w) % self.q, (r*w) % self.q v1 = pow(self.g, u1, self.p) v2 = pow(self.y, u2, self.p) v = ((v1*v2) % self.p) v = v % self.q if v==r: return 1 return 0 def size(self): "Return the maximum number of bits that can be handled by this key." return number.size(self.p) - 1 def has_private(self): """Return a Boolean denoting whether the object contains private components.""" if hasattr(self, 'x'): return 1 else: return 0 def can_sign(self): """Return a Boolean value recording whether this algorithm can generate signatures.""" return 1 def can_encrypt(self): """Return a Boolean value recording whether this algorithm can encrypt data.""" return 0 def publickey(self): """Return a new key object containing only the public information.""" return construct((self.y, self.g, self.p, self.q)) object=DSAobj generate_py = generate construct_py = construct class DSAobj_c(pubkey): keydata = ['y', 'g', 'p', 'q', 'x'] def __init__(self, key): self.key = key def __getattr__(self, attr): if attr in self.keydata: return getattr(self.key, attr) else: if self.__dict__.has_key(attr): self.__dict__[attr] else: raise AttributeError, '%s instance has no attribute %s' % (self.__class__, attr) def __getstate__(self): d = {} for k in self.keydata: if hasattr(self.key, k): d[k]=getattr(self.key, k) return d def __setstate__(self, state): y,g,p,q = state['y'], state['g'], state['p'], state['q'] if not state.has_key('x'): self.key = _fastmath.dsa_construct(y,g,p,q) else: x = state['x'] self.key = _fastmath.dsa_construct(y,g,p,q,x) def _sign(self, M, K): return self.key._sign(M, K) def _verify(self, M, (r, s)): return self.key._verify(M, r, s) def size(self): return self.key.size() def has_private(self): return self.key.has_private() def publickey(self): return construct_c((self.key.y, self.key.g, self.key.p, self.key.q)) def can_sign(self): return 1 def can_encrypt(self): return 0 def generate_c(bits, randfunc, progress_func=None): obj = generate_py(bits, randfunc, progress_func) y,g,p,q,x = obj.y, obj.g, obj.p, obj.q, obj.x return construct_c((y,g,p,q,x)) def construct_c(tuple): key = apply(_fastmath.dsa_construct, tuple) return DSAobj_c(key) if _fastmath: #print "using C version of DSA" generate = generate_c construct = construct_c error = _fastmath.error
Python
# # pubkey.py : Internal functions for public key operations # # Part of the Python Cryptography Toolkit # # Distribute and use freely; there are no restrictions on further # dissemination and usage except those imposed by the laws of your # country of residence. This software is provided "as is" without # warranty of fitness for use or suitability for any purpose, express # or implied. Use at your own risk or not at all. # __revision__ = "$Id: pubkey.py,v 1.11 2003/04/03 20:36:14 akuchling Exp $" import types, warnings from Crypto.Util.number import * # Basic public key class class pubkey: def __init__(self): pass def __getstate__(self): """To keep key objects platform-independent, the key data is converted to standard Python long integers before being written out. It will then be reconverted as necessary on restoration.""" d=self.__dict__ for key in self.keydata: if d.has_key(key): d[key]=long(d[key]) return d def __setstate__(self, d): """On unpickling a key object, the key data is converted to the big number representation being used, whether that is Python long integers, MPZ objects, or whatever.""" for key in self.keydata: if d.has_key(key): self.__dict__[key]=bignum(d[key]) def encrypt(self, plaintext, K): """encrypt(plaintext:string|long, K:string|long) : tuple Encrypt the string or integer plaintext. K is a random parameter required by some algorithms. """ wasString=0 if isinstance(plaintext, types.StringType): plaintext=bytes_to_long(plaintext) ; wasString=1 if isinstance(K, types.StringType): K=bytes_to_long(K) ciphertext=self._encrypt(plaintext, K) if wasString: return tuple(map(long_to_bytes, ciphertext)) else: return ciphertext def decrypt(self, ciphertext): """decrypt(ciphertext:tuple|string|long): string Decrypt 'ciphertext' using this key. """ wasString=0 if not isinstance(ciphertext, types.TupleType): ciphertext=(ciphertext,) if isinstance(ciphertext[0], types.StringType): ciphertext=tuple(map(bytes_to_long, ciphertext)) ; wasString=1 plaintext=self._decrypt(ciphertext) if wasString: return long_to_bytes(plaintext) else: return plaintext def sign(self, M, K): """sign(M : string|long, K:string|long) : tuple Return a tuple containing the signature for the message M. K is a random parameter required by some algorithms. """ if (not self.has_private()): raise error, 'Private key not available in this object' if isinstance(M, types.StringType): M=bytes_to_long(M) if isinstance(K, types.StringType): K=bytes_to_long(K) return self._sign(M, K) def verify (self, M, signature): """verify(M:string|long, signature:tuple) : bool Verify that the signature is valid for the message M; returns true if the signature checks out. """ if isinstance(M, types.StringType): M=bytes_to_long(M) return self._verify(M, signature) # alias to compensate for the old validate() name def validate (self, M, signature): warnings.warn("validate() method name is obsolete; use verify()", DeprecationWarning) def blind(self, M, B): """blind(M : string|long, B : string|long) : string|long Blind message M using blinding factor B. """ wasString=0 if isinstance(M, types.StringType): M=bytes_to_long(M) ; wasString=1 if isinstance(B, types.StringType): B=bytes_to_long(B) blindedmessage=self._blind(M, B) if wasString: return long_to_bytes(blindedmessage) else: return blindedmessage def unblind(self, M, B): """unblind(M : string|long, B : string|long) : string|long Unblind message M using blinding factor B. """ wasString=0 if isinstance(M, types.StringType): M=bytes_to_long(M) ; wasString=1 if isinstance(B, types.StringType): B=bytes_to_long(B) unblindedmessage=self._unblind(M, B) if wasString: return long_to_bytes(unblindedmessage) else: return unblindedmessage # The following methods will usually be left alone, except for # signature-only algorithms. They both return Boolean values # recording whether this key's algorithm can sign and encrypt. def can_sign (self): """can_sign() : bool Return a Boolean value recording whether this algorithm can generate signatures. (This does not imply that this particular key object has the private information required to to generate a signature.) """ return 1 def can_encrypt (self): """can_encrypt() : bool Return a Boolean value recording whether this algorithm can encrypt data. (This does not imply that this particular key object has the private information required to to decrypt a message.) """ return 1 def can_blind (self): """can_blind() : bool Return a Boolean value recording whether this algorithm can blind data. (This does not imply that this particular key object has the private information required to to blind a message.) """ return 0 # The following methods will certainly be overridden by # subclasses. def size (self): """size() : int Return the maximum number of bits that can be handled by this key. """ return 0 def has_private (self): """has_private() : bool Return a Boolean denoting whether the object contains private components. """ return 0 def publickey (self): """publickey(): object Return a new key object containing only the public information. """ return self def __eq__ (self, other): """__eq__(other): 0, 1 Compare us to other for equality. """ return self.__getstate__() == other.__getstate__()
Python
# # qNEW.py : The q-NEW signature algorithm. # # Part of the Python Cryptography Toolkit # # Distribute and use freely; there are no restrictions on further # dissemination and usage except those imposed by the laws of your # country of residence. This software is provided "as is" without # warranty of fitness for use or suitability for any purpose, express # or implied. Use at your own risk or not at all. # __revision__ = "$Id: qNEW.py,v 1.8 2003/04/04 15:13:35 akuchling Exp $" from Crypto.PublicKey import pubkey from Crypto.Util.number import * from Crypto.Hash import SHA class error (Exception): pass HASHBITS = 160 # Size of SHA digests def generate(bits, randfunc, progress_func=None): """generate(bits:int, randfunc:callable, progress_func:callable) Generate a qNEW key of length 'bits', using 'randfunc' to get random data and 'progress_func', if present, to display the progress of the key generation. """ obj=qNEWobj() # Generate prime numbers p and q. q is a 160-bit prime # number. p is another prime number (the modulus) whose bit # size is chosen by the caller, and is generated so that p-1 # is a multiple of q. # # Note that only a single seed is used to # generate p and q; if someone generates a key for you, you can # use the seed to duplicate the key generation. This can # protect you from someone generating values of p,q that have # some special form that's easy to break. if progress_func: progress_func('p,q\n') while (1): obj.q = getPrime(160, randfunc) # assert pow(2, 159L)<obj.q<pow(2, 160L) obj.seed = S = long_to_bytes(obj.q) C, N, V = 0, 2, {} # Compute b and n such that bits-1 = b + n*HASHBITS n= (bits-1) / HASHBITS b= (bits-1) % HASHBITS ; powb=2L << b powL1=pow(long(2), bits-1) while C<4096: # The V array will contain (bits-1) bits of random # data, that are assembled to produce a candidate # value for p. for k in range(0, n+1): V[k]=bytes_to_long(SHA.new(S+str(N)+str(k)).digest()) p = V[n] % powb for k in range(n-1, -1, -1): p= (p << long(HASHBITS) )+V[k] p = p+powL1 # Ensure the high bit is set # Ensure that p-1 is a multiple of q p = p - (p % (2*obj.q)-1) # If p is still the right size, and it's prime, we're done! if powL1<=p and isPrime(p): break # Otherwise, increment the counter and try again C, N = C+1, N+n+1 if C<4096: break # Ended early, so exit the while loop if progress_func: progress_func('4096 values of p tried\n') obj.p = p power=(p-1)/obj.q # Next parameter: g = h**((p-1)/q) mod p, such that h is any # number <p-1, and g>1. g is kept; h can be discarded. if progress_func: progress_func('h,g\n') while (1): h=bytes_to_long(randfunc(bits)) % (p-1) g=pow(h, power, p) if 1<h<p-1 and g>1: break obj.g=g # x is the private key information, and is # just a random number between 0 and q. # y=g**x mod p, and is part of the public information. if progress_func: progress_func('x,y\n') while (1): x=bytes_to_long(randfunc(20)) if 0 < x < obj.q: break obj.x, obj.y=x, pow(g, x, p) return obj # Construct a qNEW object def construct(tuple): """construct(tuple:(long,long,long,long)|(long,long,long,long,long) Construct a qNEW object from a 4- or 5-tuple of numbers. """ obj=qNEWobj() if len(tuple) not in [4,5]: raise error, 'argument for construct() wrong length' for i in range(len(tuple)): field = obj.keydata[i] setattr(obj, field, tuple[i]) return obj class qNEWobj(pubkey.pubkey): keydata=['p', 'q', 'g', 'y', 'x'] def _sign(self, M, K=''): if (self.q<=K): raise error, 'K is greater than q' if M<0: raise error, 'Illegal value of M (<0)' if M>=pow(2,161L): raise error, 'Illegal value of M (too large)' r=pow(self.g, K, self.p) % self.q s=(K- (r*M*self.x % self.q)) % self.q return (r,s) def _verify(self, M, sig): r, s = sig if r<=0 or r>=self.q or s<=0 or s>=self.q: return 0 if M<0: raise error, 'Illegal value of M (<0)' if M<=0 or M>=pow(2,161L): return 0 v1 = pow(self.g, s, self.p) v2 = pow(self.y, M*r, self.p) v = ((v1*v2) % self.p) v = v % self.q if v==r: return 1 return 0 def size(self): "Return the maximum number of bits that can be handled by this key." return 160 def has_private(self): """Return a Boolean denoting whether the object contains private components.""" return hasattr(self, 'x') def can_sign(self): """Return a Boolean value recording whether this algorithm can generate signatures.""" return 1 def can_encrypt(self): """Return a Boolean value recording whether this algorithm can encrypt data.""" return 0 def publickey(self): """Return a new key object containing only the public information.""" return construct((self.p, self.q, self.g, self.y)) object = qNEWobj
Python
# # RSA.py : RSA encryption/decryption # # Part of the Python Cryptography Toolkit # # Distribute and use freely; there are no restrictions on further # dissemination and usage except those imposed by the laws of your # country of residence. This software is provided "as is" without # warranty of fitness for use or suitability for any purpose, express # or implied. Use at your own risk or not at all. # __revision__ = "$Id: RSA.py,v 1.20 2004/05/06 12:52:54 akuchling Exp $" from Crypto.PublicKey import pubkey from Crypto.Util import number try: from Crypto.PublicKey import _fastmath except ImportError: _fastmath = None class error (Exception): pass def generate(bits, randfunc, progress_func=None): """generate(bits:int, randfunc:callable, progress_func:callable) Generate an RSA key of length 'bits', using 'randfunc' to get random data and 'progress_func', if present, to display the progress of the key generation. """ obj=RSAobj() # Generate the prime factors of n if progress_func: progress_func('p,q\n') p = q = 1L while number.size(p*q) < bits: p = pubkey.getPrime(bits/2, randfunc) q = pubkey.getPrime(bits/2, randfunc) # p shall be smaller than q (for calc of u) if p > q: (p, q)=(q, p) obj.p = p obj.q = q if progress_func: progress_func('u\n') obj.u = pubkey.inverse(obj.p, obj.q) obj.n = obj.p*obj.q obj.e = 65537L if progress_func: progress_func('d\n') obj.d=pubkey.inverse(obj.e, (obj.p-1)*(obj.q-1)) assert bits <= 1+obj.size(), "Generated key is too small" return obj def construct(tuple): """construct(tuple:(long,) : RSAobj Construct an RSA object from a 2-, 3-, 5-, or 6-tuple of numbers. """ obj=RSAobj() if len(tuple) not in [2,3,5,6]: raise error, 'argument for construct() wrong length' for i in range(len(tuple)): field = obj.keydata[i] setattr(obj, field, tuple[i]) if len(tuple) >= 5: # Ensure p is smaller than q if obj.p>obj.q: (obj.p, obj.q)=(obj.q, obj.p) if len(tuple) == 5: # u not supplied, so we're going to have to compute it. obj.u=pubkey.inverse(obj.p, obj.q) return obj class RSAobj(pubkey.pubkey): keydata = ['n', 'e', 'd', 'p', 'q', 'u'] def _encrypt(self, plaintext, K=''): if self.n<=plaintext: raise error, 'Plaintext too large' return (pow(plaintext, self.e, self.n),) def _decrypt(self, ciphertext): if (not hasattr(self, 'd')): raise error, 'Private key not available in this object' if self.n<=ciphertext[0]: raise error, 'Ciphertext too large' return pow(ciphertext[0], self.d, self.n) def _sign(self, M, K=''): return (self._decrypt((M,)),) def _verify(self, M, sig): m2=self._encrypt(sig[0]) if m2[0]==M: return 1 else: return 0 def _blind(self, M, B): tmp = pow(B, self.e, self.n) return (M * tmp) % self.n def _unblind(self, M, B): tmp = pubkey.inverse(B, self.n) return (M * tmp) % self.n def can_blind (self): """can_blind() : bool Return a Boolean value recording whether this algorithm can blind data. (This does not imply that this particular key object has the private information required to to blind a message.) """ return 1 def size(self): """size() : int Return the maximum number of bits that can be handled by this key. """ return number.size(self.n) - 1 def has_private(self): """has_private() : bool Return a Boolean denoting whether the object contains private components. """ if hasattr(self, 'd'): return 1 else: return 0 def publickey(self): """publickey(): RSAobj Return a new key object containing only the public key information. """ return construct((self.n, self.e)) class RSAobj_c(pubkey.pubkey): keydata = ['n', 'e', 'd', 'p', 'q', 'u'] def __init__(self, key): self.key = key def __getattr__(self, attr): if attr in self.keydata: return getattr(self.key, attr) else: if self.__dict__.has_key(attr): self.__dict__[attr] else: raise AttributeError, '%s instance has no attribute %s' % (self.__class__, attr) def __getstate__(self): d = {} for k in self.keydata: if hasattr(self.key, k): d[k]=getattr(self.key, k) return d def __setstate__(self, state): n,e = state['n'], state['e'] if not state.has_key('d'): self.key = _fastmath.rsa_construct(n,e) else: d = state['d'] if not state.has_key('q'): self.key = _fastmath.rsa_construct(n,e,d) else: p, q, u = state['p'], state['q'], state['u'] self.key = _fastmath.rsa_construct(n,e,d,p,q,u) def _encrypt(self, plain, K): return (self.key._encrypt(plain),) def _decrypt(self, cipher): return self.key._decrypt(cipher[0]) def _sign(self, M, K): return (self.key._sign(M),) def _verify(self, M, sig): return self.key._verify(M, sig[0]) def _blind(self, M, B): return self.key._blind(M, B) def _unblind(self, M, B): return self.key._unblind(M, B) def can_blind (self): return 1 def size(self): return self.key.size() def has_private(self): return self.key.has_private() def publickey(self): return construct_c((self.key.n, self.key.e)) def generate_c(bits, randfunc, progress_func = None): # Generate the prime factors of n if progress_func: progress_func('p,q\n') p = q = 1L while number.size(p*q) < bits: p = pubkey.getPrime(bits/2, randfunc) q = pubkey.getPrime(bits/2, randfunc) # p shall be smaller than q (for calc of u) if p > q: (p, q)=(q, p) if progress_func: progress_func('u\n') u=pubkey.inverse(p, q) n=p*q e = 65537L if progress_func: progress_func('d\n') d=pubkey.inverse(e, (p-1)*(q-1)) key = _fastmath.rsa_construct(n,e,d,p,q,u) obj = RSAobj_c(key) ## print p ## print q ## print number.size(p), number.size(q), number.size(q*p), ## print obj.size(), bits assert bits <= 1+obj.size(), "Generated key is too small" return obj def construct_c(tuple): key = apply(_fastmath.rsa_construct, tuple) return RSAobj_c(key) object = RSAobj generate_py = generate construct_py = construct if _fastmath: #print "using C version of RSA" generate = generate_c construct = construct_c error = _fastmath.error
Python
# # ElGamal.py : ElGamal encryption/decryption and signatures # # Part of the Python Cryptography Toolkit # # Distribute and use freely; there are no restrictions on further # dissemination and usage except those imposed by the laws of your # country of residence. This software is provided "as is" without # warranty of fitness for use or suitability for any purpose, express # or implied. Use at your own risk or not at all. # __revision__ = "$Id: ElGamal.py,v 1.9 2003/04/04 19:44:26 akuchling Exp $" from Crypto.PublicKey.pubkey import * from Crypto.Util import number class error (Exception): pass # Generate an ElGamal key with N bits def generate(bits, randfunc, progress_func=None): """generate(bits:int, randfunc:callable, progress_func:callable) Generate an ElGamal key of length 'bits', using 'randfunc' to get random data and 'progress_func', if present, to display the progress of the key generation. """ obj=ElGamalobj() # Generate prime p if progress_func: progress_func('p\n') obj.p=bignum(getPrime(bits, randfunc)) # Generate random number g if progress_func: progress_func('g\n') size=bits-1-(ord(randfunc(1)) & 63) # g will be from 1--64 bits smaller than p if size<1: size=bits-1 while (1): obj.g=bignum(getPrime(size, randfunc)) if obj.g < obj.p: break size=(size+1) % bits if size==0: size=4 # Generate random number x if progress_func: progress_func('x\n') while (1): size=bits-1-ord(randfunc(1)) # x will be from 1 to 256 bits smaller than p if size>2: break while (1): obj.x=bignum(getPrime(size, randfunc)) if obj.x < obj.p: break size = (size+1) % bits if size==0: size=4 if progress_func: progress_func('y\n') obj.y = pow(obj.g, obj.x, obj.p) return obj def construct(tuple): """construct(tuple:(long,long,long,long)|(long,long,long,long,long))) : ElGamalobj Construct an ElGamal key from a 3- or 4-tuple of numbers. """ obj=ElGamalobj() if len(tuple) not in [3,4]: raise error, 'argument for construct() wrong length' for i in range(len(tuple)): field = obj.keydata[i] setattr(obj, field, tuple[i]) return obj class ElGamalobj(pubkey): keydata=['p', 'g', 'y', 'x'] def _encrypt(self, M, K): a=pow(self.g, K, self.p) b=( M*pow(self.y, K, self.p) ) % self.p return ( a,b ) def _decrypt(self, M): if (not hasattr(self, 'x')): raise error, 'Private key not available in this object' ax=pow(M[0], self.x, self.p) plaintext=(M[1] * inverse(ax, self.p ) ) % self.p return plaintext def _sign(self, M, K): if (not hasattr(self, 'x')): raise error, 'Private key not available in this object' p1=self.p-1 if (GCD(K, p1)!=1): raise error, 'Bad K value: GCD(K,p-1)!=1' a=pow(self.g, K, self.p) t=(M-self.x*a) % p1 while t<0: t=t+p1 b=(t*inverse(K, p1)) % p1 return (a, b) def _verify(self, M, sig): v1=pow(self.y, sig[0], self.p) v1=(v1*pow(sig[0], sig[1], self.p)) % self.p v2=pow(self.g, M, self.p) if v1==v2: return 1 return 0 def size(self): "Return the maximum number of bits that can be handled by this key." return number.size(self.p) - 1 def has_private(self): """Return a Boolean denoting whether the object contains private components.""" if hasattr(self, 'x'): return 1 else: return 0 def publickey(self): """Return a new key object containing only the public information.""" return construct((self.p, self.g, self.y)) object=ElGamalobj
Python
"""Public-key encryption and signature algorithms. Public-key encryption uses two different keys, one for encryption and one for decryption. The encryption key can be made public, and the decryption key is kept private. Many public-key algorithms can also be used to sign messages, and some can *only* be used for signatures. Crypto.PublicKey.DSA Digital Signature Algorithm. (Signature only) Crypto.PublicKey.ElGamal (Signing and encryption) Crypto.PublicKey.RSA (Signing, encryption, and blinding) Crypto.PublicKey.qNEW (Signature only) """ __all__ = ['RSA', 'DSA', 'ElGamal', 'qNEW'] __revision__ = "$Id: __init__.py,v 1.4 2003/04/03 20:27:13 akuchling Exp $"
Python
# # Test script for the Python Cryptography Toolkit. # __revision__ = "$Id: test.py,v 1.7 2002/07/11 14:31:19 akuchling Exp $" import os, sys # Add the build directory to the front of sys.path from distutils.util import get_platform s = "build/lib.%s-%.3s" % (get_platform(), sys.version) s = os.path.join(os.getcwd(), s) sys.path.insert(0, s) s = os.path.join(os.getcwd(), 'test') sys.path.insert(0, s) from Crypto.Util import test args = sys.argv[1:] quiet = "--quiet" in args if quiet: args.remove('--quiet') if not quiet: print '\nStream Ciphers:' print '===============' if args: test.TestStreamModules(args, verbose= not quiet) else: test.TestStreamModules(verbose= not quiet) if not quiet: print '\nBlock Ciphers:' print '==============' if args: test.TestBlockModules(args, verbose= not quiet) else: test.TestBlockModules(verbose= not quiet)
Python
# # randpool.py : Cryptographically strong random number generation # # Part of the Python Cryptography Toolkit # # Distribute and use freely; there are no restrictions on further # dissemination and usage except those imposed by the laws of your # country of residence. This software is provided "as is" without # warranty of fitness for use or suitability for any purpose, express # or implied. Use at your own risk or not at all. # __revision__ = "$Id: randpool.py,v 1.14 2004/05/06 12:56:54 akuchling Exp $" import time, array, types, warnings, os.path from Crypto.Util.number import long_to_bytes try: import Crypto.Util.winrandom as winrandom except: winrandom = None STIRNUM = 3 class RandomPool: """randpool.py : Cryptographically strong random number generation. The implementation here is similar to the one in PGP. To be cryptographically strong, it must be difficult to determine the RNG's output, whether in the future or the past. This is done by using a cryptographic hash function to "stir" the random data. Entropy is gathered in the same fashion as PGP; the highest-resolution clock around is read and the data is added to the random number pool. A conservative estimate of the entropy is then kept. If a cryptographically secure random source is available (/dev/urandom on many Unixes, Windows CryptGenRandom on most Windows), then use it. Instance Attributes: bits : int Maximum size of pool in bits bytes : int Maximum size of pool in bytes entropy : int Number of bits of entropy in this pool. Methods: add_event([s]) : add some entropy to the pool get_bytes(int) : get N bytes of random data randomize([N]) : get N bytes of randomness from external source """ def __init__(self, numbytes = 160, cipher=None, hash=None): if hash is None: from Crypto.Hash import SHA as hash # The cipher argument is vestigial; it was removed from # version 1.1 so RandomPool would work even in the limited # exportable subset of the code if cipher is not None: warnings.warn("'cipher' parameter is no longer used") if isinstance(hash, types.StringType): # ugly hack to force __import__ to give us the end-path module hash = __import__('Crypto.Hash.'+hash, None, None, ['new']) warnings.warn("'hash' parameter should now be a hashing module") self.bytes = numbytes self.bits = self.bytes*8 self.entropy = 0 self._hash = hash # Construct an array to hold the random pool, # initializing it to 0. self._randpool = array.array('B', [0]*self.bytes) self._event1 = self._event2 = 0 self._addPos = 0 self._getPos = hash.digest_size self._lastcounter=time.time() self.__counter = 0 self._measureTickSize() # Estimate timer resolution self._randomize() def _updateEntropyEstimate(self, nbits): self.entropy += nbits if self.entropy < 0: self.entropy = 0 elif self.entropy > self.bits: self.entropy = self.bits def _randomize(self, N = 0, devname = '/dev/urandom'): """_randomize(N, DEVNAME:device-filepath) collects N bits of randomness from some entropy source (e.g., /dev/urandom on Unixes that have it, Windows CryptoAPI CryptGenRandom, etc) DEVNAME is optional, defaults to /dev/urandom. You can change it to /dev/random if you want to block till you get enough entropy. """ data = '' if N <= 0: nbytes = int((self.bits - self.entropy)/8+0.5) else: nbytes = int(N/8+0.5) if winrandom: # Windows CryptGenRandom provides random data. data = winrandom.new().get_bytes(nbytes) elif os.path.exists(devname): # Many OSes support a /dev/urandom device try: f=open(devname) data=f.read(nbytes) f.close() except IOError, (num, msg): if num!=2: raise IOError, (num, msg) # If the file wasn't found, ignore the error if data: self._addBytes(data) # Entropy estimate: The number of bits of # data obtained from the random source. self._updateEntropyEstimate(8*len(data)) self.stir_n() # Wash the random pool def randomize(self, N=0): """randomize(N:int) use the class entropy source to get some entropy data. This is overridden by KeyboardRandomize(). """ return self._randomize(N) def stir_n(self, N = STIRNUM): """stir_n(N) stirs the random pool N times """ for i in xrange(N): self.stir() def stir (self, s = ''): """stir(s:string) Mix up the randomness pool. This will call add_event() twice, but out of paranoia the entropy attribute will not be increased. The optional 's' parameter is a string that will be hashed with the randomness pool. """ entropy=self.entropy # Save inital entropy value self.add_event() # Loop over the randomness pool: hash its contents # along with a counter, and add the resulting digest # back into the pool. for i in range(self.bytes / self._hash.digest_size): h = self._hash.new(self._randpool) h.update(str(self.__counter) + str(i) + str(self._addPos) + s) self._addBytes( h.digest() ) self.__counter = (self.__counter + 1) & 0xFFFFffffL self._addPos, self._getPos = 0, self._hash.digest_size self.add_event() # Restore the old value of the entropy. self.entropy=entropy def get_bytes (self, N): """get_bytes(N:int) : string Return N bytes of random data. """ s='' i, pool = self._getPos, self._randpool h=self._hash.new() dsize = self._hash.digest_size num = N while num > 0: h.update( self._randpool[i:i+dsize] ) s = s + h.digest() num = num - dsize i = (i + dsize) % self.bytes if i<dsize: self.stir() i=self._getPos self._getPos = i self._updateEntropyEstimate(- 8*N) return s[:N] def add_event(self, s=''): """add_event(s:string) Add an event to the random pool. The current time is stored between calls and used to estimate the entropy. The optional 's' parameter is a string that will also be XORed into the pool. Returns the estimated number of additional bits of entropy gain. """ event = time.time()*1000 delta = self._noise() s = (s + long_to_bytes(event) + 4*chr(0xaa) + long_to_bytes(delta) ) self._addBytes(s) if event==self._event1 and event==self._event2: # If events are coming too closely together, assume there's # no effective entropy being added. bits=0 else: # Count the number of bits in delta, and assume that's the entropy. bits=0 while delta: delta, bits = delta>>1, bits+1 if bits>8: bits=8 self._event1, self._event2 = event, self._event1 self._updateEntropyEstimate(bits) return bits # Private functions def _noise(self): # Adds a bit of noise to the random pool, by adding in the # current time and CPU usage of this process. # The difference from the previous call to _noise() is taken # in an effort to estimate the entropy. t=time.time() delta = (t - self._lastcounter)/self._ticksize*1e6 self._lastcounter = t self._addBytes(long_to_bytes(long(1000*time.time()))) self._addBytes(long_to_bytes(long(1000*time.clock()))) self._addBytes(long_to_bytes(long(1000*time.time()))) self._addBytes(long_to_bytes(long(delta))) # Reduce delta to a maximum of 8 bits so we don't add too much # entropy as a result of this call. delta=delta % 0xff return int(delta) def _measureTickSize(self): # _measureTickSize() tries to estimate a rough average of the # resolution of time that you can see from Python. It does # this by measuring the time 100 times, computing the delay # between measurements, and taking the median of the resulting # list. (We also hash all the times and add them to the pool) interval = [None] * 100 h = self._hash.new(`(id(self),id(interval))`) # Compute 100 differences t=time.time() h.update(`t`) i = 0 j = 0 while i < 100: t2=time.time() h.update(`(i,j,t2)`) j += 1 delta=int((t2-t)*1e6) if delta: interval[i] = delta i += 1 t=t2 # Take the median of the array of intervals interval.sort() self._ticksize=interval[len(interval)/2] h.update(`(interval,self._ticksize)`) # mix in the measurement times and wash the random pool self.stir(h.digest()) def _addBytes(self, s): "XOR the contents of the string S into the random pool" i, pool = self._addPos, self._randpool for j in range(0, len(s)): pool[i]=pool[i] ^ ord(s[j]) i=(i+1) % self.bytes self._addPos = i # Deprecated method names: remove in PCT 2.1 or later. def getBytes(self, N): warnings.warn("getBytes() method replaced by get_bytes()", DeprecationWarning) return self.get_bytes(N) def addEvent (self, event, s=""): warnings.warn("addEvent() method replaced by add_event()", DeprecationWarning) return self.add_event(s + str(event)) class PersistentRandomPool (RandomPool): def __init__ (self, filename=None, *args, **kwargs): RandomPool.__init__(self, *args, **kwargs) self.filename = filename if filename: try: # the time taken to open and read the file might have # a little disk variability, modulo disk/kernel caching... f=open(filename, 'rb') self.add_event() data = f.read() self.add_event() # mix in the data from the file and wash the random pool self.stir(data) f.close() except IOError: # Oh, well; the file doesn't exist or is unreadable, so # we'll just ignore it. pass def save(self): if self.filename == "": raise ValueError, "No filename set for this object" # wash the random pool before save, provides some forward secrecy for # old values of the pool. self.stir_n() f=open(self.filename, 'wb') self.add_event() f.write(self._randpool.tostring()) f.close() self.add_event() # wash the pool again, provide some protection for future values self.stir() # non-echoing Windows keyboard entry _kb = 0 if not _kb: try: import msvcrt class KeyboardEntry: def getch(self): c = msvcrt.getch() if c in ('\000', '\xe0'): # function key c += msvcrt.getch() return c def close(self, delay = 0): if delay: time.sleep(delay) while msvcrt.kbhit(): msvcrt.getch() _kb = 1 except: pass # non-echoing Posix keyboard entry if not _kb: try: import termios class KeyboardEntry: def __init__(self, fd = 0): self._fd = fd self._old = termios.tcgetattr(fd) new = termios.tcgetattr(fd) new[3]=new[3] & ~termios.ICANON & ~termios.ECHO termios.tcsetattr(fd, termios.TCSANOW, new) def getch(self): termios.tcflush(0, termios.TCIFLUSH) # XXX Leave this in? return os.read(self._fd, 1) def close(self, delay = 0): if delay: time.sleep(delay) termios.tcflush(self._fd, termios.TCIFLUSH) termios.tcsetattr(self._fd, termios.TCSAFLUSH, self._old) _kb = 1 except: pass class KeyboardRandomPool (PersistentRandomPool): def __init__(self, *args, **kwargs): PersistentRandomPool.__init__(self, *args, **kwargs) def randomize(self, N = 0): "Adds N bits of entropy to random pool. If N is 0, fill up pool." import os, string, time if N <= 0: bits = self.bits - self.entropy else: bits = N*8 if bits == 0: return print bits,'bits of entropy are now required. Please type on the keyboard' print 'until enough randomness has been accumulated.' kb = KeyboardEntry() s='' # We'll save the characters typed and add them to the pool. hash = self._hash e = 0 try: while e < bits: temp=str(bits-e).rjust(6) os.write(1, temp) s=s+kb.getch() e += self.add_event(s) os.write(1, 6*chr(8)) self.add_event(s+hash.new(s).digest() ) finally: kb.close() print '\n\007 Enough. Please wait a moment.\n' self.stir_n() # wash the random pool. kb.close(4) if __name__ == '__main__': pool = RandomPool() print 'random pool entropy', pool.entropy, 'bits' pool.add_event('something') print `pool.get_bytes(100)` import tempfile, os fname = tempfile.mktemp() pool = KeyboardRandomPool(filename=fname) print 'keyboard random pool entropy', pool.entropy, 'bits' pool.randomize() print 'keyboard random pool entropy', pool.entropy, 'bits' pool.randomize(128) pool.save() saved = open(fname, 'rb').read() print 'saved', `saved` print 'pool ', `pool._randpool.tostring()` newpool = PersistentRandomPool(fname) print 'persistent random pool entropy', pool.entropy, 'bits' os.remove(fname)
Python
# # test.py : Functions used for testing the modules # # Part of the Python Cryptography Toolkit # # Distribute and use freely; there are no restrictions on further # dissemination and usage except those imposed by the laws of your # country of residence. This software is provided "as is" without # warranty of fitness for use or suitability for any purpose, express # or implied. Use at your own risk or not at all. # __revision__ = "$Id: test.py,v 1.16 2004/08/13 22:24:18 akuchling Exp $" import binascii import string import testdata from Crypto.Cipher import * def die(string): import sys print '***ERROR: ', string # sys.exit(0) # Will default to continuing onward... def print_timing (size, delta, verbose): if verbose: if delta == 0: print 'Unable to measure time -- elapsed time too small' else: print '%.2f K/sec' % (size/delta) def exerciseBlockCipher(cipher, verbose): import string, time try: ciph = eval(cipher) except NameError: print cipher, 'module not available' return None print cipher+ ':' str='1' # Build 128K of test data for i in xrange(0, 17): str=str+str if ciph.key_size==0: ciph.key_size=16 password = 'password12345678Extra text for password'[0:ciph.key_size] IV = 'Test IV Test IV Test IV Test'[0:ciph.block_size] if verbose: print ' ECB mode:', obj=ciph.new(password, ciph.MODE_ECB) if obj.block_size != ciph.block_size: die("Module and cipher object block_size don't match") text='1234567812345678'[0:ciph.block_size] c=obj.encrypt(text) if (obj.decrypt(c)!=text): die('Error encrypting "'+text+'"') text='KuchlingKuchling'[0:ciph.block_size] c=obj.encrypt(text) if (obj.decrypt(c)!=text): die('Error encrypting "'+text+'"') text='NotTodayNotEver!'[0:ciph.block_size] c=obj.encrypt(text) if (obj.decrypt(c)!=text): die('Error encrypting "'+text+'"') start=time.time() s=obj.encrypt(str) s2=obj.decrypt(s) end=time.time() if (str!=s2): die('Error in resulting plaintext from ECB mode') print_timing(256, end-start, verbose) del obj if verbose: print ' CFB mode:', obj1=ciph.new(password, ciph.MODE_CFB, IV) obj2=ciph.new(password, ciph.MODE_CFB, IV) start=time.time() ciphertext=obj1.encrypt(str[0:65536]) plaintext=obj2.decrypt(ciphertext) end=time.time() if (plaintext!=str[0:65536]): die('Error in resulting plaintext from CFB mode') print_timing(64, end-start, verbose) del obj1, obj2 if verbose: print ' CBC mode:', obj1=ciph.new(password, ciph.MODE_CBC, IV) obj2=ciph.new(password, ciph.MODE_CBC, IV) start=time.time() ciphertext=obj1.encrypt(str) plaintext=obj2.decrypt(ciphertext) end=time.time() if (plaintext!=str): die('Error in resulting plaintext from CBC mode') print_timing(256, end-start, verbose) del obj1, obj2 if verbose: print ' PGP mode:', obj1=ciph.new(password, ciph.MODE_PGP, IV) obj2=ciph.new(password, ciph.MODE_PGP, IV) start=time.time() ciphertext=obj1.encrypt(str) plaintext=obj2.decrypt(ciphertext) end=time.time() if (plaintext!=str): die('Error in resulting plaintext from PGP mode') print_timing(256, end-start, verbose) del obj1, obj2 if verbose: print ' OFB mode:', obj1=ciph.new(password, ciph.MODE_OFB, IV) obj2=ciph.new(password, ciph.MODE_OFB, IV) start=time.time() ciphertext=obj1.encrypt(str) plaintext=obj2.decrypt(ciphertext) end=time.time() if (plaintext!=str): die('Error in resulting plaintext from OFB mode') print_timing(256, end-start, verbose) del obj1, obj2 def counter(length=ciph.block_size): return length * 'a' if verbose: print ' CTR mode:', obj1=ciph.new(password, ciph.MODE_CTR, counter=counter) obj2=ciph.new(password, ciph.MODE_CTR, counter=counter) start=time.time() ciphertext=obj1.encrypt(str) plaintext=obj2.decrypt(ciphertext) end=time.time() if (plaintext!=str): die('Error in resulting plaintext from CTR mode') print_timing(256, end-start, verbose) del obj1, obj2 # Test the IV handling if verbose: print ' Testing IV handling' obj1=ciph.new(password, ciph.MODE_CBC, IV) plaintext='Test'*(ciph.block_size/4)*3 ciphertext1=obj1.encrypt(plaintext) obj1.IV=IV ciphertext2=obj1.encrypt(plaintext) if ciphertext1!=ciphertext2: die('Error in setting IV') # Test keyword arguments obj1=ciph.new(key=password) obj1=ciph.new(password, mode=ciph.MODE_CBC) obj1=ciph.new(mode=ciph.MODE_CBC, key=password) obj1=ciph.new(IV=IV, mode=ciph.MODE_CBC, key=password) return ciph def exerciseStreamCipher(cipher, verbose): import string, time try: ciph = eval(cipher) except (NameError): print cipher, 'module not available' return None print cipher + ':', str='1' # Build 128K of test data for i in xrange(0, 17): str=str+str key_size = ciph.key_size or 16 password = 'password12345678Extra text for password'[0:key_size] obj1=ciph.new(password) obj2=ciph.new(password) if obj1.block_size != ciph.block_size: die("Module and cipher object block_size don't match") if obj1.key_size != ciph.key_size: die("Module and cipher object key_size don't match") text='1234567812345678Python' c=obj1.encrypt(text) if (obj2.decrypt(c)!=text): die('Error encrypting "'+text+'"') text='B1FF I2 A R3A11Y |<00L D00D!!!!!' c=obj1.encrypt(text) if (obj2.decrypt(c)!=text): die('Error encrypting "'+text+'"') text='SpamSpamSpamSpamSpamSpamSpamSpamSpam' c=obj1.encrypt(text) if (obj2.decrypt(c)!=text): die('Error encrypting "'+text+'"') start=time.time() s=obj1.encrypt(str) str=obj2.decrypt(s) end=time.time() print_timing(256, end-start, verbose) del obj1, obj2 return ciph def TestStreamModules(args=['arc4', 'XOR'], verbose=1): import sys, string args=map(string.lower, args) if 'arc4' in args: # Test ARC4 stream cipher arc4=exerciseStreamCipher('ARC4', verbose) if (arc4!=None): for entry in testdata.arc4: key,plain,cipher=entry key=binascii.a2b_hex(key) plain=binascii.a2b_hex(plain) cipher=binascii.a2b_hex(cipher) obj=arc4.new(key) ciphertext=obj.encrypt(plain) if (ciphertext!=cipher): die('ARC4 failed on entry '+`entry`) if 'xor' in args: # Test XOR stream cipher XOR=exerciseStreamCipher('XOR', verbose) if (XOR!=None): for entry in testdata.xor: key,plain,cipher=entry key=binascii.a2b_hex(key) plain=binascii.a2b_hex(plain) cipher=binascii.a2b_hex(cipher) obj=XOR.new(key) ciphertext=obj.encrypt(plain) if (ciphertext!=cipher): die('XOR failed on entry '+`entry`) def TestBlockModules(args=['aes', 'arc2', 'des', 'blowfish', 'cast', 'des3', 'idea', 'rc5'], verbose=1): import string args=map(string.lower, args) if 'aes' in args: ciph=exerciseBlockCipher('AES', verbose) # AES if (ciph!=None): if verbose: print ' Verifying against test suite...' for entry in testdata.aes: key,plain,cipher=entry key=binascii.a2b_hex(key) plain=binascii.a2b_hex(plain) cipher=binascii.a2b_hex(cipher) obj=ciph.new(key, ciph.MODE_ECB) ciphertext=obj.encrypt(plain) if (ciphertext!=cipher): die('AES failed on entry '+`entry`) for i in ciphertext: if verbose: print hex(ord(i)), if verbose: print for entry in testdata.aes_modes: mode, key, plain, cipher, kw = entry key=binascii.a2b_hex(key) plain=binascii.a2b_hex(plain) cipher=binascii.a2b_hex(cipher) obj=ciph.new(key, mode, **kw) obj2=ciph.new(key, mode, **kw) ciphertext=obj.encrypt(plain) if (ciphertext!=cipher): die('AES encrypt failed on entry '+`entry`) for i in ciphertext: if verbose: print hex(ord(i)), if verbose: print plain2=obj2.decrypt(ciphertext) if plain2!=plain: die('AES decrypt failed on entry '+`entry`) for i in plain2: if verbose: print hex(ord(i)), if verbose: print if 'arc2' in args: ciph=exerciseBlockCipher('ARC2', verbose) # Alleged RC2 if (ciph!=None): if verbose: print ' Verifying against test suite...' for entry in testdata.arc2: key,plain,cipher=entry key=binascii.a2b_hex(key) plain=binascii.a2b_hex(plain) cipher=binascii.a2b_hex(cipher) obj=ciph.new(key, ciph.MODE_ECB) ciphertext=obj.encrypt(plain) if (ciphertext!=cipher): die('ARC2 failed on entry '+`entry`) for i in ciphertext: if verbose: print hex(ord(i)), print if 'blowfish' in args: ciph=exerciseBlockCipher('Blowfish',verbose)# Bruce Schneier's Blowfish cipher if (ciph!=None): if verbose: print ' Verifying against test suite...' for entry in testdata.blowfish: key,plain,cipher=entry key=binascii.a2b_hex(key) plain=binascii.a2b_hex(plain) cipher=binascii.a2b_hex(cipher) obj=ciph.new(key, ciph.MODE_ECB) ciphertext=obj.encrypt(plain) if (ciphertext!=cipher): die('Blowfish failed on entry '+`entry`) for i in ciphertext: if verbose: print hex(ord(i)), if verbose: print if 'cast' in args: ciph=exerciseBlockCipher('CAST', verbose) # CAST-128 if (ciph!=None): if verbose: print ' Verifying against test suite...' for entry in testdata.cast: key,plain,cipher=entry key=binascii.a2b_hex(key) plain=binascii.a2b_hex(plain) cipher=binascii.a2b_hex(cipher) obj=ciph.new(key, ciph.MODE_ECB) ciphertext=obj.encrypt(plain) if (ciphertext!=cipher): die('CAST failed on entry '+`entry`) for i in ciphertext: if verbose: print hex(ord(i)), if verbose: print if 0: # The full-maintenance test; it requires 4 million encryptions, # and correspondingly is quite time-consuming. I've disabled # it; it's faster to compile block/cast.c with -DTEST and run # the resulting program. a = b = '\x01\x23\x45\x67\x12\x34\x56\x78\x23\x45\x67\x89\x34\x56\x78\x9A' for i in range(0, 1000000): obj = cast.new(b, cast.MODE_ECB) a = obj.encrypt(a[:8]) + obj.encrypt(a[-8:]) obj = cast.new(a, cast.MODE_ECB) b = obj.encrypt(b[:8]) + obj.encrypt(b[-8:]) if a!="\xEE\xA9\xD0\xA2\x49\xFD\x3B\xA6\xB3\x43\x6F\xB8\x9D\x6D\xCA\x92": if verbose: print 'CAST test failed: value of "a" doesn\'t match' if b!="\xB2\xC9\x5E\xB0\x0C\x31\xAD\x71\x80\xAC\x05\xB8\xE8\x3D\x69\x6E": if verbose: print 'CAST test failed: value of "b" doesn\'t match' if 'des' in args: # Test/benchmark DES block cipher des=exerciseBlockCipher('DES', verbose) if (des!=None): # Various tests taken from the DES library packaged with Kerberos V4 obj=des.new(binascii.a2b_hex('0123456789abcdef'), des.MODE_ECB) s=obj.encrypt('Now is t') if (s!=binascii.a2b_hex('3fa40e8a984d4815')): die('DES fails test 1') obj=des.new(binascii.a2b_hex('08192a3b4c5d6e7f'), des.MODE_ECB) s=obj.encrypt('\000\000\000\000\000\000\000\000') if (s!=binascii.a2b_hex('25ddac3e96176467')): die('DES fails test 2') obj=des.new(binascii.a2b_hex('0123456789abcdef'), des.MODE_CBC, binascii.a2b_hex('1234567890abcdef')) s=obj.encrypt("Now is the time for all ") if (s!=binascii.a2b_hex('e5c7cdde872bf27c43e934008c389c0f683788499a7c05f6')): die('DES fails test 3') obj=des.new(binascii.a2b_hex('0123456789abcdef'), des.MODE_CBC, binascii.a2b_hex('fedcba9876543210')) s=obj.encrypt("7654321 Now is the time for \000\000\000\000") if (s!=binascii.a2b_hex("ccd173ffab2039f4acd8aefddfd8a1eb468e91157888ba681d269397f7fe62b4")): die('DES fails test 4') del obj,s # R. Rivest's test: see http://theory.lcs.mit.edu/~rivest/destest.txt x=binascii.a2b_hex('9474B8E8C73BCA7D') for i in range(0, 16): obj=des.new(x, des.MODE_ECB) if (i & 1): x=obj.decrypt(x) else: x=obj.encrypt(x) if x!=binascii.a2b_hex('1B1A2DDB4C642438'): die("DES fails Rivest's test") if verbose: print ' Verifying against test suite...' for entry in testdata.des: key,plain,cipher=entry key=binascii.a2b_hex(key) plain=binascii.a2b_hex(plain) cipher=binascii.a2b_hex(cipher) obj=des.new(key, des.MODE_ECB) ciphertext=obj.encrypt(plain) if (ciphertext!=cipher): die('DES failed on entry '+`entry`) for entry in testdata.des_cbc: key, iv, plain, cipher=entry key, iv, cipher=binascii.a2b_hex(key),binascii.a2b_hex(iv),binascii.a2b_hex(cipher) obj1=des.new(key, des.MODE_CBC, iv) obj2=des.new(key, des.MODE_CBC, iv) ciphertext=obj1.encrypt(plain) if (ciphertext!=cipher): die('DES CBC mode failed on entry '+`entry`) if 'des3' in args: ciph=exerciseBlockCipher('DES3', verbose) # Triple DES if (ciph!=None): if verbose: print ' Verifying against test suite...' for entry in testdata.des3: key,plain,cipher=entry key=binascii.a2b_hex(key) plain=binascii.a2b_hex(plain) cipher=binascii.a2b_hex(cipher) obj=ciph.new(key, ciph.MODE_ECB) ciphertext=obj.encrypt(plain) if (ciphertext!=cipher): die('DES3 failed on entry '+`entry`) for i in ciphertext: if verbose: print hex(ord(i)), if verbose: print for entry in testdata.des3_cbc: key, iv, plain, cipher=entry key, iv, cipher=binascii.a2b_hex(key),binascii.a2b_hex(iv),binascii.a2b_hex(cipher) obj1=ciph.new(key, ciph.MODE_CBC, iv) obj2=ciph.new(key, ciph.MODE_CBC, iv) ciphertext=obj1.encrypt(plain) if (ciphertext!=cipher): die('DES3 CBC mode failed on entry '+`entry`) if 'idea' in args: ciph=exerciseBlockCipher('IDEA', verbose) # IDEA block cipher if (ciph!=None): if verbose: print ' Verifying against test suite...' for entry in testdata.idea: key,plain,cipher=entry key=binascii.a2b_hex(key) plain=binascii.a2b_hex(plain) cipher=binascii.a2b_hex(cipher) obj=ciph.new(key, ciph.MODE_ECB) ciphertext=obj.encrypt(plain) if (ciphertext!=cipher): die('IDEA failed on entry '+`entry`) if 'rc5' in args: # Ronald Rivest's RC5 algorithm ciph=exerciseBlockCipher('RC5', verbose) if (ciph!=None): if verbose: print ' Verifying against test suite...' for entry in testdata.rc5: key,plain,cipher=entry key=binascii.a2b_hex(key) plain=binascii.a2b_hex(plain) cipher=binascii.a2b_hex(cipher) obj=ciph.new(key[4:], ciph.MODE_ECB, version =ord(key[0]), word_size=ord(key[1]), rounds =ord(key[2]) ) ciphertext=obj.encrypt(plain) if (ciphertext!=cipher): die('RC5 failed on entry '+`entry`) for i in ciphertext: if verbose: print hex(ord(i)), if verbose: print
Python
# # number.py : Number-theoretic functions # # Part of the Python Cryptography Toolkit # # Distribute and use freely; there are no restrictions on further # dissemination and usage except those imposed by the laws of your # country of residence. This software is provided "as is" without # warranty of fitness for use or suitability for any purpose, express # or implied. Use at your own risk or not at all. # __revision__ = "$Id: number.py,v 1.13 2003/04/04 18:21:07 akuchling Exp $" bignum = long try: from Crypto.PublicKey import _fastmath except ImportError: _fastmath = None # Commented out and replaced with faster versions below ## def long2str(n): ## s='' ## while n>0: ## s=chr(n & 255)+s ## n=n>>8 ## return s ## import types ## def str2long(s): ## if type(s)!=types.StringType: return s # Integers will be left alone ## return reduce(lambda x,y : x*256+ord(y), s, 0L) def size (N): """size(N:long) : int Returns the size of the number N in bits. """ bits, power = 0,1L while N >= power: bits += 1 power = power << 1 return bits def getRandomNumber(N, randfunc): """getRandomNumber(N:int, randfunc:callable):long Return an N-bit random number.""" S = randfunc(N/8) odd_bits = N % 8 if odd_bits != 0: char = ord(randfunc(1)) >> (8-odd_bits) S = chr(char) + S value = bytes_to_long(S) value |= 2L ** (N-1) # Ensure high bit is set assert size(value) >= N return value def GCD(x,y): """GCD(x:long, y:long): long Return the GCD of x and y. """ x = abs(x) ; y = abs(y) while x > 0: x, y = y % x, x return y def inverse(u, v): """inverse(u:long, u:long):long Return the inverse of u mod v. """ u3, v3 = long(u), long(v) u1, v1 = 1L, 0L while v3 > 0: q=u3 / v3 u1, v1 = v1, u1 - v1*q u3, v3 = v3, u3 - v3*q while u1<0: u1 = u1 + v return u1 # Given a number of bits to generate and a random generation function, # find a prime number of the appropriate size. def getPrime(N, randfunc): """getPrime(N:int, randfunc:callable):long Return a random N-bit prime number. """ number=getRandomNumber(N, randfunc) | 1 while (not isPrime(number)): number=number+2 return number def isPrime(N): """isPrime(N:long):bool Return true if N is prime. """ if N == 1: return 0 if N in sieve: return 1 for i in sieve: if (N % i)==0: return 0 # Use the accelerator if available if _fastmath is not None: return _fastmath.isPrime(N) # Compute the highest bit that's set in N N1 = N - 1L n = 1L while (n<N): n=n<<1L n = n >> 1L # Rabin-Miller test for c in sieve[:7]: a=long(c) ; d=1L ; t=n while (t): # Iterate over the bits in N1 x=(d*d) % N if x==1L and d!=1L and d!=N1: return 0 # Square root of 1 found if N1 & t: d=(x*a) % N else: d=x t = t >> 1L if d!=1L: return 0 return 1 # Small primes used for checking primality; these are all the primes # less than 256. This should be enough to eliminate most of the odd # numbers before needing to do a Rabin-Miller test at all. sieve=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251] # Improved conversion functions contributed by Barry Warsaw, after # careful benchmarking import struct def long_to_bytes(n, blocksize=0): """long_to_bytes(n:long, blocksize:int) : string Convert a long integer to a byte string. If optional blocksize is given and greater than zero, pad the front of the byte string with binary zeros so that the length is a multiple of blocksize. """ # after much testing, this algorithm was deemed to be the fastest s = '' n = long(n) pack = struct.pack while n > 0: s = pack('>I', n & 0xffffffffL) + s n = n >> 32 # strip off leading zeros for i in range(len(s)): if s[i] != '\000': break else: # only happens when n == 0 s = '\000' i = 0 s = s[i:] # add back some pad bytes. this could be done more efficiently w.r.t. the # de-padding being done above, but sigh... if blocksize > 0 and len(s) % blocksize: s = (blocksize - len(s) % blocksize) * '\000' + s return s def bytes_to_long(s): """bytes_to_long(string) : long Convert a byte string to a long integer. This is (essentially) the inverse of long_to_bytes(). """ acc = 0L unpack = struct.unpack length = len(s) if length % 4: extra = (4 - length % 4) s = '\000' * extra + s length = length + extra for i in range(0, length, 4): acc = (acc << 32) + unpack('>I', s[i:i+4])[0] return acc # For backwards compatibility... import warnings def long2str(n, blocksize=0): warnings.warn("long2str() has been replaced by long_to_bytes()") return long_to_bytes(n, blocksize) def str2long(s): warnings.warn("str2long() has been replaced by bytes_to_long()") return bytes_to_long(s)
Python
#!/usr/local/bin/python # rfc1751.py : Converts between 128-bit strings and a human-readable # sequence of words, as defined in RFC1751: "A Convention for # Human-Readable 128-bit Keys", by Daniel L. McDonald. __revision__ = "$Id: RFC1751.py,v 1.6 2003/04/04 15:15:10 akuchling Exp $" import string, binascii binary={0:'0000', 1:'0001', 2:'0010', 3:'0011', 4:'0100', 5:'0101', 6:'0110', 7:'0111', 8:'1000', 9:'1001', 10:'1010', 11:'1011', 12:'1100', 13:'1101', 14:'1110', 15:'1111'} def _key2bin(s): "Convert a key into a string of binary digits" kl=map(lambda x: ord(x), s) kl=map(lambda x: binary[x/16]+binary[x&15], kl) return ''.join(kl) def _extract(key, start, length): """Extract a bitstring from a string of binary digits, and return its numeric value.""" k=key[start:start+length] return reduce(lambda x,y: x*2+ord(y)-48, k, 0) def key_to_english (key): """key_to_english(key:string) : string Transform an arbitrary key into a string containing English words. The key length must be a multiple of 8. """ english='' for index in range(0, len(key), 8): # Loop over 8-byte subkeys subkey=key[index:index+8] # Compute the parity of the key skbin=_key2bin(subkey) ; p=0 for i in range(0, 64, 2): p=p+_extract(skbin, i, 2) # Append parity bits to the subkey skbin=_key2bin(subkey+chr((p<<6) & 255)) for i in range(0, 64, 11): english=english+wordlist[_extract(skbin, i, 11)]+' ' return english[:-1] # Remove the trailing space def english_to_key (str): """english_to_key(string):string Transform a string into a corresponding key. The string must contain words separated by whitespace; the number of words must be a multiple of 6. """ L=string.split(string.upper(str)) ; key='' for index in range(0, len(L), 6): sublist=L[index:index+6] ; char=9*[0] ; bits=0 for i in sublist: index = wordlist.index(i) shift = (8-(bits+11)%8) %8 y = index << shift cl, cc, cr = (y>>16), (y>>8)&0xff, y & 0xff if (shift>5): char[bits/8] = char[bits/8] | cl char[bits/8+1] = char[bits/8+1] | cc char[bits/8+2] = char[bits/8+2] | cr elif shift>-3: char[bits/8] = char[bits/8] | cc char[bits/8+1] = char[bits/8+1] | cr else: char[bits/8] = char[bits/8] | cr bits=bits+11 subkey=reduce(lambda x,y:x+chr(y), char, '') # Check the parity of the resulting key skbin=_key2bin(subkey) p=0 for i in range(0, 64, 2): p=p+_extract(skbin, i, 2) if (p&3) != _extract(skbin, 64, 2): raise ValueError, "Parity error in resulting key" key=key+subkey[0:8] return key wordlist=[ "A", "ABE", "ACE", "ACT", "AD", "ADA", "ADD", "AGO", "AID", "AIM", "AIR", "ALL", "ALP", "AM", "AMY", "AN", "ANA", "AND", "ANN", "ANT", "ANY", "APE", "APS", "APT", "ARC", "ARE", "ARK", "ARM", "ART", "AS", "ASH", "ASK", "AT", "ATE", "AUG", "AUK", "AVE", "AWE", "AWK", "AWL", "AWN", "AX", "AYE", "BAD", "BAG", "BAH", "BAM", "BAN", "BAR", "BAT", "BAY", "BE", "BED", "BEE", "BEG", "BEN", "BET", "BEY", "BIB", "BID", "BIG", "BIN", "BIT", "BOB", "BOG", "BON", "BOO", "BOP", "BOW", "BOY", "BUB", "BUD", "BUG", "BUM", "BUN", "BUS", "BUT", "BUY", "BY", "BYE", "CAB", "CAL", "CAM", "CAN", "CAP", "CAR", "CAT", "CAW", "COD", "COG", "COL", "CON", "COO", "COP", "COT", "COW", "COY", "CRY", "CUB", "CUE", "CUP", "CUR", "CUT", "DAB", "DAD", "DAM", "DAN", "DAR", "DAY", "DEE", "DEL", "DEN", "DES", "DEW", "DID", "DIE", "DIG", "DIN", "DIP", "DO", "DOE", "DOG", "DON", "DOT", "DOW", "DRY", "DUB", "DUD", "DUE", "DUG", "DUN", "EAR", "EAT", "ED", "EEL", "EGG", "EGO", "ELI", "ELK", "ELM", "ELY", "EM", "END", "EST", "ETC", "EVA", "EVE", "EWE", "EYE", "FAD", "FAN", "FAR", "FAT", "FAY", "FED", "FEE", "FEW", "FIB", "FIG", "FIN", "FIR", "FIT", "FLO", "FLY", "FOE", "FOG", "FOR", "FRY", "FUM", "FUN", "FUR", "GAB", "GAD", "GAG", "GAL", "GAM", "GAP", "GAS", "GAY", "GEE", "GEL", "GEM", "GET", "GIG", "GIL", "GIN", "GO", "GOT", "GUM", "GUN", "GUS", "GUT", "GUY", "GYM", "GYP", "HA", "HAD", "HAL", "HAM", "HAN", "HAP", "HAS", "HAT", "HAW", "HAY", "HE", "HEM", "HEN", "HER", "HEW", "HEY", "HI", "HID", "HIM", "HIP", "HIS", "HIT", "HO", "HOB", "HOC", "HOE", "HOG", "HOP", "HOT", "HOW", "HUB", "HUE", "HUG", "HUH", "HUM", "HUT", "I", "ICY", "IDA", "IF", "IKE", "ILL", "INK", "INN", "IO", "ION", "IQ", "IRA", "IRE", "IRK", "IS", "IT", "ITS", "IVY", "JAB", "JAG", "JAM", "JAN", "JAR", "JAW", "JAY", "JET", "JIG", "JIM", "JO", "JOB", "JOE", "JOG", "JOT", "JOY", "JUG", "JUT", "KAY", "KEG", "KEN", "KEY", "KID", "KIM", "KIN", "KIT", "LA", "LAB", "LAC", "LAD", "LAG", "LAM", "LAP", "LAW", "LAY", "LEA", "LED", "LEE", "LEG", "LEN", "LEO", "LET", "LEW", "LID", "LIE", "LIN", "LIP", "LIT", "LO", "LOB", "LOG", "LOP", "LOS", "LOT", "LOU", "LOW", "LOY", "LUG", "LYE", "MA", "MAC", "MAD", "MAE", "MAN", "MAO", "MAP", "MAT", "MAW", "MAY", "ME", "MEG", "MEL", "MEN", "MET", "MEW", "MID", "MIN", "MIT", "MOB", "MOD", "MOE", "MOO", "MOP", "MOS", "MOT", "MOW", "MUD", "MUG", "MUM", "MY", "NAB", "NAG", "NAN", "NAP", "NAT", "NAY", "NE", "NED", "NEE", "NET", "NEW", "NIB", "NIL", "NIP", "NIT", "NO", "NOB", "NOD", "NON", "NOR", "NOT", "NOV", "NOW", "NU", "NUN", "NUT", "O", "OAF", "OAK", "OAR", "OAT", "ODD", "ODE", "OF", "OFF", "OFT", "OH", "OIL", "OK", "OLD", "ON", "ONE", "OR", "ORB", "ORE", "ORR", "OS", "OTT", "OUR", "OUT", "OVA", "OW", "OWE", "OWL", "OWN", "OX", "PA", "PAD", "PAL", "PAM", "PAN", "PAP", "PAR", "PAT", "PAW", "PAY", "PEA", "PEG", "PEN", "PEP", "PER", "PET", "PEW", "PHI", "PI", "PIE", "PIN", "PIT", "PLY", "PO", "POD", "POE", "POP", "POT", "POW", "PRO", "PRY", "PUB", "PUG", "PUN", "PUP", "PUT", "QUO", "RAG", "RAM", "RAN", "RAP", "RAT", "RAW", "RAY", "REB", "RED", "REP", "RET", "RIB", "RID", "RIG", "RIM", "RIO", "RIP", "ROB", "ROD", "ROE", "RON", "ROT", "ROW", "ROY", "RUB", "RUE", "RUG", "RUM", "RUN", "RYE", "SAC", "SAD", "SAG", "SAL", "SAM", "SAN", "SAP", "SAT", "SAW", "SAY", "SEA", "SEC", "SEE", "SEN", "SET", "SEW", "SHE", "SHY", "SIN", "SIP", "SIR", "SIS", "SIT", "SKI", "SKY", "SLY", "SO", "SOB", "SOD", "SON", "SOP", "SOW", "SOY", "SPA", "SPY", "SUB", "SUD", "SUE", "SUM", "SUN", "SUP", "TAB", "TAD", "TAG", "TAN", "TAP", "TAR", "TEA", "TED", "TEE", "TEN", "THE", "THY", "TIC", "TIE", "TIM", "TIN", "TIP", "TO", "TOE", "TOG", "TOM", "TON", "TOO", "TOP", "TOW", "TOY", "TRY", "TUB", "TUG", "TUM", "TUN", "TWO", "UN", "UP", "US", "USE", "VAN", "VAT", "VET", "VIE", "WAD", "WAG", "WAR", "WAS", "WAY", "WE", "WEB", "WED", "WEE", "WET", "WHO", "WHY", "WIN", "WIT", "WOK", "WON", "WOO", "WOW", "WRY", "WU", "YAM", "YAP", "YAW", "YE", "YEA", "YES", "YET", "YOU", "ABED", "ABEL", "ABET", "ABLE", "ABUT", "ACHE", "ACID", "ACME", "ACRE", "ACTA", "ACTS", "ADAM", "ADDS", "ADEN", "AFAR", "AFRO", "AGEE", "AHEM", "AHOY", "AIDA", "AIDE", "AIDS", "AIRY", "AJAR", "AKIN", "ALAN", "ALEC", "ALGA", "ALIA", "ALLY", "ALMA", "ALOE", "ALSO", "ALTO", "ALUM", "ALVA", "AMEN", "AMES", "AMID", "AMMO", "AMOK", "AMOS", "AMRA", "ANDY", "ANEW", "ANNA", "ANNE", "ANTE", "ANTI", "AQUA", "ARAB", "ARCH", "AREA", "ARGO", "ARID", "ARMY", "ARTS", "ARTY", "ASIA", "ASKS", "ATOM", "AUNT", "AURA", "AUTO", "AVER", "AVID", "AVIS", "AVON", "AVOW", "AWAY", "AWRY", "BABE", "BABY", "BACH", "BACK", "BADE", "BAIL", "BAIT", "BAKE", "BALD", "BALE", "BALI", "BALK", "BALL", "BALM", "BAND", "BANE", "BANG", "BANK", "BARB", "BARD", "BARE", "BARK", "BARN", "BARR", "BASE", "BASH", "BASK", "BASS", "BATE", "BATH", "BAWD", "BAWL", "BEAD", "BEAK", "BEAM", "BEAN", "BEAR", "BEAT", "BEAU", "BECK", "BEEF", "BEEN", "BEER", "BEET", "BELA", "BELL", "BELT", "BEND", "BENT", "BERG", "BERN", "BERT", "BESS", "BEST", "BETA", "BETH", "BHOY", "BIAS", "BIDE", "BIEN", "BILE", "BILK", "BILL", "BIND", "BING", "BIRD", "BITE", "BITS", "BLAB", "BLAT", "BLED", "BLEW", "BLOB", "BLOC", "BLOT", "BLOW", "BLUE", "BLUM", "BLUR", "BOAR", "BOAT", "BOCA", "BOCK", "BODE", "BODY", "BOGY", "BOHR", "BOIL", "BOLD", "BOLO", "BOLT", "BOMB", "BONA", "BOND", "BONE", "BONG", "BONN", "BONY", "BOOK", "BOOM", "BOON", "BOOT", "BORE", "BORG", "BORN", "BOSE", "BOSS", "BOTH", "BOUT", "BOWL", "BOYD", "BRAD", "BRAE", "BRAG", "BRAN", "BRAY", "BRED", "BREW", "BRIG", "BRIM", "BROW", "BUCK", "BUDD", "BUFF", "BULB", "BULK", "BULL", "BUNK", "BUNT", "BUOY", "BURG", "BURL", "BURN", "BURR", "BURT", "BURY", "BUSH", "BUSS", "BUST", "BUSY", "BYTE", "CADY", "CAFE", "CAGE", "CAIN", "CAKE", "CALF", "CALL", "CALM", "CAME", "CANE", "CANT", "CARD", "CARE", "CARL", "CARR", "CART", "CASE", "CASH", "CASK", "CAST", "CAVE", "CEIL", "CELL", "CENT", "CERN", "CHAD", "CHAR", "CHAT", "CHAW", "CHEF", "CHEN", "CHEW", "CHIC", "CHIN", "CHOU", "CHOW", "CHUB", "CHUG", "CHUM", "CITE", "CITY", "CLAD", "CLAM", "CLAN", "CLAW", "CLAY", "CLOD", "CLOG", "CLOT", "CLUB", "CLUE", "COAL", "COAT", "COCA", "COCK", "COCO", "CODA", "CODE", "CODY", "COED", "COIL", "COIN", "COKE", "COLA", "COLD", "COLT", "COMA", "COMB", "COME", "COOK", "COOL", "COON", "COOT", "CORD", "CORE", "CORK", "CORN", "COST", "COVE", "COWL", "CRAB", "CRAG", "CRAM", "CRAY", "CREW", "CRIB", "CROW", "CRUD", "CUBA", "CUBE", "CUFF", "CULL", "CULT", "CUNY", "CURB", "CURD", "CURE", "CURL", "CURT", "CUTS", "DADE", "DALE", "DAME", "DANA", "DANE", "DANG", "DANK", "DARE", "DARK", "DARN", "DART", "DASH", "DATA", "DATE", "DAVE", "DAVY", "DAWN", "DAYS", "DEAD", "DEAF", "DEAL", "DEAN", "DEAR", "DEBT", "DECK", "DEED", "DEEM", "DEER", "DEFT", "DEFY", "DELL", "DENT", "DENY", "DESK", "DIAL", "DICE", "DIED", "DIET", "DIME", "DINE", "DING", "DINT", "DIRE", "DIRT", "DISC", "DISH", "DISK", "DIVE", "DOCK", "DOES", "DOLE", "DOLL", "DOLT", "DOME", "DONE", "DOOM", "DOOR", "DORA", "DOSE", "DOTE", "DOUG", "DOUR", "DOVE", "DOWN", "DRAB", "DRAG", "DRAM", "DRAW", "DREW", "DRUB", "DRUG", "DRUM", "DUAL", "DUCK", "DUCT", "DUEL", "DUET", "DUKE", "DULL", "DUMB", "DUNE", "DUNK", "DUSK", "DUST", "DUTY", "EACH", "EARL", "EARN", "EASE", "EAST", "EASY", "EBEN", "ECHO", "EDDY", "EDEN", "EDGE", "EDGY", "EDIT", "EDNA", "EGAN", "ELAN", "ELBA", "ELLA", "ELSE", "EMIL", "EMIT", "EMMA", "ENDS", "ERIC", "EROS", "EVEN", "EVER", "EVIL", "EYED", "FACE", "FACT", "FADE", "FAIL", "FAIN", "FAIR", "FAKE", "FALL", "FAME", "FANG", "FARM", "FAST", "FATE", "FAWN", "FEAR", "FEAT", "FEED", "FEEL", "FEET", "FELL", "FELT", "FEND", "FERN", "FEST", "FEUD", "FIEF", "FIGS", "FILE", "FILL", "FILM", "FIND", "FINE", "FINK", "FIRE", "FIRM", "FISH", "FISK", "FIST", "FITS", "FIVE", "FLAG", "FLAK", "FLAM", "FLAT", "FLAW", "FLEA", "FLED", "FLEW", "FLIT", "FLOC", "FLOG", "FLOW", "FLUB", "FLUE", "FOAL", "FOAM", "FOGY", "FOIL", "FOLD", "FOLK", "FOND", "FONT", "FOOD", "FOOL", "FOOT", "FORD", "FORE", "FORK", "FORM", "FORT", "FOSS", "FOUL", "FOUR", "FOWL", "FRAU", "FRAY", "FRED", "FREE", "FRET", "FREY", "FROG", "FROM", "FUEL", "FULL", "FUME", "FUND", "FUNK", "FURY", "FUSE", "FUSS", "GAFF", "GAGE", "GAIL", "GAIN", "GAIT", "GALA", "GALE", "GALL", "GALT", "GAME", "GANG", "GARB", "GARY", "GASH", "GATE", "GAUL", "GAUR", "GAVE", "GAWK", "GEAR", "GELD", "GENE", "GENT", "GERM", "GETS", "GIBE", "GIFT", "GILD", "GILL", "GILT", "GINA", "GIRD", "GIRL", "GIST", "GIVE", "GLAD", "GLEE", "GLEN", "GLIB", "GLOB", "GLOM", "GLOW", "GLUE", "GLUM", "GLUT", "GOAD", "GOAL", "GOAT", "GOER", "GOES", "GOLD", "GOLF", "GONE", "GONG", "GOOD", "GOOF", "GORE", "GORY", "GOSH", "GOUT", "GOWN", "GRAB", "GRAD", "GRAY", "GREG", "GREW", "GREY", "GRID", "GRIM", "GRIN", "GRIT", "GROW", "GRUB", "GULF", "GULL", "GUNK", "GURU", "GUSH", "GUST", "GWEN", "GWYN", "HAAG", "HAAS", "HACK", "HAIL", "HAIR", "HALE", "HALF", "HALL", "HALO", "HALT", "HAND", "HANG", "HANK", "HANS", "HARD", "HARK", "HARM", "HART", "HASH", "HAST", "HATE", "HATH", "HAUL", "HAVE", "HAWK", "HAYS", "HEAD", "HEAL", "HEAR", "HEAT", "HEBE", "HECK", "HEED", "HEEL", "HEFT", "HELD", "HELL", "HELM", "HERB", "HERD", "HERE", "HERO", "HERS", "HESS", "HEWN", "HICK", "HIDE", "HIGH", "HIKE", "HILL", "HILT", "HIND", "HINT", "HIRE", "HISS", "HIVE", "HOBO", "HOCK", "HOFF", "HOLD", "HOLE", "HOLM", "HOLT", "HOME", "HONE", "HONK", "HOOD", "HOOF", "HOOK", "HOOT", "HORN", "HOSE", "HOST", "HOUR", "HOVE", "HOWE", "HOWL", "HOYT", "HUCK", "HUED", "HUFF", "HUGE", "HUGH", "HUGO", "HULK", "HULL", "HUNK", "HUNT", "HURD", "HURL", "HURT", "HUSH", "HYDE", "HYMN", "IBIS", "ICON", "IDEA", "IDLE", "IFFY", "INCA", "INCH", "INTO", "IONS", "IOTA", "IOWA", "IRIS", "IRMA", "IRON", "ISLE", "ITCH", "ITEM", "IVAN", "JACK", "JADE", "JAIL", "JAKE", "JANE", "JAVA", "JEAN", "JEFF", "JERK", "JESS", "JEST", "JIBE", "JILL", "JILT", "JIVE", "JOAN", "JOBS", "JOCK", "JOEL", "JOEY", "JOHN", "JOIN", "JOKE", "JOLT", "JOVE", "JUDD", "JUDE", "JUDO", "JUDY", "JUJU", "JUKE", "JULY", "JUNE", "JUNK", "JUNO", "JURY", "JUST", "JUTE", "KAHN", "KALE", "KANE", "KANT", "KARL", "KATE", "KEEL", "KEEN", "KENO", "KENT", "KERN", "KERR", "KEYS", "KICK", "KILL", "KIND", "KING", "KIRK", "KISS", "KITE", "KLAN", "KNEE", "KNEW", "KNIT", "KNOB", "KNOT", "KNOW", "KOCH", "KONG", "KUDO", "KURD", "KURT", "KYLE", "LACE", "LACK", "LACY", "LADY", "LAID", "LAIN", "LAIR", "LAKE", "LAMB", "LAME", "LAND", "LANE", "LANG", "LARD", "LARK", "LASS", "LAST", "LATE", "LAUD", "LAVA", "LAWN", "LAWS", "LAYS", "LEAD", "LEAF", "LEAK", "LEAN", "LEAR", "LEEK", "LEER", "LEFT", "LEND", "LENS", "LENT", "LEON", "LESK", "LESS", "LEST", "LETS", "LIAR", "LICE", "LICK", "LIED", "LIEN", "LIES", "LIEU", "LIFE", "LIFT", "LIKE", "LILA", "LILT", "LILY", "LIMA", "LIMB", "LIME", "LIND", "LINE", "LINK", "LINT", "LION", "LISA", "LIST", "LIVE", "LOAD", "LOAF", "LOAM", "LOAN", "LOCK", "LOFT", "LOGE", "LOIS", "LOLA", "LONE", "LONG", "LOOK", "LOON", "LOOT", "LORD", "LORE", "LOSE", "LOSS", "LOST", "LOUD", "LOVE", "LOWE", "LUCK", "LUCY", "LUGE", "LUKE", "LULU", "LUND", "LUNG", "LURA", "LURE", "LURK", "LUSH", "LUST", "LYLE", "LYNN", "LYON", "LYRA", "MACE", "MADE", "MAGI", "MAID", "MAIL", "MAIN", "MAKE", "MALE", "MALI", "MALL", "MALT", "MANA", "MANN", "MANY", "MARC", "MARE", "MARK", "MARS", "MART", "MARY", "MASH", "MASK", "MASS", "MAST", "MATE", "MATH", "MAUL", "MAYO", "MEAD", "MEAL", "MEAN", "MEAT", "MEEK", "MEET", "MELD", "MELT", "MEMO", "MEND", "MENU", "MERT", "MESH", "MESS", "MICE", "MIKE", "MILD", "MILE", "MILK", "MILL", "MILT", "MIMI", "MIND", "MINE", "MINI", "MINK", "MINT", "MIRE", "MISS", "MIST", "MITE", "MITT", "MOAN", "MOAT", "MOCK", "MODE", "MOLD", "MOLE", "MOLL", "MOLT", "MONA", "MONK", "MONT", "MOOD", "MOON", "MOOR", "MOOT", "MORE", "MORN", "MORT", "MOSS", "MOST", "MOTH", "MOVE", "MUCH", "MUCK", "MUDD", "MUFF", "MULE", "MULL", "MURK", "MUSH", "MUST", "MUTE", "MUTT", "MYRA", "MYTH", "NAGY", "NAIL", "NAIR", "NAME", "NARY", "NASH", "NAVE", "NAVY", "NEAL", "NEAR", "NEAT", "NECK", "NEED", "NEIL", "NELL", "NEON", "NERO", "NESS", "NEST", "NEWS", "NEWT", "NIBS", "NICE", "NICK", "NILE", "NINA", "NINE", "NOAH", "NODE", "NOEL", "NOLL", "NONE", "NOOK", "NOON", "NORM", "NOSE", "NOTE", "NOUN", "NOVA", "NUDE", "NULL", "NUMB", "OATH", "OBEY", "OBOE", "ODIN", "OHIO", "OILY", "OINT", "OKAY", "OLAF", "OLDY", "OLGA", "OLIN", "OMAN", "OMEN", "OMIT", "ONCE", "ONES", "ONLY", "ONTO", "ONUS", "ORAL", "ORGY", "OSLO", "OTIS", "OTTO", "OUCH", "OUST", "OUTS", "OVAL", "OVEN", "OVER", "OWLY", "OWNS", "QUAD", "QUIT", "QUOD", "RACE", "RACK", "RACY", "RAFT", "RAGE", "RAID", "RAIL", "RAIN", "RAKE", "RANK", "RANT", "RARE", "RASH", "RATE", "RAVE", "RAYS", "READ", "REAL", "REAM", "REAR", "RECK", "REED", "REEF", "REEK", "REEL", "REID", "REIN", "RENA", "REND", "RENT", "REST", "RICE", "RICH", "RICK", "RIDE", "RIFT", "RILL", "RIME", "RING", "RINK", "RISE", "RISK", "RITE", "ROAD", "ROAM", "ROAR", "ROBE", "ROCK", "RODE", "ROIL", "ROLL", "ROME", "ROOD", "ROOF", "ROOK", "ROOM", "ROOT", "ROSA", "ROSE", "ROSS", "ROSY", "ROTH", "ROUT", "ROVE", "ROWE", "ROWS", "RUBE", "RUBY", "RUDE", "RUDY", "RUIN", "RULE", "RUNG", "RUNS", "RUNT", "RUSE", "RUSH", "RUSK", "RUSS", "RUST", "RUTH", "SACK", "SAFE", "SAGE", "SAID", "SAIL", "SALE", "SALK", "SALT", "SAME", "SAND", "SANE", "SANG", "SANK", "SARA", "SAUL", "SAVE", "SAYS", "SCAN", "SCAR", "SCAT", "SCOT", "SEAL", "SEAM", "SEAR", "SEAT", "SEED", "SEEK", "SEEM", "SEEN", "SEES", "SELF", "SELL", "SEND", "SENT", "SETS", "SEWN", "SHAG", "SHAM", "SHAW", "SHAY", "SHED", "SHIM", "SHIN", "SHOD", "SHOE", "SHOT", "SHOW", "SHUN", "SHUT", "SICK", "SIDE", "SIFT", "SIGH", "SIGN", "SILK", "SILL", "SILO", "SILT", "SINE", "SING", "SINK", "SIRE", "SITE", "SITS", "SITU", "SKAT", "SKEW", "SKID", "SKIM", "SKIN", "SKIT", "SLAB", "SLAM", "SLAT", "SLAY", "SLED", "SLEW", "SLID", "SLIM", "SLIT", "SLOB", "SLOG", "SLOT", "SLOW", "SLUG", "SLUM", "SLUR", "SMOG", "SMUG", "SNAG", "SNOB", "SNOW", "SNUB", "SNUG", "SOAK", "SOAR", "SOCK", "SODA", "SOFA", "SOFT", "SOIL", "SOLD", "SOME", "SONG", "SOON", "SOOT", "SORE", "SORT", "SOUL", "SOUR", "SOWN", "STAB", "STAG", "STAN", "STAR", "STAY", "STEM", "STEW", "STIR", "STOW", "STUB", "STUN", "SUCH", "SUDS", "SUIT", "SULK", "SUMS", "SUNG", "SUNK", "SURE", "SURF", "SWAB", "SWAG", "SWAM", "SWAN", "SWAT", "SWAY", "SWIM", "SWUM", "TACK", "TACT", "TAIL", "TAKE", "TALE", "TALK", "TALL", "TANK", "TASK", "TATE", "TAUT", "TEAL", "TEAM", "TEAR", "TECH", "TEEM", "TEEN", "TEET", "TELL", "TEND", "TENT", "TERM", "TERN", "TESS", "TEST", "THAN", "THAT", "THEE", "THEM", "THEN", "THEY", "THIN", "THIS", "THUD", "THUG", "TICK", "TIDE", "TIDY", "TIED", "TIER", "TILE", "TILL", "TILT", "TIME", "TINA", "TINE", "TINT", "TINY", "TIRE", "TOAD", "TOGO", "TOIL", "TOLD", "TOLL", "TONE", "TONG", "TONY", "TOOK", "TOOL", "TOOT", "TORE", "TORN", "TOTE", "TOUR", "TOUT", "TOWN", "TRAG", "TRAM", "TRAY", "TREE", "TREK", "TRIG", "TRIM", "TRIO", "TROD", "TROT", "TROY", "TRUE", "TUBA", "TUBE", "TUCK", "TUFT", "TUNA", "TUNE", "TUNG", "TURF", "TURN", "TUSK", "TWIG", "TWIN", "TWIT", "ULAN", "UNIT", "URGE", "USED", "USER", "USES", "UTAH", "VAIL", "VAIN", "VALE", "VARY", "VASE", "VAST", "VEAL", "VEDA", "VEIL", "VEIN", "VEND", "VENT", "VERB", "VERY", "VETO", "VICE", "VIEW", "VINE", "VISE", "VOID", "VOLT", "VOTE", "WACK", "WADE", "WAGE", "WAIL", "WAIT", "WAKE", "WALE", "WALK", "WALL", "WALT", "WAND", "WANE", "WANG", "WANT", "WARD", "WARM", "WARN", "WART", "WASH", "WAST", "WATS", "WATT", "WAVE", "WAVY", "WAYS", "WEAK", "WEAL", "WEAN", "WEAR", "WEED", "WEEK", "WEIR", "WELD", "WELL", "WELT", "WENT", "WERE", "WERT", "WEST", "WHAM", "WHAT", "WHEE", "WHEN", "WHET", "WHOA", "WHOM", "WICK", "WIFE", "WILD", "WILL", "WIND", "WINE", "WING", "WINK", "WINO", "WIRE", "WISE", "WISH", "WITH", "WOLF", "WONT", "WOOD", "WOOL", "WORD", "WORE", "WORK", "WORM", "WORN", "WOVE", "WRIT", "WYNN", "YALE", "YANG", "YANK", "YARD", "YARN", "YAWL", "YAWN", "YEAH", "YEAR", "YELL", "YOGA", "YOKE" ] if __name__=='__main__': data = [('EB33F77EE73D4053', 'TIDE ITCH SLOW REIN RULE MOT'), ('CCAC2AED591056BE4F90FD441C534766', 'RASH BUSH MILK LOOK BAD BRIM AVID GAFF BAIT ROT POD LOVE'), ('EFF81F9BFBC65350920CDD7416DE8009', 'TROD MUTE TAIL WARM CHAR KONG HAAG CITY BORE O TEAL AWL') ] for key, words in data: print 'Trying key', key key=binascii.a2b_hex(key) w2=key_to_english(key) if w2!=words: print 'key_to_english fails on key', repr(key), ', producing', str(w2) k2=english_to_key(words) if k2!=key: print 'english_to_key fails on key', repr(key), ', producing', repr(k2)
Python
"""Miscellaneous modules Contains useful modules that don't belong into any of the other Crypto.* subpackages. Crypto.Util.number Number-theoretic functions (primality testing, etc.) Crypto.Util.randpool Random number generation Crypto.Util.RFC1751 Converts between 128-bit keys and human-readable strings of words. """ __all__ = ['randpool', 'RFC1751', 'number'] __revision__ = "$Id: __init__.py,v 1.4 2003/02/28 15:26:00 akuchling Exp $"
Python
"""Python Cryptography Toolkit A collection of cryptographic modules implementing various algorithms and protocols. Subpackages: Crypto.Cipher Secret-key encryption algorithms (AES, DES, ARC4) Crypto.Hash Hashing algorithms (MD5, SHA, HMAC) Crypto.Protocol Cryptographic protocols (Chaffing, all-or-nothing transform). This package does not contain any network protocols. Crypto.PublicKey Public-key encryption and signature algorithms (RSA, DSA) Crypto.Util Various useful modules and functions (long-to-string conversion, random number generation, number theoretic functions) """ __all__ = ['Cipher', 'Hash', 'Protocol', 'PublicKey', 'Util'] __version__ = '2.0.1' __revision__ = "$Id: __init__.py,v 1.12 2005/06/14 01:20:22 akuchling Exp $"
Python
"""Secret-key encryption algorithms. Secret-key encryption algorithms transform plaintext in some way that is dependent on a key, producing ciphertext. This transformation can easily be reversed, if (and, hopefully, only if) one knows the key. The encryption modules here all support the interface described in PEP 272, "API for Block Encryption Algorithms". If you don't know which algorithm to choose, use AES because it's standard and has undergone a fair bit of examination. Crypto.Cipher.AES Advanced Encryption Standard Crypto.Cipher.ARC2 Alleged RC2 Crypto.Cipher.ARC4 Alleged RC4 Crypto.Cipher.Blowfish Crypto.Cipher.CAST Crypto.Cipher.DES The Data Encryption Standard. Very commonly used in the past, but today its 56-bit keys are too small. Crypto.Cipher.DES3 Triple DES. Crypto.Cipher.IDEA Crypto.Cipher.RC5 Crypto.Cipher.XOR The simple XOR cipher. """ __all__ = ['AES', 'ARC2', 'ARC4', 'Blowfish', 'CAST', 'DES', 'DES3', 'IDEA', 'RC5', 'XOR' ] __revision__ = "$Id: __init__.py,v 1.7 2003/02/28 15:28:35 akuchling Exp $"
Python
# Just use the SHA module from the Python standard library __revision__ = "$Id: SHA.py,v 1.4 2002/07/11 14:31:19 akuchling Exp $" from sha import * import sha if hasattr(sha, 'digestsize'): digest_size = digestsize del digestsize del sha
Python
"""Hashing algorithms Hash functions take arbitrary strings as input, and produce an output of fixed size that is dependent on the input; it should never be possible to derive the input data given only the hash function's output. Hash functions can be used simply as a checksum, or, in association with a public-key algorithm, can be used to implement digital signatures. The hashing modules here all support the interface described in PEP 247, "API for Cryptographic Hash Functions". Submodules: Crypto.Hash.HMAC RFC 2104: Keyed-Hashing for Message Authentication Crypto.Hash.MD2 Crypto.Hash.MD4 Crypto.Hash.MD5 Crypto.Hash.RIPEMD Crypto.Hash.SHA """ __all__ = ['HMAC', 'MD2', 'MD4', 'MD5', 'RIPEMD', 'SHA', 'SHA256'] __revision__ = "$Id: __init__.py,v 1.6 2003/12/19 14:24:25 akuchling Exp $"
Python
# Just use the MD5 module from the Python standard library __revision__ = "$Id: MD5.py,v 1.4 2002/07/11 14:31:19 akuchling Exp $" from md5 import * import md5 if hasattr(md5, 'digestsize'): digest_size = digestsize del digestsize del md5
Python
"""HMAC (Keyed-Hashing for Message Authentication) Python module. Implements the HMAC algorithm as described by RFC 2104. This is just a copy of the Python 2.2 HMAC module, modified to work when used on versions of Python before 2.2. """ __revision__ = "$Id: HMAC.py,v 1.5 2002/07/25 17:19:02 z3p Exp $" import string def _strxor(s1, s2): """Utility method. XOR the two strings s1 and s2 (must have same length). """ return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2)) # The size of the digests returned by HMAC depends on the underlying # hashing module used. digest_size = None class HMAC: """RFC2104 HMAC class. This supports the API for Cryptographic Hash Functions (PEP 247). """ def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC 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 == None: import md5 digestmod = md5 self.digestmod = digestmod self.outer = digestmod.new() self.inner = digestmod.new() try: self.digest_size = digestmod.digest_size except AttributeError: self.digest_size = len(self.outer.digest()) blocksize = 64 ipad = "\x36" * blocksize opad = "\x5C" * blocksize if len(key) > blocksize: key = digestmod.new(key).digest() key = key + chr(0) * (blocksize - len(key)) self.outer.update(_strxor(key, opad)) self.inner.update(_strxor(key, ipad)) if (msg): self.update(msg) ## def clear(self): ## raise NotImplementedError, "clear() method not available in HMAC." 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 = HMAC("") 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([string.zfill(hex(ord(x))[2:], 2) for x in tuple(self.digest())]) def new(key, msg = None, digestmod = None): """Create a new hashing object and return it. key: The starting key for the hash. msg: if available, will immediately be hashed into the object's starting state. You can now feed arbitrary strings into the object using its update() method, and can ask for the hash value at any time by calling its digest() method. """ return HMAC(key, msg, digestmod)
Python
#!/usr/bin/env python # # Copyright 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. import atom.data import gdata.client import gdata.gauth import gdata.projecthosting.data class ProjectHostingClient(gdata.client.GDClient): """Client to interact with the Project Hosting GData API.""" api_version = '1.0' auth_service = 'code' auth_scopes = gdata.gauth.AUTH_SCOPES['code'] host = 'code.google.com' ssl = True def get_issues(self, project_name, desired_class=gdata.projecthosting.data.IssuesFeed, **kwargs): """Get a feed of issues for a particular project. Args: project_name str The name of the project. query Query Set returned issues parameters. Returns: data.IssuesFeed """ return self.get_feed(gdata.projecthosting.data.ISSUES_FULL_FEED % project_name, desired_class=desired_class, **kwargs) def add_issue(self, project_name, title, content, author, status=None, owner=None, labels=None, ccs=None, **kwargs): """Create a new issue for the project. Args: project_name str The name of the project. title str The title of the new issue. content str The summary of the new issue. author str The authenticated user's username. status str The status of the new issue, Accepted, etc. owner str The username of new issue's owner. labels [str] Labels to associate with the new issue. ccs [str] usernames to Cc on the new issue. Returns: data.IssueEntry """ new_entry = gdata.projecthosting.data.IssueEntry( title=atom.data.Title(text=title), content=atom.data.Content(text=content), author=[atom.data.Author(name=atom.data.Name(text=author))]) if status: new_entry.status = gdata.projecthosting.data.Status(text=status) if owner: owner = [gdata.projecthosting.data.Owner( username=gdata.projecthosting.data.Username(text=owner))] if labels: new_entry.label = [gdata.projecthosting.data.Label(text=label) for label in labels] if ccs: new_entry.cc = [ gdata.projecthosting.data.Cc( username=gdata.projecthosting.data.Username(text=cc)) for cc in ccs] return self.post( new_entry, gdata.projecthosting.data.ISSUES_FULL_FEED % project_name, **kwargs) def update_issue(self, project_name, issue_id, author, comment=None, summary=None, status=None, owner=None, labels=None, ccs=None, **kwargs): """Update or comment on one issue for the project. Args: project_name str The name of the issue's project. issue_id str The issue number needing updated. author str The authenticated user's username. comment str A comment to append to the issue summary str Rewrite the summary of the issue. status str A new status for the issue. owner str The username of the new owner. labels [str] Labels to set on the issue (prepend issue with - to remove a label). ccs [str] Ccs to set on th enew issue (prepend cc with - to remove a cc). Returns: data.CommentEntry """ updates = gdata.projecthosting.data.Updates() if summary: updates.summary = gdata.projecthosting.data.Summary(text=summary) if status: updates.status = gdata.projecthosting.data.Status(text=status) if owner: updates.ownerUpdate = gdata.projecthosting.data.OwnerUpdate(text=owner) if labels: updates.label = [gdata.projecthosting.data.Label(text=label) for label in labels] if ccs: updates.ccUpdate = [gdata.projecthosting.data.CcUpdate(text=cc) for cc in ccs] update_entry = gdata.projecthosting.data.CommentEntry( content=atom.data.Content(text=comment), author=[atom.data.Author(name=atom.data.Name(text=author))], updates=updates) return self.post( update_entry, gdata.projecthosting.data.COMMENTS_FULL_FEED % (project_name, issue_id), **kwargs) def get_comments(self, project_name, issue_id, desired_class=gdata.projecthosting.data.CommentsFeed, **kwargs): """Get a feed of all updates to an issue. Args: project_name str The name of the issue's project. issue_id str The issue number needing updated. Returns: data.CommentsFeed """ return self.get_feed( gdata.projecthosting.data.COMMENTS_FULL_FEED % (project_name, issue_id), desired_class=desired_class, **kwargs) def update(self, entry, auth_token=None, force=False, **kwargs): """Unsupported GData update method. Use update_*() instead. """ raise NotImplementedError( 'GData Update operation unsupported, try update_*') def delete(self, entry_or_uri, auth_token=None, force=False, **kwargs): """Unsupported GData delete method. Use update_issue(status='Closed') instead. """ raise NotImplementedError( 'GData Delete API unsupported, try closing the issue instead.') class Query(gdata.client.Query): def __init__(self, issue_id=None, label=None, canned_query=None, owner=None, status=None, **kwargs): """Constructs a Google Data Query to filter feed contents serverside. Args: issue_id: int or str The issue to return based on the issue id. label: str A label returned issues must have. canned_query: str Return issues based on a canned query identifier owner: str Return issues based on the owner of the issue. For Gmail users, this will be the part of the email preceding the '@' sign. status: str Return issues based on the status of the issue. """ super(Query, self).__init__(**kwargs) self.label = label self.issue_id = issue_id self.canned_query = canned_query self.owner = owner self.status = status def modify_request(self, http_request): if self.issue_id: gdata.client._add_query_param('id', self.issue_id, http_request) if self.label: gdata.client._add_query_param('label', self.label, http_request) if self.canned_query: gdata.client._add_query_param('can', self.canned_query, http_request) if self.owner: gdata.client._add_query_param('owner', self.owner, http_request) if self.status: gdata.client._add_query_param('status', self.status, http_request) super(Query, self).modify_request(http_request) ModifyRequest = modify_request
Python
#!/usr/bin/env python # # Copyright 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 XML in the Google Project Hosting API. Canonical documentation for the raw XML which these classes represent can be found here: http://code.google.com/p/support/wiki/IssueTrackerAPI """ __author__ = 'jlapenna@google.com (Joe LaPenna)' import atom.core import gdata.data ISSUES_TEMPLATE = '{http://schemas.google.com/projecthosting/issues/2009}%s' ISSUES_FULL_FEED = '/feeds/issues/p/%s/issues/full' COMMENTS_FULL_FEED = '/feeds/issues/p/%s/issues/%s/comments/full' class Uri(atom.core.XmlElement): """The issues:uri element.""" _qname = ISSUES_TEMPLATE % 'uri' class Username(atom.core.XmlElement): """The issues:username element.""" _qname = ISSUES_TEMPLATE % 'username' class Cc(atom.core.XmlElement): """The issues:cc element.""" _qname = ISSUES_TEMPLATE % 'cc' uri = Uri username = Username class Label(atom.core.XmlElement): """The issues:label element.""" _qname = ISSUES_TEMPLATE % 'label' class Owner(atom.core.XmlElement): """The issues:owner element.""" _qname = ISSUES_TEMPLATE % 'owner' uri = Uri username = Username class Stars(atom.core.XmlElement): """The issues:stars element.""" _qname = ISSUES_TEMPLATE % 'stars' class State(atom.core.XmlElement): """The issues:state element.""" _qname = ISSUES_TEMPLATE % 'state' class Status(atom.core.XmlElement): """The issues:status element.""" _qname = ISSUES_TEMPLATE % 'status' class Summary(atom.core.XmlElement): """The issues:summary element.""" _qname = ISSUES_TEMPLATE % 'summary' class OwnerUpdate(atom.core.XmlElement): """The issues:ownerUpdate element.""" _qname = ISSUES_TEMPLATE % 'ownerUpdate' class CcUpdate(atom.core.XmlElement): """The issues:ccUpdate element.""" _qname = ISSUES_TEMPLATE % 'ccUpdate' class Updates(atom.core.XmlElement): """The issues:updates element.""" _qname = ISSUES_TEMPLATE % 'updates' summary = Summary status = Status ownerUpdate = OwnerUpdate label = [Label] ccUpdate = [CcUpdate] class IssueEntry(gdata.data.GDEntry): """Represents the information of one issue.""" _qname = atom.data.ATOM_TEMPLATE % 'entry' owner = Owner cc = [Cc] label = [Label] stars = Stars state = State status = Status class IssuesFeed(gdata.data.GDFeed): """An Atom feed listing a project's issues.""" entry = [IssueEntry] class CommentEntry(gdata.data.GDEntry): """An entry detailing one comment on an issue.""" _qname = atom.data.ATOM_TEMPLATE % 'entry' updates = Updates class CommentsFeed(gdata.data.GDFeed): """An Atom feed listing a project's issue's comments.""" entry = [CommentEntry]
Python
# -*-*- encoding: utf-8 -*-*- # # This is gdata.photos.exif, implementing the exif namespace in gdata # # $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. """This module maps elements from the {EXIF} namespace[1] to GData objects. These elements describe image data, using exif attributes[2]. Picasa Web Albums uses the exif namespace to represent Exif data encoded in a photo [3]. Picasa Web Albums uses the following exif elements: exif:distance exif:exposure exif:flash exif:focallength exif:fstop exif:imageUniqueID exif:iso exif:make exif:model exif:tags exif:time [1]: http://schemas.google.com/photos/exif/2007. [2]: http://en.wikipedia.org/wiki/Exif [3]: http://code.google.com/apis/picasaweb/reference.html#exif_reference """ __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' import atom import gdata EXIF_NAMESPACE = 'http://schemas.google.com/photos/exif/2007' class ExifBaseElement(atom.AtomBase): """Base class for elements in the EXIF_NAMESPACE (%s). To add new elements, you only need to add the element tag name to self._tag """ % EXIF_NAMESPACE _tag = '' _namespace = EXIF_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 Distance(ExifBaseElement): "(float) The distance to the subject, e.g. 0.0" _tag = 'distance' def DistanceFromString(xml_string): return atom.CreateClassFromXMLString(Distance, xml_string) class Exposure(ExifBaseElement): "(float) The exposure time used, e.g. 0.025 or 8.0E4" _tag = 'exposure' def ExposureFromString(xml_string): return atom.CreateClassFromXMLString(Exposure, xml_string) class Flash(ExifBaseElement): """(string) Boolean value indicating whether the flash was used. The .text attribute will either be `true' or `false' As a convenience, this object's .bool method will return what you want, so you can say: flash_used = bool(Flash) """ _tag = 'flash' def __bool__(self): if self.text.lower() in ('true','false'): return self.text.lower() == 'true' def FlashFromString(xml_string): return atom.CreateClassFromXMLString(Flash, xml_string) class Focallength(ExifBaseElement): "(float) The focal length used, e.g. 23.7" _tag = 'focallength' def FocallengthFromString(xml_string): return atom.CreateClassFromXMLString(Focallength, xml_string) class Fstop(ExifBaseElement): "(float) The fstop value used, e.g. 5.0" _tag = 'fstop' def FstopFromString(xml_string): return atom.CreateClassFromXMLString(Fstop, xml_string) class ImageUniqueID(ExifBaseElement): "(string) The unique image ID for the photo. Generated by Google Photo servers" _tag = 'imageUniqueID' def ImageUniqueIDFromString(xml_string): return atom.CreateClassFromXMLString(ImageUniqueID, xml_string) class Iso(ExifBaseElement): "(int) The iso equivalent value used, e.g. 200" _tag = 'iso' def IsoFromString(xml_string): return atom.CreateClassFromXMLString(Iso, xml_string) class Make(ExifBaseElement): "(string) The make of the camera used, e.g. Fictitious Camera Company" _tag = 'make' def MakeFromString(xml_string): return atom.CreateClassFromXMLString(Make, xml_string) class Model(ExifBaseElement): "(string) The model of the camera used,e.g AMAZING-100D" _tag = 'model' def ModelFromString(xml_string): return atom.CreateClassFromXMLString(Model, xml_string) class Time(ExifBaseElement): """(int) The date/time the photo was taken, e.g. 1180294337000. Represented as the number of milliseconds since January 1st, 1970. The value of this element will always be identical to the value of the <gphoto:timestamp>. Look at this object's .isoformat() for a human friendly datetime string: 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 = 'time' 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 TimeFromString(xml_string): return atom.CreateClassFromXMLString(Time, xml_string) class Tags(ExifBaseElement): """The container for all exif elements. The <exif:tags> element can appear as a child of a photo entry. """ _tag = 'tags' _children = atom.AtomBase._children.copy() _children['{%s}fstop' % EXIF_NAMESPACE] = ('fstop', Fstop) _children['{%s}make' % EXIF_NAMESPACE] = ('make', Make) _children['{%s}model' % EXIF_NAMESPACE] = ('model', Model) _children['{%s}distance' % EXIF_NAMESPACE] = ('distance', Distance) _children['{%s}exposure' % EXIF_NAMESPACE] = ('exposure', Exposure) _children['{%s}flash' % EXIF_NAMESPACE] = ('flash', Flash) _children['{%s}focallength' % EXIF_NAMESPACE] = ('focallength', Focallength) _children['{%s}iso' % EXIF_NAMESPACE] = ('iso', Iso) _children['{%s}time' % EXIF_NAMESPACE] = ('time', Time) _children['{%s}imageUniqueID' % EXIF_NAMESPACE] = ('imageUniqueID', ImageUniqueID) def __init__(self, extension_elements=None, extension_attributes=None, text=None): ExifBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.fstop=None self.make=None self.model=None self.distance=None self.exposure=None self.flash=None self.focallength=None self.iso=None self.time=None self.imageUniqueID=None def TagsFromString(xml_string): return atom.CreateClassFromXMLString(Tags, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 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. """YouTubeService extends GDataService to streamline YouTube operations. YouTubeService: Provides methods to perform CRUD operations on YouTube feeds. Extends GDataService. """ __author__ = ('api.stephaniel@gmail.com (Stephanie Liu), ' 'api.jhartmann@gmail.com (Jochen Hartmann)') 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 os import atom import gdata import gdata.service import gdata.youtube YOUTUBE_SERVER = 'gdata.youtube.com' YOUTUBE_SERVICE = 'youtube' YOUTUBE_CLIENTLOGIN_AUTHENTICATION_URL = 'https://www.google.com/youtube/accounts/ClientLogin' YOUTUBE_SUPPORTED_UPLOAD_TYPES = ('mov', 'avi', 'wmv', 'mpg', 'quicktime', 'flv', 'mp4', 'x-flv') YOUTUBE_QUERY_VALID_TIME_PARAMETERS = ('today', 'this_week', 'this_month', 'all_time') YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS = ('published', 'viewCount', 'rating', 'relevance') YOUTUBE_QUERY_VALID_RACY_PARAMETERS = ('include', 'exclude') YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS = ('1', '5', '6') YOUTUBE_STANDARDFEEDS = ('most_recent', 'recently_featured', 'top_rated', 'most_viewed','watch_on_mobile') YOUTUBE_UPLOAD_URI = 'http://uploads.gdata.youtube.com/feeds/api/users' YOUTUBE_UPLOAD_TOKEN_URI = 'http://gdata.youtube.com/action/GetUploadToken' YOUTUBE_VIDEO_URI = 'http://gdata.youtube.com/feeds/api/videos' YOUTUBE_USER_FEED_URI = 'http://gdata.youtube.com/feeds/api/users' YOUTUBE_PLAYLIST_FEED_URI = 'http://gdata.youtube.com/feeds/api/playlists' YOUTUBE_STANDARD_FEEDS = 'http://gdata.youtube.com/feeds/api/standardfeeds' YOUTUBE_STANDARD_TOP_RATED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'top_rated') YOUTUBE_STANDARD_MOST_VIEWED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_viewed') YOUTUBE_STANDARD_RECENTLY_FEATURED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'recently_featured') YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'watch_on_mobile') YOUTUBE_STANDARD_TOP_FAVORITES_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'top_favorites') YOUTUBE_STANDARD_MOST_RECENT_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_recent') YOUTUBE_STANDARD_MOST_DISCUSSED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_discussed') YOUTUBE_STANDARD_MOST_LINKED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_linked') YOUTUBE_STANDARD_MOST_RESPONDED_URI = '%s/%s' % (YOUTUBE_STANDARD_FEEDS, 'most_responded') YOUTUBE_SCHEMA = 'http://gdata.youtube.com/schemas' YOUTUBE_RATING_LINK_REL = '%s#video.ratings' % YOUTUBE_SCHEMA YOUTUBE_COMPLAINT_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA, 'complaint-reasons.cat') YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME = '%s/%s' % (YOUTUBE_SCHEMA, 'subscriptiontypes.cat') YOUTUBE_COMPLAINT_CATEGORY_TERMS = ('PORN', 'VIOLENCE', 'HATE', 'DANGEROUS', 'RIGHTS', 'SPAM') YOUTUBE_CONTACT_STATUS = ('accepted', 'rejected') YOUTUBE_CONTACT_CATEGORY = ('Friends', 'Family') UNKOWN_ERROR = 1000 YOUTUBE_BAD_REQUEST = 400 YOUTUBE_CONFLICT = 409 YOUTUBE_INTERNAL_SERVER_ERROR = 500 YOUTUBE_INVALID_ARGUMENT = 601 YOUTUBE_INVALID_CONTENT_TYPE = 602 YOUTUBE_NOT_A_VIDEO = 603 YOUTUBE_INVALID_KIND = 604 class Error(Exception): """Base class for errors within the YouTube service.""" pass class RequestError(Error): """Error class that is thrown in response to an invalid HTTP Request.""" pass class YouTubeError(Error): """YouTube service specific error class.""" pass class YouTubeService(gdata.service.GDataService): """Client for the YouTube service. Performs all documented Google Data YouTube API functions, such as inserting, updating and deleting videos, comments, playlist, subscriptions etc. YouTube Service requires authentication for any write, update or delete actions. Attributes: email: An optional string identifying the user. Required only for authenticated actions. password: An optional string identifying the user's password. source: An optional string identifying the name of your application. server: An optional address of the YouTube API server. gdata.youtube.com is provided as the default value. additional_headers: An optional dictionary containing additional headers to be passed along with each request. Use to store developer key. client_id: An optional string identifying your application, required for authenticated requests, along with a developer key. developer_key: An optional string value. Register your application at http://code.google.com/apis/youtube/dashboard to obtain a (free) key. """ def __init__(self, email=None, password=None, source=None, server=YOUTUBE_SERVER, additional_headers=None, client_id=None, developer_key=None, **kwargs): """Creates a client for the YouTube 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: 'gdata.youtube.com'. client_id: string (optional) Identifies your application, required for authenticated requests, along with a developer key. developer_key: string (optional) Register your application at http://code.google.com/apis/youtube/dashboard to obtain a (free) key. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service=YOUTUBE_SERVICE, source=source, server=server, additional_headers=additional_headers, **kwargs) if client_id is not None: self.additional_headers['X-Gdata-Client'] = client_id if developer_key is not None: self.additional_headers['X-GData-Key'] = 'key=%s' % developer_key self.auth_service_url = YOUTUBE_CLIENTLOGIN_AUTHENTICATION_URL def GetYouTubeVideoFeed(self, uri): """Retrieve a YouTubeVideoFeed. Args: uri: A string representing the URI of the feed that is to be retrieved. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.Get(uri, converter=gdata.youtube.YouTubeVideoFeedFromString) def GetYouTubeVideoEntry(self, uri=None, video_id=None): """Retrieve a YouTubeVideoEntry. Either a uri or a video_id must be provided. Args: uri: An optional string representing the URI of the entry that is to be retrieved. video_id: An optional string representing the ID of the video. Returns: A YouTubeVideoFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a video_id to the GetYouTubeVideoEntry() method. """ if uri is None and video_id is None: raise YouTubeError('You must provide at least a uri or a video_id ' 'to the GetYouTubeVideoEntry() method') elif video_id and not uri: uri = '%s/%s' % (YOUTUBE_VIDEO_URI, video_id) return self.Get(uri, converter=gdata.youtube.YouTubeVideoEntryFromString) def GetYouTubeContactFeed(self, uri=None, username='default'): """Retrieve a YouTubeContactFeed. Either a uri or a username must be provided. Args: uri: An optional string representing the URI of the contact feed that is to be retrieved. username: An optional string representing the username. Defaults to the currently authenticated user. Returns: A YouTubeContactFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a username to the GetYouTubeContactFeed() method. """ if uri is None: uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'contacts') return self.Get(uri, converter=gdata.youtube.YouTubeContactFeedFromString) def GetYouTubeContactEntry(self, uri): """Retrieve a YouTubeContactEntry. Args: uri: A string representing the URI of the contact entry that is to be retrieved. Returns: A YouTubeContactEntry if successfully retrieved. """ return self.Get(uri, converter=gdata.youtube.YouTubeContactEntryFromString) def GetYouTubeVideoCommentFeed(self, uri=None, video_id=None): """Retrieve a YouTubeVideoCommentFeed. Either a uri or a video_id must be provided. Args: uri: An optional string representing the URI of the comment feed that is to be retrieved. video_id: An optional string representing the ID of the video for which to retrieve the comment feed. Returns: A YouTubeVideoCommentFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a video_id to the GetYouTubeVideoCommentFeed() method. """ if uri is None and video_id is None: raise YouTubeError('You must provide at least a uri or a video_id ' 'to the GetYouTubeVideoCommentFeed() method') elif video_id and not uri: uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'comments') return self.Get( uri, converter=gdata.youtube.YouTubeVideoCommentFeedFromString) def GetYouTubeVideoCommentEntry(self, uri): """Retrieve a YouTubeVideoCommentEntry. Args: uri: A string representing the URI of the comment entry that is to be retrieved. Returns: A YouTubeCommentEntry if successfully retrieved. """ return self.Get( uri, converter=gdata.youtube.YouTubeVideoCommentEntryFromString) def GetYouTubeUserFeed(self, uri=None, username=None): """Retrieve a YouTubeVideoFeed of user uploaded videos Either a uri or a username must be provided. This will retrieve list of videos uploaded by specified user. The uri will be of format "http://gdata.youtube.com/feeds/api/users/{username}/uploads". Args: uri: An optional string representing the URI of the user feed that is to be retrieved. username: An optional string representing the username. Returns: A YouTubeUserFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a username to the GetYouTubeUserFeed() method. """ if uri is None and username is None: raise YouTubeError('You must provide at least a uri or a username ' 'to the GetYouTubeUserFeed() method') elif username and not uri: uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'uploads') return self.Get(uri, converter=gdata.youtube.YouTubeUserFeedFromString) def GetYouTubeUserEntry(self, uri=None, username=None): """Retrieve a YouTubeUserEntry. Either a uri or a username must be provided. Args: uri: An optional string representing the URI of the user entry that is to be retrieved. username: An optional string representing the username. Returns: A YouTubeUserEntry if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a username to the GetYouTubeUserEntry() method. """ if uri is None and username is None: raise YouTubeError('You must provide at least a uri or a username ' 'to the GetYouTubeUserEntry() method') elif username and not uri: uri = '%s/%s' % (YOUTUBE_USER_FEED_URI, username) return self.Get(uri, converter=gdata.youtube.YouTubeUserEntryFromString) def GetYouTubePlaylistFeed(self, uri=None, username='default'): """Retrieve a YouTubePlaylistFeed (a feed of playlists for a user). Either a uri or a username must be provided. Args: uri: An optional string representing the URI of the playlist feed that is to be retrieved. username: An optional string representing the username. Defaults to the currently authenticated user. Returns: A YouTubePlaylistFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a username to the GetYouTubePlaylistFeed() method. """ if uri is None: uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'playlists') return self.Get(uri, converter=gdata.youtube.YouTubePlaylistFeedFromString) def GetYouTubePlaylistEntry(self, uri): """Retrieve a YouTubePlaylistEntry. Args: uri: A string representing the URI of the playlist feed that is to be retrieved. Returns: A YouTubePlaylistEntry if successfully retrieved. """ return self.Get(uri, converter=gdata.youtube.YouTubePlaylistEntryFromString) def GetYouTubePlaylistVideoFeed(self, uri=None, playlist_id=None): """Retrieve a YouTubePlaylistVideoFeed (a feed of videos on a playlist). Either a uri or a playlist_id must be provided. Args: uri: An optional string representing the URI of the playlist video feed that is to be retrieved. playlist_id: An optional string representing the Id of the playlist whose playlist video feed is to be retrieved. Returns: A YouTubePlaylistVideoFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a playlist_id to the GetYouTubePlaylistVideoFeed() method. """ if uri is None and playlist_id is None: raise YouTubeError('You must provide at least a uri or a playlist_id ' 'to the GetYouTubePlaylistVideoFeed() method') elif playlist_id and not uri: uri = '%s/%s' % (YOUTUBE_PLAYLIST_FEED_URI, playlist_id) return self.Get( uri, converter=gdata.youtube.YouTubePlaylistVideoFeedFromString) def GetYouTubeVideoResponseFeed(self, uri=None, video_id=None): """Retrieve a YouTubeVideoResponseFeed. Either a uri or a playlist_id must be provided. Args: uri: An optional string representing the URI of the video response feed that is to be retrieved. video_id: An optional string representing the ID of the video whose response feed is to be retrieved. Returns: A YouTubeVideoResponseFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a video_id to the GetYouTubeVideoResponseFeed() method. """ if uri is None and video_id is None: raise YouTubeError('You must provide at least a uri or a video_id ' 'to the GetYouTubeVideoResponseFeed() method') elif video_id and not uri: uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses') return self.Get( uri, converter=gdata.youtube.YouTubeVideoResponseFeedFromString) def GetYouTubeVideoResponseEntry(self, uri): """Retrieve a YouTubeVideoResponseEntry. Args: uri: A string representing the URI of the video response entry that is to be retrieved. Returns: A YouTubeVideoResponseEntry if successfully retrieved. """ return self.Get( uri, converter=gdata.youtube.YouTubeVideoResponseEntryFromString) def GetYouTubeSubscriptionFeed(self, uri=None, username='default'): """Retrieve a YouTubeSubscriptionFeed. Either the uri of the feed or a username must be provided. Args: uri: An optional string representing the URI of the feed that is to be retrieved. username: An optional string representing the username whose subscription feed is to be retrieved. Defaults to the currently authenticted user. Returns: A YouTubeVideoSubscriptionFeed if successfully retrieved. """ if uri is None: uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'subscriptions') return self.Get( uri, converter=gdata.youtube.YouTubeSubscriptionFeedFromString) def GetYouTubeSubscriptionEntry(self, uri): """Retrieve a YouTubeSubscriptionEntry. Args: uri: A string representing the URI of the entry that is to be retrieved. Returns: A YouTubeVideoSubscriptionEntry if successfully retrieved. """ return self.Get( uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString) def GetYouTubeRelatedVideoFeed(self, uri=None, video_id=None): """Retrieve a YouTubeRelatedVideoFeed. Either a uri for the feed or a video_id is required. Args: uri: An optional string representing the URI of the feed that is to be retrieved. video_id: An optional string representing the ID of the video for which to retrieve the related video feed. Returns: A YouTubeRelatedVideoFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a video_id to the GetYouTubeRelatedVideoFeed() method. """ if uri is None and video_id is None: raise YouTubeError('You must provide at least a uri or a video_id ' 'to the GetYouTubeRelatedVideoFeed() method') elif video_id and not uri: uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'related') return self.Get( uri, converter=gdata.youtube.YouTubeVideoFeedFromString) def GetTopRatedVideoFeed(self): """Retrieve the 'top_rated' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_RATED_URI) def GetMostViewedVideoFeed(self): """Retrieve the 'most_viewed' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_VIEWED_URI) def GetRecentlyFeaturedVideoFeed(self): """Retrieve the 'recently_featured' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_RECENTLY_FEATURED_URI) def GetWatchOnMobileVideoFeed(self): """Retrieve the 'watch_on_mobile' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_WATCH_ON_MOBILE_URI) def GetTopFavoritesVideoFeed(self): """Retrieve the 'top_favorites' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_TOP_FAVORITES_URI) def GetMostRecentVideoFeed(self): """Retrieve the 'most_recent' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RECENT_URI) def GetMostDiscussedVideoFeed(self): """Retrieve the 'most_discussed' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_DISCUSSED_URI) def GetMostLinkedVideoFeed(self): """Retrieve the 'most_linked' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_LINKED_URI) def GetMostRespondedVideoFeed(self): """Retrieve the 'most_responded' standard video feed. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.GetYouTubeVideoFeed(YOUTUBE_STANDARD_MOST_RESPONDED_URI) def GetUserFavoritesFeed(self, username='default'): """Retrieve the favorites feed for a given user. Args: username: An optional string representing the username whose favorites feed is to be retrieved. Defaults to the currently authenticated user. Returns: A YouTubeVideoFeed if successfully retrieved. """ favorites_feed_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites') return self.GetYouTubeVideoFeed(favorites_feed_uri) def InsertVideoEntry(self, video_entry, filename_or_handle, youtube_username='default', content_type='video/quicktime'): """Upload a new video to YouTube using the direct upload mechanism. Needs authentication. Args: video_entry: The YouTubeVideoEntry to upload. filename_or_handle: A file-like object or file name where the video will be read from. youtube_username: An optional string representing the username into whose account this video is to be uploaded to. Defaults to the currently authenticated user. content_type: An optional string representing internet media type (a.k.a. mime type) of the media object. Currently the YouTube API supports these types: o video/mpeg o video/quicktime o video/x-msvideo o video/mp4 o video/x-flv Returns: The newly created YouTubeVideoEntry if successful. Raises: AssertionError: video_entry must be a gdata.youtube.VideoEntry instance. YouTubeError: An error occurred trying to read the video file provided. gdata.service.RequestError: An error occurred trying to upload the video to the API server. """ # We need to perform a series of checks on the video_entry and on the # file that we plan to upload, such as checking whether we have a valid # video_entry and that the file is the correct type and readable, prior # to performing the actual POST request. try: assert(isinstance(video_entry, gdata.youtube.YouTubeVideoEntry)) except AssertionError: raise YouTubeError({'status':YOUTUBE_INVALID_ARGUMENT, 'body':'`video_entry` must be a gdata.youtube.VideoEntry instance', 'reason':'Found %s, not VideoEntry' % type(video_entry) }) #majtype, mintype = content_type.split('/') # #try: # assert(mintype in YOUTUBE_SUPPORTED_UPLOAD_TYPES) #except (ValueError, AssertionError): # raise YouTubeError({'status':YOUTUBE_INVALID_CONTENT_TYPE, # 'body':'This is not a valid content type: %s' % content_type, # 'reason':'Accepted content types: %s' % # ['video/%s' % (t) for t in YOUTUBE_SUPPORTED_UPLOAD_TYPES]}) if (isinstance(filename_or_handle, (str, unicode)) and os.path.exists(filename_or_handle)): mediasource = gdata.MediaSource() mediasource.setFile(filename_or_handle, content_type) elif hasattr(filename_or_handle, 'read'): import StringIO if hasattr(filename_or_handle, 'seek'): filename_or_handle.seek(0) file_handle = filename_or_handle name = 'video' 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: raise YouTubeError({'status':YOUTUBE_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' % type(filename_or_handle))}) upload_uri = '%s/%s/%s' % (YOUTUBE_UPLOAD_URI, youtube_username, 'uploads') self.additional_headers['Slug'] = mediasource.file_name # Using a nested try statement to retain Python 2.4 compatibility try: try: return self.Post(video_entry, uri=upload_uri, media_source=mediasource, converter=gdata.youtube.YouTubeVideoEntryFromString) except gdata.service.RequestError, e: raise YouTubeError(e.args[0]) finally: del(self.additional_headers['Slug']) def CheckUploadStatus(self, video_entry=None, video_id=None): """Check upload status on a recently uploaded video entry. Needs authentication. Either video_entry or video_id must be provided. Args: video_entry: An optional YouTubeVideoEntry whose upload status to check video_id: An optional string representing the ID of the uploaded video whose status is to be checked. Returns: A tuple containing (video_upload_state, detailed_message) or None if no status information is found. Raises: YouTubeError: You must provide at least a video_entry or a video_id to the CheckUploadStatus() method. """ if video_entry is None and video_id is None: raise YouTubeError('You must provide at least a uri or a video_id ' 'to the CheckUploadStatus() method') elif video_id and not video_entry: video_entry = self.GetYouTubeVideoEntry(video_id=video_id) control = video_entry.control if control is not None: draft = control.draft if draft is not None: if draft.text == 'yes': yt_state = control.extension_elements[0] if yt_state is not None: state_value = yt_state.attributes['name'] message = '' if yt_state.text is not None: message = yt_state.text return (state_value, message) def GetFormUploadToken(self, video_entry, uri=YOUTUBE_UPLOAD_TOKEN_URI): """Receives a YouTube Token and a YouTube PostUrl from a YouTubeVideoEntry. Needs authentication. Args: video_entry: The YouTubeVideoEntry to upload (meta-data only). uri: An optional string representing the URI from where to fetch the token information. Defaults to the YOUTUBE_UPLOADTOKEN_URI. Returns: A tuple containing the URL to which to post your video file, along with the youtube token that must be included with your upload in the form of: (post_url, youtube_token). """ try: response = self.Post(video_entry, uri) except gdata.service.RequestError, e: raise YouTubeError(e.args[0]) tree = ElementTree.fromstring(response) for child in tree: if child.tag == 'url': post_url = child.text elif child.tag == 'token': youtube_token = child.text return (post_url, youtube_token) def UpdateVideoEntry(self, video_entry): """Updates a video entry's meta-data. Needs authentication. Args: video_entry: The YouTubeVideoEntry to update, containing updated meta-data. Returns: An updated YouTubeVideoEntry on success or None. """ for link in video_entry.link: if link.rel == 'edit': edit_uri = link.href return self.Put(video_entry, uri=edit_uri, converter=gdata.youtube.YouTubeVideoEntryFromString) def DeleteVideoEntry(self, video_entry): """Deletes a video entry. Needs authentication. Args: video_entry: The YouTubeVideoEntry to be deleted. Returns: True if entry was deleted successfully. """ for link in video_entry.link: if link.rel == 'edit': edit_uri = link.href return self.Delete(edit_uri) def AddRating(self, rating_value, video_entry): """Add a rating to a video entry. Needs authentication. Args: rating_value: The integer value for the rating (between 1 and 5). video_entry: The YouTubeVideoEntry to be rated. Returns: True if the rating was added successfully. Raises: YouTubeError: rating_value must be between 1 and 5 in AddRating(). """ if rating_value < 1 or rating_value > 5: raise YouTubeError('rating_value must be between 1 and 5 in AddRating()') entry = gdata.GDataEntry() rating = gdata.youtube.Rating(min='1', max='5') rating.extension_attributes['name'] = 'value' rating.extension_attributes['value'] = str(rating_value) entry.extension_elements.append(rating) for link in video_entry.link: if link.rel == YOUTUBE_RATING_LINK_REL: rating_uri = link.href return self.Post(entry, uri=rating_uri) def AddComment(self, comment_text, video_entry): """Add a comment to a video entry. Needs authentication. Note that each comment that is posted must contain the video entry that it is to be posted to. Args: comment_text: A string representing the text of the comment. video_entry: The YouTubeVideoEntry to be commented on. Returns: True if the comment was added successfully. """ content = atom.Content(text=comment_text) comment_entry = gdata.youtube.YouTubeVideoCommentEntry(content=content) comment_post_uri = video_entry.comments.feed_link[0].href return self.Post(comment_entry, uri=comment_post_uri) def AddVideoResponse(self, video_id_to_respond_to, video_response): """Add a video response. Needs authentication. Args: video_id_to_respond_to: A string representing the ID of the video to be responded to. video_response: YouTubeVideoEntry to be posted as a response. Returns: True if video response was posted successfully. """ post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id_to_respond_to, 'responses') return self.Post(video_response, uri=post_uri) def DeleteVideoResponse(self, video_id, response_video_id): """Delete a video response. Needs authentication. Args: video_id: A string representing the ID of video that contains the response. response_video_id: A string representing the ID of the video that was posted as a response. Returns: True if video response was deleted succcessfully. """ delete_uri = '%s/%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'responses', response_video_id) return self.Delete(delete_uri) def AddComplaint(self, complaint_text, complaint_term, video_id): """Add a complaint for a particular video entry. Needs authentication. Args: complaint_text: A string representing the complaint text. complaint_term: A string representing the complaint category term. video_id: A string representing the ID of YouTubeVideoEntry to complain about. Returns: True if posted successfully. Raises: YouTubeError: Your complaint_term is not valid. """ if complaint_term not in YOUTUBE_COMPLAINT_CATEGORY_TERMS: raise YouTubeError('Your complaint_term is not valid') content = atom.Content(text=complaint_text) category = atom.Category(term=complaint_term, scheme=YOUTUBE_COMPLAINT_CATEGORY_SCHEME) complaint_entry = gdata.GDataEntry(content=content, category=[category]) post_uri = '%s/%s/%s' % (YOUTUBE_VIDEO_URI, video_id, 'complaints') return self.Post(complaint_entry, post_uri) def AddVideoEntryToFavorites(self, video_entry, username='default'): """Add a video entry to a users favorite feed. Needs authentication. Args: video_entry: The YouTubeVideoEntry to add. username: An optional string representing the username to whose favorite feed you wish to add the entry. Defaults to the currently authenticated user. Returns: The posted YouTubeVideoEntry if successfully posted. """ post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites') return self.Post(video_entry, post_uri, converter=gdata.youtube.YouTubeVideoEntryFromString) def DeleteVideoEntryFromFavorites(self, video_id, username='default'): """Delete a video entry from the users favorite feed. Needs authentication. Args: video_id: A string representing the ID of the video that is to be removed username: An optional string representing the username of the user's favorite feed. Defaults to the currently authenticated user. Returns: True if entry was successfully deleted. """ edit_link = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'favorites', video_id) return self.Delete(edit_link) def AddPlaylist(self, playlist_title, playlist_description, playlist_private=None): """Add a new playlist to the currently authenticated users account. Needs authentication. Args: playlist_title: A string representing the title for the new playlist. playlist_description: A string representing the description of the playlist. playlist_private: An optional boolean, set to True if the playlist is to be private. Returns: The YouTubePlaylistEntry if successfully posted. """ playlist_entry = gdata.youtube.YouTubePlaylistEntry( title=atom.Title(text=playlist_title), description=gdata.youtube.Description(text=playlist_description)) if playlist_private: playlist_entry.private = gdata.youtube.Private() playlist_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, 'default', 'playlists') return self.Post(playlist_entry, playlist_post_uri, converter=gdata.youtube.YouTubePlaylistEntryFromString) def UpdatePlaylist(self, playlist_id, new_playlist_title, new_playlist_description, playlist_private=None, username='default'): """Update a playlist with new meta-data. Needs authentication. Args: playlist_id: A string representing the ID of the playlist to be updated. new_playlist_title: A string representing a new title for the playlist. new_playlist_description: A string representing a new description for the playlist. playlist_private: An optional boolean, set to True if the playlist is to be private. username: An optional string representing the username whose playlist is to be updated. Defaults to the currently authenticated user. Returns: A YouTubePlaylistEntry if the update was successful. """ updated_playlist = gdata.youtube.YouTubePlaylistEntry( title=atom.Title(text=new_playlist_title), description=gdata.youtube.Description(text=new_playlist_description)) if playlist_private: updated_playlist.private = gdata.youtube.Private() playlist_put_uri = '%s/%s/playlists/%s' % (YOUTUBE_USER_FEED_URI, username, playlist_id) return self.Put(updated_playlist, playlist_put_uri, converter=gdata.youtube.YouTubePlaylistEntryFromString) def DeletePlaylist(self, playlist_uri): """Delete a playlist from the currently authenticated users playlists. Needs authentication. Args: playlist_uri: A string representing the URI of the playlist that is to be deleted. Returns: True if successfully deleted. """ return self.Delete(playlist_uri) def AddPlaylistVideoEntryToPlaylist( self, playlist_uri, video_id, custom_video_title=None, custom_video_description=None): """Add a video entry to a playlist, optionally providing a custom title and description. Needs authentication. Args: playlist_uri: A string representing the URI of the playlist to which this video entry is to be added. video_id: A string representing the ID of the video entry to add. custom_video_title: An optional string representing a custom title for the video (only shown on the playlist). custom_video_description: An optional string representing a custom description for the video (only shown on the playlist). Returns: A YouTubePlaylistVideoEntry if successfully posted. """ playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry( atom_id=atom.Id(text=video_id)) if custom_video_title: playlist_video_entry.title = atom.Title(text=custom_video_title) if custom_video_description: playlist_video_entry.description = gdata.youtube.Description( text=custom_video_description) return self.Post(playlist_video_entry, playlist_uri, converter=gdata.youtube.YouTubePlaylistVideoEntryFromString) def UpdatePlaylistVideoEntryMetaData( self, playlist_uri, playlist_entry_id, new_video_title, new_video_description, new_video_position): """Update the meta data for a YouTubePlaylistVideoEntry. Needs authentication. Args: playlist_uri: A string representing the URI of the playlist that contains the entry to be updated. playlist_entry_id: A string representing the ID of the entry to be updated. new_video_title: A string representing the new title for the video entry. new_video_description: A string representing the new description for the video entry. new_video_position: An integer representing the new position on the playlist for the video. Returns: A YouTubePlaylistVideoEntry if the update was successful. """ playlist_video_entry = gdata.youtube.YouTubePlaylistVideoEntry( title=atom.Title(text=new_video_title), description=gdata.youtube.Description(text=new_video_description), position=gdata.youtube.Position(text=str(new_video_position))) playlist_put_uri = playlist_uri + '/' + playlist_entry_id return self.Put(playlist_video_entry, playlist_put_uri, converter=gdata.youtube.YouTubePlaylistVideoEntryFromString) def DeletePlaylistVideoEntry(self, playlist_uri, playlist_video_entry_id): """Delete a playlist video entry from a playlist. Needs authentication. Args: playlist_uri: A URI representing the playlist from which the playlist video entry is to be removed from. playlist_video_entry_id: A string representing id of the playlist video entry that is to be removed. Returns: True if entry was successfully deleted. """ delete_uri = '%s/%s' % (playlist_uri, playlist_video_entry_id) return self.Delete(delete_uri) def AddSubscriptionToChannel(self, username_to_subscribe_to, my_username = 'default'): """Add a new channel subscription to the currently authenticated users account. Needs authentication. Args: username_to_subscribe_to: A string representing the username of the channel to which we want to subscribe to. my_username: An optional string representing the name of the user which we want to subscribe. Defaults to currently authenticated user. Returns: A new YouTubeSubscriptionEntry if successfully posted. """ subscription_category = atom.Category( scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME, term='channel') subscription_username = gdata.youtube.Username( text=username_to_subscribe_to) subscription_entry = gdata.youtube.YouTubeSubscriptionEntry( category=subscription_category, username=subscription_username) post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'subscriptions') return self.Post(subscription_entry, post_uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString) def AddSubscriptionToFavorites(self, username, my_username = 'default'): """Add a new subscription to a users favorites to the currently authenticated user's account. Needs authentication Args: username: A string representing the username of the user's favorite feed to subscribe to. my_username: An optional string representing the username of the user that is to be subscribed. Defaults to currently authenticated user. Returns: A new YouTubeSubscriptionEntry if successful. """ subscription_category = atom.Category( scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME, term='favorites') subscription_username = gdata.youtube.Username(text=username) subscription_entry = gdata.youtube.YouTubeSubscriptionEntry( category=subscription_category, username=subscription_username) post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'subscriptions') return self.Post(subscription_entry, post_uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString) def AddSubscriptionToQuery(self, query, my_username = 'default'): """Add a new subscription to a specific keyword query to the currently authenticated user's account. Needs authentication Args: query: A string representing the keyword query to subscribe to. my_username: An optional string representing the username of the user that is to be subscribed. Defaults to currently authenticated user. Returns: A new YouTubeSubscriptionEntry if successful. """ subscription_category = atom.Category( scheme=YOUTUBE_SUBSCRIPTION_CATEGORY_SCHEME, term='query') subscription_query_string = gdata.youtube.QueryString(text=query) subscription_entry = gdata.youtube.YouTubeSubscriptionEntry( category=subscription_category, query_string=subscription_query_string) post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'subscriptions') return self.Post(subscription_entry, post_uri, converter=gdata.youtube.YouTubeSubscriptionEntryFromString) def DeleteSubscription(self, subscription_uri): """Delete a subscription from the currently authenticated user's account. Needs authentication. Args: subscription_uri: A string representing the URI of the subscription that is to be deleted. Returns: True if deleted successfully. """ return self.Delete(subscription_uri) def AddContact(self, contact_username, my_username='default'): """Add a new contact to the currently authenticated user's contact feed. Needs authentication. Args: contact_username: A string representing the username of the contact that you wish to add. my_username: An optional string representing the username to whose contact the new contact is to be added. Returns: A YouTubeContactEntry if added successfully. """ contact_category = atom.Category( scheme = 'http://gdata.youtube.com/schemas/2007/contact.cat', term = 'Friends') contact_username = gdata.youtube.Username(text=contact_username) contact_entry = gdata.youtube.YouTubeContactEntry( category=contact_category, username=contact_username) contact_post_uri = '%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'contacts') return self.Post(contact_entry, contact_post_uri, converter=gdata.youtube.YouTubeContactEntryFromString) def UpdateContact(self, contact_username, new_contact_status, new_contact_category, my_username='default'): """Update a contact, providing a new status and a new category. Needs authentication. Args: contact_username: A string representing the username of the contact that is to be updated. new_contact_status: A string representing the new status of the contact. This can either be set to 'accepted' or 'rejected'. new_contact_category: A string representing the new category for the contact, either 'Friends' or 'Family'. my_username: An optional string representing the username of the user whose contact feed we are modifying. Defaults to the currently authenticated user. Returns: A YouTubeContactEntry if updated succesfully. Raises: YouTubeError: New contact status must be within the accepted values. Or new contact category must be within the accepted categories. """ if new_contact_status not in YOUTUBE_CONTACT_STATUS: raise YouTubeError('New contact status must be one of %s' % (' '.join(YOUTUBE_CONTACT_STATUS))) if new_contact_category not in YOUTUBE_CONTACT_CATEGORY: raise YouTubeError('New contact category must be one of %s' % (' '.join(YOUTUBE_CONTACT_CATEGORY))) contact_category = atom.Category( scheme='http://gdata.youtube.com/schemas/2007/contact.cat', term=new_contact_category) contact_status = gdata.youtube.Status(text=new_contact_status) contact_entry = gdata.youtube.YouTubeContactEntry( category=contact_category, status=contact_status) contact_put_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'contacts', contact_username) return self.Put(contact_entry, contact_put_uri, converter=gdata.youtube.YouTubeContactEntryFromString) def DeleteContact(self, contact_username, my_username='default'): """Delete a contact from a users contact feed. Needs authentication. Args: contact_username: A string representing the username of the contact that is to be deleted. my_username: An optional string representing the username of the user's contact feed from which to delete the contact. Defaults to the currently authenticated user. Returns: True if the contact was deleted successfully """ contact_edit_uri = '%s/%s/%s/%s' % (YOUTUBE_USER_FEED_URI, my_username, 'contacts', contact_username) return self.Delete(contact_edit_uri) def _GetDeveloperKey(self): """Getter for Developer Key property. Returns: If the developer key has been set, a string representing the developer key is returned or None. """ if 'X-GData-Key' in self.additional_headers: return self.additional_headers['X-GData-Key'][4:] else: return None def _SetDeveloperKey(self, developer_key): """Setter for Developer Key property. Sets the developer key in the 'X-GData-Key' header. The actual value that is set is 'key=' plus the developer_key that was passed. """ self.additional_headers['X-GData-Key'] = 'key=' + developer_key developer_key = property(_GetDeveloperKey, _SetDeveloperKey, doc="""The Developer Key property""") def _GetClientId(self): """Getter for Client Id property. Returns: If the client_id has been set, a string representing it is returned or None. """ if 'X-Gdata-Client' in self.additional_headers: return self.additional_headers['X-Gdata-Client'] else: return None def _SetClientId(self, client_id): """Setter for Client Id property. Sets the 'X-Gdata-Client' header. """ self.additional_headers['X-Gdata-Client'] = client_id client_id = property(_GetClientId, _SetClientId, doc="""The ClientId property""") def Query(self, uri): """Performs a query and returns a resulting feed or entry. Args: uri: A string representing the URI of the feed that is to be queried. Returns: On success, a tuple in the form: (boolean succeeded=True, ElementTree._Element result) On failure, a tuple in the form: (boolean succeeded=False, {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response}) """ result = self.Get(uri) return result def YouTubeQuery(self, query): """Performs a YouTube specific query and returns a resulting feed or entry. Args: query: A Query object or one if its sub-classes (YouTubeVideoQuery, YouTubeUserQuery or YouTubePlaylistQuery). Returns: Depending on the type of Query object submitted returns either a YouTubeVideoFeed, a YouTubeUserFeed, a YouTubePlaylistFeed. If the Query object provided was not YouTube-related, a tuple is returned. On success the tuple will be in this form: (boolean succeeded=True, ElementTree._Element result) On failure, the tuple will be in this form: (boolean succeeded=False, {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server response}) """ result = self.Query(query.ToUri()) if isinstance(query, YouTubeUserQuery): return gdata.youtube.YouTubeUserFeedFromString(result.ToString()) elif isinstance(query, YouTubePlaylistQuery): return gdata.youtube.YouTubePlaylistFeedFromString(result.ToString()) elif isinstance(query, YouTubeVideoQuery): return gdata.youtube.YouTubeVideoFeedFromString(result.ToString()) else: return result class YouTubeVideoQuery(gdata.service.Query): """Subclasses gdata.service.Query to represent a YouTube Data API query. Attributes are set dynamically via properties. Properties correspond to the standard Google Data API query parameters with YouTube Data API extensions. Please refer to the API documentation for details. Attributes: vq: The vq parameter, which is only supported for video feeds, specifies a search query term. Refer to API documentation for further details. orderby: The orderby parameter, which is only supported for video feeds, specifies the value that will be used to sort videos in the search result set. Valid values for this parameter are relevance, published, viewCount and rating. time: The time parameter, which is only available for the top_rated, top_favorites, most_viewed, most_discussed, most_linked and most_responded standard feeds, restricts the search to videos uploaded within the specified time. Valid values for this parameter are today (1 day), this_week (7 days), this_month (1 month) and all_time. The default value for this parameter is all_time. format: The format parameter specifies that videos must be available in a particular video format. Refer to the API documentation for details. racy: The racy parameter allows a search result set to include restricted content as well as standard content. Valid values for this parameter are include and exclude. By default, restricted content is excluded. lr: The lr parameter restricts the search to videos that have a title, description or keywords in a specific language. Valid values for the lr parameter are ISO 639-1 two-letter language codes. restriction: The restriction parameter identifies the IP address that should be used to filter videos that can only be played in specific countries. location: A string of geo coordinates. Note that this is not used when the search is performed but rather to filter the returned videos for ones that match to the location entered. feed: str (optional) The base URL which is the beginning of the query URL. defaults to 'http://%s/feeds/videos' % (YOUTUBE_SERVER) """ def __init__(self, video_id=None, feed_type=None, text_query=None, params=None, categories=None, feed=None): if feed_type in YOUTUBE_STANDARDFEEDS and feed is None: feed = 'http://%s/feeds/standardfeeds/%s' % (YOUTUBE_SERVER, feed_type) elif (feed_type is 'responses' or feed_type is 'comments' and video_id and feed is None): feed = 'http://%s/feeds/videos/%s/%s' % (YOUTUBE_SERVER, video_id, feed_type) elif feed is None: feed = 'http://%s/feeds/videos' % (YOUTUBE_SERVER) gdata.service.Query.__init__(self, feed, text_query=text_query, params=params, categories=categories) def _GetVideoQuery(self): if 'vq' in self: return self['vq'] else: return None def _SetVideoQuery(self, val): self['vq'] = val vq = property(_GetVideoQuery, _SetVideoQuery, doc="""The video query (vq) query parameter""") def _GetOrderBy(self): if 'orderby' in self: return self['orderby'] else: return None def _SetOrderBy(self, val): if val not in YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS: if val.startswith('relevance_lang_') is False: raise YouTubeError('OrderBy must be one of: %s ' % ' '.join(YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS)) self['orderby'] = val orderby = property(_GetOrderBy, _SetOrderBy, doc="""The orderby query parameter""") def _GetTime(self): if 'time' in self: return self['time'] else: return None def _SetTime(self, val): if val not in YOUTUBE_QUERY_VALID_TIME_PARAMETERS: raise YouTubeError('Time must be one of: %s ' % ' '.join(YOUTUBE_QUERY_VALID_TIME_PARAMETERS)) self['time'] = val time = property(_GetTime, _SetTime, doc="""The time query parameter""") def _GetFormat(self): if 'format' in self: return self['format'] else: return None def _SetFormat(self, val): if val not in YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS: raise YouTubeError('Format must be one of: %s ' % ' '.join(YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS)) self['format'] = val format = property(_GetFormat, _SetFormat, doc="""The format query parameter""") def _GetRacy(self): if 'racy' in self: return self['racy'] else: return None def _SetRacy(self, val): if val not in YOUTUBE_QUERY_VALID_RACY_PARAMETERS: raise YouTubeError('Racy must be one of: %s ' % ' '.join(YOUTUBE_QUERY_VALID_RACY_PARAMETERS)) self['racy'] = val racy = property(_GetRacy, _SetRacy, doc="""The racy query parameter""") def _GetLanguageRestriction(self): if 'lr' in self: return self['lr'] else: return None def _SetLanguageRestriction(self, val): self['lr'] = val lr = property(_GetLanguageRestriction, _SetLanguageRestriction, doc="""The lr (language restriction) query parameter""") def _GetIPRestriction(self): if 'restriction' in self: return self['restriction'] else: return None def _SetIPRestriction(self, val): self['restriction'] = val restriction = property(_GetIPRestriction, _SetIPRestriction, doc="""The restriction query parameter""") def _GetLocation(self): if 'location' in self: return self['location'] else: return None def _SetLocation(self, val): self['location'] = val location = property(_GetLocation, _SetLocation, doc="""The location query parameter""") class YouTubeUserQuery(YouTubeVideoQuery): """Subclasses YouTubeVideoQuery to perform user-specific queries. Attributes are set dynamically via properties. Properties correspond to the standard Google Data API query parameters with YouTube Data API extensions. """ def __init__(self, username=None, feed_type=None, subscription_id=None, text_query=None, params=None, categories=None): uploads_favorites_playlists = ('uploads', 'favorites', 'playlists') if feed_type is 'subscriptions' and subscription_id and username: feed = "http://%s/feeds/users/%s/%s/%s" % (YOUTUBE_SERVER, username, feed_type, subscription_id) elif feed_type is 'subscriptions' and not subscription_id and username: feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username, feed_type) elif feed_type in uploads_favorites_playlists: feed = "http://%s/feeds/users/%s/%s" % (YOUTUBE_SERVER, username, feed_type) else: feed = "http://%s/feeds/users" % (YOUTUBE_SERVER) YouTubeVideoQuery.__init__(self, feed=feed, text_query=text_query, params=params, categories=categories) class YouTubePlaylistQuery(YouTubeVideoQuery): """Subclasses YouTubeVideoQuery to perform playlist-specific queries. Attributes are set dynamically via properties. Properties correspond to the standard Google Data API query parameters with YouTube Data API extensions. """ def __init__(self, playlist_id, text_query=None, params=None, categories=None): if playlist_id: feed = "http://%s/feeds/playlists/%s" % (YOUTUBE_SERVER, playlist_id) else: feed = "http://%s/feeds/playlists" % (YOUTUBE_SERVER) YouTubeVideoQuery.__init__(self, feed=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. """Contains a client to communicate with the YouTube servers. A quick and dirty port of the YouTube GDATA 1.0 Python client libraries to version 2.0 of the GDATA library. """ # __author__ = 's.@google.com (John Skidgel)' import logging import gdata.client import gdata.youtube.data import atom.data import atom.http_core # Constants # ----------------------------------------------------------------------------- YOUTUBE_CLIENTLOGIN_AUTHENTICATION_URL = 'https://www.google.com/youtube/accounts/ClientLogin' YOUTUBE_SUPPORTED_UPLOAD_TYPES = ('mov', 'avi', 'wmv', 'mpg', 'quicktime', 'flv') YOUTUBE_QUERY_VALID_TIME_PARAMETERS = ('today', 'this_week', 'this_month', 'all_time') YOUTUBE_QUERY_VALID_ORDERBY_PARAMETERS = ('published', 'viewCount', 'rating', 'relevance') YOUTUBE_QUERY_VALID_RACY_PARAMETERS = ('include', 'exclude') YOUTUBE_QUERY_VALID_FORMAT_PARAMETERS = ('1', '5', '6') YOUTUBE_STANDARDFEEDS = ('most_recent', 'recently_featured', 'top_rated', 'most_viewed','watch_on_mobile') YOUTUBE_UPLOAD_TOKEN_URI = 'http://gdata.youtube.com/action/GetUploadToken' YOUTUBE_SERVER = 'gdata.youtube.com/feeds/api' YOUTUBE_SERVICE = 'youtube' YOUTUBE_VIDEO_FEED_URI = 'http://%s/videos' % YOUTUBE_SERVER YOUTUBE_USER_FEED_URI = 'http://%s/users/' % YOUTUBE_SERVER # Takes a youtube video ID. YOUTUBE_CAPTION_FEED_URI = 'http://gdata.youtube.com/feeds/api/videos/%s/captions' # Takes a youtube video ID and a caption track ID. YOUTUBE_CAPTION_URI = 'http://gdata.youtube.com/feeds/api/videos/%s/captiondata/%s' YOUTUBE_CAPTION_MIME_TYPE = 'application/vnd.youtube.timedtext; charset=UTF-8' # Classes # ----------------------------------------------------------------------------- class Error(Exception): """Base class for errors within the YouTube service.""" pass class RequestError(Error): """Error class that is thrown in response to an invalid HTTP Request.""" pass class YouTubeError(Error): """YouTube service specific error class.""" pass class YouTubeClient(gdata.client.GDClient): """Client for the YouTube service. Performs a partial list of Google Data YouTube API functions, such as retrieving the videos feed for a user and the feed for a video. YouTube Service requires authentication for any write, update or delete actions. """ api_version = '2' auth_service = YOUTUBE_SERVICE auth_scopes = ['http://%s' % YOUTUBE_SERVER, 'https://%s' % YOUTUBE_SERVER] def get_videos(self, uri=YOUTUBE_VIDEO_FEED_URI, auth_token=None, desired_class=gdata.youtube.data.VideoFeed, **kwargs): """Retrieves a YouTube video feed. Args: uri: A string representing the URI of the feed that is to be retrieved. Returns: A YouTubeVideoFeed if successfully retrieved. """ return self.get_feed(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetVideos = get_videos def get_user_feed(self, uri=None, username=None): """Retrieve a YouTubeVideoFeed of user uploaded videos. Either a uri or a username must be provided. This will retrieve list of videos uploaded by specified user. The uri will be of format "http://gdata.youtube.com/feeds/api/users/{username}/uploads". Args: uri: An optional string representing the URI of the user feed that is to be retrieved. username: An optional string representing the username. Returns: A YouTubeUserFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a username to the GetYouTubeUserFeed() method. """ if uri is None and username is None: raise YouTubeError('You must provide at least a uri or a username ' 'to the GetYouTubeUserFeed() method') elif username and not uri: uri = '%s%s/%s' % (YOUTUBE_USER_FEED_URI, username, 'uploads') return self.get_feed(uri, desired_class=gdata.youtube.data.VideoFeed) GetUserFeed = get_user_feed def get_video_entry(self, uri=None, video_id=None, auth_token=None, **kwargs): """Retrieve a YouTubeVideoEntry. Either a uri or a video_id must be provided. Args: uri: An optional string representing the URI of the entry that is to be retrieved. video_id: An optional string representing the ID of the video. Returns: A YouTubeVideoFeed if successfully retrieved. Raises: YouTubeError: You must provide at least a uri or a video_id to the GetYouTubeVideoEntry() method. """ if uri is None and video_id is None: raise YouTubeError('You must provide at least a uri or a video_id ' 'to the get_youtube_video_entry() method') elif video_id and uri is None: uri = '%s/%s' % (YOUTUBE_VIDEO_FEED_URI, video_id) return self.get_feed(uri, desired_class=gdata.youtube.data.VideoEntry, auth_token=auth_token, **kwargs) GetVideoEntry = get_video_entry def get_caption_feed(self, uri): """Retrieve a Caption feed of tracks. Args: uri: A string representing the caption feed's URI to be retrieved. Returns: A YouTube CaptionFeed if successfully retrieved. """ return self.get_feed(uri, desired_class=gdata.youtube.data.CaptionFeed) GetCaptionFeed = get_caption_feed def get_caption_track(self, track_url, client_id, developer_key, auth_token=None, **kwargs): http_request = atom.http_core.HttpRequest(uri = track_url, method = 'GET') dev_key = 'key=' + developer_key authsub = 'AuthSub token="' + str(auth_token) + '"' http_request.headers = { 'Authorization': authsub, 'X-GData-Client': client_id, 'X-GData-Key': dev_key } return self.request(http_request=http_request, **kwargs) GetCaptionTrack = get_caption_track def create_track(self, video_id, title, language, body, client_id, developer_key, auth_token=None, title_type='text', **kwargs): """Creates a closed-caption track and adds to an existing YouTube video. """ new_entry = gdata.youtube.data.TrackEntry( content = gdata.youtube.data.TrackContent(text = body, lang = language)) uri = YOUTUBE_CAPTION_FEED_URI % video_id http_request = atom.http_core.HttpRequest(uri = uri, method = 'POST') dev_key = 'key=' + developer_key authsub = 'AuthSub token="' + str(auth_token) + '"' http_request.headers = { 'Content-Type': YOUTUBE_CAPTION_MIME_TYPE, 'Content-Language': language, 'Slug': title, 'Authorization': authsub, 'GData-Version': self.api_version, 'X-GData-Client': client_id, 'X-GData-Key': dev_key } http_request.add_body_part(body, http_request.headers['Content-Type']) return self.request(http_request = http_request, desired_class = new_entry.__class__, **kwargs) CreateTrack = create_track def delete_track(self, video_id, track, client_id, developer_key, auth_token=None, **kwargs): """Deletes a track.""" if isinstance(track, gdata.youtube.data.TrackEntry): track_id_text_node = track.get_id().split(':') track_id = track_id_text_node[3] else: track_id = track uri = YOUTUBE_CAPTION_URI % (video_id, track_id) http_request = atom.http_core.HttpRequest(uri = uri, method = 'DELETE') dev_key = 'key=' + developer_key authsub = 'AuthSub token="' + str(auth_token) + '"' http_request.headers = { 'Authorization': authsub, 'GData-Version': self.api_version, 'X-GData-Client': client_id, 'X-GData-Key': dev_key } return self.request(http_request=http_request, **kwargs) DeleteTrack = delete_track def update_track(self, video_id, track, body, client_id, developer_key, auth_token=None, **kwargs): """Updates a closed-caption track for an existing YouTube video. """ track_id_text_node = track.get_id().split(':') track_id = track_id_text_node[3] uri = YOUTUBE_CAPTION_URI % (video_id, track_id) http_request = atom.http_core.HttpRequest(uri = uri, method = 'PUT') dev_key = 'key=' + developer_key authsub = 'AuthSub token="' + str(auth_token) + '"' http_request.headers = { 'Content-Type': YOUTUBE_CAPTION_MIME_TYPE, 'Authorization': authsub, 'GData-Version': self.api_version, 'X-GData-Client': client_id, 'X-GData-Key': dev_key } http_request.add_body_part(body, http_request.headers['Content-Type']) return self.request(http_request = http_request, desired_class = track.__class__, **kwargs) UpdateTrack = update_track
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 YouTube Data API""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import atom.data import gdata.data import gdata.geo.data import gdata.media.data import gdata.opensearch.data import gdata.youtube.data YT_TEMPLATE = '{http://gdata.youtube.com/schemas/2007/}%s' class ComplaintEntry(gdata.data.GDEntry): """Describes a complaint about a video""" class ComplaintFeed(gdata.data.GDFeed): """Describes complaints about a video""" entry = [ComplaintEntry] class RatingEntry(gdata.data.GDEntry): """A rating about a video""" rating = gdata.data.Rating class RatingFeed(gdata.data.GDFeed): """Describes ratings for a video""" entry = [RatingEntry] class YouTubeMediaContent(gdata.media.data.MediaContent): """Describes a you tube media content""" _qname = gdata.media.data.MEDIA_TEMPLATE % 'content' format = 'format' class YtAge(atom.core.XmlElement): """User's age""" _qname = YT_TEMPLATE % 'age' class YtBooks(atom.core.XmlElement): """User's favorite books""" _qname = YT_TEMPLATE % 'books' class YtCompany(atom.core.XmlElement): """User's company""" _qname = YT_TEMPLATE % 'company' class YtDescription(atom.core.XmlElement): """Description""" _qname = YT_TEMPLATE % 'description' class YtDuration(atom.core.XmlElement): """Video duration""" _qname = YT_TEMPLATE % 'duration' seconds = 'seconds' class YtFirstName(atom.core.XmlElement): """User's first name""" _qname = YT_TEMPLATE % 'firstName' class YtGender(atom.core.XmlElement): """User's gender""" _qname = YT_TEMPLATE % 'gender' class YtHobbies(atom.core.XmlElement): """User's hobbies""" _qname = YT_TEMPLATE % 'hobbies' class YtHometown(atom.core.XmlElement): """User's hometown""" _qname = YT_TEMPLATE % 'hometown' class YtLastName(atom.core.XmlElement): """User's last name""" _qname = YT_TEMPLATE % 'lastName' class YtLocation(atom.core.XmlElement): """Location""" _qname = YT_TEMPLATE % 'location' class YtMovies(atom.core.XmlElement): """User's favorite movies""" _qname = YT_TEMPLATE % 'movies' class YtMusic(atom.core.XmlElement): """User's favorite music""" _qname = YT_TEMPLATE % 'music' class YtNoEmbed(atom.core.XmlElement): """Disables embedding for the video""" _qname = YT_TEMPLATE % 'noembed' class YtOccupation(atom.core.XmlElement): """User's occupation""" _qname = YT_TEMPLATE % 'occupation' class YtPlaylistId(atom.core.XmlElement): """Playlist id""" _qname = YT_TEMPLATE % 'playlistId' class YtPosition(atom.core.XmlElement): """Video position on the playlist""" _qname = YT_TEMPLATE % 'position' class YtPrivate(atom.core.XmlElement): """Flags the entry as private""" _qname = YT_TEMPLATE % 'private' class YtQueryString(atom.core.XmlElement): """Keywords or query string associated with a subscription""" _qname = YT_TEMPLATE % 'queryString' class YtRacy(atom.core.XmlElement): """Mature content""" _qname = YT_TEMPLATE % 'racy' class YtRecorded(atom.core.XmlElement): """Date when the video was recorded""" _qname = YT_TEMPLATE % 'recorded' class YtRelationship(atom.core.XmlElement): """User's relationship status""" _qname = YT_TEMPLATE % 'relationship' class YtSchool(atom.core.XmlElement): """User's school""" _qname = YT_TEMPLATE % 'school' class YtStatistics(atom.core.XmlElement): """Video and user statistics""" _qname = YT_TEMPLATE % 'statistics' favorite_count = 'favoriteCount' video_watch_count = 'videoWatchCount' view_count = 'viewCount' last_web_access = 'lastWebAccess' subscriber_count = 'subscriberCount' class YtStatus(atom.core.XmlElement): """Status of a contact""" _qname = YT_TEMPLATE % 'status' class YtUserProfileStatistics(YtStatistics): """User statistics""" _qname = YT_TEMPLATE % 'statistics' class YtUsername(atom.core.XmlElement): """Youtube username""" _qname = YT_TEMPLATE % 'username' class FriendEntry(gdata.data.BatchEntry): """Describes a contact in friend list""" username = YtUsername status = YtStatus email = gdata.data.Email class FriendFeed(gdata.data.BatchFeed): """Describes user's friends""" entry = [FriendEntry] class YtVideoStatistics(YtStatistics): """Video statistics""" _qname = YT_TEMPLATE % 'statistics' class ChannelEntry(gdata.data.GDEntry): """Describes a video channel""" class ChannelFeed(gdata.data.GDFeed): """Describes channels""" entry = [ChannelEntry] class FavoriteEntry(gdata.data.BatchEntry): """Describes a favorite video""" class FavoriteFeed(gdata.data.BatchFeed): """Describes favorite videos""" entry = [FavoriteEntry] class YouTubeMediaCredit(gdata.media.data.MediaCredit): """Describes a you tube media credit""" _qname = gdata.media.data.MEDIA_TEMPLATE % 'credit' type = 'type' class YouTubeMediaRating(gdata.media.data.MediaRating): """Describes a you tube media rating""" _qname = gdata.media.data.MEDIA_TEMPLATE % 'rating' country = 'country' class YtAboutMe(atom.core.XmlElement): """User's self description""" _qname = YT_TEMPLATE % 'aboutMe' class UserProfileEntry(gdata.data.BatchEntry): """Describes an user's profile""" relationship = YtRelationship description = YtDescription location = YtLocation statistics = YtUserProfileStatistics school = YtSchool music = YtMusic first_name = YtFirstName gender = YtGender occupation = YtOccupation hometown = YtHometown company = YtCompany movies = YtMovies books = YtBooks username = YtUsername about_me = YtAboutMe last_name = YtLastName age = YtAge thumbnail = gdata.media.data.MediaThumbnail hobbies = YtHobbies class UserProfileFeed(gdata.data.BatchFeed): """Describes a feed of user's profile""" entry = [UserProfileEntry] class YtAspectRatio(atom.core.XmlElement): """The aspect ratio of a media file""" _qname = YT_TEMPLATE % 'aspectRatio' class YtBasePublicationState(atom.core.XmlElement): """Status of an unpublished entry""" _qname = YT_TEMPLATE % 'state' help_url = 'helpUrl' class YtPublicationState(YtBasePublicationState): """Status of an unpublished video""" _qname = YT_TEMPLATE % 'state' name = 'name' reason_code = 'reasonCode' class YouTubeAppControl(atom.data.Control): """Describes a you tube app control""" _qname = (atom.data.APP_TEMPLATE_V1 % 'control', atom.data.APP_TEMPLATE_V2 % 'control') state = YtPublicationState class YtCaptionPublicationState(YtBasePublicationState): """Status of an unpublished caption track""" _qname = YT_TEMPLATE % 'state' reason_code = 'reasonCode' name = 'name' class YouTubeCaptionAppControl(atom.data.Control): """Describes a you tube caption app control""" _qname = atom.data.APP_TEMPLATE_V2 % 'control' state = YtCaptionPublicationState class CaptionTrackEntry(gdata.data.GDEntry): """Describes a caption track""" class CaptionTrackFeed(gdata.data.GDFeed): """Describes caption tracks""" entry = [CaptionTrackEntry] class YtCountHint(atom.core.XmlElement): """Hint as to how many entries the linked feed contains""" _qname = YT_TEMPLATE % 'countHint' class PlaylistLinkEntry(gdata.data.BatchEntry): """Describes a playlist""" description = YtDescription playlist_id = YtPlaylistId count_hint = YtCountHint private = YtPrivate class PlaylistLinkFeed(gdata.data.BatchFeed): """Describes list of playlists""" entry = [PlaylistLinkEntry] class YtModerationStatus(atom.core.XmlElement): """Moderation status""" _qname = YT_TEMPLATE % 'moderationStatus' class YtPlaylistTitle(atom.core.XmlElement): """Playlist title""" _qname = YT_TEMPLATE % 'playlistTitle' class SubscriptionEntry(gdata.data.BatchEntry): """Describes user's channel subscritpions""" count_hint = YtCountHint playlist_title = YtPlaylistTitle thumbnail = gdata.media.data.MediaThumbnail username = YtUsername query_string = YtQueryString playlist_id = YtPlaylistId class SubscriptionFeed(gdata.data.BatchFeed): """Describes list of user's video subscriptions""" entry = [SubscriptionEntry] class YtSpam(atom.core.XmlElement): """Indicates that the entry probably contains spam""" _qname = YT_TEMPLATE % 'spam' class CommentEntry(gdata.data.BatchEntry): """Describes a comment for a video""" spam = YtSpam class CommentFeed(gdata.data.BatchFeed): """Describes comments for a video""" entry = [CommentEntry] class YtUploaded(atom.core.XmlElement): """Date/Time at which the video was uploaded""" _qname = YT_TEMPLATE % 'uploaded' class YtVideoId(atom.core.XmlElement): """Video id""" _qname = YT_TEMPLATE % 'videoid' class YouTubeMediaGroup(gdata.media.data.MediaGroup): """Describes a you tube media group""" _qname = gdata.media.data.MEDIA_TEMPLATE % 'group' videoid = YtVideoId private = YtPrivate duration = YtDuration aspect_ratio = YtAspectRatio uploaded = YtUploaded class VideoEntryBase(gdata.data.GDEntry): """Elements that describe or contain videos""" group = YouTubeMediaGroup statistics = YtVideoStatistics racy = YtRacy recorded = YtRecorded where = gdata.geo.data.GeoRssWhere rating = gdata.data.Rating noembed = YtNoEmbed location = YtLocation comments = gdata.data.Comments class PlaylistEntry(gdata.data.BatchEntry): """Describes a video in a playlist""" description = YtDescription position = YtPosition class PlaylistFeed(gdata.data.BatchFeed): """Describes videos in a playlist""" private = YtPrivate group = YouTubeMediaGroup playlist_id = YtPlaylistId entry = [PlaylistEntry] class VideoEntry(gdata.data.BatchEntry): """Describes a video""" class VideoFeed(gdata.data.BatchFeed): """Describes a video feed""" entry = [VideoEntry] class VideoMessageEntry(gdata.data.BatchEntry): """Describes a video message""" description = YtDescription class VideoMessageFeed(gdata.data.BatchFeed): """Describes videos in a videoMessage""" entry = [VideoMessageEntry] class UserEventEntry(gdata.data.GDEntry): """Describes a user event""" playlist_id = YtPlaylistId videoid = YtVideoId username = YtUsername query_string = YtQueryString rating = gdata.data.Rating class UserEventFeed(gdata.data.GDFeed): """Describes list of events""" entry = [UserEventEntry] class VideoModerationEntry(gdata.data.GDEntry): """Describes video moderation""" moderation_status = YtModerationStatus videoid = YtVideoId class VideoModerationFeed(gdata.data.GDFeed): """Describes a video moderation feed""" entry = [VideoModerationEntry] class TrackContent(atom.data.Content): lang = atom.data.XML_TEMPLATE % 'lang' class TrackEntry(gdata.data.GDEntry): """Represents the URL for a caption track""" content = TrackContent def get_caption_track_id(self): """Extracts the ID of this caption track. Returns: The caption track's id as a string. """ if self.id.text: match = CAPTION_TRACK_ID_PATTERN.match(self.id.text) if match: return match.group(2) return None GetCaptionTrackId = get_caption_track_id class CaptionFeed(gdata.data.GDFeed): """Represents a caption feed for a video on YouTube.""" entry = [TrackEntry]
Python
#!/usr/bin/python # # Copyright (C) 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. __author__ = ('api.stephaniel@gmail.com (Stephanie Liu)' ', api.jhartmann@gmail.com (Jochen Hartmann)') import atom import gdata import gdata.media as Media import gdata.geo as Geo YOUTUBE_NAMESPACE = 'http://gdata.youtube.com/schemas/2007' YOUTUBE_FORMAT = '{http://gdata.youtube.com/schemas/2007}format' YOUTUBE_DEVELOPER_TAG_SCHEME = '%s/%s' % (YOUTUBE_NAMESPACE, 'developertags.cat') YOUTUBE_SUBSCRIPTION_TYPE_SCHEME = '%s/%s' % (YOUTUBE_NAMESPACE, 'subscriptiontypes.cat') class Username(atom.AtomBase): """The YouTube Username element""" _tag = 'username' _namespace = YOUTUBE_NAMESPACE class QueryString(atom.AtomBase): """The YouTube QueryString element""" _tag = 'queryString' _namespace = YOUTUBE_NAMESPACE class FirstName(atom.AtomBase): """The YouTube FirstName element""" _tag = 'firstName' _namespace = YOUTUBE_NAMESPACE class LastName(atom.AtomBase): """The YouTube LastName element""" _tag = 'lastName' _namespace = YOUTUBE_NAMESPACE class Age(atom.AtomBase): """The YouTube Age element""" _tag = 'age' _namespace = YOUTUBE_NAMESPACE class Books(atom.AtomBase): """The YouTube Books element""" _tag = 'books' _namespace = YOUTUBE_NAMESPACE class Gender(atom.AtomBase): """The YouTube Gender element""" _tag = 'gender' _namespace = YOUTUBE_NAMESPACE class Company(atom.AtomBase): """The YouTube Company element""" _tag = 'company' _namespace = YOUTUBE_NAMESPACE class Hobbies(atom.AtomBase): """The YouTube Hobbies element""" _tag = 'hobbies' _namespace = YOUTUBE_NAMESPACE class Hometown(atom.AtomBase): """The YouTube Hometown element""" _tag = 'hometown' _namespace = YOUTUBE_NAMESPACE class Location(atom.AtomBase): """The YouTube Location element""" _tag = 'location' _namespace = YOUTUBE_NAMESPACE class Movies(atom.AtomBase): """The YouTube Movies element""" _tag = 'movies' _namespace = YOUTUBE_NAMESPACE class Music(atom.AtomBase): """The YouTube Music element""" _tag = 'music' _namespace = YOUTUBE_NAMESPACE class Occupation(atom.AtomBase): """The YouTube Occupation element""" _tag = 'occupation' _namespace = YOUTUBE_NAMESPACE class School(atom.AtomBase): """The YouTube School element""" _tag = 'school' _namespace = YOUTUBE_NAMESPACE class Relationship(atom.AtomBase): """The YouTube Relationship element""" _tag = 'relationship' _namespace = YOUTUBE_NAMESPACE class Recorded(atom.AtomBase): """The YouTube Recorded element""" _tag = 'recorded' _namespace = YOUTUBE_NAMESPACE class Statistics(atom.AtomBase): """The YouTube Statistics element.""" _tag = 'statistics' _namespace = YOUTUBE_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['viewCount'] = 'view_count' _attributes['videoWatchCount'] = 'video_watch_count' _attributes['subscriberCount'] = 'subscriber_count' _attributes['lastWebAccess'] = 'last_web_access' _attributes['favoriteCount'] = 'favorite_count' def __init__(self, view_count=None, video_watch_count=None, favorite_count=None, subscriber_count=None, last_web_access=None, extension_elements=None, extension_attributes=None, text=None): self.view_count = view_count self.video_watch_count = video_watch_count self.subscriber_count = subscriber_count self.last_web_access = last_web_access self.favorite_count = favorite_count atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Status(atom.AtomBase): """The YouTube Status element""" _tag = 'status' _namespace = YOUTUBE_NAMESPACE class Position(atom.AtomBase): """The YouTube Position element. The position in a playlist feed.""" _tag = 'position' _namespace = YOUTUBE_NAMESPACE class Racy(atom.AtomBase): """The YouTube Racy element.""" _tag = 'racy' _namespace = YOUTUBE_NAMESPACE class Description(atom.AtomBase): """The YouTube Description element.""" _tag = 'description' _namespace = YOUTUBE_NAMESPACE class Private(atom.AtomBase): """The YouTube Private element.""" _tag = 'private' _namespace = YOUTUBE_NAMESPACE class NoEmbed(atom.AtomBase): """The YouTube VideoShare element. Whether a video can be embedded or not.""" _tag = 'noembed' _namespace = YOUTUBE_NAMESPACE class Comments(atom.AtomBase): """The GData 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]) def __init__(self, feed_link=None, extension_elements=None, extension_attributes=None, text=None): self.feed_link = feed_link atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Rating(atom.AtomBase): """The GData Rating element""" _tag = 'rating' _namespace = gdata.GDATA_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['min'] = 'min' _attributes['max'] = 'max' _attributes['numRaters'] = 'num_raters' _attributes['average'] = 'average' def __init__(self, min=None, max=None, num_raters=None, average=None, extension_elements=None, extension_attributes=None, text=None): self.min = min self.max = max self.num_raters = num_raters self.average = average atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class YouTubePlaylistVideoEntry(gdata.GDataEntry): """Represents a YouTubeVideoEntry on a YouTubePlaylist.""" _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', [gdata.FeedLink]) _children['{%s}description' % YOUTUBE_NAMESPACE] = ('description', Description) _children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating) _children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments) _children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics) _children['{%s}location' % YOUTUBE_NAMESPACE] = ('location', Location) _children['{%s}position' % YOUTUBE_NAMESPACE] = ('position', Position) _children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, feed_link=None, description=None, rating=None, comments=None, statistics=None, location=None, position=None, media=None, extension_elements=None, extension_attributes=None): self.feed_link = feed_link self.description = description self.rating = rating self.comments = comments self.statistics = statistics self.location = location self.position = position self.media = media 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) class YouTubeVideoCommentEntry(gdata.GDataEntry): """Represents a comment on YouTube.""" _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() class YouTubeSubscriptionEntry(gdata.GDataEntry): """Represents a subscription entry on YouTube.""" _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username) _children['{%s}queryString' % YOUTUBE_NAMESPACE] = ( 'query_string', QueryString) _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', [gdata.FeedLink]) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, username=None, query_string=None, feed_link=None, extension_elements=None, extension_attributes=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.username = username self.query_string = query_string self.feed_link = feed_link def GetSubscriptionType(self): """Retrieve the type of this subscription. Returns: A string that is either 'channel, 'query' or 'favorites' """ for category in self.category: if category.scheme == YOUTUBE_SUBSCRIPTION_TYPE_SCHEME: return category.term class YouTubeVideoResponseEntry(gdata.GDataEntry): """Represents a video response. """ _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating) _children['{%s}noembed' % YOUTUBE_NAMESPACE] = ('noembed', NoEmbed) _children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics) _children['{%s}racy' % YOUTUBE_NAMESPACE] = ('racy', Racy) _children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, rating=None, noembed=None, statistics=None, racy=None, media=None, extension_elements=None, extension_attributes=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.rating = rating self.noembed = noembed self.statistics = statistics self.racy = racy self.media = media or Media.Group() class YouTubeContactEntry(gdata.GDataEntry): """Represents a contact entry.""" _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username) _children['{%s}status' % YOUTUBE_NAMESPACE] = ('status', Status) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, username=None, status=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) self.username = username self.status = status class YouTubeVideoEntry(gdata.GDataEntry): """Represents a video on YouTube.""" _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}rating' % gdata.GDATA_NAMESPACE] = ('rating', Rating) _children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments) _children['{%s}noembed' % YOUTUBE_NAMESPACE] = ('noembed', NoEmbed) _children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics) _children['{%s}recorded' % YOUTUBE_NAMESPACE] = ('recorded', Recorded) _children['{%s}racy' % YOUTUBE_NAMESPACE] = ('racy', Racy) _children['{%s}group' % gdata.media.MEDIA_NAMESPACE] = ('media', Media.Group) _children['{%s}where' % gdata.geo.GEORSS_NAMESPACE] = ('geo', Geo.Where) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, rating=None, noembed=None, statistics=None, racy=None, media=None, geo=None, recorded=None, comments=None, extension_elements=None, extension_attributes=None): self.rating = rating self.noembed = noembed self.statistics = statistics self.racy = racy self.comments = comments self.media = media or Media.Group() self.geo = geo self.recorded = recorded 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) def GetSwfUrl(self): """Return the URL for the embeddable Video Returns: URL of the embeddable video """ if self.media.content: for content in self.media.content: if content.extension_attributes[YOUTUBE_FORMAT] == '5': return content.url else: return None def AddDeveloperTags(self, developer_tags): """Add a developer tag for this entry. Developer tags can only be set during the initial upload. Arguments: developer_tags: A list of developer tags as strings. Returns: A list of all developer tags for this video entry. """ for tag_text in developer_tags: self.media.category.append(gdata.media.Category( text=tag_text, label=tag_text, scheme=YOUTUBE_DEVELOPER_TAG_SCHEME)) return self.GetDeveloperTags() def GetDeveloperTags(self): """Retrieve developer tags for this video entry.""" developer_tags = [] for category in self.media.category: if category.scheme == YOUTUBE_DEVELOPER_TAG_SCHEME: developer_tags.append(category) if len(developer_tags) > 0: return developer_tags def GetYouTubeCategoryAsString(self): """Convenience method to return the YouTube category as string. YouTubeVideoEntries can contain multiple Category objects with differing schemes. This method returns only the category with the correct scheme, ignoring developer tags. """ for category in self.media.category: if category.scheme != YOUTUBE_DEVELOPER_TAG_SCHEME: return category.text class YouTubeUserEntry(gdata.GDataEntry): """Represents a user on YouTube.""" _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}username' % YOUTUBE_NAMESPACE] = ('username', Username) _children['{%s}firstName' % YOUTUBE_NAMESPACE] = ('first_name', FirstName) _children['{%s}lastName' % YOUTUBE_NAMESPACE] = ('last_name', LastName) _children['{%s}age' % YOUTUBE_NAMESPACE] = ('age', Age) _children['{%s}books' % YOUTUBE_NAMESPACE] = ('books', Books) _children['{%s}gender' % YOUTUBE_NAMESPACE] = ('gender', Gender) _children['{%s}company' % YOUTUBE_NAMESPACE] = ('company', Company) _children['{%s}description' % YOUTUBE_NAMESPACE] = ('description', Description) _children['{%s}hobbies' % YOUTUBE_NAMESPACE] = ('hobbies', Hobbies) _children['{%s}hometown' % YOUTUBE_NAMESPACE] = ('hometown', Hometown) _children['{%s}location' % YOUTUBE_NAMESPACE] = ('location', Location) _children['{%s}movies' % YOUTUBE_NAMESPACE] = ('movies', Movies) _children['{%s}music' % YOUTUBE_NAMESPACE] = ('music', Music) _children['{%s}occupation' % YOUTUBE_NAMESPACE] = ('occupation', Occupation) _children['{%s}school' % YOUTUBE_NAMESPACE] = ('school', School) _children['{%s}relationship' % YOUTUBE_NAMESPACE] = ('relationship', Relationship) _children['{%s}statistics' % YOUTUBE_NAMESPACE] = ('statistics', Statistics) _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', [gdata.FeedLink]) _children['{%s}thumbnail' % gdata.media.MEDIA_NAMESPACE] = ('thumbnail', Media.Thumbnail) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, username=None, first_name=None, last_name=None, age=None, books=None, gender=None, company=None, description=None, hobbies=None, hometown=None, location=None, movies=None, music=None, occupation=None, school=None, relationship=None, statistics=None, feed_link=None, extension_elements=None, extension_attributes=None, text=None): self.username = username self.first_name = first_name self.last_name = last_name self.age = age self.books = books self.gender = gender self.company = company self.description = description self.hobbies = hobbies self.hometown = hometown self.location = location self.movies = movies self.music = music self.occupation = occupation self.school = school self.relationship = relationship self.statistics = statistics self.feed_link = feed_link 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) class YouTubeVideoFeed(gdata.GDataFeed, gdata.LinkFinder): """Represents a video feed on YouTube.""" _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', [YouTubeVideoEntry]) class YouTubePlaylistEntry(gdata.GDataEntry): """Represents a playlist in YouTube.""" _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}description' % YOUTUBE_NAMESPACE] = ('description', Description) _children['{%s}private' % YOUTUBE_NAMESPACE] = ('private', Private) _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', [gdata.FeedLink]) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, private=None, feed_link=None, description=None, extension_elements=None, extension_attributes=None): self.description = description self.private = private self.feed_link = feed_link 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) class YouTubePlaylistFeed(gdata.GDataFeed, gdata.LinkFinder): """Represents a feed of a user's playlists """ _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', [YouTubePlaylistEntry]) class YouTubePlaylistVideoFeed(gdata.GDataFeed, gdata.LinkFinder): """Represents a feed of video entry on a playlist.""" _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', [YouTubePlaylistVideoEntry]) class YouTubeContactFeed(gdata.GDataFeed, gdata.LinkFinder): """Represents a feed of a users contacts.""" _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', [YouTubeContactEntry]) class YouTubeSubscriptionFeed(gdata.GDataFeed, gdata.LinkFinder): """Represents a feed of a users subscriptions.""" _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', [YouTubeSubscriptionEntry]) class YouTubeVideoCommentFeed(gdata.GDataFeed, gdata.LinkFinder): """Represents a feed of comments for a video.""" _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', [YouTubeVideoCommentEntry]) class YouTubeVideoResponseFeed(gdata.GDataFeed, gdata.LinkFinder): """Represents a feed of video responses.""" _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', [YouTubeVideoResponseEntry]) def YouTubeVideoFeedFromString(xml_string): return atom.CreateClassFromXMLString(YouTubeVideoFeed, xml_string) def YouTubeVideoEntryFromString(xml_string): return atom.CreateClassFromXMLString(YouTubeVideoEntry, xml_string) def YouTubeContactFeedFromString(xml_string): return atom.CreateClassFromXMLString(YouTubeContactFeed, xml_string) def YouTubeContactEntryFromString(xml_string): return atom.CreateClassFromXMLString(YouTubeContactEntry, xml_string) def YouTubeVideoCommentFeedFromString(xml_string): return atom.CreateClassFromXMLString(YouTubeVideoCommentFeed, xml_string) def YouTubeVideoCommentEntryFromString(xml_string): return atom.CreateClassFromXMLString(YouTubeVideoCommentEntry, xml_string) def YouTubeUserFeedFromString(xml_string): return atom.CreateClassFromXMLString(YouTubeVideoFeed, xml_string) def YouTubeUserEntryFromString(xml_string): return atom.CreateClassFromXMLString(YouTubeUserEntry, xml_string) def YouTubePlaylistFeedFromString(xml_string): return atom.CreateClassFromXMLString(YouTubePlaylistFeed, xml_string) def YouTubePlaylistVideoFeedFromString(xml_string): return atom.CreateClassFromXMLString(YouTubePlaylistVideoFeed, xml_string) def YouTubePlaylistEntryFromString(xml_string): return atom.CreateClassFromXMLString(YouTubePlaylistEntry, xml_string) def YouTubePlaylistVideoEntryFromString(xml_string): return atom.CreateClassFromXMLString(YouTubePlaylistVideoEntry, xml_string) def YouTubeSubscriptionFeedFromString(xml_string): return atom.CreateClassFromXMLString(YouTubeSubscriptionFeed, xml_string) def YouTubeSubscriptionEntryFromString(xml_string): return atom.CreateClassFromXMLString(YouTubeSubscriptionEntry, xml_string) def YouTubeVideoResponseFeedFromString(xml_string): return atom.CreateClassFromXMLString(YouTubeVideoResponseFeed, xml_string) def YouTubeVideoResponseEntryFromString(xml_string): return atom.CreateClassFromXMLString(YouTubeVideoResponseEntry, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 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. """Provides HTTP functions for gdata.service to use on Google App Engine AppEngineHttpClient: Provides an HTTP request method which uses App Engine's urlfetch API. Set the http_client member of a GDataService object to an instance of an AppEngineHttpClient to allow the gdata library to run on Google App Engine. run_on_appengine: Function which will modify an existing GDataService object to allow it to run on App Engine. It works by creating a new instance of the AppEngineHttpClient and replacing the GDataService object's http_client. HttpRequest: Function that wraps google.appengine.api.urlfetch.Fetch in a common interface which is used by gdata.service.GDataService. In other words, this module can be used as the gdata service request handler so that all HTTP requests will be performed by the hosting Google App Engine server. """ __author__ = 'api.jscudder (Jeff Scudder)' import StringIO import atom.service import atom.http_interface from google.appengine.api import urlfetch def run_on_appengine(gdata_service): """Modifies a GDataService object to allow it to run on App Engine. Args: gdata_service: An instance of AtomService, GDataService, or any of their subclasses which has an http_client member. """ gdata_service.http_client = AppEngineHttpClient() class AppEngineHttpClient(atom.http_interface.GenericHttpClient): def __init__(self, headers=None): self.debug = False self.headers = headers or {} def request(self, operation, url, data=None, headers=None): """Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE. Usage example, perform and HTTP GET on http://www.google.com/: import atom.http client = atom.http.HttpClient() http_response = client.request('GET', 'http://www.google.com/') Args: operation: str The HTTP operation to be performed. This is usually one of 'GET', 'POST', 'PUT', or 'DELETE' data: filestream, list of parts, or other object which can be converted to a string. Should be set to None when performing a GET or DELETE. If data is a file-like object which can be read, this method will read a chunk of 100K bytes at a time and send them. If the data is a list of parts to be sent, each part will be evaluated and sent. url: The full URL to which the request should be sent. Can be a string or atom.url.Url. headers: dict of strings. HTTP headers which should be sent in the request. """ all_headers = self.headers.copy() if headers: all_headers.update(headers) # Construct the full payload. # Assume that data is None or a string. data_str = data if data: if isinstance(data, list): # If data is a list of different objects, convert them all to strings # and join them together. converted_parts = [__ConvertDataPart(x) for x in data] data_str = ''.join(converted_parts) else: data_str = __ConvertDataPart(data) # If the list of headers does not include a Content-Length, attempt to # calculate it based on the data object. if data and 'Content-Length' not in all_headers: all_headers['Content-Length'] = len(data_str) # Set the content type to the default value if none was set. if 'Content-Type' not in all_headers: all_headers['Content-Type'] = 'application/atom+xml' # Lookup the urlfetch operation which corresponds to the desired HTTP verb. if operation == 'GET': method = urlfetch.GET elif operation == 'POST': method = urlfetch.POST elif operation == 'PUT': method = urlfetch.PUT elif operation == 'DELETE': method = urlfetch.DELETE else: method = None return HttpResponse(urlfetch.Fetch(url=str(url), payload=data_str, method=method, headers=all_headers)) def HttpRequest(service, operation, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE. This function is deprecated, use AppEngineHttpClient.request instead. To use this module with gdata.service, you can set this module to be the http_request_handler so that HTTP requests use Google App Engine's urlfetch. import gdata.service import gdata.urlfetch gdata.service.http_request_handler = gdata.urlfetch Args: service: atom.AtomService object which contains some of the parameters needed to make the request. The following members are used to construct the HTTP call: server (str), additional_headers (dict), port (int), and ssl (bool). operation: str The HTTP operation to be performed. This is usually one of 'GET', 'POST', 'PUT', or 'DELETE' data: filestream, list of parts, or other object which can be converted to a string. Should be set to None when performing a GET or PUT. If data is a file-like object which can be read, this method will read a chunk of 100K bytes at a time and send them. If the data is a list of parts to be sent, each part will be evaluated and sent. uri: The beginning of the URL to which the request should be sent. Examples: '/', '/base/feeds/snippets', '/m8/feeds/contacts/default/base' extra_headers: dict of strings. HTTP headers which should be sent in the request. These headers are in addition to those stored in service.additional_headers. url_params: dict of strings. Key value pairs to be added to the URL as URL parameters. For example {'foo':'bar', 'test':'param'} will become ?foo=bar&test=param. escape_params: bool default True. If true, the keys and values in url_params will be URL escaped when the form is constructed (Special characters converted to %XX form.) content_type: str The MIME type for the data being sent. Defaults to 'application/atom+xml', this is only used if data is set. """ full_uri = atom.service.BuildUri(uri, url_params, escape_params) (server, port, ssl, partial_uri) = atom.service.ProcessUrl(service, full_uri) # Construct the full URL for the request. if ssl: full_url = 'https://%s%s' % (server, partial_uri) else: full_url = 'http://%s%s' % (server, partial_uri) # Construct the full payload. # Assume that data is None or a string. data_str = data if data: if isinstance(data, list): # If data is a list of different objects, convert them all to strings # and join them together. converted_parts = [__ConvertDataPart(x) for x in data] data_str = ''.join(converted_parts) else: data_str = __ConvertDataPart(data) # Construct the dictionary of HTTP headers. headers = {} if isinstance(service.additional_headers, dict): headers = service.additional_headers.copy() if isinstance(extra_headers, dict): for header, value in extra_headers.iteritems(): headers[header] = value # Add the content type header (we don't need to calculate content length, # since urlfetch.Fetch will calculate for us). if content_type: headers['Content-Type'] = content_type # Lookup the urlfetch operation which corresponds to the desired HTTP verb. if operation == 'GET': method = urlfetch.GET elif operation == 'POST': method = urlfetch.POST elif operation == 'PUT': method = urlfetch.PUT elif operation == 'DELETE': method = urlfetch.DELETE else: method = None return HttpResponse(urlfetch.Fetch(url=full_url, payload=data_str, method=method, headers=headers)) def __ConvertDataPart(data): if not data or isinstance(data, str): return data elif hasattr(data, 'read'): # data is a file like object, so read it completely. return data.read() # The data object was not a file. # Try to convert to a string and send the data. return str(data) class HttpResponse(object): """Translates a urlfetch resoinse to look like an hhtplib resoinse. Used to allow the resoinse from HttpRequest to be usable by gdata.service methods. """ def __init__(self, urlfetch_response): self.body = StringIO.StringIO(urlfetch_response.content) self.headers = urlfetch_response.headers self.status = urlfetch_response.status_code self.reason = '' def read(self, length=None): if not length: return self.body.read() else: return self.body.read(length) def getheader(self, name): if not self.headers.has_key(name): return self.headers[name.lower()] return self.headers[name]
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. """Provides utility functions used with command line samples.""" # This module is used for version 2 of the Google Data APIs. import sys import getpass import urllib import gdata.gauth __author__ = 'j.s@google.com (Jeff Scudder)' CLIENT_LOGIN = 1 AUTHSUB = 2 OAUTH = 3 HMAC = 1 RSA = 2 class SettingsUtil(object): """Gather's user preferences from flags or command prompts. An instance of this object stores the choices made by the user. At some point it might be useful to save the user's preferences so that they do not need to always set flags or answer preference prompts. """ def __init__(self, prefs=None): self.prefs = prefs or {} def get_param(self, name, prompt='', secret=False, ask=True, reuse=False): # First, check in this objects stored preferences. if name in self.prefs: return self.prefs[name] # Second, check for a command line parameter. value = None for i in xrange(len(sys.argv)): if sys.argv[i].startswith('--%s=' % name): value = sys.argv[i].split('=')[1] elif sys.argv[i] == '--%s' % name: value = sys.argv[i + 1] # Third, if it was not on the command line, ask the user to input the # value. if value is None and ask: prompt = '%s: ' % prompt if secret: value = getpass.getpass(prompt) else: value = raw_input(prompt) # If we want to save the preference for reuse in future requests, add it # to this object's prefs. if value is not None and reuse: self.prefs[name] = value return value def authorize_client(self, client, auth_type=None, service=None, source=None, scopes=None, oauth_type=None, consumer_key=None, consumer_secret=None): """Uses command line arguments, or prompts user for token values.""" if 'client_auth_token' in self.prefs: return if auth_type is None: auth_type = int(self.get_param( 'auth_type', 'Please choose the authorization mechanism you want' ' to use.\n' '1. to use your email address and password (ClientLogin)\n' '2. to use a web browser to visit an auth web page (AuthSub)\n' '3. if you have registed to use OAuth\n', reuse=True)) # Get the scopes for the services we want to access. if auth_type == AUTHSUB or auth_type == OAUTH: if scopes is None: scopes = self.get_param( 'scopes', 'Enter the URL prefixes (scopes) for the resources you ' 'would like to access.\nFor multiple scope URLs, place a comma ' 'between each URL.\n' 'Example: http://www.google.com/calendar/feeds/,' 'http://www.google.com/m8/feeds/\n', reuse=True).split(',') elif isinstance(scopes, (str, unicode)): scopes = scopes.split(',') if auth_type == CLIENT_LOGIN: email = self.get_param('email', 'Please enter your username', reuse=False) password = self.get_param('password', 'Password', True, reuse=False) if service is None: service = self.get_param( 'service', 'What is the name of the service you wish to access?' '\n(See list:' ' http://code.google.com/apis/gdata/faq.html#clientlogin)', reuse=True) if source is None: source = self.get_param('source', ask=False, reuse=True) client.client_login(email, password, source=source, service=service) elif auth_type == AUTHSUB: auth_sub_token = self.get_param('auth_sub_token', ask=False, reuse=True) session_token = self.get_param('session_token', ask=False, reuse=True) private_key = None auth_url = None single_use_token = None rsa_private_key = self.get_param( 'rsa_private_key', 'If you want to use secure mode AuthSub, please provide the\n' ' location of your RSA private key which corresponds to the\n' ' certificate you have uploaded for your domain. If you do not\n' ' have an RSA key, simply press enter', reuse=True) if rsa_private_key: try: private_key_file = open(rsa_private_key, 'rb') private_key = private_key_file.read() private_key_file.close() except IOError: print 'Unable to read private key from file' if private_key is not None: if client.auth_token is None: if session_token: client.auth_token = gdata.gauth.SecureAuthSubToken( session_token, private_key, scopes) self.prefs['client_auth_token'] = gdata.gauth.token_to_blob( client.auth_token) return elif auth_sub_token: client.auth_token = gdata.gauth.SecureAuthSubToken( auth_sub_token, private_key, scopes) client.upgrade_token() self.prefs['client_auth_token'] = gdata.gauth.token_to_blob( client.auth_token) return auth_url = gdata.gauth.generate_auth_sub_url( 'http://gauthmachine.appspot.com/authsub', scopes, True) print 'with a private key, get ready for this URL', auth_url else: if client.auth_token is None: if session_token: client.auth_token = gdata.gauth.AuthSubToken(session_token, scopes) self.prefs['client_auth_token'] = gdata.gauth.token_to_blob( client.auth_token) return elif auth_sub_token: client.auth_token = gdata.gauth.AuthSubToken(auth_sub_token, scopes) client.upgrade_token() self.prefs['client_auth_token'] = gdata.gauth.token_to_blob( client.auth_token) return auth_url = gdata.gauth.generate_auth_sub_url( 'http://gauthmachine.appspot.com/authsub', scopes) print 'Visit the following URL in your browser to authorize this app:' print str(auth_url) print 'After agreeing to authorize the app, copy the token value from' print ' the URL. Example: "www.google.com/?token=ab12" token value is' print ' ab12' token_value = raw_input('Please enter the token value: ') if private_key is not None: single_use_token = gdata.gauth.SecureAuthSubToken( token_value, private_key, scopes) else: single_use_token = gdata.gauth.AuthSubToken(token_value, scopes) client.auth_token = single_use_token client.upgrade_token() elif auth_type == OAUTH: if oauth_type is None: oauth_type = int(self.get_param( 'oauth_type', 'Please choose the authorization mechanism you want' ' to use.\n' '1. use an HMAC signature using your consumer key and secret\n' '2. use RSA with your private key to sign requests\n', reuse=True)) consumer_key = self.get_param( 'consumer_key', 'Please enter your OAuth conumer key ' 'which identifies your app', reuse=True) if oauth_type == HMAC: consumer_secret = self.get_param( 'consumer_secret', 'Please enter your OAuth conumer secret ' 'which you share with the OAuth provider', True, reuse=False) # Swap out this code once the client supports requesting an oauth # token. # Get a request token. request_token = client.get_oauth_token( scopes, 'http://gauthmachine.appspot.com/oauth', consumer_key, consumer_secret=consumer_secret) elif oauth_type == RSA: rsa_private_key = self.get_param( 'rsa_private_key', 'Please provide the location of your RSA private key which\n' ' corresponds to the certificate you have uploaded for your' ' domain.', reuse=True) try: private_key_file = open(rsa_private_key, 'rb') private_key = private_key_file.read() private_key_file.close() except IOError: print 'Unable to read private key from file' request_token = client.get_oauth_token( scopes, 'http://gauthmachine.appspot.com/oauth', consumer_key, rsa_private_key=private_key) else: print 'Invalid OAuth signature type' return None # Authorize the request token in the browser. print 'Visit the following URL in your browser to authorize this app:' print str(request_token.generate_authorization_url()) print 'After agreeing to authorize the app, copy URL from the browser\'s' print ' address bar.' url = raw_input('Please enter the url: ') gdata.gauth.authorize_request_token(request_token, url) # Exchange for an access token. client.auth_token = client.get_access_token(request_token) else: print 'Invalid authorization type.' return None if client.auth_token: self.prefs['client_auth_token'] = gdata.gauth.token_to_blob( client.auth_token) def get_param(name, prompt='', secret=False, ask=True): settings = SettingsUtil() return settings.get_param(name=name, prompt=prompt, secret=secret, ask=ask) def authorize_client(client, auth_type=None, service=None, source=None, scopes=None, oauth_type=None, consumer_key=None, consumer_secret=None): """Uses command line arguments, or prompts user for token values.""" settings = SettingsUtil() return settings.authorize_client(client=client, auth_type=auth_type, service=service, source=source, scopes=scopes, oauth_type=oauth_type, consumer_key=consumer_key, consumer_secret=consumer_secret) def print_options(): """Displays usage information, available command line params.""" # TODO: fill in the usage description for authorizing the client. print ''
Python
#!/usr/bin/python # # Copyright (C) 2008 Yu-Jie Lin # # 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. """GWebmasterToolsService extends the GDataService to streamline Google Webmaster Tools operations. GWebmasterToolsService: Provides methods to query feeds and manipulate items. Extends GDataService. """ __author__ = 'livibetter (Yu-Jie Lin)' import urllib import gdata import atom.service import gdata.service import gdata.webmastertools as webmastertools import atom FEED_BASE = 'https://www.google.com/webmasters/tools/feeds/' SITES_FEED = FEED_BASE + 'sites/' SITE_TEMPLATE = SITES_FEED + '%s' SITEMAPS_FEED_TEMPLATE = FEED_BASE + '%(site_id)s/sitemaps/' SITEMAP_TEMPLATE = SITEMAPS_FEED_TEMPLATE + '%(sitemap_id)s' class Error(Exception): pass class RequestError(Error): pass class GWebmasterToolsService(gdata.service.GDataService): """Client for the Google Webmaster Tools service.""" def __init__(self, email=None, password=None, source=None, server='www.google.com', **kwargs): """Creates a client for the Google Webmaster Tools 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='sitemaps', source=source, server=server, **kwargs) def GetSitesFeed(self, uri=SITES_FEED, converter=webmastertools.SitesFeedFromString): """Gets sites feed. Args: uri: str (optional) URI to retrieve sites feed. converter: func (optional) Function which is executed on the server's response before it is returned. Usually this is a function like SitesFeedFromString 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 SitesFeed object. """ return self.Get(uri, converter=converter) def AddSite(self, site_uri, uri=SITES_FEED, url_params=None, escape_params=True, converter=None): """Adds a site to Google Webmaster Tools. Args: site_uri: str URI of which site to add. uri: str (optional) URI to add a site. 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 SitesEntryFromString 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 SitesEntry object. """ site_entry = webmastertools.SitesEntry() site_entry.content = atom.Content(src=site_uri) response = self.Post(site_entry, uri, url_params=url_params, escape_params=escape_params, converter=converter) if not converter and isinstance(response, atom.Entry): return webmastertools.SitesEntryFromString(response.ToString()) return response def DeleteSite(self, site_uri, uri=SITE_TEMPLATE, url_params=None, escape_params=True): """Removes a site from Google Webmaster Tools. Args: site_uri: str URI of which site to remove. uri: str (optional) A URI template to send DELETE request. Default SITE_TEMPLATE. 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: True if the delete succeeded. """ return self.Delete( uri % urllib.quote_plus(site_uri), url_params=url_params, escape_params=escape_params) def VerifySite(self, site_uri, verification_method, uri=SITE_TEMPLATE, url_params=None, escape_params=True, converter=None): """Requests a verification of a site. Args: site_uri: str URI of which site to add sitemap for. verification_method: str The method to verify a site. Valid values are 'htmlpage', and 'metatag'. uri: str (optional) URI template to update a site. Default SITE_TEMPLATE. 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 SitemapsEntryFromString 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 SitesEntry object. """ site_entry = webmastertools.SitesEntry( atom_id=atom.Id(text=site_uri), category=atom.Category( scheme='http://schemas.google.com/g/2005#kind', term='http://schemas.google.com/webmasters/tools/2007#sites-info'), verification_method=webmastertools.VerificationMethod( type=verification_method, in_use='true') ) response = self.Put( site_entry, uri % urllib.quote_plus(site_uri), url_params=url_params, escape_params=escape_params, converter=converter) if not converter and isinstance(response, atom.Entry): return webmastertools.SitesEntryFromString(response.ToString()) return response def UpdateGeoLocation(self, site_uri, geolocation, uri=SITE_TEMPLATE, url_params=None, escape_params=True, converter=None): """Updates geolocation setting of a site. Args: site_uri: str URI of which site to add sitemap for. geolocation: str The geographic location. Valid values are listed in http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 uri: str (optional) URI template to update a site. Default SITE_TEMPLATE. 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 SitemapsEntryFromString 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 SitesEntry object. """ site_entry = webmastertools.SitesEntry( atom_id=atom.Id(text=site_uri), category=atom.Category( scheme='http://schemas.google.com/g/2005#kind', term='http://schemas.google.com/webmasters/tools/2007#sites-info'), geolocation=webmastertools.GeoLocation(text=geolocation) ) response = self.Put( site_entry, uri % urllib.quote_plus(site_uri), url_params=url_params, escape_params=escape_params, converter=converter) if not converter and isinstance(response, atom.Entry): return webmastertools.SitesEntryFromString(response.ToString()) return response def UpdateCrawlRate(self, site_uri, crawl_rate, uri=SITE_TEMPLATE, url_params=None, escape_params=True, converter=None): """Updates crawl rate setting of a site. Args: site_uri: str URI of which site to add sitemap for. crawl_rate: str The crawl rate for a site. Valid values are 'slower', 'normal', and 'faster'. uri: str (optional) URI template to update a site. Default SITE_TEMPLATE. 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 SitemapsEntryFromString 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 SitesEntry object. """ site_entry = webmastertools.SitesEntry( atom_id=atom.Id(text=site_uri), category=atom.Category( scheme='http://schemas.google.com/g/2005#kind', term='http://schemas.google.com/webmasters/tools/2007#sites-info'), crawl_rate=webmastertools.CrawlRate(text=crawl_rate) ) response = self.Put( site_entry, uri % urllib.quote_plus(site_uri), url_params=url_params, escape_params=escape_params, converter=converter) if not converter and isinstance(response, atom.Entry): return webmastertools.SitesEntryFromString(response.ToString()) return response def UpdatePreferredDomain(self, site_uri, preferred_domain, uri=SITE_TEMPLATE, url_params=None, escape_params=True, converter=None): """Updates preferred domain setting of a site. Note that if using 'preferwww', will also need www.example.com in account to take effect. Args: site_uri: str URI of which site to add sitemap for. preferred_domain: str The preferred domain for a site. Valid values are 'none', 'preferwww', and 'prefernowww'. uri: str (optional) URI template to update a site. Default SITE_TEMPLATE. 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 SitemapsEntryFromString 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 SitesEntry object. """ site_entry = webmastertools.SitesEntry( atom_id=atom.Id(text=site_uri), category=atom.Category( scheme='http://schemas.google.com/g/2005#kind', term='http://schemas.google.com/webmasters/tools/2007#sites-info'), preferred_domain=webmastertools.PreferredDomain(text=preferred_domain) ) response = self.Put( site_entry, uri % urllib.quote_plus(site_uri), url_params=url_params, escape_params=escape_params, converter=converter) if not converter and isinstance(response, atom.Entry): return webmastertools.SitesEntryFromString(response.ToString()) return response def UpdateEnhancedImageSearch(self, site_uri, enhanced_image_search, uri=SITE_TEMPLATE, url_params=None, escape_params=True, converter=None): """Updates enhanced image search setting of a site. Args: site_uri: str URI of which site to add sitemap for. enhanced_image_search: str The enhanced image search setting for a site. Valid values are 'true', and 'false'. uri: str (optional) URI template to update a site. Default SITE_TEMPLATE. 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 SitemapsEntryFromString 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 SitesEntry object. """ site_entry = webmastertools.SitesEntry( atom_id=atom.Id(text=site_uri), category=atom.Category( scheme='http://schemas.google.com/g/2005#kind', term='http://schemas.google.com/webmasters/tools/2007#sites-info'), enhanced_image_search=webmastertools.EnhancedImageSearch( text=enhanced_image_search) ) response = self.Put( site_entry, uri % urllib.quote_plus(site_uri), url_params=url_params, escape_params=escape_params, converter=converter) if not converter and isinstance(response, atom.Entry): return webmastertools.SitesEntryFromString(response.ToString()) return response def GetSitemapsFeed(self, site_uri, uri=SITEMAPS_FEED_TEMPLATE, converter=webmastertools.SitemapsFeedFromString): """Gets sitemaps feed of a site. Args: site_uri: str (optional) URI of which site to retrieve its sitemaps feed. uri: str (optional) URI to retrieve sites feed. converter: func (optional) Function which is executed on the server's response before it is returned. Usually this is a function like SitemapsFeedFromString 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 SitemapsFeed object. """ return self.Get(uri % {'site_id': urllib.quote_plus(site_uri)}, converter=converter) def AddSitemap(self, site_uri, sitemap_uri, sitemap_type='WEB', uri=SITEMAPS_FEED_TEMPLATE, url_params=None, escape_params=True, converter=None): """Adds a regular sitemap to a site. Args: site_uri: str URI of which site to add sitemap for. sitemap_uri: str URI of sitemap to add to a site. sitemap_type: str Type of added sitemap. Valid types: WEB, VIDEO, or CODE. uri: str (optional) URI template to add a sitemap. Default SITEMAP_FEED_TEMPLATE. 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 SitemapsEntryFromString 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 SitemapsEntry object. """ sitemap_entry = webmastertools.SitemapsEntry( atom_id=atom.Id(text=sitemap_uri), category=atom.Category( scheme='http://schemas.google.com/g/2005#kind', term='http://schemas.google.com/webmasters/tools/2007#sitemap-regular'), sitemap_type=webmastertools.SitemapType(text=sitemap_type)) response = self.Post( sitemap_entry, uri % {'site_id': urllib.quote_plus(site_uri)}, url_params=url_params, escape_params=escape_params, converter=converter) if not converter and isinstance(response, atom.Entry): return webmastertools.SitemapsEntryFromString(response.ToString()) return response def AddMobileSitemap(self, site_uri, sitemap_uri, sitemap_mobile_markup_language='XHTML', uri=SITEMAPS_FEED_TEMPLATE, url_params=None, escape_params=True, converter=None): """Adds a mobile sitemap to a site. Args: site_uri: str URI of which site to add sitemap for. sitemap_uri: str URI of sitemap to add to a site. sitemap_mobile_markup_language: str Format of added sitemap. Valid types: XHTML, WML, or cHTML. uri: str (optional) URI template to add a sitemap. Default SITEMAP_FEED_TEMPLATE. 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 SitemapsEntryFromString 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 SitemapsEntry object. """ # FIXME sitemap_entry = webmastertools.SitemapsEntry( atom_id=atom.Id(text=sitemap_uri), category=atom.Category( scheme='http://schemas.google.com/g/2005#kind', term='http://schemas.google.com/webmasters/tools/2007#sitemap-mobile'), sitemap_mobile_markup_language=\ webmastertools.SitemapMobileMarkupLanguage( text=sitemap_mobile_markup_language)) print sitemap_entry response = self.Post( sitemap_entry, uri % {'site_id': urllib.quote_plus(site_uri)}, url_params=url_params, escape_params=escape_params, converter=converter) if not converter and isinstance(response, atom.Entry): return webmastertools.SitemapsEntryFromString(response.ToString()) return response def AddNewsSitemap(self, site_uri, sitemap_uri, sitemap_news_publication_label, uri=SITEMAPS_FEED_TEMPLATE, url_params=None, escape_params=True, converter=None): """Adds a news sitemap to a site. Args: site_uri: str URI of which site to add sitemap for. sitemap_uri: str URI of sitemap to add to a site. sitemap_news_publication_label: str, list of str Publication Labels for sitemap. uri: str (optional) URI template to add a sitemap. Default SITEMAP_FEED_TEMPLATE. 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 SitemapsEntryFromString 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 SitemapsEntry object. """ sitemap_entry = webmastertools.SitemapsEntry( atom_id=atom.Id(text=sitemap_uri), category=atom.Category( scheme='http://schemas.google.com/g/2005#kind', term='http://schemas.google.com/webmasters/tools/2007#sitemap-news'), sitemap_news_publication_label=[], ) if isinstance(sitemap_news_publication_label, str): sitemap_news_publication_label = [sitemap_news_publication_label] for label in sitemap_news_publication_label: sitemap_entry.sitemap_news_publication_label.append( webmastertools.SitemapNewsPublicationLabel(text=label)) print sitemap_entry response = self.Post( sitemap_entry, uri % {'site_id': urllib.quote_plus(site_uri)}, url_params=url_params, escape_params=escape_params, converter=converter) if not converter and isinstance(response, atom.Entry): return webmastertools.SitemapsEntryFromString(response.ToString()) return response def DeleteSitemap(self, site_uri, sitemap_uri, uri=SITEMAP_TEMPLATE, url_params=None, escape_params=True): """Removes a sitemap from a site. Args: site_uri: str URI of which site to remove a sitemap from. sitemap_uri: str URI of sitemap to remove from a site. uri: str (optional) A URI template to send DELETE request. Default SITEMAP_TEMPLATE. 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: True if the delete succeeded. """ return self.Delete( uri % {'site_id': urllib.quote_plus(site_uri), 'sitemap_id': urllib.quote_plus(sitemap_uri)}, url_params=url_params, escape_params=escape_params)
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 Webmaster Tools Data API""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import atom.data import gdata.data import gdata.opensearch.data WT_TEMPLATE = '{http://schemas.google.com/webmaster/tools/2007/}%s' class CrawlIssueCrawlType(atom.core.XmlElement): """Type of crawl of the crawl issue""" _qname = WT_TEMPLATE % 'crawl-type' class CrawlIssueDateDetected(atom.core.XmlElement): """Detection date for the issue""" _qname = WT_TEMPLATE % 'date-detected' class CrawlIssueDetail(atom.core.XmlElement): """Detail of the crawl issue""" _qname = WT_TEMPLATE % 'detail' class CrawlIssueIssueType(atom.core.XmlElement): """Type of crawl issue""" _qname = WT_TEMPLATE % 'issue-type' class CrawlIssueLinkedFromUrl(atom.core.XmlElement): """Source URL that links to the issue URL""" _qname = WT_TEMPLATE % 'linked-from' class CrawlIssueUrl(atom.core.XmlElement): """URL affected by the crawl issue""" _qname = WT_TEMPLATE % 'url' class CrawlIssueEntry(gdata.data.GDEntry): """Describes a crawl issue entry""" date_detected = CrawlIssueDateDetected url = CrawlIssueUrl detail = CrawlIssueDetail issue_type = CrawlIssueIssueType crawl_type = CrawlIssueCrawlType linked_from = [CrawlIssueLinkedFromUrl] class CrawlIssuesFeed(gdata.data.GDFeed): """Feed of crawl issues for a particular site""" entry = [CrawlIssueEntry] class Indexed(atom.core.XmlElement): """Describes the indexing status of a site""" _qname = WT_TEMPLATE % 'indexed' class Keyword(atom.core.XmlElement): """A keyword in a site or in a link to a site""" _qname = WT_TEMPLATE % 'keyword' source = 'source' class KeywordEntry(gdata.data.GDEntry): """Describes a keyword entry""" class KeywordsFeed(gdata.data.GDFeed): """Feed of keywords for a particular site""" entry = [KeywordEntry] keyword = [Keyword] class LastCrawled(atom.core.XmlElement): """Describes the last crawled date of a site""" _qname = WT_TEMPLATE % 'last-crawled' class MessageBody(atom.core.XmlElement): """Message body""" _qname = WT_TEMPLATE % 'body' class MessageDate(atom.core.XmlElement): """Message date""" _qname = WT_TEMPLATE % 'date' class MessageLanguage(atom.core.XmlElement): """Message language""" _qname = WT_TEMPLATE % 'language' class MessageRead(atom.core.XmlElement): """Indicates if the message has already been read""" _qname = WT_TEMPLATE % 'read' class MessageSubject(atom.core.XmlElement): """Message subject""" _qname = WT_TEMPLATE % 'subject' class SiteId(atom.core.XmlElement): """Site URL""" _qname = WT_TEMPLATE % 'id' class MessageEntry(gdata.data.GDEntry): """Describes a message entry""" wt_id = SiteId subject = MessageSubject date = MessageDate body = MessageBody language = MessageLanguage read = MessageRead class MessagesFeed(gdata.data.GDFeed): """Describes a messages feed""" entry = [MessageEntry] class SitemapEntry(gdata.data.GDEntry): """Describes a sitemap entry""" indexed = Indexed wt_id = SiteId class SitemapMobileMarkupLanguage(atom.core.XmlElement): """Describes a markup language for URLs in this sitemap""" _qname = WT_TEMPLATE % 'sitemap-mobile-markup-language' class SitemapMobile(atom.core.XmlElement): """Lists acceptable mobile markup languages for URLs in this sitemap""" _qname = WT_TEMPLATE % 'sitemap-mobile' sitemap_mobile_markup_language = [SitemapMobileMarkupLanguage] class SitemapNewsPublicationLabel(atom.core.XmlElement): """Specifies the publication label for this sitemap""" _qname = WT_TEMPLATE % 'sitemap-news-publication-label' class SitemapNews(atom.core.XmlElement): """Lists publication labels for this sitemap""" _qname = WT_TEMPLATE % 'sitemap-news' sitemap_news_publication_label = [SitemapNewsPublicationLabel] class SitemapType(atom.core.XmlElement): """Indicates the type of sitemap. Not used for News or Mobile Sitemaps""" _qname = WT_TEMPLATE % 'sitemap-type' class SitemapUrlCount(atom.core.XmlElement): """Indicates the number of URLs contained in the sitemap""" _qname = WT_TEMPLATE % 'sitemap-url-count' class SitemapsFeed(gdata.data.GDFeed): """Describes a sitemaps feed""" entry = [SitemapEntry] class VerificationMethod(atom.core.XmlElement): """Describes a verification method that may be used for a site""" _qname = WT_TEMPLATE % 'verification-method' in_use = 'in-use' type = 'type' class Verified(atom.core.XmlElement): """Describes the verification status of a site""" _qname = WT_TEMPLATE % 'verified' class SiteEntry(gdata.data.GDEntry): """Describes a site entry""" indexed = Indexed wt_id = SiteId verified = Verified last_crawled = LastCrawled verification_method = [VerificationMethod] class SitesFeed(gdata.data.GDFeed): """Describes a sites feed""" entry = [SiteEntry]
Python
#!/usr/bin/python # # Copyright (C) 2008 Yu-Jie Lin # # 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 Webmaster Tools.""" __author__ = 'livibetter (Yu-Jie Lin)' 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 Webmaster Tools entities. GWEBMASTERTOOLS_NAMESPACE = 'http://schemas.google.com/webmasters/tools/2007' GWEBMASTERTOOLS_TEMPLATE = '{http://schemas.google.com/webmasters/tools/2007}%s' class Indexed(atom.AtomBase): _tag = 'indexed' _namespace = GWEBMASTERTOOLS_NAMESPACE def IndexedFromString(xml_string): return atom.CreateClassFromXMLString(Indexed, xml_string) class Crawled(atom.Date): _tag = 'crawled' _namespace = GWEBMASTERTOOLS_NAMESPACE def CrawledFromString(xml_string): return atom.CreateClassFromXMLString(Crawled, xml_string) class GeoLocation(atom.AtomBase): _tag = 'geolocation' _namespace = GWEBMASTERTOOLS_NAMESPACE def GeoLocationFromString(xml_string): return atom.CreateClassFromXMLString(GeoLocation, xml_string) class PreferredDomain(atom.AtomBase): _tag = 'preferred-domain' _namespace = GWEBMASTERTOOLS_NAMESPACE def PreferredDomainFromString(xml_string): return atom.CreateClassFromXMLString(PreferredDomain, xml_string) class CrawlRate(atom.AtomBase): _tag = 'crawl-rate' _namespace = GWEBMASTERTOOLS_NAMESPACE def CrawlRateFromString(xml_string): return atom.CreateClassFromXMLString(CrawlRate, xml_string) class EnhancedImageSearch(atom.AtomBase): _tag = 'enhanced-image-search' _namespace = GWEBMASTERTOOLS_NAMESPACE def EnhancedImageSearchFromString(xml_string): return atom.CreateClassFromXMLString(EnhancedImageSearch, xml_string) class Verified(atom.AtomBase): _tag = 'verified' _namespace = GWEBMASTERTOOLS_NAMESPACE def VerifiedFromString(xml_string): return atom.CreateClassFromXMLString(Verified, xml_string) class VerificationMethodMeta(atom.AtomBase): _tag = 'meta' _namespace = atom.ATOM_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' _attributes['content'] = 'content' def __init__(self, text=None, name=None, content=None, extension_elements=None, extension_attributes=None): self.text = text self.name = name self.content = content self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def VerificationMethodMetaFromString(xml_string): return atom.CreateClassFromXMLString(VerificationMethodMeta, xml_string) class VerificationMethod(atom.AtomBase): _tag = 'verification-method' _namespace = GWEBMASTERTOOLS_NAMESPACE _children = atom.Text._children.copy() _attributes = atom.Text._attributes.copy() _children['{%s}meta' % atom.ATOM_NAMESPACE] = ( 'meta', VerificationMethodMeta) _attributes['in-use'] = 'in_use' _attributes['type'] = 'type' def __init__(self, text=None, in_use=None, meta=None, type=None, extension_elements=None, extension_attributes=None): self.text = text self.in_use = in_use self.meta = meta self.type = type self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def VerificationMethodFromString(xml_string): return atom.CreateClassFromXMLString(VerificationMethod, xml_string) class MarkupLanguage(atom.AtomBase): _tag = 'markup-language' _namespace = GWEBMASTERTOOLS_NAMESPACE def MarkupLanguageFromString(xml_string): return atom.CreateClassFromXMLString(MarkupLanguage, xml_string) class SitemapMobile(atom.AtomBase): _tag = 'sitemap-mobile' _namespace = GWEBMASTERTOOLS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}markup-language' % GWEBMASTERTOOLS_NAMESPACE] = ( 'markup_language', [MarkupLanguage]) def __init__(self, markup_language=None, extension_elements=None, extension_attributes=None, text=None): self.markup_language = markup_language or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SitemapMobileFromString(xml_string): return atom.CreateClassFromXMLString(SitemapMobile, xml_string) class SitemapMobileMarkupLanguage(atom.AtomBase): _tag = 'sitemap-mobile-markup-language' _namespace = GWEBMASTERTOOLS_NAMESPACE def SitemapMobileMarkupLanguageFromString(xml_string): return atom.CreateClassFromXMLString(SitemapMobileMarkupLanguage, xml_string) class PublicationLabel(atom.AtomBase): _tag = 'publication-label' _namespace = GWEBMASTERTOOLS_NAMESPACE def PublicationLabelFromString(xml_string): return atom.CreateClassFromXMLString(PublicationLabel, xml_string) class SitemapNews(atom.AtomBase): _tag = 'sitemap-news' _namespace = GWEBMASTERTOOLS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}publication-label' % GWEBMASTERTOOLS_NAMESPACE] = ( 'publication_label', [PublicationLabel]) def __init__(self, publication_label=None, extension_elements=None, extension_attributes=None, text=None): self.publication_label = publication_label or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SitemapNewsFromString(xml_string): return atom.CreateClassFromXMLString(SitemapNews, xml_string) class SitemapNewsPublicationLabel(atom.AtomBase): _tag = 'sitemap-news-publication-label' _namespace = GWEBMASTERTOOLS_NAMESPACE def SitemapNewsPublicationLabelFromString(xml_string): return atom.CreateClassFromXMLString(SitemapNewsPublicationLabel, xml_string) class SitemapLastDownloaded(atom.Date): _tag = 'sitemap-last-downloaded' _namespace = GWEBMASTERTOOLS_NAMESPACE def SitemapLastDownloadedFromString(xml_string): return atom.CreateClassFromXMLString(SitemapLastDownloaded, xml_string) class SitemapType(atom.AtomBase): _tag = 'sitemap-type' _namespace = GWEBMASTERTOOLS_NAMESPACE def SitemapTypeFromString(xml_string): return atom.CreateClassFromXMLString(SitemapType, xml_string) class SitemapStatus(atom.AtomBase): _tag = 'sitemap-status' _namespace = GWEBMASTERTOOLS_NAMESPACE def SitemapStatusFromString(xml_string): return atom.CreateClassFromXMLString(SitemapStatus, xml_string) class SitemapUrlCount(atom.AtomBase): _tag = 'sitemap-url-count' _namespace = GWEBMASTERTOOLS_NAMESPACE def SitemapUrlCountFromString(xml_string): return atom.CreateClassFromXMLString(SitemapUrlCount, xml_string) class LinkFinder(atom.LinkFinder): """An "interface" providing methods to find link elements SitesEntry 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 SitesEntry. """ 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 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 GetFeedLink(self): for a_link in self.link: if a_link.rel == 'http://schemas.google.com/g/2005#feed': return a_link return None class SitesEntry(atom.Entry, LinkFinder): """A Google Webmaster Tools meta Entry flavor of an Atom Entry """ _tag = atom.Entry._tag _namespace = atom.Entry._namespace _children = atom.Entry._children.copy() _attributes = atom.Entry._attributes.copy() _children['{%s}entryLink' % gdata.GDATA_NAMESPACE] = ( 'entry_link', [gdata.EntryLink]) _children['{%s}indexed' % GWEBMASTERTOOLS_NAMESPACE] = ('indexed', Indexed) _children['{%s}crawled' % GWEBMASTERTOOLS_NAMESPACE] = ( 'crawled', Crawled) _children['{%s}geolocation' % GWEBMASTERTOOLS_NAMESPACE] = ( 'geolocation', GeoLocation) _children['{%s}preferred-domain' % GWEBMASTERTOOLS_NAMESPACE] = ( 'preferred_domain', PreferredDomain) _children['{%s}crawl-rate' % GWEBMASTERTOOLS_NAMESPACE] = ( 'crawl_rate', CrawlRate) _children['{%s}enhanced-image-search' % GWEBMASTERTOOLS_NAMESPACE] = ( 'enhanced_image_search', EnhancedImageSearch) _children['{%s}verified' % GWEBMASTERTOOLS_NAMESPACE] = ( 'verified', Verified) _children['{%s}verification-method' % GWEBMASTERTOOLS_NAMESPACE] = ( 'verification_method', [VerificationMethod]) 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 __init__(self, category=None, content=None, atom_id=None, link=None, title=None, updated=None, entry_link=None, indexed=None, crawled=None, geolocation=None, preferred_domain=None, crawl_rate=None, enhanced_image_search=None, verified=None, verification_method=None, extension_elements=None, extension_attributes=None, text=None): atom.Entry.__init__(self, category=category, content=content, atom_id=atom_id, link=link, title=title, updated=updated, text=text) self.entry_link = entry_link or [] self.indexed = indexed self.crawled = crawled self.geolocation = geolocation self.preferred_domain = preferred_domain self.crawl_rate = crawl_rate self.enhanced_image_search = enhanced_image_search self.verified = verified self.verification_method = verification_method or [] def SitesEntryFromString(xml_string): return atom.CreateClassFromXMLString(SitesEntry, xml_string) class SitesFeed(atom.Feed, LinkFinder): """A Google Webmaster Tools meta Sites feed flavor of an Atom Feed""" _tag = atom.Feed._tag _namespace = atom.Feed._namespace _children = atom.Feed._children.copy() _attributes = atom.Feed._attributes.copy() _children['{%s}startIndex' % gdata.OPENSEARCH_NAMESPACE] = ( 'start_index', gdata.StartIndex) _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [SitesEntry]) del _children['{%s}generator' % atom.ATOM_NAMESPACE] del _children['{%s}author' % atom.ATOM_NAMESPACE] del _children['{%s}contributor' % atom.ATOM_NAMESPACE] del _children['{%s}logo' % atom.ATOM_NAMESPACE] del _children['{%s}icon' % atom.ATOM_NAMESPACE] del _children['{%s}rights' % atom.ATOM_NAMESPACE] del _children['{%s}subtitle' % atom.ATOM_NAMESPACE] 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 __init__(self, start_index=None, atom_id=None, title=None, entry=None, category=None, link=None, updated=None, extension_elements=None, extension_attributes=None, text=None): """Constructor for Source Args: category: list (optional) A list of Category instances id: Id (optional) The entry's Id element link: list (optional) A list of Link instances 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.start_index = start_index self.category = category or [] self.id = atom_id self.link = link or [] self.title = title self.updated = updated self.entry = entry or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SitesFeedFromString(xml_string): return atom.CreateClassFromXMLString(SitesFeed, xml_string) class SitemapsEntry(atom.Entry, LinkFinder): """A Google Webmaster Tools meta Sitemaps Entry flavor of an Atom Entry """ _tag = atom.Entry._tag _namespace = atom.Entry._namespace _children = atom.Entry._children.copy() _attributes = atom.Entry._attributes.copy() _children['{%s}sitemap-type' % GWEBMASTERTOOLS_NAMESPACE] = ( 'sitemap_type', SitemapType) _children['{%s}sitemap-status' % GWEBMASTERTOOLS_NAMESPACE] = ( 'sitemap_status', SitemapStatus) _children['{%s}sitemap-last-downloaded' % GWEBMASTERTOOLS_NAMESPACE] = ( 'sitemap_last_downloaded', SitemapLastDownloaded) _children['{%s}sitemap-url-count' % GWEBMASTERTOOLS_NAMESPACE] = ( 'sitemap_url_count', SitemapUrlCount) _children['{%s}sitemap-mobile-markup-language' % GWEBMASTERTOOLS_NAMESPACE] \ = ('sitemap_mobile_markup_language', SitemapMobileMarkupLanguage) _children['{%s}sitemap-news-publication-label' % GWEBMASTERTOOLS_NAMESPACE] \ = ('sitemap_news_publication_label', SitemapNewsPublicationLabel) 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 __init__(self, category=None, content=None, atom_id=None, link=None, title=None, updated=None, sitemap_type=None, sitemap_status=None, sitemap_last_downloaded=None, sitemap_url_count=None, sitemap_mobile_markup_language=None, sitemap_news_publication_label=None, extension_elements=None, extension_attributes=None, text=None): atom.Entry.__init__(self, category=category, content=content, atom_id=atom_id, link=link, title=title, updated=updated, text=text) self.sitemap_type = sitemap_type self.sitemap_status = sitemap_status self.sitemap_last_downloaded = sitemap_last_downloaded self.sitemap_url_count = sitemap_url_count self.sitemap_mobile_markup_language = sitemap_mobile_markup_language self.sitemap_news_publication_label = sitemap_news_publication_label def SitemapsEntryFromString(xml_string): return atom.CreateClassFromXMLString(SitemapsEntry, xml_string) class SitemapsFeed(atom.Feed, LinkFinder): """A Google Webmaster Tools meta Sitemaps feed flavor of an Atom Feed""" _tag = atom.Feed._tag _namespace = atom.Feed._namespace _children = atom.Feed._children.copy() _attributes = atom.Feed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [SitemapsEntry]) _children['{%s}sitemap-mobile' % GWEBMASTERTOOLS_NAMESPACE] = ( 'sitemap_mobile', SitemapMobile) _children['{%s}sitemap-news' % GWEBMASTERTOOLS_NAMESPACE] = ( 'sitemap_news', SitemapNews) del _children['{%s}generator' % atom.ATOM_NAMESPACE] del _children['{%s}author' % atom.ATOM_NAMESPACE] del _children['{%s}contributor' % atom.ATOM_NAMESPACE] del _children['{%s}logo' % atom.ATOM_NAMESPACE] del _children['{%s}icon' % atom.ATOM_NAMESPACE] del _children['{%s}rights' % atom.ATOM_NAMESPACE] del _children['{%s}subtitle' % atom.ATOM_NAMESPACE] 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 __init__(self, category=None, content=None, atom_id=None, link=None, title=None, updated=None, entry=None, sitemap_mobile=None, sitemap_news=None, extension_elements=None, extension_attributes=None, text=None): self.category = category or [] self.id = atom_id self.link = link or [] self.title = title self.updated = updated self.entry = entry or [] self.text = text self.sitemap_mobile = sitemap_mobile self.sitemap_news = sitemap_news self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SitemapsFeedFromString(xml_string): return atom.CreateClassFromXMLString(SitemapsFeed, 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 Dublin Core Metadata Initiative (DCMI) Extension""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core DC_TEMPLATE = '{http://purl.org/dc/terms/}%s' class Creator(atom.core.XmlElement): """Entity primarily responsible for making the resource.""" _qname = DC_TEMPLATE % 'creator' class Date(atom.core.XmlElement): """Point or period of time associated with an event in the lifecycle of the resource.""" _qname = DC_TEMPLATE % 'date' class Description(atom.core.XmlElement): """Account of the resource.""" _qname = DC_TEMPLATE % 'description' class Format(atom.core.XmlElement): """File format, physical medium, or dimensions of the resource.""" _qname = DC_TEMPLATE % 'format' class Identifier(atom.core.XmlElement): """An unambiguous reference to the resource within a given context.""" _qname = DC_TEMPLATE % 'identifier' class Language(atom.core.XmlElement): """Language of the resource.""" _qname = DC_TEMPLATE % 'language' class Publisher(atom.core.XmlElement): """Entity responsible for making the resource available.""" _qname = DC_TEMPLATE % 'publisher' class Rights(atom.core.XmlElement): """Information about rights held in and over the resource.""" _qname = DC_TEMPLATE % 'rights' class Subject(atom.core.XmlElement): """Topic of the resource.""" _qname = DC_TEMPLATE % 'subject' class Title(atom.core.XmlElement): """Name given to the resource.""" _qname = DC_TEMPLATE % 'title'
Python