code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
#!/usr/bin/python2.4
#
# Copyright 2011 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 tests for the Provisioning API."""
__author__ = 'Shraddha Gupta <shraddhag@google.com>'
import unittest
import atom.core
from gdata import test_data
import gdata.apps.data
import gdata.test_config as conf
class UserEntryTest(unittest.TestCase):
def setUp(self):
self.entry = atom.core.parse(test_data.USER_ENTRY1,
gdata.apps.data.UserEntry)
self.feed = atom.core.parse(test_data.USER_FEED1,
gdata.apps.data.UserFeed)
def testUserEntryFromString(self):
self.assert_(isinstance(self.entry,
gdata.apps.data.UserEntry))
self.assertEquals(self.entry.name.given_name, 'abcd33')
self.assertEquals(self.entry.name.family_name, 'efgh3')
self.assertEquals(self.entry.login.user_name, 'abcd12310')
self.assertEquals(self.entry.login.suspended, 'false')
self.assertEquals(self.entry.login.admin, 'false')
self.assertEquals(self.entry.quota.limit, '25600')
def testUserFeedFromString(self):
self.assertEquals(len(self.feed.entry), 2)
self.assert_(isinstance(self.feed, gdata.apps.data.UserFeed))
self.assert_(isinstance(self.feed.entry[0], gdata.apps.data.UserEntry))
self.assert_(isinstance(self.feed.entry[1], gdata.apps.data.UserEntry))
self.assertEquals(self.feed.entry[0].find_edit_link(),
('https://apps-apis.google.com/a/feeds/srkapps.com/user/2.0/user8306'))
self.assertEquals(self.feed.entry[0].name.given_name, 'FirstName8306')
self.assertEquals(self.feed.entry[0].name.family_name, 'LastName8306')
self.assertEquals(self.feed.entry[0].login.user_name, 'user8306')
self.assertEquals(self.feed.entry[0].login.admin, 'false')
self.assertEquals(self.feed.entry[0].login.suspended, 'false')
self.assertEquals(self.feed.entry[0].login.change_password, 'false')
self.assertEquals(self.feed.entry[0].login.ip_whitelisted, 'false')
self.assertEquals(self.feed.entry[0].quota.limit, '25600')
self.assertEquals(
self.feed.entry[1].find_edit_link(),
('https://apps-apis.google.com/a/feeds/srkapps.com/user/2.0/user8307'))
self.assertEquals(self.feed.entry[1].name.given_name, 'FirstName8307')
self.assertEquals(self.feed.entry[1].name.family_name, 'LastName8307')
self.assertEquals(self.feed.entry[1].login.user_name, 'user8307')
self.assertEquals(self.feed.entry[1].login.admin, 'false')
self.assertEquals(self.feed.entry[1].login.suspended, 'false')
self.assertEquals(self.feed.entry[1].login.change_password, 'false')
self.assertEquals(self.feed.entry[1].login.ip_whitelisted, 'false')
self.assertEquals(self.feed.entry[1].quota.limit, '25600')
class NicknameEntryTest(unittest.TestCase):
def setUp(self):
self.entry = atom.core.parse(test_data.NICKNAME_ENTRY,
gdata.apps.data.NicknameEntry)
self.feed = atom.core.parse(test_data.NICKNAME_FEED,
gdata.apps.data.NicknameFeed)
def testNicknameEntryFromString(self):
self.assert_(isinstance(self.entry,
gdata.apps.data.NicknameEntry))
self.assertEquals(self.entry.nickname.name, 'nehag')
self.assertEquals(self.entry.login.user_name, 'neha')
def testNicknameFeedFromString(self):
self.assertEquals(len(self.feed.entry), 2)
self.assert_(isinstance(self.feed,
gdata.apps.data.NicknameFeed))
self.assert_(isinstance(self.feed.entry[0],
gdata.apps.data.NicknameEntry))
self.assert_(isinstance(self.feed.entry[1],
gdata.apps.data.NicknameEntry))
self.assertEquals(
self.feed.entry[0].find_edit_link(),
('https://apps-apis.google.com/a/feeds/srkapps.net/'
'nickname/2.0/nehag'))
self.assertEquals(self.feed.entry[0].nickname.name, 'nehag')
self.assertEquals(self.feed.entry[0].login.user_name, 'neha')
self.assertEquals(
self.feed.entry[1].find_edit_link(),
('https://apps-apis.google.com/a/feeds/srkapps.net/'
'nickname/2.0/richag'))
self.assertEquals(self.feed.entry[1].nickname.name, 'richag')
self.assertEquals(self.feed.entry[1].login.user_name, 'richa')
def suite():
return conf.build_suite([UserEntryTest, NicknameEntryTest])
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python2.4
#
# Copyright 2011 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.
"""Live client tests for the Organization Unit Provisioning API."""
# This module is used for version 2 of the Google Data APIs.
# These tests attempt to connect to Google servers.
__author__ = 'Gunjan Sharma <gunjansharma@google.com>'
import random
import unittest
import gdata.apps.organization.client
import gdata.apps.organization.data
import gdata.client
import gdata.data
import gdata.gauth
import gdata.test_config as conf
conf.options.register_option(conf.APPS_DOMAIN_OPTION)
class OrganizationUnitProvisioningClientTest(unittest.TestCase):
def setUp(self):
self.client = gdata.apps.organization.client.OrganizationUnitProvisioningClient(
domain='example.com')
if conf.options.get_value('runlive') == 'true':
self.client = gdata.apps.organization.client.OrganizationUnitProvisioningClient(
domain=conf.options.get_value('appsdomain'))
if conf.options.get_value('ssl') == 'true':
self.client.ssl = True
conf.configure_client(self.client,
'OrganizationUnitProvisioningClientTest',
self.client.auth_service, True)
def tearDown(self):
conf.close_client(self.client)
def testClientConfiguration(self):
self.assertEqual('apps-apis.google.com', self.client.host)
self.assertEqual('2.0', self.client.api_version)
self.assertEqual('apps', self.client.auth_service)
self.assertEqual(
('https://apps-apis.google.com/a/feeds/user/',
'https://apps-apis.google.com/a/feeds/policies/',
'https://apps-apis.google.com/a/feeds/alias/',
'https://apps-apis.google.com/a/feeds/groups/'),
self.client.auth_scopes)
if conf.options.get_value('runlive') == 'true':
self.assertEqual(self.client.domain,
conf.options.get_value('appsdomain'))
else:
self.assertEqual(self.client.domain, 'example.com')
def testMakeCustomerIdFeedUri(self):
self.assertEqual('/a/feeds/customer/2.0/customerId',
self.client.MakeCustomerIdFeedUri())
def testMakeOrganizationUnitOrgunitProvisioningUri(self):
self.customer_id = 'tempo'
self.assertEqual('/a/feeds/orgunit/2.0/%s' % self.customer_id,
self.client.MakeOrganizationUnitOrgunitProvisioningUri(
self.customer_id))
self.assertEqual(
'/a/feeds/orgunit/2.0/%s/testing/Test+Test' % self.customer_id,
self.client.MakeOrganizationUnitOrgunitProvisioningUri(
self.customer_id, org_unit_path='testing/Test+Test'))
self.assertEqual(
'/a/feeds/orgunit/2.0/%s?get=all' % (self.customer_id),
self.client.MakeOrganizationUnitOrgunitProvisioningUri(
self.customer_id, params={'get': 'all'}))
def testMakeOrganizationUnitOrguserProvisioningUri(self):
self.customer_id = 'tempo'
self.assertEqual('/a/feeds/orguser/2.0/%s' % self.customer_id,
self.client.MakeOrganizationUnitOrguserProvisioningUri(
self.customer_id))
self.assertEqual(
'/a/feeds/orguser/2.0/%s/admin@example.com' % self.customer_id,
self.client.MakeOrganizationUnitOrguserProvisioningUri(
self.customer_id, org_user_email='admin@example.com'))
self.assertEqual(
'/a/feeds/orguser/2.0/%s?get=all' % (self.customer_id),
self.client.MakeOrganizationUnitOrguserProvisioningUri(
self.customer_id, params={'get': 'all'}))
def testCreateRetrieveUpdateDelete(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'testCreateRetrieveUpdateDelete')
customer_id = self.client.RetrieveCustomerId().GetCustomerId()
rnd_number = random.randrange(0, 100001)
org_unit_name = 'test_org_unit_name%s' % (rnd_number)
org_unit_description = 'test_org_unit_description%s' % (rnd_number)
org_unit_path = org_unit_name
new_entry = self.client.CreateOrgUnit(customer_id, org_unit_name,
parent_org_unit_path='/',
description=org_unit_description,
block_inheritance=False)
self.assert_(isinstance(new_entry,
gdata.apps.organization.data.OrgUnitEntry))
self.assertEquals(new_entry.org_unit_path, org_unit_path)
entry = self.client.RetrieveOrgUnit(customer_id, org_unit_path)
self.assert_(isinstance(entry,
gdata.apps.organization.data.OrgUnitEntry))
self.assertEquals(entry.org_unit_name, org_unit_name)
self.assertEquals(entry.org_unit_description, org_unit_description)
self.assertEquals(entry.parent_org_unit_path, '')
self.assertEquals(entry.org_unit_path, org_unit_path)
self.assertEquals(entry.org_unit_block_inheritance, 'false')
self.client.DeleteOrgUnit(customer_id, org_unit_name)
def suite():
return conf.build_suite([OrganizationUnitProvisioningClientTest])
if __name__ == '__main__':
unittest.TextTestRunner().run(suite())
| 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.
"""Test for Organization service."""
__author__ = 'Alexandre Vivien (alex@simplecode.fr)'
import urllib
import unittest
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata.apps
import gdata.apps.service
import gdata.apps.organization.service
import getpass
import time
domain = ''
admin_email = ''
admin_password = ''
username = ''
class OrganizationTest(unittest.TestCase):
"""Test for the OrganizationService."""
def setUp(self):
self.postfix = time.strftime("%Y%m%d%H%M%S")
self.apps_client = gdata.apps.service.AppsService(
email=admin_email, domain=domain, password=admin_password,
source='OrganizationClient "Unit" Tests')
self.apps_client.ProgrammaticLogin()
self.organization_client = gdata.apps.organization.service.OrganizationService(
email=admin_email, domain=domain, password=admin_password,
source='GroupsClient "Unit" Tests')
self.organization_client.ProgrammaticLogin()
self.created_users = []
self.created_org_units = []
self.cutomer_id = None
self.createUsers();
def createUsers(self):
user_name = 'yujimatsuo-' + self.postfix
family_name = 'Matsuo'
given_name = 'Yuji'
password = '123$$abc'
suspended = 'false'
try:
self.user_yuji = self.apps_client.CreateUser(user_name=user_name,
family_name=family_name,
given_name=given_name,
password=password,
suspended=suspended)
print 'User ' + user_name + ' created'
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.created_users.append(self.user_yuji)
user_name = 'taromatsuo-' + self.postfix
family_name = 'Matsuo'
given_name = 'Taro'
password = '123$$abc'
suspended = 'false'
try:
self.user_taro = self.apps_client.CreateUser(user_name=user_name,
family_name=family_name,
given_name=given_name,
password=password,
suspended=suspended)
print 'User ' + user_name + ' created'
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.created_users.append(self.user_taro)
user_name = 'alexandrevivien-' + self.postfix
family_name = 'Vivien'
given_name = 'Alexandre'
password = '123$$abc'
suspended = 'false'
try:
self.user_alex = self.apps_client.CreateUser(user_name=user_name,
family_name=family_name,
given_name=given_name,
password=password,
suspended=suspended)
print 'User ' + user_name + ' created'
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.created_users.append(self.user_alex)
def tearDown(self):
print '\n'
for user in self.created_users:
try:
self.apps_client.DeleteUser(user.login.user_name)
print 'User ' + user.login.user_name + ' deleted'
except Exception, e:
print e
# We reverse to delete sub OrgUnit first
self.created_org_units.reverse()
for org_unit_path in self.created_org_units:
try:
self.organization_client.DeleteOrgUnit(self.customer_id, org_unit_path)
print 'OrgUnit ' + org_unit_path + ' deleted'
except Exception, e:
print e
def testOrganizationService(self):
# tests RetrieveCustomerId method
try:
customer = self.organization_client.RetrieveCustomerId()
self.customer_id = customer['customerId']
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
print 'tests RetrieveCustomerId successful'
# tests CreateOrgUnit method
orgUnit01_name = 'OrgUnit01-' + self.postfix
orgUnit02_name = 'OrgUnit02-' + self.postfix
sub0rgUnit01_name = 'SubOrgUnit01-' + self.postfix
orgUnit03_name = 'OrgUnit03-' + self.postfix
try:
orgUnit01 = self.organization_client.CreateOrgUnit(self.customer_id,
name=orgUnit01_name,
parent_org_unit_path='/',
description='OrgUnit Test 01',
block_inheritance=False)
orgUnit02 = self.organization_client.CreateOrgUnit(self.customer_id,
name=orgUnit02_name,
parent_org_unit_path='/',
description='OrgUnit Test 02',
block_inheritance=False)
sub0rgUnit01 = self.organization_client.CreateOrgUnit(self.customer_id,
name=sub0rgUnit01_name,
parent_org_unit_path=orgUnit02['orgUnitPath'],
description='SubOrgUnit Test 01',
block_inheritance=False)
orgUnit03 = self.organization_client.CreateOrgUnit(self.customer_id,
name=orgUnit03_name,
parent_org_unit_path='/',
description='OrgUnit Test 03',
block_inheritance=False)
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(orgUnit01['orgUnitPath'], urllib.quote_plus(orgUnit01_name))
self.assertEquals(orgUnit02['orgUnitPath'], urllib.quote_plus(orgUnit02_name))
self.assertEquals(sub0rgUnit01['orgUnitPath'], urllib.quote_plus(orgUnit02_name) + '/' + urllib.quote_plus(sub0rgUnit01_name))
self.assertEquals(orgUnit03['orgUnitPath'], urllib.quote_plus(orgUnit03_name))
self.created_org_units.append(orgUnit01['orgUnitPath'])
self.created_org_units.append(orgUnit02['orgUnitPath'])
self.created_org_units.append(sub0rgUnit01['orgUnitPath'])
self.created_org_units.append(orgUnit03['orgUnitPath'])
print 'tests CreateOrgUnit successful'
# tests UpdateOrgUnit method
try:
updated_orgunit = self.organization_client.UpdateOrgUnit(self.customer_id,
org_unit_path=self.created_org_units[3],
description='OrgUnit Test 03 Updated description')
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(updated_orgunit['orgUnitPath'], self.created_org_units[3])
print 'tests UpdateOrgUnit successful'
# tests RetrieveOrgUnit method
try:
retrieved_orgunit = self.organization_client.RetrieveOrgUnit(self.customer_id,
org_unit_path=self.created_org_units[1])
retrieved_suborgunit = self.organization_client.RetrieveOrgUnit(self.customer_id,
org_unit_path=self.created_org_units[2])
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(retrieved_orgunit['orgUnitPath'], self.created_org_units[1])
self.assertEquals(retrieved_suborgunit['orgUnitPath'], self.created_org_units[2])
print 'tests RetrieveOrgUnit successful'
# tests RetrieveAllOrgUnits method
try:
retrieved_orgunits = self.organization_client.RetrieveAllOrgUnits(self.customer_id)
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertTrue(len(retrieved_orgunits) >= len(self.created_org_units))
print 'tests RetrieveAllOrgUnits successful'
# tests MoveUserToOrgUnit method
try:
updated_orgunit01 = self.organization_client.MoveUserToOrgUnit(self.customer_id,
org_unit_path=self.created_org_units[0],
users_to_move=[self.user_yuji.login.user_name + '@' + domain])
updated_orgunit02 = self.organization_client.MoveUserToOrgUnit(self.customer_id,
org_unit_path=self.created_org_units[1],
users_to_move=[self.user_taro.login.user_name + '@' + domain,
self.user_alex.login.user_name + '@' + domain])
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(updated_orgunit01['usersMoved'], self.user_yuji.login.user_name + '@' + domain)
self.assertEquals(updated_orgunit02['usersMoved'], self.user_taro.login.user_name + '@' + domain + ',' + \
self.user_alex.login.user_name + '@' + domain)
print 'tests MoveUserToOrgUnit successful'
# tests RetrieveSubOrgUnits method
try:
retrieved_suborgunits = self.organization_client.RetrieveSubOrgUnits(self.customer_id,
org_unit_path=self.created_org_units[1])
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(len(retrieved_suborgunits), 1)
self.assertEquals(retrieved_suborgunits[0]['orgUnitPath'], self.created_org_units[2])
print 'tests RetrieveSubOrgUnits successful'
# tests RetrieveOrgUser method
try:
retrieved_orguser = self.organization_client.RetrieveOrgUser(self.customer_id,
user_email=self.user_yuji.login.user_name + '@' + domain)
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(retrieved_orguser['orgUserEmail'], self.user_yuji.login.user_name + '@' + domain)
self.assertEquals(retrieved_orguser['orgUnitPath'], self.created_org_units[0])
print 'tests RetrieveOrgUser successful'
# tests UpdateOrgUser method
try:
updated_orguser = self.organization_client.UpdateOrgUser(self.customer_id,
org_unit_path=self.created_org_units[0],
user_email=self.user_alex.login.user_name + '@' + domain)
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(updated_orguser['orgUserEmail'], self.user_alex.login.user_name + '@' + domain)
self.assertEquals(updated_orguser['orgUnitPath'], self.created_org_units[0])
print 'tests UpdateOrgUser successful'
# tests RetrieveAllOrgUsers method
try:
retrieved_orgusers = self.organization_client.RetrieveAllOrgUsers(self.customer_id)
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertTrue(len(retrieved_orgusers) >= len(self.created_users))
print 'tests RetrieveAllOrgUsers successful'
""" This test needs to create more than 100 test users
# tests RetrievePageOfOrgUsers method
try:
retrieved_orgusers01_feed = self.organization_client.RetrievePageOfOrgUsers(self.customer_id)
next = retrieved_orgusers01_feed.GetNextLink()
self.assertNotEquals(next, None)
startKey = next.href.split("startKey=")[1]
retrieved_orgusers02_feed = self.organization_client.RetrievePageOfOrgUsers(self.customer_id, startKey=startKey)
retrieved_orgusers01_entry = self.organization_client._PropertyEntry2Dict(retrieved_orgusers01_feed.entry[0])
retrieved_orgusers02_entry = self.organization_client._PropertyEntry2Dict(retrieved_orgusers02_feed.entry[0])
self.assertNotEquals(retrieved_orgusers01_entry['orgUserEmail'], retrieved_orgusers02_entry['orgUserEmail'])
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
print 'tests RetrievePageOfOrgUsers successful'
"""
# tests RetrieveOrgUnitUsers method
try:
retrieved_orgusers = self.organization_client.RetrieveOrgUnitUsers(self.customer_id,
org_unit_path=self.created_org_units[0])
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
self.assertEquals(len(retrieved_orgusers), 2)
print 'tests RetrieveOrgUnitUsers successful'
""" This test needs to create more than 100 test users
# tests RetrieveOrgUnitPageOfUsers method
try:
retrieved_orgusers01_feed = self.organization_client.RetrieveOrgUnitPageOfUsers(self.customer_id,
org_unit_path='/')
next = retrieved_orgusers01_feed.GetNextLink()
self.assertNotEquals(next, None)
startKey = next.href.split("startKey=")[1]
retrieved_orgusers02_feed = self.organization_client.RetrieveOrgUnitPageOfUsers(self.customer_id,
org_unit_path='/',
startKey=startKey)
retrieved_orgusers01_entry = self.organization_client._PropertyEntry2Dict(retrieved_orgusers01_feed.entry[0])
retrieved_orgusers02_entry = self.organization_client._PropertyEntry2Dict(retrieved_orgusers02_feed.entry[0])
self.assertNotEquals(retrieved_orgusers01_entry['orgUserEmail'], retrieved_orgusers02_entry['orgUserEmail'])
except Exception, e:
self.fail('Unexpected exception occurred: %s' % e)
print 'tests RetrieveOrgUnitPageOfUsers successful'
"""
if __name__ == '__main__':
print("""Google Apps Groups Service Tests
NOTE: Please run these tests only with a test user account.
""")
domain = raw_input('Google Apps domain: ')
admin_email = '%s@%s' % (raw_input('Administrator username: '), domain)
admin_password = getpass.getpass('Administrator password: ')
unittest.main()
| Python |
#!/usr/bin/python2.4
#
# Copyright 2011 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 tests for the Organization Unit Provisioning API."""
__author__ = 'Gunjan Sharma <gunjansharma@google.com>'
import unittest
import atom.core
from gdata import test_data
import gdata.apps.organization.data
import gdata.test_config as conf
class CustomerIdEntryTest(unittest.TestCase):
def setUp(self):
self.entry = atom.core.parse(test_data.ORGANIZATION_UNIT_CUSTOMER_ID_ENTRY,
gdata.apps.organization.data.CustomerIdEntry)
def testCustomerIdEntryFromString(self):
self.assert_(isinstance(self.entry,
gdata.apps.organization.data.CustomerIdEntry))
self.assertEquals(self.entry.customer_id, 'C123A456B')
self.assertEquals(self.entry.customer_org_unit_name, 'example.com')
self.assertEquals(self.entry.customer_org_unit_description, 'example.com')
self.assertEquals(self.entry.org_unit_name, 'example.com')
self.assertEquals(self.entry.org_unit_description, 'tempdescription')
class OrgUnitEntryTest(unittest.TestCase):
def setUp(self):
self.entry = atom.core.parse(test_data.ORGANIZATION_UNIT_ORGUNIT_ENTRY,
gdata.apps.organization.data.OrgUnitEntry)
self.feed = atom.core.parse(test_data.ORGANIZATION_UNIT_ORGUNIT_FEED,
gdata.apps.organization.data.OrgUnitFeed)
def testOrgUnitEntryFromString(self):
self.assert_(isinstance(self.entry,
gdata.apps.organization.data.OrgUnitEntry))
self.assertEquals(self.entry.org_unit_description, 'New Test Org')
self.assertEquals(self.entry.org_unit_name, 'Test Organization')
self.assertEquals(self.entry.org_unit_path, 'Test/Test+Organization')
self.assertEquals(self.entry.parent_org_unit_path, 'Test')
self.assertEquals(self.entry.org_unit_block_inheritance, 'false')
def testOrgUnitFeedFromString(self):
self.assertEquals(len(self.feed.entry), 2)
self.assert_(isinstance(self.feed,
gdata.apps.organization.data.OrgUnitFeed))
self.assert_(isinstance(self.feed.entry[0],
gdata.apps.organization.data.OrgUnitEntry))
self.assert_(isinstance(self.feed.entry[1],
gdata.apps.organization.data.OrgUnitEntry))
self.assertEquals(
self.feed.entry[0].find_edit_link(),
('https://apps-apis.google.com/a/feeds/orgunit/2.0/'
'C123A456B/testOrgUnit92'))
self.assertEquals(self.feed.entry[0].org_unit_description, 'test92')
self.assertEquals(self.feed.entry[0].org_unit_name, 'testOrgUnit92')
self.assertEquals(self.feed.entry[0].org_unit_path, 'Test/testOrgUnit92')
self.assertEquals(self.feed.entry[0].parent_org_unit_path, 'Test')
self.assertEquals(self.feed.entry[0].org_unit_block_inheritance, 'false')
self.assertEquals(
self.feed.entry[1].find_edit_link(),
('https://apps-apis.google.com/a/feeds/orgunit/2.0/'
'C123A456B/testOrgUnit93'))
self.assertEquals(self.feed.entry[1].org_unit_description, 'test93')
self.assertEquals(self.feed.entry[1].org_unit_name, 'testOrgUnit93')
self.assertEquals(self.feed.entry[1].org_unit_path, 'Test/testOrgUnit93')
self.assertEquals(self.feed.entry[1].parent_org_unit_path, 'Test')
self.assertEquals(self.feed.entry[1].org_unit_block_inheritance, 'false')
class OrgUserEntryTest(unittest.TestCase):
def setUp(self):
self.entry = atom.core.parse(test_data.ORGANIZATION_UNIT_ORGUSER_ENTRY,
gdata.apps.organization.data.OrgUserEntry)
self.feed = atom.core.parse(test_data.ORGANIZATION_UNIT_ORGUSER_FEED,
gdata.apps.organization.data.OrgUserFeed)
def testOrgUserEntryFromString(self):
self.assert_(isinstance(self.entry,
gdata.apps.organization.data.OrgUserEntry))
self.assertEquals(self.entry.user_email, 'admin@example.com')
self.assertEquals(self.entry.org_unit_path, 'Test')
def testOrgUserFeedFromString(self):
self.assertEquals(len(self.feed.entry), 2)
self.assert_(isinstance(self.feed,
gdata.apps.organization.data.OrgUserFeed))
self.assert_(isinstance(self.feed.entry[0],
gdata.apps.organization.data.OrgUserEntry))
self.assert_(isinstance(self.feed.entry[1],
gdata.apps.organization.data.OrgUserEntry))
self.assertEquals(
self.feed.entry[0].find_edit_link(),
('https://apps-apis.google.com/a/feeds/orguser/2.0/'
'C123A456B/user720430%40example.com'))
self.assertEquals(self.feed.entry[0].user_email, 'user720430@example.com')
self.assertEquals(self.feed.entry[0].org_unit_path, 'Test')
self.assertEquals(
self.feed.entry[1].find_edit_link(),
('https://apps-apis.google.com/a/feeds/orguser/2.0/'
'C123A456B/user832648%40example.com'))
self.assertEquals(self.feed.entry[1].user_email, 'user832648@example.com')
self.assertEquals(self.feed.entry[1].org_unit_path, 'Test')
def suite():
return conf.build_suite([OrgUnitEntryTest, OrgUserEntryTest])
if __name__ == '__main__':
unittest.main()
| 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)'
import unittest
import time, os
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import re
import pickle
import atom
import atom.http
import atom.service
from atom import mock_http
import gdata.apps
import gdata.apps.service
import getpass
apps_domain = 'test.shehas.net'
apps_username = ''
apps_password = ''
def conceal_secrets(recordings):
ret = []
for rec in recordings:
req, res = rec
if req.data:
req.data = re.sub(r'Passwd=[^&]+', 'Passwd=hogehoge', req.data)
if res.body:
res.body = re.sub(r'SID=[^\n]+', 'SID=hogehoge', res.body)
res.body = re.sub(r'LSID=[^\n]+', 'LSID=hogehoge', res.body)
res.body = re.sub(r'Auth=[^\n]+', 'Auth=hogehoge', res.body)
if req.headers.has_key('Authorization'):
req.headers['Authorization'] = 'hogehoge'
ret.append((req, res))
return ret
class AppsServiceBaseTest(object):
def setUp(self):
self.datafile = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"%s.pickle" % self.name)
if os.path.isfile(self.datafile):
f = open(self.datafile, "rb")
data = pickle.load(f)
f.close()
http_client = mock_http.MockHttpClient(recordings=data)
else:
real_client = atom.http.ProxiedHttpClient()
http_client = mock_http.MockHttpClient(real_client=real_client)
email = apps_username + '@' + apps_domain
self.apps_client = gdata.apps.service.AppsService(
email=email, domain=apps_domain, password=apps_password,
source='AppsClient "Unit" Tests')
self.apps_client.http_client = http_client
self.apps_client.ProgrammaticLogin()
def tearDown(self):
if self.apps_client.http_client.real_client:
# create pickle file
f = open(self.datafile, "wb")
data = conceal_secrets(self.apps_client.http_client.recordings)
pickle.dump(data, f)
f.close()
class AppsServiceTestForGetGeneratorForAllRecipients(AppsServiceBaseTest,
unittest.TestCase):
name = "AppsServiceTestForGetGeneratorForAllRecipients"
def testGetGeneratorForAllRecipients(self):
"""Tests GetGeneratorForAllRecipientss method"""
generator = self.apps_client.GetGeneratorForAllRecipients(
"b101-20091013151051")
i = 0
for recipient_feed in generator:
for a_recipient in recipient_feed.entry:
i = i + 1
self.assert_(i == 102)
class AppsServiceTestForGetGeneratorForAllEmailLists(AppsServiceBaseTest,
unittest.TestCase):
name = "AppsServiceTestForGetGeneratorForAllEmailLists"
def testGetGeneratorForAllEmailLists(self):
"""Tests GetGeneratorForAllEmailLists method"""
generator = self.apps_client.GetGeneratorForAllEmailLists()
i = 0
for emaillist_feed in generator:
for a_emaillist in emaillist_feed.entry:
i = i + 1
self.assert_(i == 105)
class AppsServiceTestForGetGeneratorForAllNicknames(AppsServiceBaseTest,
unittest.TestCase):
name = "AppsServiceTestForGetGeneratorForAllNicknames"
def testGetGeneratorForAllNicknames(self):
"""Tests GetGeneratorForAllNicknames method"""
generator = self.apps_client.GetGeneratorForAllNicknames()
i = 0
for nickname_feed in generator:
for a_nickname in nickname_feed.entry:
i = i + 1
self.assert_(i == 102)
class AppsServiceTestForGetGeneratorForAllUsers(AppsServiceBaseTest,
unittest.TestCase):
name = "AppsServiceTestForGetGeneratorForAllUsers"
def testGetGeneratorForAllUsers(self):
"""Tests GetGeneratorForAllUsers method"""
generator = self.apps_client.GetGeneratorForAllUsers()
i = 0
for user_feed in generator:
for a_user in user_feed.entry:
i = i + 1
self.assert_(i == 102)
if __name__ == '__main__':
print ('The tests may delete or update your data.')
apps_username = raw_input('Please enter your username: ')
apps_password = getpass.getpass()
unittest.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.
# This module is used for version 2 of the Google Data APIs.
# These tests attempt to connect to Google servers.
__author__ = 'Claudio Cherubino <ccherubino@google.com>'
import unittest
import gdata.apps.emailsettings.client
import gdata.apps.emailsettings.data
import gdata.client
import gdata.data
import gdata.gauth
import gdata.test_config as conf
conf.options.register_option(conf.APPS_DOMAIN_OPTION)
conf.options.register_option(conf.TARGET_USERNAME_OPTION)
class EmailSettingsClientTest(unittest.TestCase):
def setUp(self):
self.client = gdata.apps.emailsettings.client.EmailSettingsClient(
domain='example.com')
if conf.options.get_value('runlive') == 'true':
self.client = gdata.apps.emailsettings.client.EmailSettingsClient(
domain=conf.options.get_value('appsdomain'))
if conf.options.get_value('ssl') == 'true':
self.client.ssl = True
conf.configure_client(self.client, 'EmailSettingsClientTest',
self.client.auth_service, True)
self.username = conf.options.get_value('appsusername').split('@')[0]
def tearDown(self):
conf.close_client(self.client)
def testClientConfiguration(self):
self.assertEqual('apps-apis.google.com', self.client.host)
self.assertEqual('2.0', self.client.api_version)
self.assertEqual('apps', self.client.auth_service)
if conf.options.get_value('runlive') == 'true':
self.assertEqual(self.client.domain, conf.options.get_value('appsdomain'))
else:
self.assertEqual(self.client.domain, 'example.com')
def testMakeEmailSettingsUri(self):
self.assertEqual('/a/feeds/emailsettings/2.0/%s/%s/%s' % (self.client.domain,
'abc', 'label'),
self.client.MakeEmailSettingsUri('abc', 'label'))
def testCreateDeleteLabel(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'testCreateLabel')
new_label = self.client.CreateLabel(
username=conf.options.get_value('targetusername'),
name='status updates')
self.assert_(isinstance(new_label,
gdata.apps.emailsettings.data.EmailSettingsLabel))
self.assertEqual(new_label.name, 'status updates')
self.client.DeleteLabel(
username=conf.options.get_value('targetusername'),
label='status updates')
def testCreateFilter(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'testCreateFilter')
new_filter = self.client.CreateFilter(
username=conf.options.get_value('targetusername'),
from_address='alice@gmail.com',
has_the_word='project proposal', mark_as_read=True)
self.assert_(isinstance(new_filter,
gdata.apps.emailsettings.data.EmailSettingsFilter))
self.assertEqual(new_filter.from_address, 'alice@gmail.com')
self.assertEqual(new_filter.has_the_word, 'project proposal')
self.assertEqual(new_filter.mark_as_read, 'True')
new_filter = self.client.CreateFilter(
username=conf.options.get_value('targetusername'),
to_address='announcements@example.com',
label="announcements")
self.assert_(isinstance(new_filter,
gdata.apps.emailsettings.data.EmailSettingsFilter))
self.assertEqual(new_filter.to_address, 'announcements@example.com')
self.assertEqual(new_filter.label, 'announcements')
new_filter = self.client.CreateFilter(
username=conf.options.get_value('targetusername'),
subject='urgent',
does_not_have_the_word='spam',
has_attachments=True,
archive=True)
self.assert_(isinstance(new_filter,
gdata.apps.emailsettings.data.EmailSettingsFilter))
self.assertEqual(new_filter.subject, 'urgent')
self.assertEqual(new_filter.does_not_have_the_word, 'spam')
self.assertEqual(new_filter.has_attachments, 'True')
self.assertEqual(new_filter.archive, 'True')
def testCreateSendAs(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'testCreateSendAs')
new_sendas = self.client.CreateSendAs(
username=conf.options.get_value('targetusername'),
name='Sales', address=conf.options.get_value('appsusername'),
reply_to='abc@gmail.com',
make_default=True)
self.assert_(isinstance(new_sendas,
gdata.apps.emailsettings.data.EmailSettingsSendAsAlias))
self.assertEqual(new_sendas.name, 'Sales')
self.assertEqual(new_sendas.address,
conf.options.get_value('appsusername'))
self.assertEqual(new_sendas.reply_to, 'abc@gmail.com')
self.assertEqual(new_sendas.make_default, 'True')
def testUpdateWebclip(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'testUpdateWebclip')
new_webclip = self.client.UpdateWebclip(
username=conf.options.get_value('targetusername'),
enable=True)
self.assert_(isinstance(new_webclip,
gdata.apps.emailsettings.data.EmailSettingsWebClip))
self.assertEqual(new_webclip.enable, 'True')
new_webclip = self.client.UpdateWebclip(
username=conf.options.get_value('targetusername'),
enable=False)
self.assert_(isinstance(new_webclip,
gdata.apps.emailsettings.data.EmailSettingsWebClip))
self.assertEqual(new_webclip.enable, 'False')
def testUpdateForwarding(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'testUpdateForwarding')
new_forwarding = self.client.UpdateForwarding(
username=conf.options.get_value('targetusername'),
enable=True,
forward_to=conf.options.get_value('appsusername'),
action='KEEP')
self.assert_(isinstance(new_forwarding,
gdata.apps.emailsettings.data.EmailSettingsForwarding))
self.assertEqual(new_forwarding.enable, 'True')
self.assertEqual(new_forwarding.forward_to,
conf.options.get_value('appsusername'))
self.assertEqual(new_forwarding.action, 'KEEP')
new_forwarding = self.client.UpdateForwarding(
username=conf.options.get_value('targetusername'),
enable=False)
self.assert_(isinstance(new_forwarding,
gdata.apps.emailsettings.data.EmailSettingsForwarding))
self.assertEqual(new_forwarding.enable, 'False')
def testUpdatePop(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'testUpdatePop')
new_pop = self.client.UpdatePop(
username=conf.options.get_value('targetusername'),
enable=True, enable_for='MAIL_FROM_NOW_ON', action='KEEP')
self.assert_(isinstance(new_pop,
gdata.apps.emailsettings.data.EmailSettingsPop))
self.assertEqual(new_pop.enable, 'True')
self.assertEqual(new_pop.enable_for, 'MAIL_FROM_NOW_ON')
self.assertEqual(new_pop.action, 'KEEP')
new_pop = self.client.UpdatePop(
username=conf.options.get_value('targetusername'),
enable=False)
self.assert_(isinstance(new_pop,
gdata.apps.emailsettings.data.EmailSettingsPop))
self.assertEqual(new_pop.enable, 'False')
def testUpdateImap(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'testUpdateImap')
new_imap = self.client.UpdateImap(
username=conf.options.get_value('targetusername'),
enable=True)
self.assert_(isinstance(new_imap,
gdata.apps.emailsettings.data.EmailSettingsImap))
self.assertEqual(new_imap.enable, 'True')
new_imap = self.client.UpdateImap(
username=conf.options.get_value('targetusername'),
enable=False)
self.assert_(isinstance(new_imap,
gdata.apps.emailsettings.data.EmailSettingsImap))
self.assertEqual(new_imap.enable, 'False')
def testUpdateVacation(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'testUpdateVacation')
new_vacation = self.client.UpdateVacation(
username=conf.options.get_value('targetusername'),
enable=True, subject='Out of office',
message='If urgent call me at 555-5555.',
start_date='2011-12-05', end_date='2011-12-06',
contacts_only=True, domain_only=False)
self.assert_(isinstance(new_vacation,
gdata.apps.emailsettings.data.EmailSettingsVacationResponder))
self.assertEqual(new_vacation.enable, 'True')
self.assertEqual(new_vacation.subject, 'Out of office')
self.assertEqual(new_vacation.message, 'If urgent call me at 555-5555.')
self.assertEqual(new_vacation.start_date, '2011-12-05')
self.assertEqual(new_vacation.end_date, '2011-12-06')
self.assertEqual(new_vacation.contacts_only, 'True')
self.assertEqual(new_vacation.domain_only, 'False')
new_vacation = self.client.UpdateVacation(
username=conf.options.get_value('targetusername'),
enable=False)
self.assert_(isinstance(new_vacation,
gdata.apps.emailsettings.data.EmailSettingsVacationResponder))
self.assertEqual(new_vacation.enable, 'False')
def testUpdateSignature(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'testUpdateSignature')
new_signature = self.client.UpdateSignature(
username=conf.options.get_value('targetusername'),
signature='Regards, Joe')
self.assert_(isinstance(new_signature,
gdata.apps.emailsettings.data.EmailSettingsSignature))
self.assertEqual(new_signature.signature_value, 'Regards, Joe')
new_signature = self.client.UpdateSignature(
username=conf.options.get_value('targetusername'),
signature='')
self.assert_(isinstance(new_signature,
gdata.apps.emailsettings.data.EmailSettingsSignature))
self.assertEqual(new_signature.signature_value, '')
def testUpdateLanguage(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'testUpdateLanguage')
new_language = self.client.UpdateLanguage(
username=conf.options.get_value('targetusername'),
language='es')
self.assert_(isinstance(new_language,
gdata.apps.emailsettings.data.EmailSettingsLanguage))
self.assertEqual(new_language.language_tag, 'es')
def testUpdateGeneral(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'testUpdateGeneral')
new_general = self.client.UpdateGeneralSettings(
username=conf.options.get_value('targetusername'),
page_size=25, arrows=True)
self.assert_(isinstance(new_general,
gdata.apps.emailsettings.data.EmailSettingsGeneral))
self.assertEqual(new_general.page_size, '25')
self.assertEqual(new_general.arrows, 'True')
new_general = self.client.UpdateGeneralSettings(
username=conf.options.get_value('targetusername'),
shortcuts=False, snippets=True, use_unicode=False)
self.assert_(isinstance(new_general,
gdata.apps.emailsettings.data.EmailSettingsGeneral))
self.assertEqual(new_general.shortcuts, 'False')
self.assertEqual(new_general.snippets, 'True')
self.assertEqual(new_general.use_unicode, 'False')
def suite():
return conf.build_suite([EmailSettingsClientTest])
if __name__ == '__main__':
unittest.TextTestRunner().run(suite())
| 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.
"""Test for Email Settings service."""
__author__ = 'google-apps-apis@googlegroups.com'
import getpass
import gdata.apps.emailsettings.service
import unittest
domain = ''
admin_email = ''
admin_password = ''
username = ''
class EmailSettingsTest(unittest.TestCase):
"""Test for the EmailSettingsService."""
def setUp(self):
self.es = gdata.apps.emailsettings.service.EmailSettingsService(
email=admin_email, password=admin_password, domain=domain)
self.es.ProgrammaticLogin()
def testCreateLabel(self):
result = self.es.CreateLabel(username, label='New label!!!')
self.assertEquals(result['label'], 'New label!!!')
def testCreateFilter(self):
result = self.es.CreateFilter(username,
from_='from_foo',
to='to_foo',
subject='subject_foo',
has_the_word='has_the_words_foo',
does_not_have_the_word='doesnt_have_foo',
has_attachment=True,
label='label_foo',
should_mark_as_read=True,
should_archive=True)
self.assertEquals(result['from'], 'from_foo')
self.assertEquals(result['to'], 'to_foo')
self.assertEquals(result['subject'], 'subject_foo')
def testCreateSendAsAlias(self):
result = self.es.CreateSendAsAlias(username,
name='Send-as Alias',
address='user2@sizzles.org',
reply_to='user3@sizzles.org',
make_default=True)
self.assertEquals(result['name'], 'Send-as Alias')
def testUpdateWebClipSettings(self):
result = self.es.UpdateWebClipSettings(username, enable=True)
self.assertEquals(result['enable'], 'true')
def testUpdateForwarding(self):
result = self.es.UpdateForwarding(username,
enable=True,
forward_to='user4@sizzles.org',
action=gdata.apps.emailsettings.service.KEEP)
self.assertEquals(result['enable'], 'true')
def testUpdatePop(self):
result = self.es.UpdatePop(username,
enable=True,
enable_for=gdata.apps.emailsettings.service.ALL_MAIL,
action=gdata.apps.emailsettings.service.ARCHIVE)
self.assertEquals(result['enable'], 'true')
def testUpdateImap(self):
result = self.es.UpdateImap(username, enable=True)
self.assertEquals(result['enable'], 'true')
def testUpdateVacation(self):
result = self.es.UpdateVacation(username,
enable=True,
subject='Hawaii',
message='Wish you were here!',
contacts_only=True)
self.assertEquals(result['subject'], 'Hawaii')
def testUpdateSignature(self):
result = self.es.UpdateSignature(username, signature='Signature')
self.assertEquals(result['signature'], 'Signature')
def testUpdateLanguage(self):
result = self.es.UpdateLanguage(username, language='fr')
self.assertEquals(result['language'], 'fr')
def testUpdateGeneral(self):
result = self.es.UpdateGeneral(username,
page_size=100,
shortcuts=True,
arrows=True,
snippets=True,
unicode=True)
self.assertEquals(result['pageSize'], '100')
if __name__ == '__main__':
print("""Google Apps Email Settings Service Tests
NOTE: Please run these tests only with a test user account.
""")
domain = raw_input('Google Apps domain: ')
admin_email = '%s@%s' % (raw_input('Administrator username: '), domain)
admin_password = getpass.getpass('Administrator password: ')
username = raw_input('Test username: ')
unittest.main()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'Claudio Cherubino <ccherubino@google.com>'
import unittest
import gdata.apps.emailsettings.data
import gdata.test_config as conf
class EmailSettingsLabelTest(unittest.TestCase):
def setUp(self):
self.entry = gdata.apps.emailsettings.data.EmailSettingsLabel()
def testName(self):
self.entry.name = 'test label'
self.assertEquals(self.entry.name, 'test label')
class EmailSettingsFilterTest(unittest.TestCase):
def setUp(self):
self.entry = gdata.apps.emailsettings.data.EmailSettingsFilter()
def testFrom(self):
self.entry.from_address = 'abc@example.com'
self.assertEquals(self.entry.from_address, 'abc@example.com')
def testTo(self):
self.entry.to_address = 'to@example.com'
self.assertEquals(self.entry.to_address, 'to@example.com')
def testFrom(self):
self.entry.from_address = 'abc@example.com'
self.assertEquals(self.entry.from_address, 'abc@example.com')
def testSubject(self):
self.entry.subject = 'Read me'
self.assertEquals(self.entry.subject, 'Read me')
def testHasTheWord(self):
self.entry.has_the_word = 'important'
self.assertEquals(self.entry.has_the_word, 'important')
def testDoesNotHaveTheWord(self):
self.entry.does_not_have_the_word = 'spam'
self.assertEquals(self.entry.does_not_have_the_word, 'spam')
def testHasAttachments(self):
self.entry.has_attachments = True
self.assertEquals(self.entry.has_attachments, True)
def testLabel(self):
self.entry.label = 'Trip reports'
self.assertEquals(self.entry.label, 'Trip reports')
def testMarkHasRead(self):
self.entry.mark_has_read = True
self.assertEquals(self.entry.mark_has_read, True)
def testArchive(self):
self.entry.archive = True
self.assertEquals(self.entry.archive, True)
class EmailSettingsSendAsAliasTest(unittest.TestCase):
def setUp(self):
self.entry = gdata.apps.emailsettings.data.EmailSettingsSendAsAlias()
def testName(self):
self.entry.name = 'Sales'
self.assertEquals(self.entry.name, 'Sales')
def testAddress(self):
self.entry.address = 'sales@example.com'
self.assertEquals(self.entry.address, 'sales@example.com')
def testReplyTo(self):
self.entry.reply_to = 'support@example.com'
self.assertEquals(self.entry.reply_to, 'support@example.com')
def testMakeDefault(self):
self.entry.make_default = True
self.assertEquals(self.entry.make_default, True)
class EmailSettingsWebClipTest(unittest.TestCase):
def setUp(self):
self.entry = gdata.apps.emailsettings.data.EmailSettingsWebClip()
def testEnable(self):
self.entry.enable = True
self.assertEquals(self.entry.enable, True)
class EmailSettingsForwardingTest(unittest.TestCase):
def setUp(self):
self.entry = gdata.apps.emailsettings.data.EmailSettingsForwarding()
def testEnable(self):
self.entry.enable = True
self.assertEquals(self.entry.enable, True)
def testForwardTo(self):
self.entry.forward_to = 'fred@example.com'
self.assertEquals(self.entry.forward_to, 'fred@example.com')
def testAction(self):
self.entry.action = 'KEEP'
self.assertEquals(self.entry.action, 'KEEP')
class EmailSettingsPopTest(unittest.TestCase):
def setUp(self):
self.entry = gdata.apps.emailsettings.data.EmailSettingsPop()
def testEnable(self):
self.entry.enable = True
self.assertEquals(self.entry.enable, True)
def testForwardTo(self):
self.entry.enable_for = 'ALL_MAIL'
self.assertEquals(self.entry.enable_for, 'ALL_MAIL')
def testAction(self):
self.entry.action = 'KEEP'
self.assertEquals(self.entry.action, 'KEEP')
class EmailSettingsImapTest(unittest.TestCase):
def setUp(self):
self.entry = gdata.apps.emailsettings.data.EmailSettingsImap()
def testEnable(self):
self.entry.enable = True
self.assertEquals(self.entry.enable, True)
class EmailSettingsVacationResponderTest(unittest.TestCase):
def setUp(self):
self.entry = gdata.apps.emailsettings.data.EmailSettingsVacationResponder()
def testEnable(self):
self.entry.enable = True
self.assertEquals(self.entry.enable, True)
def testSubject(self):
self.entry.subject = 'On vacation!'
self.assertEquals(self.entry.subject, 'On vacation!')
def testMessage(self):
self.entry.message = 'See you on September 1st'
self.assertEquals(self.entry.message, 'See you on September 1st')
def testStartDate(self):
self.entry.start_date = '2011-12-05'
self.assertEquals(self.entry.start_date, '2011-12-05')
def testEndDate(self):
self.entry.end_date = '2011-12-06'
self.assertEquals(self.entry.end_date, '2011-12-06')
def testContactsOnly(self):
self.entry.contacts_only = True
self.assertEquals(self.entry.contacts_only, True)
def testDomainOnly(self):
self.entry.domain_only = True
self.assertEquals(self.entry.domain_only, True)
class EmailSettingsSignatureTest(unittest.TestCase):
def setUp(self):
self.entry = gdata.apps.emailsettings.data.EmailSettingsSignature()
def testValue(self):
self.entry.signature_value = 'Regards, Joe'
self.assertEquals(self.entry.signature_value, 'Regards, Joe')
class EmailSettingsLanguageTest(unittest.TestCase):
def setUp(self):
self.entry = gdata.apps.emailsettings.data.EmailSettingsLanguage()
def testLanguage(self):
self.entry.language_tag = 'es'
self.assertEquals(self.entry.language_tag, 'es')
class EmailSettingsGeneralTest(unittest.TestCase):
def setUp(self):
self.entry = gdata.apps.emailsettings.data.EmailSettingsGeneral()
def testPageSize(self):
self.entry.page_size = 25
self.assertEquals(self.entry.page_size, 25)
def testShortcuts(self):
self.entry.shortcuts = True
self.assertEquals(self.entry.shortcuts, True)
def testArrows(self):
self.entry.arrows = True
self.assertEquals(self.entry.arrows, True)
def testSnippets(self):
self.entry.snippets = True
self.assertEquals(self.entry.snippets, True)
def testUnicode(self):
self.entry.use_unicode = True
self.assertEquals(self.entry.use_unicode, True)
def suite():
return conf.build_suite([EmailSettingsLabelTest, EmailSettingsFilterTest,
EmailSettingsSendAsAliasTest, EmailSettingsWebClipTest,
EmailSettingsForwardingTest, EmailSettingsPopTest,
EmailSettingsImapTest, EmailSettingsVacationResponderTest,
EmailSettingsSignatureTest, EmailSettingsLanguageTest,
EmailSettingsGeneralTest])
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python2.4
#
# 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.
"""Test for Email Migration service."""
__author__ = 'google-apps-apis@googlegroups.com'
import getpass
import unittest
import gdata.apps.migration.service
domain = ''
admin_email = ''
admin_password = ''
username = ''
MESSAGE = """From: joe@blow.com
To: jane@doe.com
Date: Mon, 29 Sep 2008 20:00:34 -0500 (CDT)
Subject: %s
%s"""
class MigrationTest(unittest.TestCase):
"""Test for the MigrationService."""
def setUp(self):
self.ms = gdata.apps.migration.service.MigrationService(
email=admin_email, password=admin_password, domain=domain)
self.ms.ProgrammaticLogin()
def testImportMail(self):
self.ms.ImportMail(user_name=username,
mail_message=MESSAGE % ('Test subject', 'Test body'),
mail_item_properties=['IS_STARRED'],
mail_labels=['Test'])
def testImportMultipleMails(self):
for i in xrange(1, 10):
self.ms.AddMailEntry(mail_message=MESSAGE % ('Test thread %d' % i,
'Test thread'),
mail_item_properties=['IS_UNREAD'],
mail_labels=['Test', 'Thread'],
identifier=str(i))
self.ms.ImportMultipleMails(user_name=username)
if __name__ == '__main__':
print("Google Apps Email Migration Service Tests\n\n"
"NOTE: Please run these tests only with a test user account.\n")
domain = raw_input('Google Apps domain: ')
admin_email = '%s@%s' % (raw_input('Administrator username: '), domain)
admin_password = getpass.getpass('Administrator password: ')
username = raw_input('Test username: ')
unittest.main()
| Python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'samuel.cyprian@gmail.com (Samuel Cyprian)'
import unittest
from gdata import oauth, test_config
HTTP_METHOD_POST = 'POST'
VERSION = '1.0'
class OauthUtilsTest(unittest.TestCase):
def test_build_authenticate_header(self):
self.assertEqual(oauth.build_authenticate_header(),
{'WWW-Authenticate' :'OAuth realm=""'})
self.assertEqual(oauth.build_authenticate_header('foo'),
{'WWW-Authenticate': 'OAuth realm="foo"'})
def test_escape(self):
#Special cases
self.assertEqual(oauth.escape('~'), '~')
self.assertEqual(oauth.escape('/'), '%2F')
self.assertEqual(oauth.escape('+'), '%2B')
self.assertEqual(oauth.escape(' '), '%20')
self.assertEqual(oauth.escape('Peter Strömberg'),
'Peter%20Str%C3%B6mberg')
def test_generate_timestamp(self):
self.assertTrue(oauth.generate_timestamp()>0)
self.assertTrue(type(oauth.generate_timestamp()) is type(0))
def test_generate_nonce(self):
DEFAULT_NONCE_LENGTH = 8
self.assertTrue(len(oauth.generate_nonce()) is DEFAULT_NONCE_LENGTH)
self.assertTrue(type(oauth.generate_nonce()) is type(''))
class OAuthConsumerTest(unittest.TestCase):
def setUp(self):
self.key = 'key'
self.secret = 'secret'
self.consumer = oauth.OAuthConsumer(self.key, self.secret)
def test_OAuthConsumer_attr_key(self):
self.assertEqual(self.consumer.key, self.key)
def test_OAuthConsumer_attr_secret(self):
self.assertEqual(self.consumer.secret, self.secret)
class OAuthTokenTest(unittest.TestCase):
def setUp(self):
self.key = 'key'
self.secret = 'secret'
self.token = oauth.OAuthToken(self.key, self.secret)
def test_OAuthToken_attr_key(self):
self.assertEqual(self.token.key, self.key)
def test_OAuthToken_attr_secret(self):
self.assertEqual(self.token.secret, self.secret)
def test_to_string(self):
self.assertEqual(self.token.to_string(),
'oauth_token_secret=secret&oauth_token=key')
t = oauth.OAuthToken('+', '%')
self.assertEqual(t.to_string(),
'oauth_token_secret=%25&oauth_token=%2B')
def test_from_string(self):
s = 'oauth_token_secret=secret&oauth_token=key'
t = oauth.OAuthToken.from_string(s)
self.assertEqual(t.key, 'key')
self.assertEqual(t.secret, 'secret')
t = oauth.OAuthToken.from_string('oauth_token_secret=%25&oauth_token=%2B')
self.assertEqual(t.key, '+')
self.assertEqual(t.secret, '%')
def test___str__(self):
self.assertEqual(str(self.token),
'oauth_token_secret=secret&oauth_token=key')
t = oauth.OAuthToken('+', '%')
self.assertEqual(str(t), 'oauth_token_secret=%25&oauth_token=%2B')
class OAuthParameters(object):
CONSUMER_KEY = 'oauth_consumer_key'
TOKEN = 'oauth_token'
SIGNATURE_METHOD = 'oauth_signature_method'
SIGNATURE = 'oauth_signature'
TIMESTAMP = 'oauth_timestamp'
NONCE = 'oauth_nonce'
VERSION = 'oauth_version'
CALLBACK = 'oauth_callback'
ALL_PARAMETERS = (CONSUMER_KEY,
TOKEN,
SIGNATURE_METHOD,
SIGNATURE,
TIMESTAMP,
NONCE,
VERSION)
class OAuthTest(unittest.TestCase):
def setUp(self):
self.consumer = oauth.OAuthConsumer('a56b5ff0a637ab283d1d8e32ced37a9c',
'9a3248210c84b264b56b98c0b872bc8a')
self.token = oauth.OAuthToken('5b2cafbf20b11bace53b29e37d8a673d',
'3f71254637df2002d8819458ae4f6c51')
self.http_url = 'http://dev.alicehub.com/server/api/newsfeed/update/'
self.http_method = HTTP_METHOD_POST
class OAuthRequestTest(OAuthTest):
def setUp(self):
super(OAuthRequestTest, self).setUp()
self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
self.non_oauth_param_message = 'message'
self.non_oauth_param_context_id = 'context_id'
self.parameters = {OAuthParameters.CONSUMER_KEY:self.consumer.key,
OAuthParameters.TOKEN: self.token.key,
OAuthParameters.SIGNATURE_METHOD: 'HMAC-SHA1',
OAuthParameters.SIGNATURE:
'947ysBZiMn6FGZ11AW06Ioco4mo=',
OAuthParameters.TIMESTAMP: '1278573584',
OAuthParameters.NONCE: '1770704051',
OAuthParameters.VERSION: VERSION,
self.non_oauth_param_message:'hey',
self.non_oauth_param_context_id:'',}
oauth_params_string = """
oauth_nonce="1770704051",
oauth_timestamp="1278573584",
oauth_consumer_key="a56b5ff0a637ab283d1d8e32ced37a9c",
oauth_signature_method="HMAC-SHA1",
oauth_version="1.0",
oauth_token="5b2cafbf20b11bace53b29e37d8a673d",
oauth_signature="947ysBZiMn6FGZ11AW06Ioco4mo%3D"
"""
self.oauth_header_with_realm = {'Authorization': """OAuth
realm="http://example.com", %s """ % oauth_params_string}
self.oauth_header_without_realm = {'Authorization': 'OAuth %s'
% oauth_params_string}
self.additional_param = 'foo'
self.additional_value = 'bar'
self.oauth_request = oauth.OAuthRequest(self.http_method,
self.http_url,
self.parameters)
def test_set_parameter(self):
self.oauth_request.set_parameter(self.additional_param,
self.additional_value)
self.assertEqual(self.oauth_request.get_parameter(self.additional_param),
self.additional_value)
def test_get_parameter(self):
self.assertRaises(oauth.OAuthError,
self.oauth_request.get_parameter,
self.additional_param)
self.oauth_request.set_parameter(self.additional_param,
self.additional_value)
self.assertEqual(self.oauth_request.get_parameter(self.additional_param),
self.additional_value)
def test__get_timestamp_nonce(self):
self.assertEqual(self.oauth_request._get_timestamp_nonce(),
(self.parameters[OAuthParameters.TIMESTAMP],
self.parameters[OAuthParameters.NONCE]))
def test_get_nonoauth_parameters(self):
non_oauth_params = self.oauth_request.get_nonoauth_parameters()
self.assertTrue(non_oauth_params.has_key(self.non_oauth_param_message))
self.assertFalse(non_oauth_params.has_key(OAuthParameters.CONSUMER_KEY))
def test_to_header(self):
realm = 'google'
header_without_realm = self.oauth_request.to_header()\
.get('Authorization')
header_with_realm = self.oauth_request.to_header(realm)\
.get('Authorization')
self.assertTrue(header_with_realm.find(realm))
for k in OAuthParameters.ALL_PARAMETERS:
self.assertTrue(header_without_realm.find(k) > -1)
self.assertTrue(header_with_realm.find(k) > -1)
def check_for_params_in_string(self, params, s):
for k, v in params.iteritems():
self.assertTrue(s.find(oauth.escape(k)) > -1)
self.assertTrue(s.find(oauth.escape(v)) > -1)
def test_to_postdata(self):
post_data = self.oauth_request.to_postdata()
self.check_for_params_in_string(self.parameters, post_data)
def test_to_url(self):
GET_url = self.oauth_request.to_url()
self.assertTrue(GET_url\
.find(self.oauth_request.get_normalized_http_url()) > -1)
self.assertTrue(GET_url.find('?') > -1)
self.check_for_params_in_string(self.parameters, GET_url)
def test_get_normalized_parameters(self):
_params = self.parameters.copy()
normalized_params = self.oauth_request.get_normalized_parameters()
self.assertFalse(normalized_params\
.find(OAuthParameters.SIGNATURE + '=') > -1)
self.assertTrue(self.parameters.get(OAuthParameters.SIGNATURE) is None)
key_values = [tuple(kv.split('=')) for kv in normalized_params.split('&')]
del _params[OAuthParameters.SIGNATURE]
expected_key_values = _params.items()
expected_key_values.sort()
for k, v in expected_key_values:
self.assertTrue(expected_key_values.index((k,v))\
is key_values.index((oauth.escape(k), oauth.escape(v))))
def test_get_normalized_http_method(self):
lower_case_http_method = HTTP_METHOD_POST.lower()
self.oauth_request.http_method = lower_case_http_method
self.assertEqual(self.oauth_request.get_normalized_http_method(),
lower_case_http_method.upper())
def test_get_normalized_http_url(self):
url1 = 'HTTP://Example.com:80/resource?id=123'
expected_url1 = "http://example.com/resource"
self.oauth_request.http_url = url1
self.assertEqual(self.oauth_request.get_normalized_http_url(),
expected_url1)
url2 = 'HTTPS://Example.com:443/resource?id=123'
expected_url2 = "https://example.com/resource"
self.oauth_request.http_url = url2
self.assertEqual(self.oauth_request.get_normalized_http_url(),
expected_url2)
url3 = 'HTTP://Example.com:8080/resource?id=123'
expected_url3 = "http://example.com:8080/resource"
self.oauth_request.http_url = url3
self.assertEqual(self.oauth_request.get_normalized_http_url(),
expected_url3)
def test_sign_request(self):
expected_signature = self.oauth_request.parameters\
.get(OAuthParameters.SIGNATURE)
del self.oauth_request.parameters[OAuthParameters.SIGNATURE]
self.oauth_request.sign_request(self.signature_method,
self.consumer,
self.token)
self.assertEqual(self.oauth_request.parameters\
.get(OAuthParameters.SIGNATURE), expected_signature)
def test_build_signature(self):
expected_signature = self.oauth_request.parameters\
.get(OAuthParameters.SIGNATURE)
self.assertEqual(self.oauth_request.build_signature(self.signature_method,
self.consumer,
self.token),
expected_signature)
def test_from_request(self):
request = oauth.OAuthRequest.from_request(self.http_method, self.http_url,
self.oauth_header_with_realm,
{},
"message=hey&context_id=")
self.assertEqual(request.__dict__, self.oauth_request.__dict__)
self.assertTrue(isinstance(request, oauth.OAuthRequest))
def test_from_consumer_and_token(self):
request = oauth.OAuthRequest.from_consumer_and_token(self.consumer,
self.token,
self.http_method,
self.http_url)
self.assertTrue(isinstance(request, oauth.OAuthRequest))
def test_from_token_and_callback(self):
callback = 'http://example.com'
request = oauth.OAuthRequest.from_token_and_callback(self.token,
callback,
self.http_method,
self.http_url)
self.assertTrue(isinstance(request, oauth.OAuthRequest))
self.assertEqual(request.get_parameter(OAuthParameters.CALLBACK), callback)
def test__split_header(self):
del self.parameters[self.non_oauth_param_message]
del self.parameters[self.non_oauth_param_context_id]
self.assertEqual(oauth.OAuthRequest._split_header(self\
.oauth_header_with_realm['Authorization']), self.parameters)
self.assertEqual(oauth.OAuthRequest._split_header(self\
.oauth_header_without_realm['Authorization']), self.parameters)
def test_split_url_string(self):
qs = "a=1&c=hi%20there&empty="
expected_result = {'a': '1',
'c': 'hi there',
'empty': ''}
self.assertEqual(oauth.OAuthRequest._split_url_string(qs), expected_result)
class OAuthServerTest(OAuthTest):
def setUp(self):
super(OAuthServerTest, self).setUp()
self.signature_method = oauth.OAuthSignatureMethod_HMAC_SHA1()
self.data_store = MockOAuthDataStore()
self.user = MockUser('Foo Bar')
self.request_token_url = "http://example.com/oauth/request_token"
self.access_token_url = "http://example.com/oauth/access_token"
self.oauth_server = oauth.OAuthServer(self.data_store,
{self.signature_method.get_name():self.signature_method})
def _prepare_request(self, request, token = None):
request.set_parameter(OAuthParameters.SIGNATURE_METHOD,
self.signature_method.get_name())
request.set_parameter(OAuthParameters.NONCE, oauth.generate_nonce())
request.set_parameter(OAuthParameters.TIMESTAMP,
oauth.generate_timestamp())
request.sign_request(self.signature_method, self.consumer, token)
def _get_token(self, request):
self._prepare_request(request)
return self.oauth_server.fetch_request_token(request)
def _get_authorized_token(self, request):
req_token = self._get_token(request)
return self.oauth_server.authorize_token(req_token, self.user)
def test_set_data_store(self):
self.oauth_server.data_store = None
self.assertTrue(self.oauth_server.data_store is None)
self.oauth_server.set_data_store(self.data_store)
self.assertTrue(self.oauth_server.data_store is not None)
self.assertTrue(isinstance(self.oauth_server.data_store,
oauth.OAuthDataStore))
def test_get_data_store(self):
self.assertEqual(self.oauth_server.data_store, self.data_store)
def test_add_signature_method(self):
signature_method = oauth.OAuthSignatureMethod_PLAINTEXT()
self.oauth_server.add_signature_method(signature_method)
self.assertTrue(isinstance(self.oauth_server.signature_methods\
.get(signature_method.get_name()),
oauth.OAuthSignatureMethod_PLAINTEXT))
def test_fetch_request_token(self):
initial_request = oauth.OAuthRequest.from_consumer_and_token(
self.consumer,
http_method=self.http_method,
http_url=self.request_token_url
)
req_token_1 = self._get_token(initial_request)
authorization_request = oauth.OAuthRequest.from_consumer_and_token(
self.consumer,
req_token_1,
http_method=self.http_method,
http_url=self.http_url
)
req_token_2 = self._get_token(authorization_request)
self.assertEqual(req_token_1.key, req_token_2.key)
self.assertEqual(req_token_1.secret, req_token_2.secret)
def _get_token_for_authorization(self):
request = oauth.OAuthRequest.from_consumer_and_token(
self.consumer,
http_method=self.http_method,
http_url=self.request_token_url
)
request_token = self._get_token(request)
authorization_request = oauth.OAuthRequest.from_consumer_and_token(
self.consumer,
request_token,
http_method=self.http_method,
http_url=self.http_url
)
return self._get_authorized_token(authorization_request)
def test_authorize_token(self):
authorized_token = self._get_token_for_authorization()
self.assertTrue(authorized_token is not None)
def _get_access_token_request(self, authorized_token):
access_token_request = oauth.OAuthRequest.from_consumer_and_token(
self.consumer,
authorized_token,
http_method=self.http_method,
http_url=self.access_token_url
)
self._prepare_request(access_token_request, authorized_token)
return access_token_request
def test_fetch_access_token(self):
authorized_token = self._get_token_for_authorization()
access_token_request = self._get_access_token_request(authorized_token)
access_token = self.oauth_server.fetch_access_token(access_token_request)
self.assertTrue(access_token is not None)
self.assertNotEqual(str(authorized_token), str(access_token))
# Try to fetch access_token with used request token
self.assertRaises(oauth.OAuthError, self.oauth_server.fetch_access_token,
access_token_request)
def test_verify_request(self):
authorized_token = self._get_token_for_authorization()
access_token_request = self._get_access_token_request(authorized_token)
access_token = self.oauth_server.fetch_access_token(access_token_request)
param1 = 'p1'
value1 = 'v1'
api_request = oauth.OAuthRequest.from_consumer_and_token(
self.consumer,
access_token,
http_method=self.http_method,
http_url=self.http_url,
parameters={param1:value1}
)
self._prepare_request(api_request, access_token)
result = self.oauth_server.verify_request(api_request)
self.assertTrue(result is not None)
consumer, token, parameters = result
self.assertEqual(parameters.get(param1), value1)
def test_get_callback(self):
request = oauth.OAuthRequest.from_consumer_and_token(
self.consumer,
None,
http_method=self.http_method,
http_url=self.http_url
)
self._prepare_request(request)
cb_url = 'http://example.com/cb'
request.set_parameter(OAuthParameters.CALLBACK, cb_url)
self.assertEqual(self.oauth_server.get_callback(request), cb_url)
def test_build_authenticate_header(self):
self.assertEqual(oauth.build_authenticate_header(), {'WWW-Authenticate':
'OAuth realm=""'})
self.assertEqual(oauth.build_authenticate_header('foo'),
{'WWW-Authenticate': 'OAuth realm="foo"'})
class OAuthClientTest(OAuthTest):
def setUp(self):
super(OAuthClientTest, self).setUp()
self.oauth_client = oauth.OAuthClient(self.consumer, self.token)
def test_get_consumer(self):
consumer = self.oauth_client.get_consumer()
self.assertTrue(isinstance(consumer, oauth.OAuthConsumer))
self.assertEqual(consumer.__dict__, self.consumer.__dict__)
def test_get_token(self):
token = self.oauth_client.get_token()
self.assertTrue(isinstance(token, oauth.OAuthToken))
self.assertEqual(token.__dict__, self.token.__dict__)
#Mockup OAuthDataStore
TOKEN_TYPE_REQUEST = 'request'
TOKEN_TYPE_ACCESS = 'access'
class MockOAuthDataStore(oauth.OAuthDataStore):
def __init__(self):
self.consumer = oauth.OAuthConsumer('a56b5ff0a637ab283d1d8e32ced37a9c',
'9a3248210c84b264b56b98c0b872bc8a')
self.consumer_db = {self.consumer.key: self.consumer}
self.request_token_db = {}
self.access_token_db = {}
self.nonce = None
def lookup_consumer(self, key):
return self.consumer_db.get(key)
def lookup_token(self, oauth_consumer, token_type, token_field):
data = None
if token_type == TOKEN_TYPE_REQUEST:
data = self.request_token_db.get(token_field)
elif token_type == TOKEN_TYPE_ACCESS:
data = self.access_token_db.get(token_field)
if data:
token, consumer, authenticated_user = data
if consumer.key == oauth_consumer.key:
return token
return None
def lookup_nonce(self, oauth_consumer, oauth_token, nonce):
is_used = self.nonce == nonce
self.nonce = nonce
return is_used
def fetch_request_token(self, oauth_consumer):
token = oauth.OAuthToken("5b2cafbf20b11bace53b29e37d8a673dRT",
"3f71254637df2002d8819458ae4f6c51RT")
self.request_token_db[token.key] = (token, oauth_consumer, None)
return token
def fetch_access_token(self, oauth_consumer, oauth_token):
data = self.request_token_db.get(oauth_token.key)
if data:
del self.request_token_db[oauth_token.key]
request_token, consumer, authenticated_user = data
access_token = oauth.OAuthToken("5b2cafbf20b11bace53b29e37d8a673dAT",
"3f71254637df2002d8819458ae4f6c51AT")
self.access_token_db[access_token.key] = (access_token,
consumer,
authenticated_user)
return access_token
else:
return None
def authorize_request_token(self, oauth_token, user):
data = self.request_token_db.get(oauth_token.key)
if data and data[2] == None:
request_token, consumer, authenticated_user = data
authenticated_user = user
self.request_token_db[request_token.key] = (request_token,
consumer,
authenticated_user)
return request_token
else:
return None
#Mock user
class MockUser(object):
def __init__(self, name):
self.name = name
def suite():
return test_config.build_suite([OauthUtilsTest,
OAuthConsumerTest,
OAuthTokenTest,
OAuthRequestTest,
OAuthServerTest,
OAuthClientTest])
if __name__ == '__main__':
unittest.main() | Python |
#!/usr/bin/python
__author__ = "James Sams <sams.james@gmail.com>"
import unittest
import getpass
import atom
import gdata.books
import gdata.books.service
from gdata import test_data
username = ""
password = ""
class BookCRUDTests(unittest.TestCase):
def setUp(self):
self.service = gdata.books.service.BookService(email=username,
password=password, source="Google-PythonGdataTest-1")
if username and password:
self.authenticated = True
self.service.ProgrammaticLogin()
else:
self.authenticated = False
def testPublicSearch(self):
entry = self.service.get_by_google_id("b7GZr5Btp30C")
self.assertEquals((entry.creator[0].text, entry.dc_title[0].text),
('John Rawls', 'A theory of justice'))
feed = self.service.search_by_keyword(isbn="9780198250548")
feed1 = self.service.search("9780198250548")
self.assertEquals(len(feed.entry), 1)
self.assertEquals(len(feed1.entry), 1)
def testLibraryCrd(self):
"""
the success of the create operations assumes the book was not already
in the library. if it was, there will not be a failure, but a successful
add will not actually be tested.
"""
if not self.authenticated:
return
entry = self.service.get_by_google_id("b7GZr5Btp30C")
entry = self.service.add_item_to_library(entry)
lib = list(self.service.get_library())
self.assert_(entry.to_dict()['title'] in
[x.to_dict()['title'] for x in lib])
self.service.remove_item_from_library(entry)
lib = list(self.service.get_library())
self.assert_(entry.to_dict()['title'] not in
[x.to_dict()['title'] for x in lib])
def testAnnotations(self):
"annotations do not behave as expected"
pass
if __name__ == "__main__":
print "Please use a test account. May cause data loss."
username = raw_input("Google Username: ").strip()
password = getpass.getpass()
unittest.main()
| 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)'
import unittest
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
from gdata import test_data
import gdata.apps
class AppsEmailListRecipientFeedTest(unittest.TestCase):
def setUp(self):
self.rcpt_feed = gdata.apps.EmailListRecipientFeedFromString(
test_data.EMAIL_LIST_RECIPIENT_FEED)
def testEmailListRecipientEntryCount(self):
"""Count EmailListRecipient entries in EmailListRecipientFeed"""
self.assertEquals(len(self.rcpt_feed.entry), 2)
def testLinkFinderFindsHtmlLink(self):
"""Tests the return value of GetXXXLink() methods"""
self.assert_(self.rcpt_feed.GetSelfLink() is not None)
self.assert_(self.rcpt_feed.GetNextLink() is not None)
self.assert_(self.rcpt_feed.GetEditLink() is None)
self.assert_(self.rcpt_feed.GetHtmlLink() is None)
def testStartItem(self):
"""Tests the existence of <openSearch:startIndex> in
EmailListRecipientFeed and verifies the value"""
self.assert_(isinstance(self.rcpt_feed.start_index, gdata.StartIndex),
"EmailListRecipient feed <openSearch:startIndex> element must be " +
"an instance of gdata.OpenSearch: %s" % self.rcpt_feed.start_index)
self.assertEquals(self.rcpt_feed.start_index.text, "1")
def testEmailListRecipientEntries(self):
"""Tests the existence of <atom:entry> in EmailListRecipientFeed
and simply verifies the value"""
for a_entry in self.rcpt_feed.entry:
self.assert_(isinstance(a_entry, gdata.apps.EmailListRecipientEntry),
"EmailListRecipient Feed <atom:entry> must be an instance of " +
"apps.EmailListRecipientEntry: %s" % a_entry)
self.assertEquals(self.rcpt_feed.entry[0].who.email, "joe@example.com")
self.assertEquals(self.rcpt_feed.entry[1].who.email, "susan@example.com")
class AppsEmailListFeedTest(unittest.TestCase):
def setUp(self):
self.list_feed = gdata.apps.EmailListFeedFromString(
test_data.EMAIL_LIST_FEED)
def testEmailListEntryCount(self):
"""Count EmailList entries in EmailListFeed"""
self.assertEquals(len(self.list_feed.entry), 2)
def testLinkFinderFindsHtmlLink(self):
"""Tests the return value of GetXXXLink() methods"""
self.assert_(self.list_feed.GetSelfLink() is not None)
self.assert_(self.list_feed.GetNextLink() is not None)
self.assert_(self.list_feed.GetEditLink() is None)
self.assert_(self.list_feed.GetHtmlLink() is None)
def testStartItem(self):
"""Tests the existence of <openSearch:startIndex> in EmailListFeed
and verifies the value"""
self.assert_(isinstance(self.list_feed.start_index, gdata.StartIndex),
"EmailList feed <openSearch:startIndex> element must be an instance " +
"of gdata.OpenSearch: %s" % self.list_feed.start_index)
self.assertEquals(self.list_feed.start_index.text, "1")
def testUserEntries(self):
"""Tests the existence of <atom:entry> in EmailListFeed and simply
verifies the value"""
for a_entry in self.list_feed.entry:
self.assert_(isinstance(a_entry, gdata.apps.EmailListEntry),
"EmailList Feed <atom:entry> must be an instance of " +
"apps.EmailListEntry: %s" % a_entry)
self.assertEquals(self.list_feed.entry[0].email_list.name, "us-sales")
self.assertEquals(self.list_feed.entry[1].email_list.name, "us-eng")
class AppsUserFeedTest(unittest.TestCase):
def setUp(self):
self.user_feed = gdata.apps.UserFeedFromString(test_data.USER_FEED)
def testUserEntryCount(self):
"""Count User entries in UserFeed"""
self.assertEquals(len(self.user_feed.entry), 2)
def testLinkFinderFindsHtmlLink(self):
"""Tests the return value of GetXXXLink() methods"""
self.assert_(self.user_feed.GetSelfLink() is not None)
self.assert_(self.user_feed.GetNextLink() is not None)
self.assert_(self.user_feed.GetEditLink() is None)
self.assert_(self.user_feed.GetHtmlLink() is None)
def testStartItem(self):
"""Tests the existence of <openSearch:startIndex> in UserFeed and
verifies the value"""
self.assert_(isinstance(self.user_feed.start_index, gdata.StartIndex),
"User feed <openSearch:startIndex> element must be an instance " +
"of gdata.OpenSearch: %s" % self.user_feed.start_index)
self.assertEquals(self.user_feed.start_index.text, "1")
def testUserEntries(self):
"""Tests the existence of <atom:entry> in UserFeed and simply
verifies the value"""
for a_entry in self.user_feed.entry:
self.assert_(isinstance(a_entry, gdata.apps.UserEntry),
"User Feed <atom:entry> must be an instance of " +
"apps.UserEntry: %s" % a_entry)
self.assertEquals(self.user_feed.entry[0].login.user_name, "TestUser")
self.assertEquals(self.user_feed.entry[0].who.email,
"TestUser@example.com")
self.assertEquals(self.user_feed.entry[1].login.user_name, "JohnSmith")
self.assertEquals(self.user_feed.entry[1].who.email,
"JohnSmith@example.com")
class AppsNicknameFeedTest(unittest.TestCase):
def setUp(self):
self.nick_feed = gdata.apps.NicknameFeedFromString(test_data.NICK_FEED)
def testNicknameEntryCount(self):
"""Count Nickname entries in NicknameFeed"""
self.assertEquals(len(self.nick_feed.entry), 2)
def testId(self):
"""Tests the existence of <atom:id> in NicknameFeed and verifies
the value"""
self.assert_(isinstance(self.nick_feed.id, atom.Id),
"Nickname feed <atom:id> element must be an instance of " +
"atom.Id: %s" % self.nick_feed.id)
self.assertEquals(self.nick_feed.id.text,
"http://apps-apis.google.com/a/feeds/example.com/nickname/2.0")
def testStartItem(self):
"""Tests the existence of <openSearch:startIndex> in NicknameFeed
and verifies the value"""
self.assert_(isinstance(self.nick_feed.start_index, gdata.StartIndex),
"Nickname feed <openSearch:startIndex> element must be an instance " +
"of gdata.OpenSearch: %s" % self.nick_feed.start_index)
self.assertEquals(self.nick_feed.start_index.text, "1")
def testItemsPerPage(self):
"""Tests the existence of <openSearch:itemsPerPage> in
NicknameFeed and verifies the value"""
self.assert_(isinstance(self.nick_feed.items_per_page, gdata.ItemsPerPage),
"Nickname feed <openSearch:itemsPerPage> element must be an " +
"instance of gdata.ItemsPerPage: %s" % self.nick_feed.items_per_page)
self.assertEquals(self.nick_feed.items_per_page.text, "2")
def testLinkFinderFindsHtmlLink(self):
"""Tests the return value of GetXXXLink() methods"""
self.assert_(self.nick_feed.GetSelfLink() is not None)
self.assert_(self.nick_feed.GetEditLink() is None)
self.assert_(self.nick_feed.GetHtmlLink() is None)
def testNicknameEntries(self):
"""Tests the existence of <atom:entry> in NicknameFeed and simply
verifies the value"""
for a_entry in self.nick_feed.entry:
self.assert_(isinstance(a_entry, gdata.apps.NicknameEntry),
"Nickname Feed <atom:entry> must be an instance of " +
"apps.NicknameEntry: %s" % a_entry)
self.assertEquals(self.nick_feed.entry[0].nickname.name, "Foo")
self.assertEquals(self.nick_feed.entry[1].nickname.name, "Bar")
class AppsEmailListRecipientEntryTest(unittest.TestCase):
def setUp(self):
self.rcpt_entry = gdata.apps.EmailListRecipientEntryFromString(
test_data.EMAIL_LIST_RECIPIENT_ENTRY)
def testId(self):
"""Tests the existence of <atom:id> in EmailListRecipientEntry and
verifies the value"""
self.assert_(
isinstance(self.rcpt_entry.id, atom.Id),
"EmailListRecipient entry <atom:id> element must be an instance of " +
"atom.Id: %s" %
self.rcpt_entry.id)
self.assertEquals(
self.rcpt_entry.id.text,
'https://apps-apis.google.com/a/feeds/example.com/emailList/2.0/us-sales/' +
'recipient/TestUser%40example.com')
def testUpdated(self):
"""Tests the existence of <atom:updated> in
EmailListRecipientEntry and verifies the value"""
self.assert_(
isinstance(self.rcpt_entry.updated, atom.Updated),
"EmailListRecipient entry <atom:updated> element must be an instance " +
"of atom.Updated: %s" % self.rcpt_entry.updated)
self.assertEquals(self.rcpt_entry.updated.text,
'1970-01-01T00:00:00.000Z')
def testCategory(self):
"""Tests the existence of <atom:category> in
EmailListRecipientEntry and verifies the value"""
for a_category in self.rcpt_entry.category:
self.assert_(
isinstance(a_category, atom.Category),
"EmailListRecipient entry <atom:category> element must be an " +
"instance of atom.Category: %s" % a_category)
self.assertEquals(a_category.scheme,
"http://schemas.google.com/g/2005#kind")
self.assertEquals(a_category.term,
"http://schemas.google.com/apps/2006#" +
"emailList.recipient")
def testTitle(self):
"""Tests the existence of <atom:title> in EmailListRecipientEntry
and verifies the value"""
self.assert_(
isinstance(self.rcpt_entry.title, atom.Title),
"EmailListRecipient entry <atom:title> element must be an instance of " +
"atom.Title: %s" % self.rcpt_entry.title)
self.assertEquals(self.rcpt_entry.title.text, 'TestUser')
def testLinkFinderFindsHtmlLink(self):
"""Tests the return value of GetXXXLink() methods"""
self.assert_(self.rcpt_entry.GetSelfLink() is not None)
self.assert_(self.rcpt_entry.GetEditLink() is not None)
self.assert_(self.rcpt_entry.GetHtmlLink() is None)
def testWho(self):
"""Tests the existence of a <gdata:who> in EmailListRecipientEntry
and verifies the value"""
self.assert_(isinstance(self.rcpt_entry.who, gdata.apps.Who),
"EmailListRecipient entry <gdata:who> must be an instance of " +
"apps.Who: %s" % self.rcpt_entry.who)
self.assertEquals(self.rcpt_entry.who.email, 'TestUser@example.com')
class AppsEmailListEntryTest(unittest.TestCase):
def setUp(self):
self.list_entry = gdata.apps.EmailListEntryFromString(
test_data.EMAIL_LIST_ENTRY)
def testId(self):
"""Tests the existence of <atom:id> in EmailListEntry and verifies
the value"""
self.assert_(
isinstance(self.list_entry.id, atom.Id),
"EmailList entry <atom:id> element must be an instance of atom.Id: %s" %
self.list_entry.id)
self.assertEquals(
self.list_entry.id.text,
'https://apps-apis.google.com/a/feeds/example.com/emailList/2.0/testlist')
def testUpdated(self):
"""Tests the existence of <atom:updated> in EmailListEntry and
verifies the value"""
self.assert_(
isinstance(self.list_entry.updated, atom.Updated),
"EmailList entry <atom:updated> element must be an instance of " +
"atom.Updated: %s" % self.list_entry.updated)
self.assertEquals(self.list_entry.updated.text,
'1970-01-01T00:00:00.000Z')
def testCategory(self):
"""Tests the existence of <atom:category> in EmailListEntry and
verifies the value"""
for a_category in self.list_entry.category:
self.assert_(
isinstance(a_category, atom.Category),
"EmailList entry <atom:category> element must be an instance " +
"of atom.Category: %s" % a_category)
self.assertEquals(a_category.scheme,
"http://schemas.google.com/g/2005#kind")
self.assertEquals(a_category.term,
"http://schemas.google.com/apps/2006#emailList")
def testTitle(self):
"""Tests the existence of <atom:title> in EmailListEntry and verifies
the value"""
self.assert_(
isinstance(self.list_entry.title, atom.Title),
"EmailList entry <atom:title> element must be an instance of " +
"atom.Title: %s" % self.list_entry.title)
self.assertEquals(self.list_entry.title.text, 'testlist')
def testLinkFinderFindsHtmlLink(self):
"""Tests the return value of GetXXXLink() methods"""
self.assert_(self.list_entry.GetSelfLink() is not None)
self.assert_(self.list_entry.GetEditLink() is not None)
self.assert_(self.list_entry.GetHtmlLink() is None)
def testEmailList(self):
"""Tests the existence of a <apps:emailList> in EmailListEntry and
verifies the value"""
self.assert_(isinstance(self.list_entry.email_list, gdata.apps.EmailList),
"EmailList entry <apps:emailList> must be an instance of " +
"apps.EmailList: %s" % self.list_entry.email_list)
self.assertEquals(self.list_entry.email_list.name, 'testlist')
def testFeedLink(self):
"""Test the existence of a <gdata:feedLink> in EmailListEntry and
verifies the value"""
for an_feed_link in self.list_entry.feed_link:
self.assert_(isinstance(an_feed_link, gdata.FeedLink),
"EmailList entry <gdata:feedLink> must be an instance of " +
"gdata.FeedLink: %s" % an_feed_link)
self.assertEquals(self.list_entry.feed_link[0].rel,
'http://schemas.google.com/apps/2006#' +
'emailList.recipients')
self.assertEquals(self.list_entry.feed_link[0].href,
'http://apps-apis.google.com/a/feeds/example.com/emailList/' +
'2.0/testlist/recipient/')
class AppsNicknameEntryTest(unittest.TestCase):
def setUp(self):
self.nick_entry = gdata.apps.NicknameEntryFromString(test_data.NICK_ENTRY)
def testId(self):
"""Tests the existence of <atom:id> in NicknameEntry and verifies
the value"""
self.assert_(
isinstance(self.nick_entry.id, atom.Id),
"Nickname entry <atom:id> element must be an instance of atom.Id: %s" %
self.nick_entry.id)
self.assertEquals(
self.nick_entry.id.text,
'https://apps-apis.google.com/a/feeds/example.com/nickname/2.0/Foo')
def testCategory(self):
"""Tests the existence of <atom:category> in NicknameEntry and
verifies the value"""
for a_category in self.nick_entry.category:
self.assert_(
isinstance(a_category, atom.Category),
"Nickname entry <atom:category> element must be an instance " +
"of atom.Category: %s" % a_category)
self.assertEquals(a_category.scheme,
"http://schemas.google.com/g/2005#kind")
self.assertEquals(a_category.term,
"http://schemas.google.com/apps/2006#nickname")
def testTitle(self):
"""Tests the existence of <atom:title> in NicknameEntry and
verifies the value"""
self.assert_(isinstance(self.nick_entry.title, atom.Title),
"Nickname entry <atom:title> element must be an instance " +
"of atom.Title: %s" % self.nick_entry.title)
self.assertEquals(self.nick_entry.title.text, "Foo")
def testLogin(self):
"""Tests the existence of <apps:login> in NicknameEntry and
verifies the value"""
self.assert_(isinstance(self.nick_entry.login, gdata.apps.Login),
"Nickname entry <apps:login> element must be an instance " +
"of apps.Login: %s" % self.nick_entry.login)
self.assertEquals(self.nick_entry.login.user_name, "TestUser")
def testNickname(self):
"""Tests the existence of <apps:nickname> in NicknameEntry and
verifies the value"""
self.assert_(isinstance(self.nick_entry.nickname, gdata.apps.Nickname),
"Nickname entry <apps:nickname> element must be an instance " +
"of apps.Nickname: %s" % self.nick_entry.nickname)
self.assertEquals(self.nick_entry.nickname.name, "Foo")
def testLinkFinderFindsHtmlLink(self):
"""Tests the return value of GetXXXLink() methods"""
self.assert_(self.nick_entry.GetSelfLink() is not None)
self.assert_(self.nick_entry.GetEditLink() is not None)
self.assert_(self.nick_entry.GetHtmlLink() is None)
class AppsUserEntryTest(unittest.TestCase):
def setUp(self):
self.user_entry = gdata.apps.UserEntryFromString(test_data.USER_ENTRY)
def testId(self):
"""Tests the existence of <atom:id> in UserEntry and verifies the
value"""
self.assert_(
isinstance(self.user_entry.id, atom.Id),
"User entry <atom:id> element must be an instance of atom.Id: %s" %
self.user_entry.id)
self.assertEquals(
self.user_entry.id.text,
'https://apps-apis.google.com/a/feeds/example.com/user/2.0/TestUser')
def testUpdated(self):
"""Tests the existence of <atom:updated> in UserEntry and verifies
the value"""
self.assert_(
isinstance(self.user_entry.updated, atom.Updated),
"User entry <atom:updated> element must be an instance of " +
"atom.Updated: %s" % self.user_entry.updated)
self.assertEquals(self.user_entry.updated.text,
'1970-01-01T00:00:00.000Z')
def testCategory(self):
"""Tests the existence of <atom:category> in UserEntry and
verifies the value"""
for a_category in self.user_entry.category:
self.assert_(
isinstance(a_category, atom.Category),
"User entry <atom:category> element must be an instance " +
"of atom.Category: %s" % a_category)
self.assertEquals(a_category.scheme,
"http://schemas.google.com/g/2005#kind")
self.assertEquals(a_category.term,
"http://schemas.google.com/apps/2006#user")
def testTitle(self):
"""Tests the existence of <atom:title> in UserEntry and verifies
the value"""
self.assert_(
isinstance(self.user_entry.title, atom.Title),
"User entry <atom:title> element must be an instance of atom.Title: %s" %
self.user_entry.title)
self.assertEquals(self.user_entry.title.text, 'TestUser')
def testLinkFinderFindsHtmlLink(self):
"""Tests the return value of GetXXXLink() methods"""
self.assert_(self.user_entry.GetSelfLink() is not None)
self.assert_(self.user_entry.GetEditLink() is not None)
self.assert_(self.user_entry.GetHtmlLink() is None)
def testLogin(self):
"""Tests the existence of <apps:login> in UserEntry and verifies
the value"""
self.assert_(isinstance(self.user_entry.login, gdata.apps.Login),
"User entry <apps:login> element must be an instance of apps.Login: %s"
% self.user_entry.login)
self.assertEquals(self.user_entry.login.user_name, 'TestUser')
self.assertEquals(self.user_entry.login.password, 'password')
self.assertEquals(self.user_entry.login.suspended, 'false')
self.assertEquals(self.user_entry.login.ip_whitelisted, 'false')
self.assertEquals(self.user_entry.login.hash_function_name, 'SHA-1')
def testName(self):
"""Tests the existence of <apps:name> in UserEntry and verifies
the value"""
self.assert_(isinstance(self.user_entry.name, gdata.apps.Name),
"User entry <apps:name> element must be an instance of apps.Name: %s"
% self.user_entry.name)
self.assertEquals(self.user_entry.name.family_name, 'Test')
self.assertEquals(self.user_entry.name.given_name, 'User')
def testQuota(self):
"""Tests the existence of <apps:quota> in UserEntry and verifies
the value"""
self.assert_(isinstance(self.user_entry.quota, gdata.apps.Quota),
"User entry <apps:quota> element must be an instance of apps.Quota: %s"
% self.user_entry.quota)
self.assertEquals(self.user_entry.quota.limit, '1024')
def testFeedLink(self):
"""Test the existence of a <gdata:feedLink> in UserEntry and
verifies the value"""
for an_feed_link in self.user_entry.feed_link:
self.assert_(isinstance(an_feed_link, gdata.FeedLink),
"User entry <gdata:feedLink> must be an instance of gdata.FeedLink" +
": %s" % an_feed_link)
self.assertEquals(self.user_entry.feed_link[0].rel,
'http://schemas.google.com/apps/2006#user.nicknames')
self.assertEquals(self.user_entry.feed_link[0].href,
'https://apps-apis.google.com/a/feeds/example.com/nickname/' +
'2.0?username=Test-3121')
self.assertEquals(self.user_entry.feed_link[1].rel,
'http://schemas.google.com/apps/2006#user.emailLists')
self.assertEquals(self.user_entry.feed_link[1].href,
'https://apps-apis.google.com/a/feeds/example.com/emailList/' +
'2.0?recipient=testlist@example.com')
def testUpdate(self):
"""Tests for modifing attributes of UserEntry"""
self.user_entry.name.family_name = 'ModifiedFamilyName'
self.user_entry.name.given_name = 'ModifiedGivenName'
self.user_entry.quota.limit = '2048'
self.user_entry.login.password = 'ModifiedPassword'
self.user_entry.login.suspended = 'true'
modified = gdata.apps.UserEntryFromString(self.user_entry.ToString())
self.assertEquals(modified.name.family_name, 'ModifiedFamilyName')
self.assertEquals(modified.name.given_name, 'ModifiedGivenName')
self.assertEquals(modified.quota.limit, '2048')
self.assertEquals(modified.login.password, 'ModifiedPassword')
self.assertEquals(modified.login.suspended, 'true')
if __name__ == '__main__':
unittest.main()
| 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.
__author__ = 'j.s@google.com (Jeff Scudder)'
import unittest
import gdata.test_config as conf
import gdata.data
import gdata.acl.data
import gdata.analytics.data
import gdata.dublincore.data
import gdata.books.data
import gdata.calendar.data
import gdata.geo.data
import gdata.finance.data
import gdata.notebook.data
import gdata.media.data
import gdata.youtube.data
import gdata.webmastertools.data
import gdata.contacts.data
import gdata.opensearch.data
class DataSmokeTest(unittest.TestCase):
def test_check_all_data_classes(self):
conf.check_data_classes(self, (
gdata.data.TotalResults, gdata.data.StartIndex,
gdata.data.ItemsPerPage, gdata.data.ExtendedProperty,
gdata.data.GDEntry, gdata.data.GDFeed, gdata.data.BatchId,
gdata.data.BatchOperation, gdata.data.BatchStatus,
gdata.data.BatchEntry, gdata.data.BatchInterrupted,
gdata.data.BatchFeed, gdata.data.EntryLink, gdata.data.FeedLink,
gdata.data.AdditionalName, gdata.data.Comments, gdata.data.Country,
gdata.data.Email, gdata.data.FamilyName, gdata.data.Im,
gdata.data.GivenName, gdata.data.NamePrefix, gdata.data.NameSuffix,
gdata.data.FullName, gdata.data.Name, gdata.data.OrgDepartment,
gdata.data.OrgName, gdata.data.OrgSymbol, gdata.data.OrgTitle,
gdata.data.Organization, gdata.data.When, gdata.data.Who,
gdata.data.OriginalEvent, gdata.data.PhoneNumber,
gdata.data.PostalAddress, gdata.data.Rating, gdata.data.Recurrence,
gdata.data.RecurrenceException, gdata.data.Reminder,
gdata.data.Agent, gdata.data.HouseName, gdata.data.Street,
gdata.data.PoBox, gdata.data.Neighborhood, gdata.data.City,
gdata.data.Subregion, gdata.data.Region, gdata.data.Postcode,
gdata.data.Country, gdata.data.FormattedAddress,
gdata.data.StructuredPostalAddress, gdata.data.Where,
gdata.data.AttendeeType, gdata.data.AttendeeStatus,
gdata.data.Deleted, gdata.data.Money,
gdata.acl.data.AclRole, gdata.acl.data.AclScope,
gdata.acl.data.AclWithKey,
gdata.acl.data.AclEntry, gdata.acl.data.AclFeed,
gdata.analytics.data.Dimension,
gdata.analytics.data.EndDate,
gdata.analytics.data.Metric,
gdata.analytics.data.Aggregates,
gdata.analytics.data.DataEntry,
gdata.analytics.data.Property,
gdata.analytics.data.StartDate,
gdata.analytics.data.TableId,
gdata.analytics.data.AccountEntry,
gdata.analytics.data.TableName,
gdata.analytics.data.DataSource,
gdata.analytics.data.AccountFeed,
gdata.analytics.data.DataFeed,
gdata.dublincore.data.Creator,
gdata.dublincore.data.Date,
gdata.dublincore.data.Description,
gdata.dublincore.data.Format,
gdata.dublincore.data.Identifier,
gdata.dublincore.data.Language,
gdata.dublincore.data.Publisher,
gdata.dublincore.data.Rights,
gdata.dublincore.data.Subject,
gdata.dublincore.data.Title,
gdata.books.data.CollectionEntry,
gdata.books.data.CollectionFeed,
gdata.books.data.Embeddability,
gdata.books.data.OpenAccess,
gdata.books.data.Review,
gdata.books.data.Viewability,
gdata.books.data.VolumeEntry,
gdata.books.data.VolumeFeed,
gdata.calendar.data.AccessLevelProperty,
gdata.calendar.data.AllowGSync2Property,
gdata.calendar.data.AllowGSyncProperty,
gdata.calendar.data.AnyoneCanAddSelfProperty,
gdata.calendar.data.CalendarAclRole,
gdata.calendar.data.CalendarCommentEntry,
gdata.calendar.data.CalendarCommentFeed,
gdata.calendar.data.CalendarComments,
gdata.calendar.data.CalendarExtendedProperty,
gdata.calendar.data.CalendarWhere,
gdata.calendar.data.ColorProperty,
gdata.calendar.data.GuestsCanInviteOthersProperty,
gdata.calendar.data.GuestsCanModifyProperty,
gdata.calendar.data.GuestsCanSeeGuestsProperty,
gdata.calendar.data.HiddenProperty,
gdata.calendar.data.IcalUIDProperty,
gdata.calendar.data.OverrideNameProperty,
gdata.calendar.data.PrivateCopyProperty,
gdata.calendar.data.QuickAddProperty,
gdata.calendar.data.ResourceProperty,
gdata.calendar.data.EventWho,
gdata.calendar.data.SelectedProperty,
gdata.calendar.data.SendAclNotificationsProperty,
gdata.calendar.data.CalendarAclEntry,
gdata.calendar.data.CalendarAclFeed,
gdata.calendar.data.SendEventNotificationsProperty,
gdata.calendar.data.SequenceNumberProperty,
gdata.calendar.data.CalendarRecurrenceExceptionEntry,
gdata.calendar.data.CalendarRecurrenceException,
gdata.calendar.data.SettingsProperty,
gdata.calendar.data.SettingsEntry,
gdata.calendar.data.CalendarSettingsFeed,
gdata.calendar.data.SuppressReplyNotificationsProperty,
gdata.calendar.data.SyncEventProperty,
gdata.calendar.data.CalendarEventEntry,
gdata.calendar.data.TimeZoneProperty,
gdata.calendar.data.TimesCleanedProperty,
gdata.calendar.data.CalendarEntry,
gdata.calendar.data.CalendarEventFeed,
gdata.calendar.data.CalendarFeed,
gdata.calendar.data.WebContentGadgetPref,
gdata.calendar.data.WebContent,
gdata.finance.data.Commission,
gdata.finance.data.CostBasis,
gdata.finance.data.DaysGain,
gdata.finance.data.Gain,
gdata.finance.data.MarketValue,
gdata.finance.data.PortfolioData,
gdata.finance.data.PortfolioEntry,
gdata.finance.data.PortfolioFeed,
gdata.finance.data.PositionData,
gdata.finance.data.Price,
gdata.finance.data.Symbol,
gdata.finance.data.PositionEntry,
gdata.finance.data.PositionFeed,
gdata.finance.data.TransactionData,
gdata.finance.data.TransactionEntry,
gdata.finance.data.TransactionFeed,
gdata.notebook.data.ComesAfter,
gdata.notebook.data.NoteEntry,
gdata.notebook.data.NotebookFeed,
gdata.notebook.data.NotebookListEntry,
gdata.notebook.data.NotebookListFeed,
gdata.youtube.data.ComplaintEntry,
gdata.youtube.data.ComplaintFeed,
gdata.youtube.data.RatingEntry,
gdata.youtube.data.RatingFeed,
gdata.youtube.data.YouTubeMediaContent,
gdata.youtube.data.YtAge,
gdata.youtube.data.YtBooks,
gdata.youtube.data.YtCompany,
gdata.youtube.data.YtDescription,
gdata.youtube.data.YtDuration,
gdata.youtube.data.YtFirstName,
gdata.youtube.data.YtGender,
gdata.youtube.data.YtHobbies,
gdata.youtube.data.YtHometown,
gdata.youtube.data.YtLastName,
gdata.youtube.data.YtLocation,
gdata.youtube.data.YtMovies,
gdata.youtube.data.YtMusic,
gdata.youtube.data.YtNoEmbed,
gdata.youtube.data.YtOccupation,
gdata.youtube.data.YtPlaylistId,
gdata.youtube.data.YtPosition,
gdata.youtube.data.YtPrivate,
gdata.youtube.data.YtQueryString,
gdata.youtube.data.YtRacy,
gdata.youtube.data.YtRecorded,
gdata.youtube.data.YtRelationship,
gdata.youtube.data.YtSchool,
gdata.youtube.data.YtStatistics,
gdata.youtube.data.YtStatus,
gdata.youtube.data.YtUserProfileStatistics,
gdata.youtube.data.YtUsername,
gdata.youtube.data.FriendEntry,
gdata.youtube.data.FriendFeed,
gdata.youtube.data.YtVideoStatistics,
gdata.youtube.data.ChannelEntry,
gdata.youtube.data.ChannelFeed,
gdata.youtube.data.FavoriteEntry,
gdata.youtube.data.FavoriteFeed,
gdata.youtube.data.YouTubeMediaCredit,
gdata.youtube.data.YouTubeMediaRating,
gdata.youtube.data.YtAboutMe,
gdata.youtube.data.UserProfileEntry,
gdata.youtube.data.UserProfileFeed,
gdata.youtube.data.YtAspectRatio,
gdata.youtube.data.YtBasePublicationState,
gdata.youtube.data.YtPublicationState,
gdata.youtube.data.YouTubeAppControl,
gdata.youtube.data.YtCaptionPublicationState,
gdata.youtube.data.YouTubeCaptionAppControl,
gdata.youtube.data.CaptionTrackEntry,
gdata.youtube.data.CaptionTrackFeed,
gdata.youtube.data.YtCountHint,
gdata.youtube.data.PlaylistLinkEntry,
gdata.youtube.data.PlaylistLinkFeed,
gdata.youtube.data.YtModerationStatus,
gdata.youtube.data.YtPlaylistTitle,
gdata.youtube.data.SubscriptionEntry,
gdata.youtube.data.SubscriptionFeed,
gdata.youtube.data.YtSpam,
gdata.youtube.data.CommentEntry,
gdata.youtube.data.CommentFeed,
gdata.youtube.data.YtUploaded,
gdata.youtube.data.YtVideoId,
gdata.youtube.data.YouTubeMediaGroup,
gdata.youtube.data.VideoEntryBase,
gdata.youtube.data.PlaylistEntry,
gdata.youtube.data.PlaylistFeed,
gdata.youtube.data.VideoEntry,
gdata.youtube.data.VideoFeed,
gdata.youtube.data.VideoMessageEntry,
gdata.youtube.data.VideoMessageFeed,
gdata.youtube.data.UserEventEntry,
gdata.youtube.data.UserEventFeed,
gdata.youtube.data.VideoModerationEntry,
gdata.youtube.data.VideoModerationFeed,
gdata.media.data.MediaCategory,
gdata.media.data.MediaCopyright,
gdata.media.data.MediaCredit,
gdata.media.data.MediaDescription,
gdata.media.data.MediaHash,
gdata.media.data.MediaKeywords,
gdata.media.data.MediaPlayer,
gdata.media.data.MediaRating,
gdata.media.data.MediaRestriction,
gdata.media.data.MediaText,
gdata.media.data.MediaThumbnail,
gdata.media.data.MediaTitle,
gdata.media.data.MediaContent,
gdata.media.data.MediaGroup,
gdata.webmastertools.data.CrawlIssueCrawlType,
gdata.webmastertools.data.CrawlIssueDateDetected,
gdata.webmastertools.data.CrawlIssueDetail,
gdata.webmastertools.data.CrawlIssueIssueType,
gdata.webmastertools.data.CrawlIssueLinkedFromUrl,
gdata.webmastertools.data.CrawlIssueUrl,
gdata.webmastertools.data.CrawlIssueEntry,
gdata.webmastertools.data.CrawlIssuesFeed,
gdata.webmastertools.data.Indexed,
gdata.webmastertools.data.Keyword,
gdata.webmastertools.data.KeywordEntry,
gdata.webmastertools.data.KeywordsFeed,
gdata.webmastertools.data.LastCrawled,
gdata.webmastertools.data.MessageBody,
gdata.webmastertools.data.MessageDate,
gdata.webmastertools.data.MessageLanguage,
gdata.webmastertools.data.MessageRead,
gdata.webmastertools.data.MessageSubject,
gdata.webmastertools.data.SiteId,
gdata.webmastertools.data.MessageEntry,
gdata.webmastertools.data.MessagesFeed,
gdata.webmastertools.data.SitemapEntry,
gdata.webmastertools.data.SitemapMobileMarkupLanguage,
gdata.webmastertools.data.SitemapMobile,
gdata.webmastertools.data.SitemapNewsPublicationLabel,
gdata.webmastertools.data.SitemapNews,
gdata.webmastertools.data.SitemapType,
gdata.webmastertools.data.SitemapUrlCount,
gdata.webmastertools.data.SitemapsFeed,
gdata.webmastertools.data.VerificationMethod,
gdata.webmastertools.data.Verified,
gdata.webmastertools.data.SiteEntry,
gdata.webmastertools.data.SitesFeed,
gdata.contacts.data.BillingInformation,
gdata.contacts.data.Birthday,
gdata.contacts.data.CalendarLink,
gdata.contacts.data.DirectoryServer,
gdata.contacts.data.Event,
gdata.contacts.data.ExternalId,
gdata.contacts.data.Gender,
gdata.contacts.data.Hobby,
gdata.contacts.data.Initials,
gdata.contacts.data.Jot,
gdata.contacts.data.Language,
gdata.contacts.data.MaidenName,
gdata.contacts.data.Mileage,
gdata.contacts.data.NickName,
gdata.contacts.data.Occupation,
gdata.contacts.data.Priority,
gdata.contacts.data.Relation,
gdata.contacts.data.Sensitivity,
gdata.contacts.data.UserDefinedField,
gdata.contacts.data.Website,
gdata.contacts.data.HouseName,
gdata.contacts.data.Street,
gdata.contacts.data.POBox,
gdata.contacts.data.Neighborhood,
gdata.contacts.data.City,
gdata.contacts.data.SubRegion,
gdata.contacts.data.Region,
gdata.contacts.data.PostalCode,
gdata.contacts.data.Country,
gdata.contacts.data.PersonEntry,
gdata.contacts.data.Deleted,
gdata.contacts.data.GroupMembershipInfo,
gdata.contacts.data.ContactEntry,
gdata.contacts.data.ContactsFeed,
gdata.contacts.data.SystemGroup,
gdata.contacts.data.GroupEntry,
gdata.contacts.data.GroupsFeed,
gdata.contacts.data.ProfileEntry,
gdata.contacts.data.ProfilesFeed,
gdata.opensearch.data.ItemsPerPage,
gdata.opensearch.data.StartIndex,
gdata.opensearch.data.TotalResults,
))
def suite():
return conf.build_suite([DataSmokeTest])
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = ('api.jfisher (Jeff Fisher), '
'api.eric@google.com (Eric Bidelman)')
import unittest
from gdata import test_data
import gdata.docs
class DocumentListEntryTest(unittest.TestCase):
def setUp(self):
self.dl_entry = gdata.docs.DocumentListEntryFromString(
test_data.DOCUMENT_LIST_ENTRY)
def testToAndFromStringWithData(self):
entry = gdata.docs.DocumentListEntryFromString(str(self.dl_entry))
self.assertEqual(entry.author[0].name.text, 'test.user')
self.assertEqual(entry.author[0].email.text, 'test.user@gmail.com')
self.assertEqual(entry.GetDocumentType(), 'spreadsheet')
self.assertEqual(entry.id.text,
'https://docs.google.com/feeds/documents/private/full/' +\
'spreadsheet%3Asupercalifragilisticexpealidocious')
self.assertEqual(entry.title.text,'Test Spreadsheet')
self.assertEqual(entry.resourceId.text,
'spreadsheet:supercalifragilisticexpealidocious')
self.assertEqual(entry.lastModifiedBy.name.text,'test.user')
self.assertEqual(entry.lastModifiedBy.email.text,'test.user@gmail.com')
self.assertEqual(entry.lastViewed.text,'2009-03-05T07:48:21.493Z')
self.assertEqual(entry.writersCanInvite.value, 'true')
class DocumentListFeedTest(unittest.TestCase):
def setUp(self):
self.dl_feed = gdata.docs.DocumentListFeedFromString(
test_data.DOCUMENT_LIST_FEED)
def testToAndFromString(self):
self.assert_(len(self.dl_feed.entry) == 2)
for an_entry in self.dl_feed.entry:
self.assert_(isinstance(an_entry, gdata.docs.DocumentListEntry))
new_dl_feed = gdata.docs.DocumentListFeedFromString(str(self.dl_feed))
for an_entry in new_dl_feed.entry:
self.assert_(isinstance(an_entry, gdata.docs.DocumentListEntry))
def testConvertActualData(self):
for an_entry in self.dl_feed.entry:
self.assertEqual(an_entry.author[0].name.text, 'test.user')
self.assertEqual(an_entry.author[0].email.text, 'test.user@gmail.com')
self.assertEqual(an_entry.lastModifiedBy.name.text, 'test.user')
self.assertEqual(an_entry.lastModifiedBy.email.text,
'test.user@gmail.com')
self.assertEqual(an_entry.lastViewed.text,'2009-03-05T07:48:21.493Z')
if(an_entry.GetDocumentType() == 'spreadsheet'):
self.assertEqual(an_entry.title.text, 'Test Spreadsheet')
self.assertEqual(an_entry.writersCanInvite.value, 'true')
elif(an_entry.GetDocumentType() == 'document'):
self.assertEqual(an_entry.title.text, 'Test Document')
self.assertEqual(an_entry.writersCanInvite.value, 'false')
def testLinkFinderFindsLinks(self):
for entry in self.dl_feed.entry:
# All Document List entries should have a self link
self.assert_(entry.GetSelfLink() is not None)
# All Document List entries should have an HTML link
self.assert_(entry.GetHtmlLink() is not None)
self.assert_(entry.feedLink.href is not None)
class DocumentListAclEntryTest(unittest.TestCase):
def setUp(self):
self.acl_entry = gdata.docs.DocumentListAclEntryFromString(
test_data.DOCUMENT_LIST_ACL_ENTRY)
def testToAndFromString(self):
self.assert_(isinstance(self.acl_entry, gdata.docs.DocumentListAclEntry))
self.assert_(isinstance(self.acl_entry.role, gdata.docs.Role))
self.assert_(isinstance(self.acl_entry.scope, gdata.docs.Scope))
self.assertEqual(self.acl_entry.scope.value, 'user@gmail.com')
self.assertEqual(self.acl_entry.scope.type, 'user')
self.assertEqual(self.acl_entry.role.value, 'writer')
acl_entry_str = str(self.acl_entry)
new_acl_entry = gdata.docs.DocumentListAclEntryFromString(acl_entry_str)
self.assert_(isinstance(new_acl_entry, gdata.docs.DocumentListAclEntry))
self.assert_(isinstance(new_acl_entry.role, gdata.docs.Role))
self.assert_(isinstance(new_acl_entry.scope, gdata.docs.Scope))
self.assertEqual(new_acl_entry.scope.value, self.acl_entry.scope.value)
self.assertEqual(new_acl_entry.scope.type, self.acl_entry.scope.type)
self.assertEqual(new_acl_entry.role.value, self.acl_entry.role.value)
def testCreateNewAclEntry(self):
cat = gdata.atom.Category(
term='http://schemas.google.com/acl/2007#accessRule',
scheme='http://schemas.google.com/g/2005#kind')
acl_entry = gdata.docs.DocumentListAclEntry(category=[cat])
acl_entry.scope = gdata.docs.Scope(value='user@gmail.com', type='user')
acl_entry.role = gdata.docs.Role(value='writer')
self.assert_(isinstance(acl_entry, gdata.docs.DocumentListAclEntry))
self.assert_(isinstance(acl_entry.role, gdata.docs.Role))
self.assert_(isinstance(acl_entry.scope, gdata.docs.Scope))
self.assertEqual(acl_entry.scope.value, 'user@gmail.com')
self.assertEqual(acl_entry.scope.type, 'user')
self.assertEqual(acl_entry.role.value, 'writer')
class DocumentListAclFeedTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.docs.DocumentListAclFeedFromString(
test_data.DOCUMENT_LIST_ACL_FEED)
def testToAndFromString(self):
for entry in self.feed.entry:
self.assert_(isinstance(entry, gdata.docs.DocumentListAclEntry))
feed = gdata.docs.DocumentListAclFeedFromString(str(self.feed))
for entry in feed.entry:
self.assert_(isinstance(entry, gdata.docs.DocumentListAclEntry))
def testConvertActualData(self):
entries = self.feed.entry
self.assert_(len(entries) == 2)
self.assertEqual(entries[0].title.text,
'Document Permission - user@gmail.com')
self.assertEqual(entries[0].role.value, 'owner')
self.assertEqual(entries[0].scope.type, 'user')
self.assertEqual(entries[0].scope.value, 'user@gmail.com')
self.assert_(entries[0].GetSelfLink() is not None)
self.assert_(entries[0].GetEditLink() is not None)
self.assertEqual(entries[1].title.text,
'Document Permission - user2@google.com')
self.assertEqual(entries[1].role.value, 'writer')
self.assertEqual(entries[1].scope.type, 'domain')
self.assertEqual(entries[1].scope.value, 'google.com')
self.assert_(entries[1].GetSelfLink() is not None)
self.assert_(entries[1].GetEditLink() is not None)
if __name__ == '__main__':
unittest.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.jscudder (Jeffrey Scudder)'
import getpass
import time
import unittest
import StringIO
import gdata.photos.service
import gdata.photos
import atom
username = ''
password = ''
test_image_location = '../../testimage.jpg'
test_image_name = 'testimage.jpg'
class PhotosServiceTest(unittest.TestCase):
def setUp(self):
# Initialize the client and create a new album for testing.
self.client = gdata.photos.service.PhotosService()
self.client.email = username
self.client.password = password
self.client.source = 'Photos Client Unit Tests'
self.client.ProgrammaticLogin()
# Give the album a unique title by appending the current time.
self.test_album = self.client.InsertAlbum(
'Python library test' + str(time.time()),
'A temporary test album.')
def testUploadGetAndDeletePhoto(self):
image_entry = self.client.InsertPhotoSimple(self.test_album,
'test', 'a pretty testing picture', test_image_location)
self.assert_(image_entry.title.text == 'test')
results_feed = self.client.SearchUserPhotos('test')
self.assert_(len(results_feed.entry) > 0)
self.client.Delete(image_entry)
def testInsertPhotoUpdateBlobAndDelete(self):
new_entry = gdata.photos.PhotoEntry()
new_entry.title = atom.Title(text='a_test_image')
new_entry.summary = atom.Summary(text='Just a test.')
new_entry.category.append(atom.Category(
scheme='http://schemas.google.com/g/2005#kind',
term='http://schemas.google.com/photos/2007#photo'))
entry = self.client.InsertPhoto(self.test_album, new_entry,
test_image_location, content_type='image/jpeg')
self.assert_(entry.id.text)
updated_entry = self.client.UpdatePhotoBlob(entry, test_image_location)
self.assert_(entry.GetEditLink().href != updated_entry.GetEditLink().href)
self.client.Delete(updated_entry)
def tearDown(self):
# Delete the test album.
test_album = self.client.GetEntry(self.test_album.GetSelfLink().href)
self.client.Delete(test_album)
if __name__ == '__main__':
print ('Google Photos test\nNOTE: Please run these tests only with a test '
'account. The tests may delete or update your data.')
username = raw_input('Please enter your username: ')
password = getpass.getpass()
unittest.main()
| 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.
__author__ = 'livibetter (Yu-Jie Lin)'
import unittest
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import gdata
from gdata import test_data
import gdata.webmastertools as webmastertools
class IndexedTest(unittest.TestCase):
def setUp(self):
self.indexed = webmastertools.Indexed()
def testToAndFromString(self):
self.indexed.text = 'true'
self.assert_(self.indexed.text == 'true')
new_indexed = webmastertools.IndexedFromString(self.indexed.ToString())
self.assert_(self.indexed.text == new_indexed.text)
class CrawledTest(unittest.TestCase):
def setUp(self):
self.crawled = webmastertools.Crawled()
def testToAndFromString(self):
self.crawled.text = 'true'
self.assert_(self.crawled.text == 'true')
new_crawled = webmastertools.CrawledFromString(self.crawled.ToString())
self.assert_(self.crawled.text == new_crawled.text)
class GeoLocationTest(unittest.TestCase):
def setUp(self):
self.geolocation = webmastertools.GeoLocation()
def testToAndFromString(self):
self.geolocation.text = 'US'
self.assert_(self.geolocation.text == 'US')
new_geolocation = webmastertools.GeoLocationFromString(
self.geolocation.ToString())
self.assert_(self.geolocation.text == new_geolocation.text)
class PreferredDomainTest(unittest.TestCase):
def setUp(self):
self.preferred_domain = webmastertools.PreferredDomain()
def testToAndFromString(self):
self.preferred_domain.text = 'none'
self.assert_(self.preferred_domain.text == 'none')
new_preferred_domain = webmastertools.PreferredDomainFromString(
self.preferred_domain.ToString())
self.assert_(self.preferred_domain.text == new_preferred_domain.text)
class CrawlRateTest(unittest.TestCase):
def setUp(self):
self.crawl_rate = webmastertools.CrawlRate()
def testToAndFromString(self):
self.crawl_rate.text = 'normal'
self.assert_(self.crawl_rate.text == 'normal')
new_crawl_rate = webmastertools.CrawlRateFromString(
self.crawl_rate.ToString())
self.assert_(self.crawl_rate.text == new_crawl_rate.text)
class EnhancedImageSearchTest(unittest.TestCase):
def setUp(self):
self.enhanced_image_search = webmastertools.EnhancedImageSearch()
def testToAndFromString(self):
self.enhanced_image_search.text = 'true'
self.assert_(self.enhanced_image_search.text == 'true')
new_enhanced_image_search = webmastertools.EnhancedImageSearchFromString(
self.enhanced_image_search.ToString())
self.assert_(self.enhanced_image_search.text ==
new_enhanced_image_search.text)
class VerifiedTest(unittest.TestCase):
def setUp(self):
self.verified = webmastertools.Verified()
def testToAndFromString(self):
self.verified.text = 'true'
self.assert_(self.verified.text == 'true')
new_verified = webmastertools.VerifiedFromString(self.verified.ToString())
self.assert_(self.verified.text == new_verified.text)
class VerificationMethodMetaTest(unittest.TestCase):
def setUp(self):
self.meta = webmastertools.VerificationMethodMeta()
def testToAndFromString(self):
self.meta.name = 'verify-vf1'
self.meta.content = 'a2Ai'
self.assert_(self.meta.name == 'verify-vf1')
self.assert_(self.meta.content == 'a2Ai')
new_meta = webmastertools.VerificationMethodMetaFromString(
self.meta.ToString())
self.assert_(self.meta.name == new_meta.name)
self.assert_(self.meta.content == new_meta.content)
class VerificationMethodTest(unittest.TestCase):
def setUp(self):
pass
def testMetaTagToAndFromString(self):
self.method = webmastertools.VerificationMethod()
self.method.type = 'metatag'
self.method.in_use = 'false'
self.assert_(self.method.type == 'metatag')
self.assert_(self.method.in_use == 'false')
self.method.meta = webmastertools.VerificationMethodMeta(name='verify-vf1',
content='a2Ai')
self.assert_(self.method.meta.name == 'verify-vf1')
self.assert_(self.method.meta.content == 'a2Ai')
new_method = webmastertools.VerificationMethodFromString(
self.method.ToString())
self.assert_(self.method.type == new_method.type)
self.assert_(self.method.in_use == new_method.in_use)
self.assert_(self.method.meta.name == new_method.meta.name)
self.assert_(self.method.meta.content == new_method.meta.content)
method = webmastertools.VerificationMethod(type='xyz')
self.assertEqual(method.type, 'xyz')
method = webmastertools.VerificationMethod()
self.assert_(method.type is None)
def testHtmlPageToAndFromString(self):
self.method = webmastertools.VerificationMethod()
self.method.type = 'htmlpage'
self.method.in_use = 'false'
self.method.text = '456456-google.html'
self.assert_(self.method.type == 'htmlpage')
self.assert_(self.method.in_use == 'false')
self.assert_(self.method.text == '456456-google.html')
self.assert_(self.method.meta is None)
new_method = webmastertools.VerificationMethodFromString(
self.method.ToString())
self.assert_(self.method.type == new_method.type)
self.assert_(self.method.in_use == new_method.in_use)
self.assert_(self.method.text == new_method.text)
self.assert_(self.method.meta is None)
def testConvertActualData(self):
feed = webmastertools.SitesFeedFromString(test_data.SITES_FEED)
self.assert_(len(feed.entry[0].verification_method) == 2)
check = 0
for method in feed.entry[0].verification_method:
self.assert_(isinstance(method, webmastertools.VerificationMethod))
if method.type == 'metatag':
self.assert_(method.in_use == 'false')
self.assert_(method.text is None)
self.assert_(method.meta.name == 'verify-v1')
self.assert_(method.meta.content == 'a2Ai')
check = check | 1
elif method.type == 'htmlpage':
self.assert_(method.in_use == 'false')
self.assert_(method.text == '456456-google.html')
check = check | 2
else:
self.fail('Wrong Verification Method: %s' % method.type)
self.assert_(check == 2 ** 2 - 1,
'Should only have two Verification Methods, metatag and htmlpage')
class MarkupLanguageTest(unittest.TestCase):
def setUp(self):
self.markup_language = webmastertools.MarkupLanguage()
def testToAndFromString(self):
self.markup_language.text = 'HTML'
self.assert_(self.markup_language.text == 'HTML')
new_markup_language = webmastertools.MarkupLanguageFromString(
self.markup_language.ToString())
self.assert_(self.markup_language.text == new_markup_language.text)
class SitemapMobileTest(unittest.TestCase):
def setUp(self):
self.sitemap_mobile = webmastertools.SitemapMobile()
def testToAndFromString(self):
self.sitemap_mobile.markup_language.append(webmastertools.MarkupLanguage(
text = 'HTML'))
self.assert_(self.sitemap_mobile.text is None)
self.assert_(self.sitemap_mobile.markup_language[0].text == 'HTML')
new_sitemap_mobile = webmastertools.SitemapMobileFromString(
self.sitemap_mobile.ToString())
self.assert_(new_sitemap_mobile.text is None)
self.assert_(self.sitemap_mobile.markup_language[0].text ==
new_sitemap_mobile.markup_language[0].text)
def testConvertActualData(self):
feed = webmastertools.SitemapsFeedFromString(test_data.SITEMAPS_FEED)
self.assert_(feed.sitemap_mobile.text.strip() == '')
self.assert_(len(feed.sitemap_mobile.markup_language) == 2)
check = 0
for markup_language in feed.sitemap_mobile.markup_language:
self.assert_(isinstance(markup_language, webmastertools.MarkupLanguage))
if markup_language.text == "HTML":
check = check | 1
elif markup_language.text == "WAP":
check = check | 2
else:
self.fail('Unexpected markup language: %s' % markup_language.text)
self.assert_(check == 2 ** 2 - 1, "Something is wrong with markup language")
class SitemapMobileMarkupLanguageTest(unittest.TestCase):
def setUp(self):
self.sitemap_mobile_markup_language =\
webmastertools.SitemapMobileMarkupLanguage()
def testToAndFromString(self):
self.sitemap_mobile_markup_language.text = 'HTML'
self.assert_(self.sitemap_mobile_markup_language.text == 'HTML')
new_sitemap_mobile_markup_language =\
webmastertools.SitemapMobileMarkupLanguageFromString(
self.sitemap_mobile_markup_language.ToString())
self.assert_(self.sitemap_mobile_markup_language.text ==\
new_sitemap_mobile_markup_language.text)
class PublicationLabelTest(unittest.TestCase):
def setUp(self):
self.publication_label = webmastertools.PublicationLabel()
def testToAndFromString(self):
self.publication_label.text = 'Value1'
self.assert_(self.publication_label.text == 'Value1')
new_publication_label = webmastertools.PublicationLabelFromString(
self.publication_label.ToString())
self.assert_(self.publication_label.text == new_publication_label.text)
class SitemapNewsTest(unittest.TestCase):
def setUp(self):
self.sitemap_news = webmastertools.SitemapNews()
def testToAndFromString(self):
self.sitemap_news.publication_label.append(webmastertools.PublicationLabel(
text = 'Value1'))
self.assert_(self.sitemap_news.text is None)
self.assert_(self.sitemap_news.publication_label[0].text == 'Value1')
new_sitemap_news = webmastertools.SitemapNewsFromString(
self.sitemap_news.ToString())
self.assert_(new_sitemap_news.text is None)
self.assert_(self.sitemap_news.publication_label[0].text ==
new_sitemap_news.publication_label[0].text)
def testConvertActualData(self):
feed = webmastertools.SitemapsFeedFromString(test_data.SITEMAPS_FEED)
self.assert_(len(feed.sitemap_news.publication_label) == 3)
check = 0
for publication_label in feed.sitemap_news.publication_label:
if publication_label.text == "Value1":
check = check | 1
elif publication_label.text == "Value2":
check = check | 2
elif publication_label.text == "Value3":
check = check | 4
else:
self.fail('Unexpected publication label: %s' % markup_language.text)
self.assert_(check == 2 ** 3 - 1,
'Something is wrong with publication label')
class SitemapNewsPublicationLabelTest(unittest.TestCase):
def setUp(self):
self.sitemap_news_publication_label =\
webmastertools.SitemapNewsPublicationLabel()
def testToAndFromString(self):
self.sitemap_news_publication_label.text = 'LabelValue'
self.assert_(self.sitemap_news_publication_label.text == 'LabelValue')
new_sitemap_news_publication_label =\
webmastertools.SitemapNewsPublicationLabelFromString(
self.sitemap_news_publication_label.ToString())
self.assert_(self.sitemap_news_publication_label.text ==\
new_sitemap_news_publication_label.text)
class SitemapLastDownloadedTest(unittest.TestCase):
def setUp(self):
self.sitemap_last_downloaded = webmastertools.SitemapLastDownloaded()
def testToAndFromString(self):
self.sitemap_last_downloaded.text = '2006-11-18T19:27:32.543Z'
self.assert_(self.sitemap_last_downloaded.text ==\
'2006-11-18T19:27:32.543Z')
new_sitemap_last_downloaded =\
webmastertools.SitemapLastDownloadedFromString(
self.sitemap_last_downloaded.ToString())
self.assert_(self.sitemap_last_downloaded.text ==\
new_sitemap_last_downloaded.text)
class SitemapTypeTest(unittest.TestCase):
def setUp(self):
self.sitemap_type = webmastertools.SitemapType()
def testToAndFromString(self):
self.sitemap_type.text = 'WEB'
self.assert_(self.sitemap_type.text == 'WEB')
new_sitemap_type = webmastertools.SitemapTypeFromString(
self.sitemap_type.ToString())
self.assert_(self.sitemap_type.text == new_sitemap_type.text)
class SitemapStatusTest(unittest.TestCase):
def setUp(self):
self.sitemap_status = webmastertools.SitemapStatus()
def testToAndFromString(self):
self.sitemap_status.text = 'Pending'
self.assert_(self.sitemap_status.text == 'Pending')
new_sitemap_status = webmastertools.SitemapStatusFromString(
self.sitemap_status.ToString())
self.assert_(self.sitemap_status.text == new_sitemap_status.text)
class SitemapUrlCountTest(unittest.TestCase):
def setUp(self):
self.sitemap_url_count = webmastertools.SitemapUrlCount()
def testToAndFromString(self):
self.sitemap_url_count.text = '0'
self.assert_(self.sitemap_url_count.text == '0')
new_sitemap_url_count = webmastertools.SitemapUrlCountFromString(
self.sitemap_url_count.ToString())
self.assert_(self.sitemap_url_count.text == new_sitemap_url_count.text)
class SitesEntryTest(unittest.TestCase):
def setUp(self):
pass
def testToAndFromString(self):
entry = webmastertools.SitesEntry(
indexed=webmastertools.Indexed(text='true'),
crawled=webmastertools.Crawled(text='2008-09-14T08:59:28.000'),
geolocation=webmastertools.GeoLocation(text='US'),
preferred_domain=webmastertools.PreferredDomain(text='none'),
crawl_rate=webmastertools.CrawlRate(text='normal'),
enhanced_image_search=webmastertools.EnhancedImageSearch(text='true'),
verified=webmastertools.Verified(text='false'),
)
self.assert_(entry.indexed.text == 'true')
self.assert_(entry.crawled.text == '2008-09-14T08:59:28.000')
self.assert_(entry.geolocation.text == 'US')
self.assert_(entry.preferred_domain.text == 'none')
self.assert_(entry.crawl_rate.text == 'normal')
self.assert_(entry.enhanced_image_search.text == 'true')
self.assert_(entry.verified.text == 'false')
new_entry = webmastertools.SitesEntryFromString(entry.ToString())
self.assert_(new_entry.indexed.text == 'true')
self.assert_(new_entry.crawled.text == '2008-09-14T08:59:28.000')
self.assert_(new_entry.geolocation.text == 'US')
self.assert_(new_entry.preferred_domain.text == 'none')
self.assert_(new_entry.crawl_rate.text == 'normal')
self.assert_(new_entry.enhanced_image_search.text == 'true')
self.assert_(new_entry.verified.text == 'false')
def testConvertActualData(self):
feed = webmastertools.SitesFeedFromString(test_data.SITES_FEED)
self.assert_(len(feed.entry) == 1)
entry = feed.entry[0]
self.assert_(isinstance(entry, webmastertools.SitesEntry))
self.assert_(entry.indexed.text == 'true')
self.assert_(entry.crawled.text == '2008-09-14T08:59:28.000')
self.assert_(entry.geolocation.text == 'US')
self.assert_(entry.preferred_domain.text == 'none')
self.assert_(entry.crawl_rate.text == 'normal')
self.assert_(entry.enhanced_image_search.text == 'true')
self.assert_(entry.verified.text == 'false')
class SitesFeedTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.webmastertools.SitesFeedFromString(test_data.SITES_FEED)
def testToAndFromString(self):
self.assert_(len(self.feed.entry) == 1)
for entry in self.feed.entry:
self.assert_(isinstance(entry, webmastertools.SitesEntry))
new_feed = webmastertools.SitesFeedFromString(self.feed.ToString())
self.assert_(len(new_feed.entry) == 1)
for entry in new_feed.entry:
self.assert_(isinstance(entry, webmastertools.SitesEntry))
class SitemapsEntryTest(unittest.TestCase):
def testRegularToAndFromString(self):
entry = webmastertools.SitemapsEntry(
sitemap_type=webmastertools.SitemapType(text='WEB'),
sitemap_status=webmastertools.SitemapStatus(text='Pending'),
sitemap_last_downloaded=webmastertools.SitemapLastDownloaded(
text='2006-11-18T19:27:32.543Z'),
sitemap_url_count=webmastertools.SitemapUrlCount(text='102'),
)
self.assert_(entry.sitemap_type.text == 'WEB')
self.assert_(entry.sitemap_status.text == 'Pending')
self.assert_(entry.sitemap_last_downloaded.text ==\
'2006-11-18T19:27:32.543Z')
self.assert_(entry.sitemap_url_count.text == '102')
new_entry = webmastertools.SitemapsEntryFromString(entry.ToString())
self.assert_(new_entry.sitemap_type.text == 'WEB')
self.assert_(new_entry.sitemap_status.text == 'Pending')
self.assert_(new_entry.sitemap_last_downloaded.text ==\
'2006-11-18T19:27:32.543Z')
self.assert_(new_entry.sitemap_url_count.text == '102')
def testConvertActualData(self):
feed = gdata.webmastertools.SitemapsFeedFromString(test_data.SITEMAPS_FEED)
self.assert_(len(feed.entry) == 3)
for entry in feed.entry:
self.assert_(entry, webmastertools.SitemapsEntry)
self.assert_(entry.sitemap_status, webmastertools.SitemapStatus)
self.assert_(entry.sitemap_last_downloaded,
webmastertools.SitemapLastDownloaded)
self.assert_(entry.sitemap_url_count, webmastertools.SitemapUrlCount)
self.assert_(entry.sitemap_status.text == 'StatusValue')
self.assert_(entry.sitemap_last_downloaded.text ==\
'2006-11-18T19:27:32.543Z')
self.assert_(entry.sitemap_url_count.text == '102')
if entry.id.text == 'http://www.example.com/sitemap-index.xml':
self.assert_(entry.sitemap_type, webmastertools.SitemapType)
self.assert_(entry.sitemap_type.text == 'WEB')
self.assert_(entry.sitemap_mobile_markup_language is None)
self.assert_(entry.sitemap_news_publication_label is None)
elif entry.id.text == 'http://www.example.com/mobile/sitemap-index.xml':
self.assert_(entry.sitemap_mobile_markup_language,
webmastertools.SitemapMobileMarkupLanguage)
self.assert_(entry.sitemap_mobile_markup_language.text == 'HTML')
self.assert_(entry.sitemap_type is None)
self.assert_(entry.sitemap_news_publication_label is None)
elif entry.id.text == 'http://www.example.com/news/sitemap-index.xml':
self.assert_(entry.sitemap_news_publication_label,
webmastertools.SitemapNewsPublicationLabel)
self.assert_(entry.sitemap_news_publication_label.text == 'LabelValue')
self.assert_(entry.sitemap_type is None)
self.assert_(entry.sitemap_mobile_markup_language is None)
class SitemapsFeedTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.webmastertools.SitemapsFeedFromString(
test_data.SITEMAPS_FEED)
def testToAndFromString(self):
self.assert_(len(self.feed.entry) == 3)
for entry in self.feed.entry:
self.assert_(isinstance(entry, webmastertools.SitemapsEntry))
new_feed = webmastertools.SitemapsFeedFromString(self.feed.ToString())
self.assert_(len(new_feed.entry) == 3)
for entry in new_feed.entry:
self.assert_(isinstance(entry, webmastertools.SitemapsEntry))
if __name__ == '__main__':
unittest.main()
| 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.
# These tests attempt to connect to Google servers.
__author__ = 'jlapenna@google.com (Joe LaPenna)'
import unittest
import gdata.projecthosting.client
import gdata.projecthosting.data
import gdata.gauth
import gdata.client
import atom.http_core
import atom.mock_http_core
import atom.core
import gdata.data
import gdata.test_config as conf
conf.options.register_option(conf.PROJECT_NAME_OPTION)
conf.options.register_option(conf.ISSUE_ASSIGNEE_OPTION)
class ProjectHostingClientTest(unittest.TestCase):
def setUp(self):
self.client = None
if conf.options.get_value('runlive') == 'true':
self.client = gdata.projecthosting.client.ProjectHostingClient()
conf.configure_client(self.client, 'ProjectHostingClientTest', 'code')
self.project_name = conf.options.get_value('project_name')
self.assignee = conf.options.get_value('issue_assignee')
self.owner = conf.options.get_value('username')
def tearDown(self):
conf.close_client(self.client)
def create_issue(self):
# Add an issue
created = self.client.add_issue(
self.project_name,
'my title',
'my summary',
self.owner,
labels=['label0'])
self.assertEqual(created.title.text, 'my title')
self.assertEqual(created.content.text, 'my summary')
self.assertEqual(len(created.label), 1)
self.assertEqual(created.label[0].text, 'label0')
return created
def test_create_update_close(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'test_create_update_delete')
# Create the issue:
created = self.create_issue()
# Change the issue we just added.
issue_id = created.id.text.split('/')[-1]
update_response = self.client.update_issue(
self.project_name,
issue_id,
self.owner,
comment='My comment here.',
summary='New Summary',
status='Accepted',
owner=self.assignee,
labels=['-label0', 'label1'],
ccs=[self.owner])
updates = update_response.updates
# Make sure it changed our status, summary, and added the comment.
self.assertEqual(update_response.content.text, 'My comment here.')
self.assertEqual(updates.summary.text, 'New Summary')
self.assertEqual(updates.status.text, 'Accepted')
# Make sure it got all our label change requests.
self.assertEquals(len(updates.label), 2)
self.assertEquals(updates.label[0].text, '-label0')
self.assertEquals(updates.label[1].text, 'label1')
# Be sure it saw our CC change. We can't check the specific values (yet)
# because ccUpdate and ownerUpdate responses are mungled.
self.assertEquals(len(updates.ccUpdate), 1)
self.assert_(updates.ownerUpdate.text)
def test_get_issues(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'test_create_update_delete')
# Create an issue so we have something to look up.
created = self.create_issue()
# The fully qualified id is a url, we just want the number.
issue_id = created.id.text.split('/')[-1]
# Get the specific issue in our issues feed. You could use label,
# canned_query and others just the same.
query = gdata.projecthosting.client.Query(label='label0')
feed = self.client.get_issues(self.project_name, query=query)
# Make sure we at least find the entry we created with that label.
self.assert_(len(feed.entry) > 0)
for issue in feed.entry:
label_texts = [label.text for label in issue.label]
self.assert_('label0' in label_texts, 'Issue does not have label label0')
def test_get_comments(self):
if not conf.options.get_value('runlive') == 'true':
return
# Either load the recording or prepare to make a live request.
conf.configure_cache(self.client, 'test_create_update_delete')
# Create an issue so we have something to look up.
created = self.create_issue()
# The fully qualified id is a url, we just want the number.
issue_id = created.id.text.split('/')[-1]
# Now lets add two comments to that issue.
for i in range(2):
update_response = self.client.update_issue(
self.project_name,
issue_id,
self.owner,
comment='My comment here %s' % i)
# We have an issue that has several comments. Lets get them.
comments_feed = self.client.get_comments(self.project_name, issue_id)
# It has 2 comments.
self.assertEqual(2, len(comments_feed.entry))
class ProjectHostingDocExamplesTest(unittest.TestCase):
def setUp(self):
self.project_name = conf.options.get_value('project_name')
self.assignee = conf.options.get_value('issue_assignee')
self.owner = conf.options.get_value('username')
self.password = conf.options.get_value('password')
def test_doc_examples(self):
if not conf.options.get_value('runlive') == 'true':
return
issues_client = gdata.projecthosting.client.ProjectHostingClient()
self.authenticating_client(issues_client, self.owner, self.password)
issue = self.creating_issues(issues_client, self.project_name, self.owner)
issue_id = issue.id.text.split('/')[-1]
self.retrieving_all_issues(issues_client, self.project_name)
self.retrieving_issues_using_query_parameters(
issues_client,
self.project_name)
self.modifying_an_issue_or_creating_issue_comments(
issues_client,
self.project_name,
issue_id,
self.owner,
self.assignee)
self.retrieving_issues_comments_for_an_issue(
issues_client,
self.project_name,
issue_id)
def authenticating_client(self, client, username, password):
return client.client_login(
username,
password,
source='your-client-name',
service='code')
def creating_issues(self, client, project_name, owner):
"""Create an issue."""
return client.add_issue(
project_name,
'my title',
'my summary',
owner,
labels=['label0'])
def retrieving_all_issues(self, client, project_name):
"""Retrieve all the issues in a project."""
feed = client.get_issues(project_name)
for issue in feed.entry:
self.assert_(issue.title.text is not None)
def retrieving_issues_using_query_parameters(self, client, project_name):
"""Retrieve a set of issues in a project."""
query = gdata.projecthosting.client.Query(label='label0', max_results=1000)
feed = client.get_issues(project_name, query=query)
for issue in feed.entry:
self.assert_(issue.title.text is not None)
return feed
def retrieving_issues_comments_for_an_issue(self, client, project_name,
issue_id):
"""Retrieve all issue comments for an issue."""
comments_feed = client.get_comments(project_name, issue_id)
for comment in comments_feed.entry:
self.assert_(comment.content is not None)
return comments_feed
def modifying_an_issue_or_creating_issue_comments(self, client, project_name,
issue_id, owner, assignee):
"""Add a comment and update metadata in an issue."""
return client.update_issue(
project_name,
issue_id,
owner,
comment='My comment here.',
summary='New Summary',
status='Accepted',
owner=assignee,
labels=['-label0', 'label1'],
ccs=[owner])
def suite():
return conf.build_suite([ProjectHostingClientTest,
ProjectHostingDocExamplesTest])
if __name__ == '__main__':
unittest.TextTestRunner().run(suite())
| 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.
__author__ = 'jlapenna@google.com (Joe LaPenna)'
import unittest
from gdata import test_data
import gdata.projecthosting.data
import atom.core
import gdata.test_config as conf
ISSUE_ENTRY = """\
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:issues='http://schemas.google.com/projecthosting/issues/2009'>
<id>http://code.google.com/feeds/issues/p/PROJECT_NAME/issues/full/1</id>
<updated>2009-09-09T20:34:35.365Z</updated>
<title>This is updated issue summary</title>
<content type='html'>This is issue description</content>
<link rel='self' type='application/atom+xml'
href='http://code.google.com/feeds/issues/p/PROJECT_NAME/issues/full/3'/>
<link rel='edit' type='application/atom+xml'
href='http://code.google.com/feeds/issues/p/PROJECT_NAME/issues/full/3'/>
<author>
<name>elizabeth.bennet</name>
<uri>/u/elizabeth.bennet/</uri>
</author>
<issues:cc>
<issues:uri>/u/@UBhTQl1UARRAVga7/</issues:uri>
<issues:username>mar...@domain.com</issues:username>
</issues:cc>
<issues:cc>
<issues:uri>/u/fitzwilliam.darcy/</issues:uri>
<issues:username>fitzwilliam.darcy</issues:username>
</issues:cc>
<issues:label>Type-Enhancement</issues:label>
<issues:label>Priority-Low</issues:label>
<issues:owner>
<issues:uri>/u/charlotte.lucas/</issues:uri>
<issues:username>charlotte.lucas</issues:username>
</issues:owner>
<issues:stars>0</issues:stars>
<issues:state>open</issues:state>
<issues:status>Started</issues:status>
</entry>
"""
ISSUES_FEED = """\
<?xml version='1.0' encoding='UTF-8'?>
<feed xmlns='http://www.w3.org/2005/Atom'>
<id>http://code.google.com/feeds/issues/p/android-test2/issues/full</id>
<link href="http://code.google.com/feeds/issues/p/android-test2/issues/full"
rel="http://schemas.google.com/g/2005#feed" type="application/atom+xml" />
<link href="http://code.google.com/feeds/issues/p/android-test2/issues/full"
rel="http://schemas.google.com/g/2005#post" type="application/atom+xml" />
<link href="http://code.google.com/feeds/issues/p/android-test2/issues/full"
rel="self" type="application/atom+xml" />
<updated>2009-09-22T04:06:32.794Z</updated>
%s
</feed>
""" % ISSUE_ENTRY
COMMENT_ENTRY = """\
<?xml version='1.0' encoding='UTF-8'?>
<entry xmlns='http://www.w3.org/2005/Atom'
xmlns:issues='http://schemas.google.com/projecthosting/issues/2009'>
<content type='html'>This is comment - update issue</content>
<author>
<name>elizabeth.bennet</name>
</author>
<issues:updates>
<issues:summary>This is updated issue summary</issues:summary>
<issues:status>Started</issues:status>
<issues:ownerUpdate>charlotte.lucas</issues:ownerUpdate>
<issues:label>-Type-Defect</issues:label>
<issues:label>Type-Enhancement</issues:label>
<issues:label>-Milestone-2009</issues:label>
<issues:label>-Priority-Medium</issues:label>
<issues:label>Priority-Low</issues:label>
<issues:ccUpdate>-fitzwilliam.darcy</issues:ccUpdate>
<issues:ccUpdate>marialucas@domain.com</issues:ccUpdate>
</issues:updates>
</entry>
"""
class CommentEntryTest(unittest.TestCase):
def testParsing(self):
entry = atom.core.parse(COMMENT_ENTRY,
gdata.projecthosting.data.CommentEntry)
updates = entry.updates
self.assertEquals(updates.summary.text, 'This is updated issue summary')
self.assertEquals(updates.status.text, 'Started')
self.assertEquals(updates.ownerUpdate.text, 'charlotte.lucas')
self.assertEquals(len(updates.label), 5)
self.assertEquals(updates.label[0].text, '-Type-Defect')
self.assertEquals(updates.label[1].text, 'Type-Enhancement')
self.assertEquals(updates.label[2].text, '-Milestone-2009')
self.assertEquals(updates.label[3].text, '-Priority-Medium')
self.assertEquals(updates.label[4].text, 'Priority-Low')
self.assertEquals(len(updates.ccUpdate), 2)
self.assertEquals(updates.ccUpdate[0].text, '-fitzwilliam.darcy')
self.assertEquals(updates.ccUpdate[1].text, 'marialucas@domain.com')
class IssueEntryTest(unittest.TestCase):
def testParsing(self):
entry = atom.core.parse(ISSUE_ENTRY, gdata.projecthosting.data.IssueEntry)
self.assertEquals(entry.owner.uri.text, '/u/charlotte.lucas/')
self.assertEqual(entry.owner.username.text, 'charlotte.lucas')
self.assertEquals(len(entry.cc), 2)
cc_0 = entry.cc[0]
self.assertEquals(cc_0.uri.text, '/u/@UBhTQl1UARRAVga7/')
self.assertEquals(cc_0.username.text, 'mar...@domain.com')
cc_1 = entry.cc[1]
self.assertEquals(cc_1.uri.text, '/u/fitzwilliam.darcy/')
self.assertEquals(cc_1.username.text, 'fitzwilliam.darcy')
self.assertEquals(len(entry.label), 2)
self.assertEquals(entry.label[0].text, 'Type-Enhancement')
self.assertEquals(entry.label[1].text, 'Priority-Low')
self.assertEquals(entry.stars.text, '0')
self.assertEquals(entry.state.text, 'open')
self.assertEquals(entry.status.text, 'Started')
class DataClassSanityTest(unittest.TestCase):
def test_basic_element_structure(self):
conf.check_data_classes(self, [
gdata.projecthosting.data.Uri,
gdata.projecthosting.data.Username,
gdata.projecthosting.data.Cc,
gdata.projecthosting.data.Label,
gdata.projecthosting.data.Owner,
gdata.projecthosting.data.Stars,
gdata.projecthosting.data.State,
gdata.projecthosting.data.Status,
gdata.projecthosting.data.Summary,
gdata.projecthosting.data.Updates,
gdata.projecthosting.data.IssueEntry,
gdata.projecthosting.data.IssuesFeed,
gdata.projecthosting.data.CommentEntry,
gdata.projecthosting.data.CommentsFeed])
def suite():
return conf.build_suite([IssueEntryTest, DataClassSanityTest])
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/env python
#
# Copyright (C) 2008, 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This module is used for version 2 of the Google Data APIs.
__author__ = 'j.s@google.com (Jeff Scudder)'
import unittest
import gdata.client
import gdata.gauth
import gdata.data
import atom.mock_http_core
import StringIO
class ClientLoginTest(unittest.TestCase):
def test_token_request(self):
client = gdata.client.GDClient()
client.http_client = atom.mock_http_core.SettableHttpClient(200, 'OK',
'SID=DQAAAGgA...7Zg8CTN\n'
'LSID=DQAAAGsA...lk8BBbG\n'
'Auth=DQAAAGgA...dk3fA5N', {'Content-Type': 'text/plain'})
token = client.request_client_login_token('email', 'pw', 'cp', 'test')
self.assert_(isinstance(token, gdata.gauth.ClientLoginToken))
self.assertEqual(token.token_string, 'DQAAAGgA...dk3fA5N')
# Test a server response without a ClientLogin token.`
client.http_client.set_response(200, 'OK', 'SID=12345\nLSID=34567', {})
self.assertRaises(gdata.client.ClientLoginTokenMissing,
client.request_client_login_token, 'email', 'pw', '', '')
# Test a 302 redirect from the server on a login request.
client.http_client.set_response(302, 'ignored', '', {})
# TODO: change the exception class to one in gdata.client.
self.assertRaises(gdata.client.BadAuthenticationServiceURL,
client.request_client_login_token, 'email', 'pw', '', '')
# Test a CAPTCHA challenge from the server
client.http_client.set_response(403, 'Access Forbidden',
'Url=http://www.google.com/login/captcha\n'
'Error=CaptchaRequired\n'
'CaptchaToken=DQAAAGgA...dkI1LK9\n'
# TODO: verify this sample CAPTCHA URL matches an
# actual challenge from the server.
'CaptchaUrl=Captcha?ctoken=HiteT4bVoP6-yFkHPibe7O9EqxeiI7lUSN', {})
try:
token = client.request_client_login_token('email', 'pw', '', '')
self.fail('should raise a CaptchaChallenge on a 403 with a '
'CaptchRequired error.')
except gdata.client.CaptchaChallenge, challenge:
self.assertEquals(challenge.captcha_url,
'http://www.google.com/accounts/'
'Captcha?ctoken=HiteT4bVoP6-yFkHPibe7O9EqxeiI7lUSN')
self.assertEquals(challenge.captcha_token, 'DQAAAGgA...dkI1LK9')
# Test an unexpected response, a 404 for example.
client.http_client.set_response(404, 'ignored', '', {})
self.assertRaises(gdata.client.ClientLoginFailed,
client.request_client_login_token, 'email', 'pw', '', '')
def test_client_login(self):
client = gdata.client.GDClient()
client.http_client = atom.mock_http_core.SettableHttpClient(200, 'OK',
'SID=DQAAAGgA...7Zg8CTN\n'
'LSID=DQAAAGsA...lk8BBbG\n'
'Auth=DQAAAGgA...dk3fA5N', {'Content-Type': 'text/plain'})
client.client_login('me@example.com', 'password', 'wise', 'unit test')
self.assert_(isinstance(client.auth_token, gdata.gauth.ClientLoginToken))
self.assertEqual(client.auth_token.token_string, 'DQAAAGgA...dk3fA5N')
class AuthSubTest(unittest.TestCase):
def test_get_and_upgrade_token(self):
client = gdata.client.GDClient()
client.http_client = atom.mock_http_core.SettableHttpClient(200, 'OK',
'Token=UpgradedTokenVal\n'
'Extra data', {'Content-Type': 'text/plain'})
page_url = 'http://example.com/showcalendar.html?token=CKF50YzIHxCTKMAg'
client.auth_token = gdata.gauth.AuthSubToken.from_url(page_url)
self.assert_(isinstance(client.auth_token, gdata.gauth.AuthSubToken))
self.assertEqual(client.auth_token.token_string, 'CKF50YzIHxCTKMAg')
upgraded = client.upgrade_token()
self.assert_(isinstance(client.auth_token, gdata.gauth.AuthSubToken))
self.assertEqual(client.auth_token.token_string, 'UpgradedTokenVal')
self.assertEqual(client.auth_token, upgraded)
# Ensure passing in a token returns without modifying client's auth_token.
client.http_client.set_response(200, 'OK', 'Token=4567', {})
upgraded = client.upgrade_token(
gdata.gauth.AuthSubToken.from_url('?token=1234'))
self.assertEqual(upgraded.token_string, '4567')
self.assertEqual(client.auth_token.token_string, 'UpgradedTokenVal')
self.assertNotEqual(client.auth_token, upgraded)
# Test exception cases
client.auth_token = None
self.assertRaises(gdata.client.UnableToUpgradeToken, client.upgrade_token,
None)
self.assertRaises(gdata.client.UnableToUpgradeToken, client.upgrade_token)
def test_revoke_token(self):
client = gdata.client.GDClient()
client.http_client = atom.mock_http_core.SettableHttpClient(
200, 'OK', '', {})
page_url = 'http://example.com/showcalendar.html?token=CKF50YzIHxCTKMAg'
client.auth_token = gdata.gauth.AuthSubToken.from_url(page_url)
deleted = client.revoke_token()
self.assert_(deleted)
self.assertEqual(
client.http_client.last_request.headers['Authorization'],
'AuthSub token=CKF50YzIHxCTKMAg')
class OAuthTest(unittest.TestCase):
def test_hmac_flow(self):
client = gdata.client.GDClient()
client.http_client = atom.mock_http_core.SettableHttpClient(
200, 'OK', 'oauth_token=ab3cd9j4ks7&oauth_token_secret=ZXhhbXBsZS',
{})
request_token = client.get_oauth_token(
['http://example.com/service'], 'http://example.net/myapp',
'consumer', consumer_secret='secret')
# Check that the response was correctly parsed.
self.assertEqual(request_token.token, 'ab3cd9j4ks7')
self.assertEqual(request_token.token_secret, 'ZXhhbXBsZS')
self.assertEqual(request_token.auth_state, gdata.gauth.REQUEST_TOKEN)
# Also check the Authorization header which was sent in the request.
auth_header = client.http_client.last_request.headers['Authorization']
self.assert_('OAuth' in auth_header)
self.assert_(
'oauth_callback="http%3A%2F%2Fexample.net%2Fmyapp"' in auth_header)
self.assert_('oauth_version="1.0"' in auth_header)
self.assert_('oauth_signature_method="HMAC-SHA1"' in auth_header)
self.assert_('oauth_consumer_key="consumer"' in auth_header)
# Check generation of the authorization URL.
authorize_url = request_token.generate_authorization_url()
self.assert_(str(authorize_url).startswith(
'https://www.google.com/accounts/OAuthAuthorizeToken'))
self.assert_('oauth_token=ab3cd9j4ks7' in str(authorize_url))
# Check that the token information from the browser's URL is parsed.
redirected_url = (
'http://example.net/myapp?oauth_token=CKF5zz&oauth_verifier=Xhhbas')
gdata.gauth.authorize_request_token(request_token, redirected_url)
self.assertEqual(request_token.token, 'CKF5zz')
self.assertEqual(request_token.verifier, 'Xhhbas')
self.assertEqual(request_token.auth_state,
gdata.gauth.AUTHORIZED_REQUEST_TOKEN)
# Check that the token upgrade response was correctly parsed.
client.http_client.set_response(
200, 'OK', 'oauth_token=3cd9Fj417&oauth_token_secret=Xhrh6bXBs', {})
access_token = client.get_access_token(request_token)
self.assertEqual(request_token.token, '3cd9Fj417')
self.assertEqual(request_token.token_secret, 'Xhrh6bXBs')
self.assert_(request_token.verifier is None)
self.assertEqual(request_token.auth_state, gdata.gauth.ACCESS_TOKEN)
self.assertEqual(request_token.token, access_token.token)
self.assertEqual(request_token.token_secret, access_token.token_secret)
self.assert_(access_token.verifier is None)
self.assertEqual(request_token.auth_state, access_token.auth_state)
# Also check the Authorization header which was sent in the request.
auth_header = client.http_client.last_request.headers['Authorization']
self.assert_('OAuth' in auth_header)
self.assert_('oauth_callback="' not in auth_header)
self.assert_('oauth_version="1.0"' in auth_header)
self.assert_('oauth_verifier="Xhhbas"' in auth_header)
self.assert_('oauth_signature_method="HMAC-SHA1"' in auth_header)
self.assert_('oauth_consumer_key="consumer"' in auth_header)
class RequestTest(unittest.TestCase):
def test_simple_request(self):
client = gdata.client.GDClient()
client.http_client = atom.mock_http_core.EchoHttpClient()
response = client.request('GET', 'https://example.com/test')
self.assertEqual(response.getheader('Echo-Host'), 'example.com:None')
self.assertEqual(response.getheader('Echo-Uri'), '/test')
self.assertEqual(response.getheader('Echo-Scheme'), 'https')
self.assertEqual(response.getheader('Echo-Method'), 'GET')
http_request = atom.http_core.HttpRequest(
uri=atom.http_core.Uri(scheme='http', host='example.net', port=8080),
method='POST', headers={'X': 1})
http_request.add_body_part('test', 'text/plain')
response = client.request(http_request=http_request)
self.assertEqual(response.getheader('Echo-Host'), 'example.net:8080')
# A Uri with path set to None should default to /.
self.assertEqual(response.getheader('Echo-Uri'), '/')
self.assertEqual(response.getheader('Echo-Scheme'), 'http')
self.assertEqual(response.getheader('Echo-Method'), 'POST')
self.assertEqual(response.getheader('Content-Type'), 'text/plain')
self.assertEqual(response.getheader('X'), '1')
self.assertEqual(response.read(), 'test')
# Use the same request object from above, but overwrite the request path
# by passing in a URI.
response = client.request(uri='/new/path?p=1', http_request=http_request)
self.assertEqual(response.getheader('Echo-Host'), 'example.net:8080')
self.assertEqual(response.getheader('Echo-Uri'), '/new/path?p=1')
self.assertEqual(response.getheader('Echo-Scheme'), 'http')
self.assertEqual(response.read(), 'test')
def test_gdata_version_header(self):
client = gdata.client.GDClient()
client.http_client = atom.mock_http_core.EchoHttpClient()
response = client.request('GET', 'http://example.com')
self.assertEqual(response.getheader('GData-Version'), None)
client.api_version = '2'
response = client.request('GET', 'http://example.com')
self.assertEqual(response.getheader('GData-Version'), '2')
def test_redirects(self):
client = gdata.client.GDClient()
client.http_client = atom.mock_http_core.MockHttpClient()
# Add the redirect response for the initial request.
first_request = atom.http_core.HttpRequest('http://example.com/1',
'POST')
client.http_client.add_response(first_request, 302, None,
{'Location': 'http://example.com/1?gsessionid=12'})
second_request = atom.http_core.HttpRequest(
'http://example.com/1?gsessionid=12', 'POST')
client.http_client.AddResponse(second_request, 200, 'OK', body='Done')
response = client.Request('POST', 'http://example.com/1')
self.assertEqual(response.status, 200)
self.assertEqual(response.reason, 'OK')
self.assertEqual(response.read(), 'Done')
redirect_loop_request = atom.http_core.HttpRequest(
'http://example.com/2?gsessionid=loop', 'PUT')
client.http_client.add_response(redirect_loop_request, 302, None,
{'Location': 'http://example.com/2?gsessionid=loop'})
try:
response = client.request(method='PUT', uri='http://example.com/2?gsessionid=loop')
self.fail('Loop URL should have redirected forever.')
except gdata.client.RedirectError, err:
self.assert_(str(err).startswith('Too many redirects from server'))
def test_lowercase_location(self):
client = gdata.client.GDClient()
client.http_client = atom.mock_http_core.MockHttpClient()
# Add the redirect response for the initial request.
first_request = atom.http_core.HttpRequest('http://example.com/1',
'POST')
# In some environments, notably App Engine, the HTTP headers which come
# back from a server will be normalized to all lowercase.
client.http_client.add_response(first_request, 302, None,
{'location': 'http://example.com/1?gsessionid=12'})
second_request = atom.http_core.HttpRequest(
'http://example.com/1?gsessionid=12', 'POST')
client.http_client.AddResponse(second_request, 200, 'OK', body='Done')
response = client.Request('POST', 'http://example.com/1')
self.assertEqual(response.status, 200)
self.assertEqual(response.reason, 'OK')
self.assertEqual(response.read(), 'Done')
def test_exercise_exceptions(self):
# TODO
pass
def test_converter_vs_desired_class(self):
def bad_converter(string):
return 1
class TestClass(atom.core.XmlElement):
_qname = '{http://www.w3.org/2005/Atom}entry'
client = gdata.client.GDClient()
client.http_client = atom.mock_http_core.EchoHttpClient()
test_entry = gdata.data.GDEntry()
result = client.post(test_entry, 'http://example.com')
self.assert_(isinstance(result, gdata.data.GDEntry))
result = client.post(test_entry, 'http://example.com', converter=bad_converter)
self.assertEquals(result, 1)
result = client.post(test_entry, 'http://example.com', desired_class=TestClass)
self.assert_(isinstance(result, TestClass))
class QueryTest(unittest.TestCase):
def test_query_modifies_request(self):
request = atom.http_core.HttpRequest()
gdata.client.Query(
text_query='foo', categories=['a', 'b']).modify_request(request)
# categories param from above is named category in URL
self.assertEqual(request.uri.query, {'q': 'foo', 'category': 'a,b'})
def test_client_uses_query_modification(self):
"""If the Query is passed as an unexpected param it should apply"""
client = gdata.client.GDClient()
client.http_client = atom.mock_http_core.EchoHttpClient()
query = gdata.client.Query(max_results=7)
client.http_client = atom.mock_http_core.SettableHttpClient(
201, 'CREATED', gdata.data.GDEntry().ToString(), {})
response = client.get('https://example.com/foo', a_random_param=query)
self.assertEqual(
client.http_client.last_request.uri.query['max-results'], '7')
class VersionConversionTest(unittest.TestCase):
def test_use_default_version(self):
self.assertEquals(gdata.client.get_xml_version(None), 1)
def test_str_to_int_version(self):
self.assertEquals(gdata.client.get_xml_version('1'), 1)
self.assertEquals(gdata.client.get_xml_version('2'), 2)
self.assertEquals(gdata.client.get_xml_version('2.1.2'), 2)
self.assertEquals(gdata.client.get_xml_version('10.4'), 10)
class UpdateTest(unittest.TestCase):
"""Test Update/PUT"""
def test_update_uri_editlink(self):
"""Test that the PUT uri is grabbed from the entry's edit link"""
client = gdata.client.GDClient()
client.http_client = atom.mock_http_core.SettableHttpClient(
200, 'OK', gdata.data.GDEntry().ToString(), {})
entry = gdata.data.GDEntry()
entry.link.append(atom.data.Link(rel='edit', href='https://example.com/edit'))
response = client.update(entry)
request = client.http_client.last_request
self.assertEqual(str(client.http_client.last_request.uri),
'https://example.com/edit')
def test_update_uri(self):
"""Test that when passed, a uri overrides the entry's edit link"""
client = gdata.client.GDClient()
client.http_client = atom.mock_http_core.SettableHttpClient(
200, 'OK', gdata.data.GDEntry().ToString(), {})
entry = gdata.data.GDEntry()
entry.link.append(atom.data.Link(rel='edit', href='https://example.com/edit'))
response = client.update(entry, uri='https://example.com/test')
self.assertEqual(str(client.http_client.last_request.uri),
'https://example.com/test')
def suite():
return unittest.TestSuite((unittest.makeSuite(ClientLoginTest, 'test'),
unittest.makeSuite(AuthSubTest, 'test'),
unittest.makeSuite(OAuthTest, 'test'),
unittest.makeSuite(RequestTest, 'test'),
unittest.makeSuite(VersionConversionTest, 'test'),
unittest.makeSuite(QueryTest, 'test'),
unittest.makeSuite(UpdateTest, 'test')))
if __name__ == '__main__':
unittest.main()
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'api.jhartmann@gmail.com (Jochen Hartmann)'
import unittest
from gdata import test_data
import gdata.youtube
import gdata.youtube.service
import atom
YOUTUBE_TEMPLATE = '{http://gdata.youtube.com/schemas/2007}%s'
YT_FORMAT = YOUTUBE_TEMPLATE % ('format')
class VideoEntryTest(unittest.TestCase):
def setUp(self):
self.video_feed = gdata.youtube.YouTubeVideoFeedFromString(
test_data.YOUTUBE_VIDEO_FEED)
def testCorrectXmlParsing(self):
self.assertEquals(self.video_feed.id.text,
'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated')
self.assertEquals(len(self.video_feed.entry), 2)
for entry in self.video_feed.entry:
if (entry.id.text ==
'http://gdata.youtube.com/feeds/api/videos/C71ypXYGho8'):
self.assertEquals(entry.published.text, '2008-03-20T10:17:27.000-07:00')
self.assertEquals(entry.updated.text, '2008-05-14T04:26:37.000-07:00')
self.assertEquals(entry.category[0].scheme,
'http://gdata.youtube.com/schemas/2007/keywords.cat')
self.assertEquals(entry.category[0].term, 'karyn')
self.assertEquals(entry.category[1].scheme,
'http://gdata.youtube.com/schemas/2007/keywords.cat')
self.assertEquals(entry.category[1].term, 'garcia')
self.assertEquals(entry.category[2].scheme,
'http://gdata.youtube.com/schemas/2007/keywords.cat')
self.assertEquals(entry.category[2].term, 'me')
self.assertEquals(entry.category[3].scheme,
'http://schemas.google.com/g/2005#kind')
self.assertEquals(entry.category[3].term,
'http://gdata.youtube.com/schemas/2007#video')
self.assertEquals(entry.title.text,
'Me odeio por te amar - KARYN GARCIA')
self.assertEquals(entry.content.text, 'http://www.karyngarcia.com.br')
self.assertEquals(entry.link[0].rel, 'alternate')
self.assertEquals(entry.link[0].href,
'http://www.youtube.com/watch?v=C71ypXYGho8')
self.assertEquals(entry.link[1].rel,
'http://gdata.youtube.com/schemas/2007#video.related')
self.assertEquals(entry.link[1].href,
'http://gdata.youtube.com/feeds/api/videos/C71ypXYGho8/related')
self.assertEquals(entry.link[2].rel, 'self')
self.assertEquals(entry.link[2].href,
('http://gdata.youtube.com/feeds/api/standardfeeds'
'/top_rated/C71ypXYGho8'))
self.assertEquals(entry.author[0].name.text, 'TvKarynGarcia')
self.assertEquals(entry.author[0].uri.text,
'http://gdata.youtube.com/feeds/api/users/tvkaryngarcia')
self.assertEquals(entry.media.title.text,
'Me odeio por te amar - KARYN GARCIA')
self.assertEquals(entry.media.description.text,
'http://www.karyngarcia.com.br')
self.assertEquals(entry.media.keywords.text,
'amar, boyfriend, garcia, karyn, me, odeio, por, te')
self.assertEquals(entry.media.duration.seconds, '203')
self.assertEquals(entry.media.category[0].label, 'Music')
self.assertEquals(entry.media.category[0].scheme,
'http://gdata.youtube.com/schemas/2007/categories.cat')
self.assertEquals(entry.media.category[0].text, 'Music')
self.assertEquals(entry.media.category[1].label, 'test111')
self.assertEquals(entry.media.category[1].scheme,
'http://gdata.youtube.com/schemas/2007/developertags.cat')
self.assertEquals(entry.media.category[1].text, 'test111')
self.assertEquals(entry.media.category[2].label, 'test222')
self.assertEquals(entry.media.category[2].scheme,
'http://gdata.youtube.com/schemas/2007/developertags.cat')
self.assertEquals(entry.media.category[2].text, 'test222')
self.assertEquals(entry.media.content[0].url,
'http://www.youtube.com/v/C71ypXYGho8')
self.assertEquals(entry.media.content[0].type,
'application/x-shockwave-flash')
self.assertEquals(entry.media.content[0].medium, 'video')
self.assertEquals(
entry.media.content[0].extension_attributes['isDefault'], 'true')
self.assertEquals(
entry.media.content[0].extension_attributes['expression'], 'full')
self.assertEquals(
entry.media.content[0].extension_attributes['duration'], '203')
self.assertEquals(
entry.media.content[0].extension_attributes[YT_FORMAT], '5')
self.assertEquals(entry.media.content[1].url,
('rtsp://rtsp2.youtube.com/ChoLENy73wIaEQmPhgZ2pXK9CxMYDSANFEgGDA'
'==/0/0/0/video.3gp'))
self.assertEquals(entry.media.content[1].type, 'video/3gpp')
self.assertEquals(entry.media.content[1].medium, 'video')
self.assertEquals(
entry.media.content[1].extension_attributes['expression'], 'full')
self.assertEquals(
entry.media.content[1].extension_attributes['duration'], '203')
self.assertEquals(
entry.media.content[1].extension_attributes[YT_FORMAT], '1')
self.assertEquals(entry.media.content[2].url,
('rtsp://rtsp2.youtube.com/ChoLENy73wIaEQmPhgZ2pXK9CxMYESARFEgGDA=='
'/0/0/0/video.3gp'))
self.assertEquals(entry.media.content[2].type, 'video/3gpp')
self.assertEquals(entry.media.content[2].medium, 'video')
self.assertEquals(
entry.media.content[2].extension_attributes['expression'], 'full')
self.assertEquals(
entry.media.content[2].extension_attributes['duration'], '203')
self.assertEquals(
entry.media.content[2].extension_attributes[YT_FORMAT], '6')
self.assertEquals(entry.media.player.url,
'http://www.youtube.com/watch?v=C71ypXYGho8')
self.assertEquals(entry.media.thumbnail[0].url,
'http://img.youtube.com/vi/C71ypXYGho8/2.jpg')
self.assertEquals(entry.media.thumbnail[0].height, '97')
self.assertEquals(entry.media.thumbnail[0].width, '130')
self.assertEquals(entry.media.thumbnail[0].extension_attributes['time'],
'00:01:41.500')
self.assertEquals(entry.media.thumbnail[1].url,
'http://img.youtube.com/vi/C71ypXYGho8/1.jpg')
self.assertEquals(entry.media.thumbnail[1].height, '97')
self.assertEquals(entry.media.thumbnail[1].width, '130')
self.assertEquals(entry.media.thumbnail[1].extension_attributes['time'],
'00:00:50.750')
self.assertEquals(entry.media.thumbnail[2].url,
'http://img.youtube.com/vi/C71ypXYGho8/3.jpg')
self.assertEquals(entry.media.thumbnail[2].height, '97')
self.assertEquals(entry.media.thumbnail[2].width, '130')
self.assertEquals(entry.media.thumbnail[2].extension_attributes['time'],
'00:02:32.250')
self.assertEquals(entry.media.thumbnail[3].url,
'http://img.youtube.com/vi/C71ypXYGho8/0.jpg')
self.assertEquals(entry.media.thumbnail[3].height, '240')
self.assertEquals(entry.media.thumbnail[3].width, '320')
self.assertEquals(entry.media.thumbnail[3].extension_attributes['time'],
'00:01:41.500')
self.assertEquals(entry.statistics.view_count, '138864')
self.assertEquals(entry.statistics.favorite_count, '2474')
self.assertEquals(entry.rating.min, '1')
self.assertEquals(entry.rating.max, '5')
self.assertEquals(entry.rating.num_raters, '4626')
self.assertEquals(entry.rating.average, '4.95')
self.assertEquals(entry.comments.feed_link[0].href,
('http://gdata.youtube.com/feeds/api/videos/'
'C71ypXYGho8/comments'))
self.assertEquals(entry.comments.feed_link[0].count_hint, '27')
self.assertEquals(entry.GetSwfUrl(),
'http://www.youtube.com/v/C71ypXYGho8')
self.assertEquals(entry.GetYouTubeCategoryAsString(), 'Music')
class VideoEntryPrivateTest(unittest.TestCase):
def setUp(self):
self.entry = gdata.youtube.YouTubeVideoEntryFromString(
test_data.YOUTUBE_ENTRY_PRIVATE)
def testCorrectXmlParsing(self):
self.assert_(isinstance(self.entry,
gdata.youtube.YouTubeVideoEntry))
self.assert_(self.entry.media.private)
class VideoFeedTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.youtube.YouTubeVideoFeedFromString(
test_data.YOUTUBE_VIDEO_FEED)
def testCorrectXmlParsing(self):
self.assertEquals(self.feed.id.text,
'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated')
self.assertEquals(self.feed.generator.text, 'YouTube data API')
self.assertEquals(self.feed.generator.uri, 'http://gdata.youtube.com/')
self.assertEquals(len(self.feed.author), 1)
self.assertEquals(self.feed.author[0].name.text, 'YouTube')
self.assertEquals(len(self.feed.category), 1)
self.assertEquals(self.feed.category[0].scheme,
'http://schemas.google.com/g/2005#kind')
self.assertEquals(self.feed.category[0].term,
'http://gdata.youtube.com/schemas/2007#video')
self.assertEquals(self.feed.items_per_page.text, '25')
self.assertEquals(len(self.feed.link), 4)
self.assertEquals(self.feed.link[0].href,
'http://www.youtube.com/browse?s=tr')
self.assertEquals(self.feed.link[0].rel, 'alternate')
self.assertEquals(self.feed.link[1].href,
'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated')
self.assertEquals(self.feed.link[1].rel,
'http://schemas.google.com/g/2005#feed')
self.assertEquals(self.feed.link[2].href,
('http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?'
'start-index=1&max-results=25'))
self.assertEquals(self.feed.link[2].rel, 'self')
self.assertEquals(self.feed.link[3].href,
('http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?'
'start-index=26&max-results=25'))
self.assertEquals(self.feed.link[3].rel, 'next')
self.assertEquals(self.feed.start_index.text, '1')
self.assertEquals(self.feed.title.text, 'Top Rated')
self.assertEquals(self.feed.total_results.text, '100')
self.assertEquals(self.feed.updated.text, '2008-05-14T02:24:07.000-07:00')
self.assertEquals(len(self.feed.entry), 2)
class YouTubePlaylistFeedTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.youtube.YouTubePlaylistFeedFromString(
test_data.YOUTUBE_PLAYLIST_FEED)
def testCorrectXmlParsing(self):
self.assertEquals(len(self.feed.entry), 1)
self.assertEquals(
self.feed.category[0].scheme, 'http://schemas.google.com/g/2005#kind')
self.assertEquals(self.feed.category[0].term,
'http://gdata.youtube.com/schemas/2007#playlistLink')
class YouTubePlaylistEntryTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.youtube.YouTubePlaylistFeedFromString(
test_data.YOUTUBE_PLAYLIST_FEED)
def testCorrectXmlParsing(self):
for entry in self.feed.entry:
self.assertEquals(entry.category[0].scheme,
'http://schemas.google.com/g/2005#kind')
self.assertEquals(entry.category[0].term,
'http://gdata.youtube.com/schemas/2007#playlistLink')
self.assertEquals(entry.description.text,
'My new playlist Description')
self.assertEquals(entry.feed_link[0].href,
'http://gdata.youtube.com/feeds/playlists/8BCDD04DE8F771B2')
self.assertEquals(entry.feed_link[0].rel,
'http://gdata.youtube.com/schemas/2007#playlist')
class YouTubePlaylistVideoFeedTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.youtube.YouTubePlaylistVideoFeedFromString(
test_data.YOUTUBE_PLAYLIST_VIDEO_FEED)
def testCorrectXmlParsing(self):
self.assertEquals(len(self.feed.entry), 1)
self.assertEquals(self.feed.category[0].scheme,
'http://schemas.google.com/g/2005#kind')
self.assertEquals(self.feed.category[0].term,
'http://gdata.youtube.com/schemas/2007#playlist')
self.assertEquals(self.feed.category[1].scheme,
'http://gdata.youtube.com/schemas/2007/tags.cat')
self.assertEquals(self.feed.category[1].term, 'videos')
self.assertEquals(self.feed.category[2].scheme,
'http://gdata.youtube.com/schemas/2007/tags.cat')
self.assertEquals(self.feed.category[2].term, 'python')
class YouTubePlaylistVideoEntryTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.youtube.YouTubePlaylistVideoFeedFromString(
test_data.YOUTUBE_PLAYLIST_VIDEO_FEED)
def testCorrectXmlParsing(self):
self.assertEquals(len(self.feed.entry), 1)
for entry in self.feed.entry:
self.assertEquals(entry.position.text, '1')
class YouTubeVideoCommentFeedTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.youtube.YouTubeVideoCommentFeedFromString(
test_data.YOUTUBE_COMMENT_FEED)
def testCorrectXmlParsing(self):
self.assertEquals(len(self.feed.category), 1)
self.assertEquals(self.feed.category[0].scheme,
'http://schemas.google.com/g/2005#kind')
self.assertEquals(self.feed.category[0].term,
'http://gdata.youtube.com/schemas/2007#comment')
self.assertEquals(len(self.feed.link), 4)
self.assertEquals(self.feed.link[0].rel, 'related')
self.assertEquals(self.feed.link[0].href,
'http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU')
self.assertEquals(self.feed.link[1].rel, 'alternate')
self.assertEquals(self.feed.link[1].href,
'http://www.youtube.com/watch?v=2Idhz9ef5oU')
self.assertEquals(self.feed.link[2].rel,
'http://schemas.google.com/g/2005#feed')
self.assertEquals(self.feed.link[2].href,
'http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments')
self.assertEquals(self.feed.link[3].rel, 'self')
self.assertEquals(self.feed.link[3].href,
('http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU/comments?'
'start-index=1&max-results=25'))
self.assertEquals(len(self.feed.entry), 3)
class YouTubeVideoCommentEntryTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.youtube.YouTubeVideoCommentFeedFromString(
test_data.YOUTUBE_COMMENT_FEED)
def testCorrectXmlParsing(self):
self.assertEquals(len(self.feed.entry), 3)
self.assert_(isinstance(self.feed.entry[0],
gdata.youtube.YouTubeVideoCommentEntry))
for entry in self.feed.entry:
if (entry.id.text ==
('http://gdata.youtube.com/feeds/videos/'
'2Idhz9ef5oU/comments/91F809A3DE2EB81B')):
self.assertEquals(entry.category[0].scheme,
'http://schemas.google.com/g/2005#kind')
self.assertEquals(entry.category[0].term,
'http://gdata.youtube.com/schemas/2007#comment')
self.assertEquals(entry.link[0].href,
'http://gdata.youtube.com/feeds/videos/2Idhz9ef5oU')
self.assertEquals(entry.link[0].rel, 'related')
self.assertEquals(entry.content.text, 'test66')
class YouTubeVideoSubscriptionFeedTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.youtube.YouTubeSubscriptionFeedFromString(
test_data.YOUTUBE_SUBSCRIPTION_FEED)
def testCorrectXmlParsing(self):
self.assertEquals(len(self.feed.category), 1)
self.assertEquals(self.feed.category[0].scheme,
'http://schemas.google.com/g/2005#kind')
self.assertEquals(self.feed.category[0].term,
'http://gdata.youtube.com/schemas/2007#subscription')
self.assertEquals(len(self.feed.link), 4)
self.assertEquals(self.feed.link[0].rel, 'related')
self.assertEquals(self.feed.link[0].href,
'http://gdata.youtube.com/feeds/users/andyland74')
self.assertEquals(self.feed.link[1].rel, 'alternate')
self.assertEquals(self.feed.link[1].href,
'http://www.youtube.com/profile_subscriptions?user=andyland74')
self.assertEquals(self.feed.link[2].rel,
'http://schemas.google.com/g/2005#feed')
self.assertEquals(self.feed.link[2].href,
'http://gdata.youtube.com/feeds/users/andyland74/subscriptions')
self.assertEquals(self.feed.link[3].rel, 'self')
self.assertEquals(self.feed.link[3].href,
('http://gdata.youtube.com/feeds/users/andyland74/subscriptions?'
'start-index=1&max-results=25'))
self.assertEquals(len(self.feed.entry), 1)
class YouTubeVideoSubscriptionEntryTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.youtube.YouTubeSubscriptionFeedFromString(
test_data.YOUTUBE_SUBSCRIPTION_FEED)
def testCorrectXmlParsing(self):
for entry in self.feed.entry:
self.assertEquals(len(entry.category), 2)
self.assertEquals(entry.category[0].scheme,
'http://gdata.youtube.com/schemas/2007/subscriptiontypes.cat')
self.assertEquals(entry.category[0].term, 'channel')
self.assertEquals(entry.category[1].scheme,
'http://schemas.google.com/g/2005#kind')
self.assertEquals(entry.category[1].term,
'http://gdata.youtube.com/schemas/2007#subscription')
self.assertEquals(len(entry.link), 3)
self.assertEquals(entry.link[0].href,
'http://gdata.youtube.com/feeds/users/andyland74')
self.assertEquals(entry.link[0].rel, 'related')
self.assertEquals(entry.link[1].href,
'http://www.youtube.com/profile_videos?user=NBC')
self.assertEquals(entry.link[1].rel, 'alternate')
self.assertEquals(entry.link[2].href,
('http://gdata.youtube.com/feeds/users/andyland74/subscriptions/'
'd411759045e2ad8c'))
self.assertEquals(entry.link[2].rel, 'self')
self.assertEquals(len(entry.feed_link), 1)
self.assertEquals(entry.feed_link[0].href,
'http://gdata.youtube.com/feeds/api/users/nbc/uploads')
self.assertEquals(entry.feed_link[0].rel,
'http://gdata.youtube.com/schemas/2007#user.uploads')
self.assertEquals(entry.username.text, 'NBC')
class YouTubeVideoResponseFeedTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.youtube.YouTubeVideoFeedFromString(
test_data.YOUTUBE_VIDEO_RESPONSE_FEED)
def testCorrectXmlParsing(self):
self.assertEquals(len(self.feed.category), 1)
self.assertEquals(self.feed.category[0].scheme,
'http://schemas.google.com/g/2005#kind')
self.assertEquals(self.feed.category[0].term,
'http://gdata.youtube.com/schemas/2007#video')
self.assertEquals(len(self.feed.link), 4)
self.assertEquals(self.feed.link[0].href,
'http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY')
self.assertEquals(self.feed.link[0].rel, 'related')
self.assertEquals(self.feed.link[1].href,
'http://www.youtube.com/video_response_view_all?v=2c3q9K4cHzY')
self.assertEquals(self.feed.link[1].rel, 'alternate')
self.assertEquals(self.feed.link[2].href,
'http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses')
self.assertEquals(self.feed.link[2].rel,
'http://schemas.google.com/g/2005#feed')
self.assertEquals(self.feed.link[3].href,
('http://gdata.youtube.com/feeds/videos/2c3q9K4cHzY/responses?'
'start-index=1&max-results=25'))
self.assertEquals(self.feed.link[3].rel, 'self')
self.assertEquals(len(self.feed.entry), 1)
class YouTubeVideoResponseEntryTest(unittest.TestCase):
def setUp(self):
self.feed = gdata.youtube.YouTubeVideoFeedFromString(
test_data.YOUTUBE_VIDEO_RESPONSE_FEED)
def testCorrectXmlParsing(self):
for entry in self.feed.entry:
self.assert_(isinstance(entry, gdata.youtube.YouTubeVideoEntry))
class YouTubeContactFeed(unittest.TestCase):
def setUp(self):
self.feed = gdata.youtube.YouTubeContactFeedFromString(
test_data.YOUTUBE_CONTACTS_FEED)
def testCorrectXmlParsing(self):
self.assertEquals(len(self.feed.entry), 2)
self.assertEquals(self.feed.category[0].scheme,
'http://schemas.google.com/g/2005#kind')
self.assertEquals(self.feed.category[0].term,
'http://gdata.youtube.com/schemas/2007#friend')
class YouTubeContactEntry(unittest.TestCase):
def setUp(self):
self.feed= gdata.youtube.YouTubeContactFeedFromString(
test_data.YOUTUBE_CONTACTS_FEED)
def testCorrectXmlParsing(self):
for entry in self.feed.entry:
if (entry.id.text == ('http://gdata.youtube.com/feeds/users/'
'apitestjhartmann/contacts/testjfisher')):
self.assertEquals(entry.username.text, 'testjfisher')
self.assertEquals(entry.status.text, 'pending')
class YouTubeUserEntry(unittest.TestCase):
def setUp(self):
self.feed = gdata.youtube.YouTubeUserEntryFromString(
test_data.YOUTUBE_PROFILE)
def testCorrectXmlParsing(self):
self.assertEquals(self.feed.author[0].name.text, 'andyland74')
self.assertEquals(self.feed.books.text, 'Catch-22')
self.assertEquals(self.feed.category[0].scheme,
'http://gdata.youtube.com/schemas/2007/channeltypes.cat')
self.assertEquals(self.feed.category[0].term, 'Standard')
self.assertEquals(self.feed.category[1].scheme,
'http://schemas.google.com/g/2005#kind')
self.assertEquals(self.feed.category[1].term,
'http://gdata.youtube.com/schemas/2007#userProfile')
self.assertEquals(self.feed.company.text, 'Google')
self.assertEquals(self.feed.gender.text, 'm')
self.assertEquals(self.feed.hobbies.text, 'Testing YouTube APIs')
self.assertEquals(self.feed.hometown.text, 'Somewhere')
self.assertEquals(len(self.feed.feed_link), 6)
self.assertEquals(self.feed.feed_link[0].count_hint, '4')
self.assertEquals(self.feed.feed_link[0].href,
'http://gdata.youtube.com/feeds/users/andyland74/favorites')
self.assertEquals(self.feed.feed_link[0].rel,
'http://gdata.youtube.com/schemas/2007#user.favorites')
self.assertEquals(self.feed.feed_link[1].count_hint, '1')
self.assertEquals(self.feed.feed_link[1].href,
'http://gdata.youtube.com/feeds/users/andyland74/contacts')
self.assertEquals(self.feed.feed_link[1].rel,
'http://gdata.youtube.com/schemas/2007#user.contacts')
self.assertEquals(self.feed.feed_link[2].count_hint, '0')
self.assertEquals(self.feed.feed_link[2].href,
'http://gdata.youtube.com/feeds/users/andyland74/inbox')
self.assertEquals(self.feed.feed_link[2].rel,
'http://gdata.youtube.com/schemas/2007#user.inbox')
self.assertEquals(self.feed.feed_link[3].count_hint, None)
self.assertEquals(self.feed.feed_link[3].href,
'http://gdata.youtube.com/feeds/users/andyland74/playlists')
self.assertEquals(self.feed.feed_link[3].rel,
'http://gdata.youtube.com/schemas/2007#user.playlists')
self.assertEquals(self.feed.feed_link[4].count_hint, '4')
self.assertEquals(self.feed.feed_link[4].href,
'http://gdata.youtube.com/feeds/users/andyland74/subscriptions')
self.assertEquals(self.feed.feed_link[4].rel,
'http://gdata.youtube.com/schemas/2007#user.subscriptions')
self.assertEquals(self.feed.feed_link[5].count_hint, '1')
self.assertEquals(self.feed.feed_link[5].href,
'http://gdata.youtube.com/feeds/users/andyland74/uploads')
self.assertEquals(self.feed.feed_link[5].rel,
'http://gdata.youtube.com/schemas/2007#user.uploads')
self.assertEquals(self.feed.first_name.text, 'andy')
self.assertEquals(self.feed.last_name.text, 'example')
self.assertEquals(self.feed.link[0].href,
'http://www.youtube.com/profile?user=andyland74')
self.assertEquals(self.feed.link[0].rel, 'alternate')
self.assertEquals(self.feed.link[1].href,
'http://gdata.youtube.com/feeds/users/andyland74')
self.assertEquals(self.feed.link[1].rel, 'self')
self.assertEquals(self.feed.location.text, 'US')
self.assertEquals(self.feed.movies.text, 'Aqua Teen Hungerforce')
self.assertEquals(self.feed.music.text, 'Elliott Smith')
self.assertEquals(self.feed.occupation.text, 'Technical Writer')
self.assertEquals(self.feed.published.text, '2006-10-16T00:09:45.000-07:00')
self.assertEquals(self.feed.school.text, 'University of North Carolina')
self.assertEquals(self.feed.statistics.last_web_access,
'2008-02-25T16:03:38.000-08:00')
self.assertEquals(self.feed.statistics.subscriber_count, '1')
self.assertEquals(self.feed.statistics.video_watch_count, '21')
self.assertEquals(self.feed.statistics.view_count, '9')
self.assertEquals(self.feed.thumbnail.url,
'http://i.ytimg.com/vi/YFbSxcdOL-w/default.jpg')
self.assertEquals(self.feed.title.text, 'andyland74 Channel')
self.assertEquals(self.feed.updated.text, '2008-02-26T11:48:21.000-08:00')
self.assertEquals(self.feed.username.text, 'andyland74')
if __name__ == '__main__':
unittest.main()
| 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.
__author__ = 'j.s@google.com (Jeff Scudder)'
import unittest
# Tests for v2 features.
import atom_tests.core_test
import atom_tests.data_test
import atom_tests.http_core_test
import atom_tests.auth_test
import atom_tests.mock_http_core_test
import atom_tests.client_test
import gdata_tests.client_test
import gdata_tests.core_test
import gdata_tests.data_test
import gdata_tests.data_smoke_test
import gdata_tests.client_smoke_test
import gdata_tests.live_client_test
import gdata_tests.gauth_test
import gdata_tests.blogger.data_test
import gdata_tests.blogger.live_client_test
import gdata_tests.spreadsheets.data_test
import gdata_tests.spreadsheets.live_client_test
import gdata_tests.projecthosting.data_test
import gdata_tests.projecthosting.live_client_test
import gdata_tests.sites.data_test
import gdata_tests.sites.live_client_test
import gdata_tests.analytics.data_test
import gdata_tests.analytics.live_client_test
import gdata_tests.contacts.live_client_test
import gdata_tests.contacts.profiles.live_client_test
import gdata_tests.calendar_resource.live_client_test
import gdata_tests.calendar_resource.data_test
import gdata_tests.apps.emailsettings.data_test
import gdata_tests.apps.emailsettings.live_client_test
import gdata_tests.apps.multidomain.data_test
import gdata_tests.apps.multidomain.live_client_test
import gdata_tests.youtube.live_client_test
def suite():
return unittest.TestSuite((
gdata_tests.contacts.profiles.live_client_test.suite(),
atom_tests.core_test.suite(),
atom_tests.data_test.suite(),
atom_tests.http_core_test.suite(),
atom_tests.auth_test.suite(),
atom_tests.mock_http_core_test.suite(),
atom_tests.client_test.suite(),
gdata_tests.client_test.suite(),
gdata_tests.core_test.suite(),
gdata_tests.data_test.suite(),
gdata_tests.data_smoke_test.suite(),
gdata_tests.client_smoke_test.suite(),
gdata_tests.live_client_test.suite(),
gdata_tests.gauth_test.suite(),
gdata_tests.blogger.data_test.suite(),
gdata_tests.blogger.live_client_test.suite(),
gdata_tests.spreadsheets.data_test.suite(),
gdata_tests.spreadsheets.live_client_test.suite(),
gdata_tests.projecthosting.data_test.suite(),
gdata_tests.projecthosting.live_client_test.suite(),
gdata_tests.sites.data_test.suite(),
gdata_tests.sites.live_client_test.suite(),
gdata_tests.analytics.data_test.suite(),
gdata_tests.analytics.live_client_test.suite(),
gdata_tests.contacts.live_client_test.suite(),
gdata_tests.calendar_resource.live_client_test.suite(),
gdata_tests.calendar_resource.data_test.suite(),
gdata_tests.apps.emailsettings.live_client_test.suite(),
gdata_tests.apps.emailsettings.data_test.suite(),
gdata_tests.apps.multidomain.live_client_test.suite(),
gdata_tests.apps.multidomain.data_test.suite(),
gdata_tests.youtube.live_client_test.suite(),
))
if __name__ == '__main__':
unittest.TextTestRunner().run(suite())
| 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.
__author__ = 'j.s@google.com (Jeff Scudder)'
import unittest
import all_tests
import gdata.test_config as conf
conf.options.set_value('runlive', 'true')
conf.options.set_value('savecache', 'true')
conf.options.set_value('clearcache', 'false')
def suite():
return unittest.TestSuite((atom_tests.core_test.suite(),))
if __name__ == '__main__':
unittest.TextTestRunner().run(all_tests.suite())
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'api.jscudder@gmail.com (Jeff Scudder)'
import unittest
class ModuleTestRunner(object):
def __init__(self, module_list=None, module_settings=None):
"""Constructor for a runner to run tests in the modules listed.
Args:
module_list: list (optional) The modules whose test cases will be run.
module_settings: dict (optional) A dictionary of module level varables
which should be set in the modules if they are present. An
example is the username and password which is a module variable
in most service_test modules.
"""
self.modules = module_list or []
self.settings = module_settings or {}
def RunAllTests(self):
"""Executes all tests in this objects modules list.
It also sets any module variables which match the settings keys to the
corresponding values in the settings member.
"""
runner = unittest.TextTestRunner()
for module in self.modules:
# Set any module variables according to the contents in the settings
for setting, value in self.settings.iteritems():
try:
setattr(module, setting, value)
except AttributeError:
# This module did not have a variable for the current setting, so
# we skip it and try the next setting.
pass
# We have set all of the applicable settings for the module, now
# run the tests.
print '\nRunning all tests in module', module.__name__
runner.run(unittest.defaultTestLoader.loadTestsFromModule(module))
| 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.
__author__ = 'j.s@google.com (Jeff Scudder)'
import unittest
import all_tests
from gdata.test_config import settings
settings.RUN_LIVE_TESTS = True
settings.CACHE_RESPONSES = True
settings.CLEAR_CACHE = True
def suite():
return unittest.TestSuite((atom_tests.core_test.suite(),))
if __name__ == '__main__':
unittest.TextTestRunner().run(all_tests.suite())
| Python |
#!/usr/bin/python
import sys
import unittest
import module_test_runner
import getopt
import getpass
# Modules whose tests we will run.
import gdata_test
import atom_test
import atom_tests.http_interface_test
import atom_tests.mock_http_test
import atom_tests.token_store_test
import atom_tests.url_test
import atom_tests.core_test
import gdata_tests.apps.emailsettings.data_test
import gdata_tests.apps.multidomain.data_test
import gdata_tests.apps_test
import gdata_tests.auth_test
import gdata_tests.books_test
import gdata_tests.blogger_test
import gdata_tests.calendar_test
import gdata_tests.calendar_resource.data_test
import gdata_tests.client_test
import gdata_tests.codesearch_test
import gdata_tests.contacts_test
import gdata_tests.docs_test
import gdata_tests.health_test
import gdata_tests.photos_test
import gdata_tests.spreadsheet_test
import gdata_tests.youtube_test
import gdata_tests.webmastertools_test
import gdata_tests.oauth.data_test
def RunAllTests():
test_runner = module_test_runner.ModuleTestRunner()
test_runner.modules = [gdata_test, atom_test, atom_tests.url_test,
atom_tests.http_interface_test,
atom_tests.mock_http_test,
atom_tests.core_test,
atom_tests.token_store_test,
gdata_tests.client_test,
gdata_tests.apps_test,
gdata_tests.apps.emailsettings.data_test,
gdata_tests.apps.multidomain.data_test,
gdata_tests.auth_test,
gdata_tests.books_test,
gdata_tests.calendar_test, gdata_tests.docs_test,
gdata_tests.health_test, gdata_tests.spreadsheet_test,
gdata_tests.photos_test, gdata_tests.codesearch_test,
gdata_tests.contacts_test,
gdata_tests.youtube_test, gdata_tests.blogger_test,
gdata_tests.webmastertools_test,
gdata_tests.calendar_resource.data_test,
gdata_tests.oauth.data_test]
test_runner.RunAllTests()
if __name__ == '__main__':
RunAllTests()
| Python |
#!/usr/bin/env python
#
# Perforce Defect Tracking Integration Project
# <http://www.ravenbrook.com/project/p4dti/>
#
# COVERAGE.PY -- COVERAGE TESTING
#
# Gareth Rees, Ravenbrook Limited, 2001-12-04
#
#
# 1. INTRODUCTION
#
# This module provides coverage testing for Python code.
#
# The intended readership is all Python developers.
#
# This document is not confidential.
#
# See [GDR 2001-12-04a] for the command-line interface, programmatic
# interface and limitations. See [GDR 2001-12-04b] for requirements and
# design.
"""Usage:
coverage.py -x MODULE.py [ARG1 ARG2 ...]
Execute module, passing the given command-line arguments, collecting
coverage data.
coverage.py -e
Erase collected coverage data.
coverage.py -r [-m] FILE1 FILE2 ...
Report on the statement coverage for the given files. With the -m
option, show line numbers of the statements that weren't executed.
coverage.py -a [-d dir] FILE1 FILE2 ...
Make annotated copies of the given files, marking statements that
are executed with > and statements that are missed with !. With
the -d option, make the copies in that directory. Without the -d
option, make each copy in the same directory as the original.
Coverage data is saved in the file .coverage by default. Set the
COVERAGE_FILE environment variable to save it somewhere else."""
import os
import re
import string
import sys
import types
# 2. IMPLEMENTATION
#
# This uses the "singleton" pattern.
#
# The word "morf" means a module object (from which the source file can
# be deduced by suitable manipulation of the __file__ attribute) or a
# filename.
#
# When we generate a coverage report we have to canonicalize every
# filename in the coverage dictionary just in case it refers to the
# module we are reporting on. It seems a shame to throw away this
# information so the data in the coverage dictionary is transferred to
# the 'cexecuted' dictionary under the canonical filenames.
#
# The coverage dictionary is called "c" and the trace function "t". The
# reason for these short names is that Python looks up variables by name
# at runtime and so execution time depends on the length of variables!
# In the bottleneck of this application it's appropriate to abbreviate
# names to increase speed.
# A dictionary with an entry for (Python source file name, line number
# in that file) if that line has been executed.
c = {}
# t(f, x, y). This method is passed to sys.settrace as a trace
# function. See [van Rossum 2001-07-20b, 9.2] for an explanation of
# sys.settrace and the arguments and return value of the trace function.
# See [van Rossum 2001-07-20a, 3.2] for a description of frame and code
# objects.
def t(f, x, y):
c[(f.f_code.co_filename, f.f_lineno)] = 1
return t
the_coverage = None
class coverage:
error = "coverage error"
# Name of the cache file (unless environment variable is set).
cache_default = ".coverage"
# Environment variable naming the cache file.
cache_env = "COVERAGE_FILE"
# A map from canonical Python source file name to a dictionary in
# which there's an entry for each line number that has been
# executed.
cexecuted = {}
# Cache of results of calling the analysis() method, so that you can
# specify both -r and -a without doing double work.
analysis_cache = {}
# Cache of results of calling the canonical_filename() method, to
# avoid duplicating work.
canonical_filename_cache = {}
def __init__(self):
global the_coverage
if the_coverage:
raise self.error, "Only one coverage object allowed."
self.cache = os.environ.get(self.cache_env, self.cache_default)
self.restore()
self.analysis_cache = {}
def help(self, error=None):
if error:
print error
print
print __doc__
sys.exit(1)
def command_line(self):
import getopt
settings = {}
optmap = {
'-a': 'annotate',
'-d:': 'directory=',
'-e': 'erase',
'-h': 'help',
'-i': 'ignore-errors',
'-m': 'show-missing',
'-r': 'report',
'-x': 'execute',
}
short_opts = string.join(map(lambda o: o[1:], optmap.keys()), '')
long_opts = optmap.values()
options, args = getopt.getopt(sys.argv[1:], short_opts,
long_opts)
for o, a in options:
if optmap.has_key(o):
settings[optmap[o]] = 1
elif optmap.has_key(o + ':'):
settings[optmap[o + ':']] = a
elif o[2:] in long_opts:
settings[o[2:]] = 1
elif o[2:] + '=' in long_opts:
settings[o[2:]] = a
else:
self.help("Unknown option: '%s'." % o)
if settings.get('help'):
self.help()
for i in ['erase', 'execute']:
for j in ['annotate', 'report']:
if settings.get(i) and settings.get(j):
self.help("You can't specify the '%s' and '%s' "
"options at the same time." % (i, j))
args_needed = (settings.get('execute')
or settings.get('annotate')
or settings.get('report'))
action = settings.get('erase') or args_needed
if not action:
self.help("You must specify at least one of -e, -x, -r, "
"or -a.")
if not args_needed and args:
self.help("Unexpected arguments %s." % args)
if settings.get('erase'):
self.erase()
if settings.get('execute'):
if not args:
self.help("Nothing to do.")
sys.argv = args
self.start()
import __main__
# When Python starts a script, sys.path[0] is the directory
# in which the Python script was found. So when we run a
# script, change sys.path so that it matches what the script
# would have found if it had been run normally.
sys.path[0] = os.path.dirname(sys.argv[0])
execfile(sys.argv[0], __main__.__dict__)
if not args:
args = self.cexecuted.keys()
ignore_errors = settings.get('ignore-errors')
show_missing = settings.get('show-missing')
directory = settings.get('directory=')
if settings.get('report'):
self.report(args, show_missing, ignore_errors)
if settings.get('annotate'):
self.annotate(args, directory, ignore_errors)
def start(self):
sys.settrace(t)
def stop(self):
sys.settrace(None)
def erase(self):
global c
c = {}
self.analysis_cache = {}
self.cexecuted = {}
if os.path.exists(self.cache):
os.remove(self.cache)
# save(). Save coverage data to the coverage cache.
def save(self):
self.canonicalize_filenames()
cache = open(self.cache, 'wb')
import marshal
marshal.dump(self.cexecuted, cache)
cache.close()
# restore(). Restore coverage data from the coverage cache (if it
# exists).
def restore(self):
global c
c = {}
self.cexecuted = {}
if not os.path.exists(self.cache):
return
try:
cache = open(self.cache, 'rb')
import marshal
cexecuted = marshal.load(cache)
cache.close()
if isinstance(cexecuted, types.DictType):
self.cexecuted = cexecuted
except:
pass
# canonical_filename(filename). Return a canonical filename for the
# file (that is, an absolute path with no redundant components and
# normalized case). See [GDR 2001-12-04b, 3.3].
def canonical_filename(self, filename):
if not self.canonical_filename_cache.has_key(filename):
f = filename
if os.path.isabs(f) and not os.path.exists(f):
f = os.path.basename(f)
if not os.path.isabs(f):
for path in [os.curdir] + sys.path:
g = os.path.join(path, f)
if os.path.exists(g):
f = g
break
cf = os.path.normcase(os.path.abspath(f))
self.canonical_filename_cache[filename] = cf
return self.canonical_filename_cache[filename]
# canonicalize_filenames(). Copy results from "executed" to
# "cexecuted", canonicalizing filenames on the way. Clear the
# "executed" map.
def canonicalize_filenames(self):
global c
for filename, lineno in c.keys():
f = self.canonical_filename(filename)
if not self.cexecuted.has_key(f):
self.cexecuted[f] = {}
self.cexecuted[f][lineno] = 1
c = {}
# morf_filename(morf). Return the filename for a module or file.
def morf_filename(self, morf):
if isinstance(morf, types.ModuleType):
if not hasattr(morf, '__file__'):
raise self.error, "Module has no __file__ attribute."
file = morf.__file__
else:
file = morf
return self.canonical_filename(file)
# analyze_morf(morf). Analyze the module or filename passed as
# the argument. If the source code can't be found, raise an error.
# Otherwise, return a pair of (1) the canonical filename of the
# source code for the module, and (2) a list of lines of statements
# in the source code.
def analyze_morf(self, morf):
if self.analysis_cache.has_key(morf):
return self.analysis_cache[morf]
filename = self.morf_filename(morf)
ext = os.path.splitext(filename)[1]
if ext == '.pyc':
if not os.path.exists(filename[0:-1]):
raise self.error, ("No source for compiled code '%s'."
% filename)
filename = filename[0:-1]
elif ext != '.py':
raise self.error, "File '%s' not Python source." % filename
source = open(filename, 'r')
import parser
tree = parser.suite(source.read()).totuple(1)
source.close()
statements = {}
self.find_statements(tree, statements)
lines = statements.keys()
lines.sort()
result = filename, lines
self.analysis_cache[morf] = result
return result
# find_statements(tree, dict). Find each statement in the parse
# tree and record the line on which the statement starts in the
# dictionary (by assigning it to 1).
#
# It works by walking the whole tree depth-first. Every time it
# comes across a statement (symbol.stmt -- this includes compound
# statements like 'if' and 'while') it calls find_statement, which
# descends the tree below the statement to find the first terminal
# token in that statement and record the lines on which that token
# was found.
#
# This algorithm may find some lines several times (because of the
# grammar production statement -> compound statement -> statement),
# but that doesn't matter because we record lines as the keys of the
# dictionary.
#
# See also [GDR 2001-12-04b, 3.2].
def find_statements(self, tree, dict):
import symbol, token
if token.ISNONTERMINAL(tree[0]):
for t in tree[1:]:
self.find_statements(t, dict)
if tree[0] == symbol.stmt:
self.find_statement(tree[1], dict)
elif (tree[0] == token.NAME
and tree[1] in ['elif', 'except', 'finally']):
dict[tree[2]] = 1
def find_statement(self, tree, dict):
import token
while token.ISNONTERMINAL(tree[0]):
tree = tree[1]
dict[tree[2]] = 1
# format_lines(statements, lines). Format a list of line numbers
# for printing by coalescing groups of lines as long as the lines
# represent consecutive statements. This will coalesce even if
# there are gaps between statements, so if statements =
# [1,2,3,4,5,10,11,12,13,14] and lines = [1,2,5,10,11,13,14] then
# format_lines will return "1-2, 5-11, 13-14".
def format_lines(self, statements, lines):
pairs = []
i = 0
j = 0
start = None
pairs = []
while i < len(statements) and j < len(lines):
if statements[i] == lines[j]:
if start == None:
start = lines[j]
end = lines[j]
j = j + 1
elif start:
pairs.append((start, end))
start = None
i = i + 1
if start:
pairs.append((start, end))
def stringify(pair):
start, end = pair
if start == end:
return "%d" % start
else:
return "%d-%d" % (start, end)
import string
return string.join(map(stringify, pairs), ", ")
def analysis(self, morf):
filename, statements = self.analyze_morf(morf)
self.canonicalize_filenames()
if not self.cexecuted.has_key(filename):
self.cexecuted[filename] = {}
missing = []
for line in statements:
if not self.cexecuted[filename].has_key(line):
missing.append(line)
return (filename, statements, missing,
self.format_lines(statements, missing))
def morf_name(self, morf):
if isinstance(morf, types.ModuleType):
return morf.__name__
else:
return os.path.splitext(os.path.basename(morf))[0]
def report(self, morfs, show_missing=1, ignore_errors=0):
if not isinstance(morfs, types.ListType):
morfs = [morfs]
max_name = max([5,] + map(len, map(self.morf_name, morfs)))
fmt_name = "%%- %ds " % max_name
fmt_err = fmt_name + "%s: %s"
header = fmt_name % "Name" + " Stmts Exec Cover"
fmt_coverage = fmt_name + "% 6d % 6d % 5d%%"
if show_missing:
header = header + " Missing"
fmt_coverage = fmt_coverage + " %s"
print header
print "-" * len(header)
total_statements = 0
total_executed = 0
for morf in morfs:
name = self.morf_name(morf)
try:
_, statements, missing, readable = self.analysis(morf)
n = len(statements)
m = n - len(missing)
if n > 0:
pc = 100.0 * m / n
else:
pc = 100.0
args = (name, n, m, pc)
if show_missing:
args = args + (readable,)
print fmt_coverage % args
total_statements = total_statements + n
total_executed = total_executed + m
except KeyboardInterrupt:
raise
except:
if not ignore_errors:
type, msg = sys.exc_info()[0:2]
print fmt_err % (name, type, msg)
if len(morfs) > 1:
print "-" * len(header)
if total_statements > 0:
pc = 100.0 * total_executed / total_statements
else:
pc = 100.0
args = ("TOTAL", total_statements, total_executed, pc)
if show_missing:
args = args + ("",)
print fmt_coverage % args
# annotate(morfs, ignore_errors).
blank_re = re.compile("\\s*(#|$)")
else_re = re.compile("\\s*else\\s*:\\s*(#|$)")
def annotate(self, morfs, directory=None, ignore_errors=0):
for morf in morfs:
try:
filename, statements, missing, _ = self.analysis(morf)
source = open(filename, 'r')
if directory:
dest_file = os.path.join(directory,
os.path.basename(filename)
+ ',cover')
else:
dest_file = filename + ',cover'
dest = open(dest_file, 'w')
lineno = 0
i = 0
j = 0
covered = 1
while 1:
line = source.readline()
if line == '':
break
lineno = lineno + 1
while i < len(statements) and statements[i] < lineno:
i = i + 1
while j < len(missing) and missing[j] < lineno:
j = j + 1
if i < len(statements) and statements[i] == lineno:
covered = j >= len(missing) or missing[j] > lineno
if self.blank_re.match(line):
dest.write(' ')
elif self.else_re.match(line):
# Special logic for lines containing only
# 'else:'. See [GDR 2001-12-04b, 3.2].
if i >= len(statements) and j >= len(missing):
dest.write('! ')
elif i >= len(statements) or j >= len(missing):
dest.write('> ')
elif statements[i] == missing[j]:
dest.write('! ')
else:
dest.write('> ')
elif covered:
dest.write('> ')
else:
dest.write('! ')
dest.write(line)
source.close()
dest.close()
except KeyboardInterrupt:
raise
except:
if not ignore_errors:
raise
# Singleton object.
the_coverage = coverage()
# Module functions call methods in the singleton object.
def start(*args, **kw): return apply(the_coverage.start, args, kw)
def stop(*args, **kw): return apply(the_coverage.stop, args, kw)
def erase(*args, **kw): return apply(the_coverage.erase, args, kw)
def analysis(*args, **kw): return apply(the_coverage.analysis, args, kw)
def report(*args, **kw): return apply(the_coverage.report, args, kw)
# Save coverage data when Python exits. (The atexit module wasn't
# introduced until Python 2.0, so use sys.exitfunc when it's not
# available.)
try:
import atexit
atexit.register(the_coverage.save)
except ImportError:
sys.exitfunc = the_coverage.save
# Command-line interface.
if __name__ == '__main__':
the_coverage.command_line()
# A. REFERENCES
#
# [GDR 2001-12-04a] "Statement coverage for Python"; Gareth Rees;
# Ravenbrook Limited; 2001-12-04;
# <http://garethrees.org/2001/12/04/python-coverage/>.
#
# [GDR 2001-12-04b] "Statement coverage for Python: design and
# analysis"; Gareth Rees; Ravenbrook Limited; 2001-12-04;
# <http://garethrees.org/2001/12/04/python-coverage/design.html>.
#
# [van Rossum 2001-07-20a] "Python Reference Manual (releae 2.1.1)";
# Guide van Rossum; 2001-07-20;
# <http://www.python.org/doc/2.1.1/ref/ref.html>.
#
# [van Rossum 2001-07-20b] "Python Library Reference"; Guido van Rossum;
# 2001-07-20; <http://www.python.org/doc/2.1.1/lib/lib.html>.
#
#
# B. DOCUMENT HISTORY
#
# 2001-12-04 GDR Created.
#
# 2001-12-06 GDR Added command-line interface and source code
# annotation.
#
# 2001-12-09 GDR Moved design and interface to separate documents.
#
# 2001-12-10 GDR Open cache file as binary on Windows. Allow
# simultaneous -e and -x, or -a and -r.
#
# 2001-12-12 GDR Added command-line help. Cache analysis so that it
# only needs to be done once when you specify -a and -r.
#
# 2001-12-13 GDR Improved speed while recording. Portable between
# Python 1.5.2 and 2.1.1.
#
# 2002-01-03 GDR Module-level functions work correctly.
#
# 2002-01-07 GDR Update sys.path when running a file with the -x option,
# so that it matches the value the program would get if it were run on
# its own.
#
#
# C. COPYRIGHT AND LICENCE
#
# Copyright 2001 Gareth Rees. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. 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.
#
# 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
# HOLDERS AND 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.
#
#
#
# $Id: //info.ravenbrook.com/user/gdr/www.garethrees.org/2001/12/04/python-coverage/coverage.py#9 $
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
__author__ = 'j.s@google.com (Jeff Scudder)'
import unittest
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import gdata
import atom
from gdata import test_data
import gdata.test_config as conf
class StartIndexTest(unittest.TestCase):
def setUp(self):
self.start_index = gdata.StartIndex()
def testToAndFromString(self):
self.start_index.text = '1'
self.assert_(self.start_index.text == '1')
new_start_index = gdata.StartIndexFromString(self.start_index.ToString())
self.assert_(self.start_index.text == new_start_index.text)
class ItemsPerPageTest(unittest.TestCase):
def setUp(self):
self.items_per_page = gdata.ItemsPerPage()
def testToAndFromString(self):
self.items_per_page.text = '10'
self.assert_(self.items_per_page.text == '10')
new_items_per_page = gdata.ItemsPerPageFromString(
self.items_per_page.ToString())
self.assert_(self.items_per_page.text == new_items_per_page.text)
class GDataEntryTest(unittest.TestCase):
def testIdShouldBeCleaned(self):
entry = gdata.GDataEntryFromString(test_data.XML_ENTRY_1)
element_tree = ElementTree.fromstring(test_data.XML_ENTRY_1)
self.assert_(element_tree.findall(
'{http://www.w3.org/2005/Atom}id')[0].text != entry.id.text)
self.assert_(entry.id.text == 'http://www.google.com/test/id/url')
def testGeneratorShouldBeCleaned(self):
feed = gdata.GDataFeedFromString(test_data.GBASE_FEED)
element_tree = ElementTree.fromstring(test_data.GBASE_FEED)
self.assert_(element_tree.findall('{http://www.w3.org/2005/Atom}generator'
)[0].text != feed.generator.text)
self.assert_(feed.generator.text == 'GoogleBase')
def testAllowsEmptyId(self):
entry = gdata.GDataEntry()
try:
entry.id = atom.Id()
except AttributeError:
self.fail('Empty id should not raise an attribute error.')
class LinkFinderTest(unittest.TestCase):
def setUp(self):
self.entry = gdata.GDataEntryFromString(test_data.XML_ENTRY_1)
def testLinkFinderGetsLicenseLink(self):
self.assertEquals(isinstance(self.entry.GetLicenseLink(), atom.Link),
True)
self.assertEquals(self.entry.GetLicenseLink().href,
'http://creativecommons.org/licenses/by-nc/2.5/rdf')
self.assertEquals(self.entry.GetLicenseLink().rel, 'license')
def testLinkFinderGetsAlternateLink(self):
self.assertEquals(isinstance(self.entry.GetAlternateLink(), atom.Link),
True)
self.assertEquals(self.entry.GetAlternateLink().href,
'http://www.provider-host.com/123456789')
self.assertEquals(self.entry.GetAlternateLink().rel, 'alternate')
class GDataFeedTest(unittest.TestCase):
def testCorrectConversionToElementTree(self):
test_feed = gdata.GDataFeedFromString(test_data.GBASE_FEED)
self.assert_(test_feed.total_results is not None)
element_tree = test_feed._ToElementTree()
feed = element_tree.find('{http://www.w3.org/2005/Atom}feed')
self.assert_(element_tree.find(
'{http://a9.com/-/spec/opensearchrss/1.0/}totalResults') is not None)
def testAllowsEmptyId(self):
feed = gdata.GDataFeed()
try:
feed.id = atom.Id()
except AttributeError:
self.fail('Empty id should not raise an attribute error.')
class BatchEntryTest(unittest.TestCase):
def testCorrectConversionFromAndToString(self):
batch_entry = gdata.BatchEntryFromString(test_data.BATCH_ENTRY)
self.assertEquals(batch_entry.batch_id.text, 'itemB')
self.assertEquals(batch_entry.id.text,
'http://www.google.com/base/feeds/items/'
'2173859253842813008')
self.assertEquals(batch_entry.batch_operation.type, 'insert')
self.assertEquals(batch_entry.batch_status.code, '201')
self.assertEquals(batch_entry.batch_status.reason, 'Created')
new_entry = gdata.BatchEntryFromString(str(batch_entry))
self.assertEquals(batch_entry.batch_id.text, new_entry.batch_id.text)
self.assertEquals(batch_entry.id.text, new_entry.id.text)
self.assertEquals(batch_entry.batch_operation.type,
new_entry.batch_operation.type)
self.assertEquals(batch_entry.batch_status.code,
new_entry.batch_status.code)
self.assertEquals(batch_entry.batch_status.reason,
new_entry.batch_status.reason)
class BatchFeedTest(unittest.TestCase):
def setUp(self):
self.batch_feed = gdata.BatchFeed()
self.example_entry = gdata.BatchEntry(
atom_id=atom.Id(text='http://example.com/1'), text='This is a test')
def testConvertRequestFeed(self):
batch_feed = gdata.BatchFeedFromString(test_data.BATCH_FEED_REQUEST)
self.assertEquals(len(batch_feed.entry), 4)
for entry in batch_feed.entry:
self.assert_(isinstance(entry, gdata.BatchEntry))
self.assertEquals(batch_feed.title.text, 'My Batch Feed')
new_feed = gdata.BatchFeedFromString(str(batch_feed))
self.assertEquals(len(new_feed.entry), 4)
for entry in new_feed.entry:
self.assert_(isinstance(entry, gdata.BatchEntry))
self.assertEquals(new_feed.title.text, 'My Batch Feed')
def testConvertResultFeed(self):
batch_feed = gdata.BatchFeedFromString(test_data.BATCH_FEED_RESULT)
self.assertEquals(len(batch_feed.entry), 4)
for entry in batch_feed.entry:
self.assert_(isinstance(entry, gdata.BatchEntry))
if entry.id.text == ('http://www.google.com/base/feeds/items/'
'2173859253842813008'):
self.assertEquals(entry.batch_operation.type, 'insert')
self.assertEquals(entry.batch_id.text, 'itemB')
self.assertEquals(entry.batch_status.code, '201')
self.assertEquals(entry.batch_status.reason, 'Created')
self.assertEquals(batch_feed.title.text, 'My Batch')
new_feed = gdata.BatchFeedFromString(str(batch_feed))
self.assertEquals(len(new_feed.entry), 4)
for entry in new_feed.entry:
self.assert_(isinstance(entry, gdata.BatchEntry))
if entry.id.text == ('http://www.google.com/base/feeds/items/'
'2173859253842813008'):
self.assertEquals(entry.batch_operation.type, 'insert')
self.assertEquals(entry.batch_id.text, 'itemB')
self.assertEquals(entry.batch_status.code, '201')
self.assertEquals(entry.batch_status.reason, 'Created')
self.assertEquals(new_feed.title.text, 'My Batch')
def testAddBatchEntry(self):
try:
self.batch_feed.AddBatchEntry(batch_id_string='a')
self.fail('AddBatchEntry with neither entry or URL should raise Error')
except gdata.MissingRequiredParameters:
pass
new_entry = self.batch_feed.AddBatchEntry(
id_url_string='http://example.com/1')
self.assertEquals(len(self.batch_feed.entry), 1)
self.assertEquals(self.batch_feed.entry[0].id.text,
'http://example.com/1')
self.assertEquals(self.batch_feed.entry[0].batch_id.text, '0')
self.assertEquals(new_entry.id.text, 'http://example.com/1')
self.assertEquals(new_entry.batch_id.text, '0')
to_add = gdata.BatchEntry(atom_id=atom.Id(text='originalId'))
new_entry = self.batch_feed.AddBatchEntry(entry=to_add,
batch_id_string='foo')
self.assertEquals(new_entry.batch_id.text, 'foo')
self.assertEquals(new_entry.id.text, 'originalId')
to_add = gdata.BatchEntry(atom_id=atom.Id(text='originalId'),
batch_id=gdata.BatchId(text='bar'))
new_entry = self.batch_feed.AddBatchEntry(entry=to_add,
id_url_string='newId',
batch_id_string='foo')
self.assertEquals(new_entry.batch_id.text, 'foo')
self.assertEquals(new_entry.id.text, 'originalId')
to_add = gdata.BatchEntry(atom_id=atom.Id(text='originalId'),
batch_id=gdata.BatchId(text='bar'))
new_entry = self.batch_feed.AddBatchEntry(entry=to_add,
id_url_string='newId')
self.assertEquals(new_entry.batch_id.text, 'bar')
self.assertEquals(new_entry.id.text, 'originalId')
to_add = gdata.BatchEntry(atom_id=atom.Id(text='originalId'),
batch_id=gdata.BatchId(text='bar'),
batch_operation=gdata.BatchOperation(
op_type=gdata.BATCH_INSERT))
self.assertEquals(to_add.batch_operation.type, gdata.BATCH_INSERT)
new_entry = self.batch_feed.AddBatchEntry(entry=to_add,
id_url_string='newId', batch_id_string='foo',
operation_string=gdata.BATCH_UPDATE)
self.assertEquals(new_entry.batch_operation.type, gdata.BATCH_UPDATE)
def testAddInsert(self):
first_entry = gdata.BatchEntry(
atom_id=atom.Id(text='http://example.com/1'), text='This is a test1')
self.batch_feed.AddInsert(first_entry)
self.assertEquals(self.batch_feed.entry[0].batch_operation.type,
gdata.BATCH_INSERT)
self.assertEquals(self.batch_feed.entry[0].batch_id.text, '0')
second_entry = gdata.BatchEntry(
atom_id=atom.Id(text='http://example.com/2'), text='This is a test2')
self.batch_feed.AddInsert(second_entry, batch_id_string='foo')
self.assertEquals(self.batch_feed.entry[1].batch_operation.type,
gdata.BATCH_INSERT)
self.assertEquals(self.batch_feed.entry[1].batch_id.text, 'foo')
third_entry = gdata.BatchEntry(
atom_id=atom.Id(text='http://example.com/3'), text='This is a test3')
third_entry.batch_operation = gdata.BatchOperation(
op_type=gdata.BATCH_DELETE)
# Add an entry with a delete operation already assigned.
self.batch_feed.AddInsert(third_entry)
# The batch entry should not have the original operation, it should
# have been changed to an insert.
self.assertEquals(self.batch_feed.entry[2].batch_operation.type,
gdata.BATCH_INSERT)
self.assertEquals(self.batch_feed.entry[2].batch_id.text, '2')
def testAddDelete(self):
# Try deleting an entry
delete_entry = gdata.BatchEntry(
atom_id=atom.Id(text='http://example.com/1'), text='This is a test')
self.batch_feed.AddDelete(entry=delete_entry)
self.assertEquals(self.batch_feed.entry[0].batch_operation.type,
gdata.BATCH_DELETE)
self.assertEquals(self.batch_feed.entry[0].id.text,
'http://example.com/1')
self.assertEquals(self.batch_feed.entry[0].text, 'This is a test')
# Try deleting a URL
self.batch_feed.AddDelete(url_string='http://example.com/2')
self.assertEquals(self.batch_feed.entry[0].batch_operation.type,
gdata.BATCH_DELETE)
self.assertEquals(self.batch_feed.entry[1].id.text,
'http://example.com/2')
self.assert_(self.batch_feed.entry[1].text is None)
def testAddQuery(self):
# Try querying with an existing batch entry
delete_entry = gdata.BatchEntry(
atom_id=atom.Id(text='http://example.com/1'))
self.batch_feed.AddQuery(entry=delete_entry)
self.assertEquals(self.batch_feed.entry[0].batch_operation.type,
gdata.BATCH_QUERY)
self.assertEquals(self.batch_feed.entry[0].id.text,
'http://example.com/1')
# Try querying a URL
self.batch_feed.AddQuery(url_string='http://example.com/2')
self.assertEquals(self.batch_feed.entry[0].batch_operation.type,
gdata.BATCH_QUERY)
self.assertEquals(self.batch_feed.entry[1].id.text,
'http://example.com/2')
def testAddUpdate(self):
# Try updating an entry
delete_entry = gdata.BatchEntry(
atom_id=atom.Id(text='http://example.com/1'), text='This is a test')
self.batch_feed.AddUpdate(entry=delete_entry)
self.assertEquals(self.batch_feed.entry[0].batch_operation.type,
gdata.BATCH_UPDATE)
self.assertEquals(self.batch_feed.entry[0].id.text,
'http://example.com/1')
self.assertEquals(self.batch_feed.entry[0].text, 'This is a test')
class ExtendedPropertyTest(unittest.TestCase):
def testXmlBlobRoundTrip(self):
ep = gdata.ExtendedProperty(name='blobby')
ep.SetXmlBlob('<some_xml attr="test"/>')
extension = ep.GetXmlBlobExtensionElement()
self.assertEquals(extension.tag, 'some_xml')
self.assert_(extension.namespace is None)
self.assertEquals(extension.attributes['attr'], 'test')
ep2 = gdata.ExtendedPropertyFromString(ep.ToString())
extension = ep2.GetXmlBlobExtensionElement()
self.assertEquals(extension.tag, 'some_xml')
self.assert_(extension.namespace is None)
self.assertEquals(extension.attributes['attr'], 'test')
def testGettersShouldReturnNoneWithNoBlob(self):
ep = gdata.ExtendedProperty(name='no blob')
self.assert_(ep.GetXmlBlobExtensionElement() is None)
self.assert_(ep.GetXmlBlobString() is None)
def testGettersReturnCorrectTypes(self):
ep = gdata.ExtendedProperty(name='has blob')
ep.SetXmlBlob('<some_xml attr="test"/>')
self.assert_(isinstance(ep.GetXmlBlobExtensionElement(),
atom.ExtensionElement))
self.assert_(isinstance(ep.GetXmlBlobString(), str))
class FeedLinkTest(unittest.TestCase):
def testCorrectFromStringType(self):
link = gdata.FeedLinkFromString(
'<feedLink xmlns="http://schemas.google.com/g/2005" countHint="5"/>')
self.assert_(isinstance(link, gdata.FeedLink))
self.assertEqual(link.count_hint, '5')
def suite():
return conf.build_suite([StartIndexTest, StartIndexTest, GDataEntryTest,
LinkFinderTest, GDataFeedTest, BatchEntryTest, BatchFeedTest,
ExtendedPropertyTest, FeedLinkTest])
if __name__ == '__main__':
unittest.main()
| 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.
__author__ = 'j.s@google.com (Jeff Scudder)'
import unittest
import all_tests
import gdata.test_config as conf
conf.options.set_value('runlive', 'false')
def suite():
return unittest.TestSuite((atom_tests.core_test.suite(),))
if __name__ == '__main__':
unittest.TextTestRunner().run(all_tests.suite())
| 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.
__author__ = 'j.s@google.com (Jeff Scudder)'
import base64
class BasicAuth(object):
"""Sets the Authorization header as defined in RFC1945"""
def __init__(self, user_id, password):
self.basic_cookie = base64.encodestring(
'%s:%s' % (user_id, password)).strip()
def modify_request(self, http_request):
http_request.headers['Authorization'] = 'Basic %s' % self.basic_cookie
ModifyRequest = modify_request
class NoAuth(object):
def modify_request(self, http_request):
pass
| 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 (Jeff Scudder)'
import atom.http_interface
import atom.url
class Error(Exception):
pass
class NoRecordingFound(Error):
pass
class MockRequest(object):
"""Holds parameters of an HTTP request for matching against future requests.
"""
def __init__(self, operation, url, data=None, headers=None):
self.operation = operation
if isinstance(url, (str, unicode)):
url = atom.url.parse_url(url)
self.url = url
self.data = data
self.headers = headers
class MockResponse(atom.http_interface.HttpResponse):
"""Simulates an httplib.HTTPResponse object."""
def __init__(self, body=None, status=None, reason=None, headers=None):
if body and hasattr(body, 'read'):
self.body = body.read()
else:
self.body = body
if status is not None:
self.status = int(status)
else:
self.status = None
self.reason = reason
self._headers = headers or {}
def read(self):
return self.body
class MockHttpClient(atom.http_interface.GenericHttpClient):
def __init__(self, headers=None, recordings=None, real_client=None):
"""An HttpClient which responds to request with stored data.
The request-response pairs are stored as tuples in a member list named
recordings.
The MockHttpClient can be switched from replay mode to record mode by
setting the real_client member to an instance of an HttpClient which will
make real HTTP requests and store the server's response in list of
recordings.
Args:
headers: dict containing HTTP headers which should be included in all
HTTP requests.
recordings: The initial recordings to be used for responses. This list
contains tuples in the form: (MockRequest, MockResponse)
real_client: An HttpClient which will make a real HTTP request. The
response will be converted into a MockResponse and stored in
recordings.
"""
self.recordings = recordings or []
self.real_client = real_client
self.headers = headers or {}
def add_response(self, response, operation, url, data=None, headers=None):
"""Adds a request-response pair to the recordings list.
After the recording is added, future matching requests will receive the
response.
Args:
response: MockResponse
operation: str
url: str
data: str, Currently the data is ignored when looking for matching
requests.
headers: dict of strings: Currently the headers are ignored when
looking for matching requests.
"""
request = MockRequest(operation, url, data=data, headers=headers)
self.recordings.append((request, response))
def request(self, operation, url, data=None, headers=None):
"""Returns a matching MockResponse from the recordings.
If the real_client is set, the request will be passed along and the
server's response will be added to the recordings and also returned.
If there is no match, a NoRecordingFound error will be raised.
"""
if self.real_client is None:
if isinstance(url, (str, unicode)):
url = atom.url.parse_url(url)
for recording in self.recordings:
if recording[0].operation == operation and recording[0].url == url:
return recording[1]
raise NoRecordingFound('No recodings found for %s %s' % (
operation, url))
else:
# There is a real HTTP client, so make the request, and record the
# response.
response = self.real_client.request(operation, url, data=data,
headers=headers)
# TODO: copy the headers
stored_response = MockResponse(body=response, status=response.status,
reason=response.reason)
self.add_response(stored_response, operation, url, data=data,
headers=headers)
return stored_response
| 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.
__author__ = 'j.s@google.com (Jeff Scudder)'
import atom.core
XML_TEMPLATE = '{http://www.w3.org/XML/1998/namespace}%s'
ATOM_TEMPLATE = '{http://www.w3.org/2005/Atom}%s'
APP_TEMPLATE_V1 = '{http://purl.org/atom/app#}%s'
APP_TEMPLATE_V2 = '{http://www.w3.org/2007/app}%s'
class Name(atom.core.XmlElement):
"""The atom:name element."""
_qname = ATOM_TEMPLATE % 'name'
class Email(atom.core.XmlElement):
"""The atom:email element."""
_qname = ATOM_TEMPLATE % 'email'
class Uri(atom.core.XmlElement):
"""The atom:uri element."""
_qname = ATOM_TEMPLATE % 'uri'
class Person(atom.core.XmlElement):
"""A foundation class which atom:author and atom:contributor extend.
A person contains information like name, email address, and web page URI for
an author or contributor to an Atom feed.
"""
name = Name
email = Email
uri = Uri
class Author(Person):
"""The atom:author element.
An author is a required element in Feed unless each Entry contains an Author.
"""
_qname = ATOM_TEMPLATE % 'author'
class Contributor(Person):
"""The atom:contributor element."""
_qname = ATOM_TEMPLATE % 'contributor'
class Link(atom.core.XmlElement):
"""The atom:link element."""
_qname = ATOM_TEMPLATE % 'link'
href = 'href'
rel = 'rel'
type = 'type'
hreflang = 'hreflang'
title = 'title'
length = 'length'
class Generator(atom.core.XmlElement):
"""The atom:generator element."""
_qname = ATOM_TEMPLATE % 'generator'
uri = 'uri'
version = 'version'
class Text(atom.core.XmlElement):
"""A foundation class from which atom:title, summary, etc. extend.
This class should never be instantiated.
"""
type = 'type'
class Title(Text):
"""The atom:title element."""
_qname = ATOM_TEMPLATE % 'title'
class Subtitle(Text):
"""The atom:subtitle element."""
_qname = ATOM_TEMPLATE % 'subtitle'
class Rights(Text):
"""The atom:rights element."""
_qname = ATOM_TEMPLATE % 'rights'
class Summary(Text):
"""The atom:summary element."""
_qname = ATOM_TEMPLATE % 'summary'
class Content(Text):
"""The atom:content element."""
_qname = ATOM_TEMPLATE % 'content'
src = 'src'
class Category(atom.core.XmlElement):
"""The atom:category element."""
_qname = ATOM_TEMPLATE % 'category'
term = 'term'
scheme = 'scheme'
label = 'label'
class Id(atom.core.XmlElement):
"""The atom:id element."""
_qname = ATOM_TEMPLATE % 'id'
class Icon(atom.core.XmlElement):
"""The atom:icon element."""
_qname = ATOM_TEMPLATE % 'icon'
class Logo(atom.core.XmlElement):
"""The atom:logo element."""
_qname = ATOM_TEMPLATE % 'logo'
class Draft(atom.core.XmlElement):
"""The app:draft element which indicates if this entry should be public."""
_qname = (APP_TEMPLATE_V1 % 'draft', APP_TEMPLATE_V2 % 'draft')
class Control(atom.core.XmlElement):
"""The app:control element indicating restrictions on publication.
The APP control element may contain a draft element indicating whether or
not this entry should be publicly available.
"""
_qname = (APP_TEMPLATE_V1 % 'control', APP_TEMPLATE_V2 % 'control')
draft = Draft
class Date(atom.core.XmlElement):
"""A parent class for atom:updated, published, etc."""
class Updated(Date):
"""The atom:updated element."""
_qname = ATOM_TEMPLATE % 'updated'
class Published(Date):
"""The atom:published element."""
_qname = ATOM_TEMPLATE % 'published'
class LinkFinder(object):
"""An "interface" providing methods to find link elements
Entry elements often contain multiple links which differ in the rel
attribute or content type. Often, developers are interested in a specific
type of link so this class provides methods to find specific classes of
links.
This class is used as a mixin in Atom entries and feeds.
"""
def find_url(self, rel):
"""Returns the URL (as a string) in a link with the desired rel value."""
for link in self.link:
if link.rel == rel and link.href:
return link.href
return None
FindUrl = find_url
def get_link(self, rel):
"""Returns a link object which has the desired rel value.
If you are interested in the URL instead of the link object,
consider using find_url instead.
"""
for link in self.link:
if link.rel == rel and link.href:
return link
return None
GetLink = get_link
def find_self_link(self):
"""Find the first link with rel set to 'self'
Returns:
A str containing the link's href or None if none of the links had rel
equal to 'self'
"""
return self.find_url('self')
FindSelfLink = find_self_link
def get_self_link(self):
return self.get_link('self')
GetSelfLink = get_self_link
def find_edit_link(self):
return self.find_url('edit')
FindEditLink = find_edit_link
def get_edit_link(self):
return self.get_link('edit')
GetEditLink = get_edit_link
def find_edit_media_link(self):
link = self.find_url('edit-media')
# Search for media-edit as well since Picasa API used media-edit instead.
if link is None:
return self.find_url('media-edit')
return link
FindEditMediaLink = find_edit_media_link
def get_edit_media_link(self):
link = self.get_link('edit-media')
if link is None:
return self.get_link('media-edit')
return link
GetEditMediaLink = get_edit_media_link
def find_next_link(self):
return self.find_url('next')
FindNextLink = find_next_link
def get_next_link(self):
return self.get_link('next')
GetNextLink = get_next_link
def find_license_link(self):
return self.find_url('license')
FindLicenseLink = find_license_link
def get_license_link(self):
return self.get_link('license')
GetLicenseLink = get_license_link
def find_alternate_link(self):
return self.find_url('alternate')
FindAlternateLink = find_alternate_link
def get_alternate_link(self):
return self.get_link('alternate')
GetAlternateLink = get_alternate_link
class FeedEntryParent(atom.core.XmlElement, LinkFinder):
"""A super class for atom:feed and entry, contains shared attributes"""
author = [Author]
category = [Category]
contributor = [Contributor]
id = Id
link = [Link]
rights = Rights
title = Title
updated = Updated
def __init__(self, atom_id=None, text=None, *args, **kwargs):
if atom_id is not None:
self.id = atom_id
atom.core.XmlElement.__init__(self, text=text, *args, **kwargs)
class Source(FeedEntryParent):
"""The atom:source element."""
_qname = ATOM_TEMPLATE % 'source'
generator = Generator
icon = Icon
logo = Logo
subtitle = Subtitle
class Entry(FeedEntryParent):
"""The atom:entry element."""
_qname = ATOM_TEMPLATE % 'entry'
content = Content
published = Published
source = Source
summary = Summary
control = Control
class Feed(Source):
"""The atom:feed element which contains entries."""
_qname = ATOM_TEMPLATE % 'feed'
entry = [Entry]
class ExtensionElement(atom.core.XmlElement):
"""Provided for backwards compatibility to the v1 atom.ExtensionElement."""
def __init__(self, tag=None, namespace=None, attributes=None,
children=None, text=None, *args, **kwargs):
if namespace:
self._qname = '{%s}%s' % (namespace, tag)
else:
self._qname = tag
self.children = children or []
self.attributes = attributes or {}
self.text = text
_BecomeChildElement = atom.core.XmlElement._become_child
| Python |
#!/usr/bin/env 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.
# This module is used for version 2 of the Google Data APIs.
__author__ = 'j.s@google.com (Jeff Scudder)'
import inspect
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
try:
from xml.dom.minidom import parseString as xmlString
except ImportError:
xmlString = None
STRING_ENCODING = 'utf-8'
class XmlElement(object):
"""Represents an element node in an XML document.
The text member is a UTF-8 encoded str or unicode.
"""
_qname = None
_other_elements = None
_other_attributes = None
# The rule set contains mappings for XML qnames to child members and the
# appropriate member classes.
_rule_set = None
_members = None
text = None
def __init__(self, text=None, *args, **kwargs):
if ('_members' not in self.__class__.__dict__
or self.__class__._members is None):
self.__class__._members = tuple(self.__class__._list_xml_members())
for member_name, member_type in self.__class__._members:
if member_name in kwargs:
setattr(self, member_name, kwargs[member_name])
else:
if isinstance(member_type, list):
setattr(self, member_name, [])
else:
setattr(self, member_name, None)
self._other_elements = []
self._other_attributes = {}
if text is not None:
self.text = text
def _list_xml_members(cls):
"""Generator listing all members which are XML elements or attributes.
The following members would be considered XML members:
foo = 'abc' - indicates an XML attribute with the qname abc
foo = SomeElement - indicates an XML child element
foo = [AnElement] - indicates a repeating XML child element, each instance
will be stored in a list in this member
foo = ('att1', '{http://example.com/namespace}att2') - indicates an XML
attribute which has different parsing rules in different versions of
the protocol. Version 1 of the XML parsing rules will look for an
attribute with the qname 'att1' but verion 2 of the parsing rules will
look for a namespaced attribute with the local name of 'att2' and an
XML namespace of 'http://example.com/namespace'.
"""
members = []
for pair in inspect.getmembers(cls):
if not pair[0].startswith('_') and pair[0] != 'text':
member_type = pair[1]
if (isinstance(member_type, tuple) or isinstance(member_type, list)
or isinstance(member_type, (str, unicode))
or (inspect.isclass(member_type)
and issubclass(member_type, XmlElement))):
members.append(pair)
return members
_list_xml_members = classmethod(_list_xml_members)
def _get_rules(cls, version):
"""Initializes the _rule_set for the class which is used when parsing XML.
This method is used internally for parsing and generating XML for an
XmlElement. It is not recommended that you call this method directly.
Returns:
A tuple containing the XML parsing rules for the appropriate version.
The tuple looks like:
(qname, {sub_element_qname: (member_name, member_class, repeating), ..},
{attribute_qname: member_name})
To give a couple of concrete example, the atom.data.Control _get_rules
with version of 2 will return:
('{http://www.w3.org/2007/app}control',
{'{http://www.w3.org/2007/app}draft': ('draft',
<class 'atom.data.Draft'>,
False)},
{})
Calling _get_rules with version 1 on gdata.data.FeedLink will produce:
('{http://schemas.google.com/g/2005}feedLink',
{'{http://www.w3.org/2005/Atom}feed': ('feed',
<class 'gdata.data.GDFeed'>,
False)},
{'href': 'href', 'readOnly': 'read_only', 'countHint': 'count_hint',
'rel': 'rel'})
"""
# Initialize the _rule_set to make sure there is a slot available to store
# the parsing rules for this version of the XML schema.
# Look for rule set in the class __dict__ proxy so that only the
# _rule_set for this class will be found. By using the dict proxy
# we avoid finding rule_sets defined in superclasses.
# The four lines below provide support for any number of versions, but it
# runs a bit slower then hard coding slots for two versions, so I'm using
# the below two lines.
#if '_rule_set' not in cls.__dict__ or cls._rule_set is None:
# cls._rule_set = []
#while len(cls.__dict__['_rule_set']) < version:
# cls._rule_set.append(None)
# If there is no rule set cache in the class, provide slots for two XML
# versions. If and when there is a version 3, this list will need to be
# expanded.
if '_rule_set' not in cls.__dict__ or cls._rule_set is None:
cls._rule_set = [None, None]
# If a version higher than 2 is requested, fall back to version 2 because
# 2 is currently the highest supported version.
if version > 2:
return cls._get_rules(2)
# Check the dict proxy for the rule set to avoid finding any rule sets
# which belong to the superclass. We only want rule sets for this class.
if cls._rule_set[version-1] is None:
# The rule set for each version consists of the qname for this element
# ('{namespace}tag'), a dictionary (elements) for looking up the
# corresponding class member when given a child element's qname, and a
# dictionary (attributes) for looking up the corresponding class member
# when given an XML attribute's qname.
elements = {}
attributes = {}
if ('_members' not in cls.__dict__ or cls._members is None):
cls._members = tuple(cls._list_xml_members())
for member_name, target in cls._members:
if isinstance(target, list):
# This member points to a repeating element.
elements[_get_qname(target[0], version)] = (member_name, target[0],
True)
elif isinstance(target, tuple):
# This member points to a versioned XML attribute.
if version <= len(target):
attributes[target[version-1]] = member_name
else:
attributes[target[-1]] = member_name
elif isinstance(target, (str, unicode)):
# This member points to an XML attribute.
attributes[target] = member_name
elif issubclass(target, XmlElement):
# This member points to a single occurance element.
elements[_get_qname(target, version)] = (member_name, target, False)
version_rules = (_get_qname(cls, version), elements, attributes)
cls._rule_set[version-1] = version_rules
return version_rules
else:
return cls._rule_set[version-1]
_get_rules = classmethod(_get_rules)
def get_elements(self, tag=None, namespace=None, version=1):
"""Find all sub elements which match the tag and namespace.
To find all elements in this object, call get_elements with the tag and
namespace both set to None (the default). This method searches through
the object's members and the elements stored in _other_elements which
did not match any of the XML parsing rules for this class.
Args:
tag: str
namespace: str
version: int Specifies the version of the XML rules to be used when
searching for matching elements.
Returns:
A list of the matching XmlElements.
"""
matches = []
ignored1, elements, ignored2 = self.__class__._get_rules(version)
if elements:
for qname, element_def in elements.iteritems():
member = getattr(self, element_def[0])
if member:
if _qname_matches(tag, namespace, qname):
if element_def[2]:
# If this is a repeating element, copy all instances into the
# result list.
matches.extend(member)
else:
matches.append(member)
for element in self._other_elements:
if _qname_matches(tag, namespace, element._qname):
matches.append(element)
return matches
GetElements = get_elements
# FindExtensions and FindChildren are provided for backwards compatibility
# to the atom.AtomBase class.
# However, FindExtensions may return more results than the v1 atom.AtomBase
# method does, because get_elements searches both the expected children
# and the unexpected "other elements". The old AtomBase.FindExtensions
# method searched only "other elements" AKA extension_elements.
FindExtensions = get_elements
FindChildren = get_elements
def get_attributes(self, tag=None, namespace=None, version=1):
"""Find all attributes which match the tag and namespace.
To find all attributes in this object, call get_attributes with the tag
and namespace both set to None (the default). This method searches
through the object's members and the attributes stored in
_other_attributes which did not fit any of the XML parsing rules for this
class.
Args:
tag: str
namespace: str
version: int Specifies the version of the XML rules to be used when
searching for matching attributes.
Returns:
A list of XmlAttribute objects for the matching attributes.
"""
matches = []
ignored1, ignored2, attributes = self.__class__._get_rules(version)
if attributes:
for qname, attribute_def in attributes.iteritems():
if isinstance(attribute_def, (list, tuple)):
attribute_def = attribute_def[0]
member = getattr(self, attribute_def)
# TODO: ensure this hasn't broken existing behavior.
#member = getattr(self, attribute_def[0])
if member:
if _qname_matches(tag, namespace, qname):
matches.append(XmlAttribute(qname, member))
for qname, value in self._other_attributes.iteritems():
if _qname_matches(tag, namespace, qname):
matches.append(XmlAttribute(qname, value))
return matches
GetAttributes = get_attributes
def _harvest_tree(self, tree, version=1):
"""Populates object members from the data in the tree Element."""
qname, elements, attributes = self.__class__._get_rules(version)
for element in tree:
if elements and element.tag in elements:
definition = elements[element.tag]
# If this is a repeating element, make sure the member is set to a
# list.
if definition[2]:
if getattr(self, definition[0]) is None:
setattr(self, definition[0], [])
getattr(self, definition[0]).append(_xml_element_from_tree(element,
definition[1], version))
else:
setattr(self, definition[0], _xml_element_from_tree(element,
definition[1], version))
else:
self._other_elements.append(_xml_element_from_tree(element, XmlElement,
version))
for attrib, value in tree.attrib.iteritems():
if attributes and attrib in attributes:
setattr(self, attributes[attrib], value)
else:
self._other_attributes[attrib] = value
if tree.text:
self.text = tree.text
def _to_tree(self, version=1, encoding=None):
new_tree = ElementTree.Element(_get_qname(self, version))
self._attach_members(new_tree, version, encoding)
return new_tree
def _attach_members(self, tree, version=1, encoding=None):
"""Convert members to XML elements/attributes and add them to the tree.
Args:
tree: An ElementTree.Element which will be modified. The members of
this object will be added as child elements or attributes
according to the rules described in _expected_elements and
_expected_attributes. The elements and attributes stored in
other_attributes and other_elements are also added a children
of this tree.
version: int Ingnored in this method but used by VersionedElement.
encoding: str (optional)
"""
qname, elements, attributes = self.__class__._get_rules(version)
encoding = encoding or STRING_ENCODING
# Add the expected elements and attributes to the tree.
if elements:
for tag, element_def in elements.iteritems():
member = getattr(self, element_def[0])
# If this is a repeating element and there are members in the list.
if member and element_def[2]:
for instance in member:
instance._become_child(tree, version)
elif member:
member._become_child(tree, version)
if attributes:
for attribute_tag, member_name in attributes.iteritems():
value = getattr(self, member_name)
if value:
tree.attrib[attribute_tag] = value
# Add the unexpected (other) elements and attributes to the tree.
for element in self._other_elements:
element._become_child(tree, version)
for key, value in self._other_attributes.iteritems():
# I'm not sure if unicode can be used in the attribute name, so for now
# we assume the encoding is correct for the attribute name.
if not isinstance(value, unicode):
value = value.decode(encoding)
tree.attrib[key] = value
if self.text:
if isinstance(self.text, unicode):
tree.text = self.text
else:
tree.text = self.text.decode(encoding)
def to_string(self, version=1, encoding=None, pretty_print=None):
"""Converts this object to XML."""
tree_string = ElementTree.tostring(self._to_tree(version, encoding))
if pretty_print and xmlString is not None:
return xmlString(tree_string).toprettyxml()
return tree_string
ToString = to_string
def __str__(self):
return self.to_string()
def _become_child(self, tree, version=1):
"""Adds a child element to tree with the XML data in self."""
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = _get_qname(self, version)
self._attach_members(new_child, version)
def __get_extension_elements(self):
return self._other_elements
def __set_extension_elements(self, elements):
self._other_elements = elements
extension_elements = property(__get_extension_elements,
__set_extension_elements,
"""Provides backwards compatibility for v1 atom.AtomBase classes.""")
def __get_extension_attributes(self):
return self._other_attributes
def __set_extension_attributes(self, attributes):
self._other_attributes = attributes
extension_attributes = property(__get_extension_attributes,
__set_extension_attributes,
"""Provides backwards compatibility for v1 atom.AtomBase classes.""")
def _get_tag(self, version=1):
qname = _get_qname(self, version)
if qname:
return qname[qname.find('}')+1:]
return None
def _get_namespace(self, version=1):
qname = _get_qname(self, version)
if qname.startswith('{'):
return qname[1:qname.find('}')]
else:
return None
def _set_tag(self, tag):
if isinstance(self._qname, tuple):
self._qname = self._qname.copy()
if self._qname[0].startswith('{'):
self._qname[0] = '{%s}%s' % (self._get_namespace(1), tag)
else:
self._qname[0] = tag
else:
if self._qname is not None and self._qname.startswith('{'):
self._qname = '{%s}%s' % (self._get_namespace(), tag)
else:
self._qname = tag
def _set_namespace(self, namespace):
tag = self._get_tag(1)
if tag is None:
tag = ''
if isinstance(self._qname, tuple):
self._qname = self._qname.copy()
if namespace:
self._qname[0] = '{%s}%s' % (namespace, tag)
else:
self._qname[0] = tag
else:
if namespace:
self._qname = '{%s}%s' % (namespace, tag)
else:
self._qname = tag
tag = property(_get_tag, _set_tag,
"""Provides backwards compatibility for v1 atom.AtomBase classes.""")
namespace = property(_get_namespace, _set_namespace,
"""Provides backwards compatibility for v1 atom.AtomBase classes.""")
# Provided for backwards compatibility to atom.ExtensionElement
children = extension_elements
attributes = extension_attributes
def _get_qname(element, version):
if isinstance(element._qname, tuple):
if version <= len(element._qname):
return element._qname[version-1]
else:
return element._qname[-1]
else:
return element._qname
def _qname_matches(tag, namespace, qname):
"""Logic determines if a QName matches the desired local tag and namespace.
This is used in XmlElement.get_elements and XmlElement.get_attributes to
find matches in the element's members (among all expected-and-unexpected
elements-and-attributes).
Args:
expected_tag: string
expected_namespace: string
qname: string in the form '{xml_namespace}localtag' or 'tag' if there is
no namespace.
Returns:
boolean True if the member's tag and namespace fit the expected tag and
namespace.
"""
# If there is no expected namespace or tag, then everything will match.
if qname is None:
member_tag = None
member_namespace = None
else:
if qname.startswith('{'):
member_namespace = qname[1:qname.index('}')]
member_tag = qname[qname.index('}') + 1:]
else:
member_namespace = None
member_tag = qname
return ((tag is None and namespace is None)
# If there is a tag, but no namespace, see if the local tag matches.
or (namespace is None and member_tag == tag)
# There was no tag, but there was a namespace so see if the namespaces
# match.
or (tag is None and member_namespace == namespace)
# There was no tag, and the desired elements have no namespace, so check
# to see that the member's namespace is None.
or (tag is None and namespace == ''
and member_namespace is None)
# The tag and the namespace both match.
or (tag == member_tag
and namespace == member_namespace)
# The tag matches, and the expected namespace is the empty namespace,
# check to make sure the member's namespace is None.
or (tag == member_tag and namespace == ''
and member_namespace is None))
def parse(xml_string, target_class=None, version=1, encoding=None):
"""Parses the XML string according to the rules for the target_class.
Args:
xml_string: str or unicode
target_class: XmlElement or a subclass. If None is specified, the
XmlElement class is used.
version: int (optional) The version of the schema which should be used when
converting the XML into an object. The default is 1.
encoding: str (optional) The character encoding of the bytes in the
xml_string. Default is 'UTF-8'.
"""
if target_class is None:
target_class = XmlElement
if isinstance(xml_string, unicode):
if encoding is None:
xml_string = xml_string.encode(STRING_ENCODING)
else:
xml_string = xml_string.encode(encoding)
tree = ElementTree.fromstring(xml_string)
return _xml_element_from_tree(tree, target_class, version)
Parse = parse
xml_element_from_string = parse
XmlElementFromString = xml_element_from_string
def _xml_element_from_tree(tree, target_class, version=1):
if target_class._qname is None:
instance = target_class()
instance._qname = tree.tag
instance._harvest_tree(tree, version)
return instance
# TODO handle the namespace-only case
# Namespace only will be used with Google Spreadsheets rows and
# Google Base item attributes.
elif tree.tag == _get_qname(target_class, version):
instance = target_class()
instance._harvest_tree(tree, version)
return instance
return None
class XmlAttribute(object):
def __init__(self, qname, value):
self._qname = qname
self.value = value
| 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.
"""AtomPubClient provides CRUD ops. in line with the Atom Publishing Protocol.
"""
__author__ = 'j.s@google.com (Jeff Scudder)'
import atom.http_core
class Error(Exception):
pass
class MissingHost(Error):
pass
class AtomPubClient(object):
host = None
auth_token = None
ssl = False # Whether to force all requests over https
xoauth_requestor_id = None
def __init__(self, http_client=None, host=None, auth_token=None, source=None,
xoauth_requestor_id=None, **kwargs):
"""Creates a new AtomPubClient instance.
Args:
source: The name of your application.
http_client: An object capable of performing HTTP requests through a
request method. This object is used to perform the request
when the AtomPubClient's request method is called. Used to
allow HTTP requests to be directed to a mock server, or use
an alternate library instead of the default of httplib to
make HTTP requests.
host: str The default host name to use if a host is not specified in the
requested URI.
auth_token: An object which sets the HTTP Authorization header when its
modify_request method is called.
"""
self.http_client = http_client or atom.http_core.ProxiedHttpClient()
if host is not None:
self.host = host
if auth_token is not None:
self.auth_token = auth_token
self.xoauth_requestor_id = xoauth_requestor_id
self.source = source
def request(self, method=None, uri=None, auth_token=None,
http_request=None, **kwargs):
"""Performs an HTTP request to the server indicated.
Uses the http_client instance to make the request.
Args:
method: The HTTP method as a string, usually one of 'GET', 'POST',
'PUT', or 'DELETE'
uri: The URI desired as a string or atom.http_core.Uri.
http_request:
auth_token: An authorization token object whose modify_request method
sets the HTTP Authorization header.
Returns:
The results of calling self.http_client.request. With the default
http_client, this is an HTTP response object.
"""
# Modify the request based on the AtomPubClient settings and parameters
# passed in to the request.
http_request = self.modify_request(http_request)
if isinstance(uri, (str, unicode)):
uri = atom.http_core.Uri.parse_uri(uri)
if uri is not None:
uri.modify_request(http_request)
if isinstance(method, (str, unicode)):
http_request.method = method
# Any unrecognized arguments are assumed to be capable of modifying the
# HTTP request.
for name, value in kwargs.iteritems():
if value is not None:
value.modify_request(http_request)
# Default to an http request if the protocol scheme is not set.
if http_request.uri.scheme is None:
http_request.uri.scheme = 'http'
# Override scheme. Force requests over https.
if self.ssl:
http_request.uri.scheme = 'https'
if http_request.uri.path is None:
http_request.uri.path = '/'
# Add the Authorization header at the very end. The Authorization header
# value may need to be calculated using information in the request.
if auth_token:
auth_token.modify_request(http_request)
elif self.auth_token:
self.auth_token.modify_request(http_request)
# Check to make sure there is a host in the http_request.
if http_request.uri.host is None:
raise MissingHost('No host provided in request %s %s' % (
http_request.method, str(http_request.uri)))
# Perform the fully specified request using the http_client instance.
# Sends the request to the server and returns the server's response.
return self.http_client.request(http_request)
Request = request
def get(self, uri=None, auth_token=None, http_request=None, **kwargs):
"""Performs a request using the GET method, returns an HTTP response."""
return self.request(method='GET', uri=uri, auth_token=auth_token,
http_request=http_request, **kwargs)
Get = get
def post(self, uri=None, data=None, auth_token=None, http_request=None,
**kwargs):
"""Sends data using the POST method, returns an HTTP response."""
return self.request(method='POST', uri=uri, auth_token=auth_token,
http_request=http_request, data=data, **kwargs)
Post = post
def put(self, uri=None, data=None, auth_token=None, http_request=None,
**kwargs):
"""Sends data using the PUT method, returns an HTTP response."""
return self.request(method='PUT', uri=uri, auth_token=auth_token,
http_request=http_request, data=data, **kwargs)
Put = put
def delete(self, uri=None, auth_token=None, http_request=None, **kwargs):
"""Performs a request using the DELETE method, returns an HTTP response."""
return self.request(method='DELETE', uri=uri, auth_token=auth_token,
http_request=http_request, **kwargs)
Delete = delete
def modify_request(self, http_request):
"""Changes the HTTP request before sending it to the server.
Sets the User-Agent HTTP header and fills in the HTTP host portion
of the URL if one was not included in the request (for this it uses
the self.host member if one is set). This method is called in
self.request.
Args:
http_request: An atom.http_core.HttpRequest() (optional) If one is
not provided, a new HttpRequest is instantiated.
Returns:
An atom.http_core.HttpRequest() with the User-Agent header set and
if this client has a value in its host member, the host in the request
URL is set.
"""
if http_request is None:
http_request = atom.http_core.HttpRequest()
if self.host is not None and http_request.uri.host is None:
http_request.uri.host = self.host
if self.xoauth_requestor_id is not None:
http_request.uri.query['xoauth_requestor_id'] = self.xoauth_requestor_id
# Set the user agent header for logging purposes.
if self.source:
http_request.headers['User-Agent'] = '%s gdata-py/2.0.16' % self.source
else:
http_request.headers['User-Agent'] = 'gdata-py/2.0.16'
return http_request
ModifyRequest = modify_request
class CustomHeaders(object):
"""Add custom headers to an http_request.
Usage:
>>> custom_headers = atom.client.CustomHeaders(header1='value1',
header2='value2')
>>> client.get(uri, custom_headers=custom_headers)
"""
def __init__(self, **kwargs):
"""Creates a CustomHeaders instance.
Initialize the headers dictionary with the arguments list.
"""
self.headers = kwargs
def modify_request(self, http_request):
"""Changes the HTTP request before sending it to the server.
Adds the custom headers to the HTTP request.
Args:
http_request: An atom.http_core.HttpRequest().
Returns:
An atom.http_core.HttpRequest() with the added custom headers.
"""
for name, value in self.headers.iteritems():
if value is not None:
http_request.headers[name] = value
return http_request
| 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.
"""HttpClients in this module use httplib to make HTTP requests.
This module make HTTP requests based on httplib, but there are environments
in which an httplib based approach will not work (if running in Google App
Engine for example). In those cases, higher level classes (like AtomService
and GDataService) can swap out the HttpClient to transparently use a
different mechanism for making HTTP requests.
HttpClient: Contains a request method which performs an HTTP call to the
server.
ProxiedHttpClient: Contains a request method which connects to a proxy using
settings stored in operating system environment variables then
performs an HTTP call to the endpoint server.
"""
__author__ = 'api.jscudder (Jeff Scudder)'
import types
import os
import httplib
import atom.url
import atom.http_interface
import socket
import base64
import atom.http_core
ssl_imported = False
ssl = None
try:
import ssl
ssl_imported = True
except ImportError:
pass
class ProxyError(atom.http_interface.Error):
pass
class TestConfigurationError(Exception):
pass
DEFAULT_CONTENT_TYPE = 'application/atom+xml'
class HttpClient(atom.http_interface.GenericHttpClient):
# Added to allow old v1 HttpClient objects to use the new
# http_code.HttpClient. Used in unit tests to inject a mock client.
v2_http_client = None
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)
# 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:
if isinstance(data, types.StringTypes):
all_headers['Content-Length'] = str(len(data))
else:
raise atom.http_interface.ContentLengthRequired('Unable to calculate '
'the length of the data parameter. Specify a value for '
'Content-Length')
# Set the content type to the default value if none was set.
if 'Content-Type' not in all_headers:
all_headers['Content-Type'] = DEFAULT_CONTENT_TYPE
if self.v2_http_client is not None:
http_request = atom.http_core.HttpRequest(method=operation)
atom.http_core.Uri.parse_uri(str(url)).modify_request(http_request)
http_request.headers = all_headers
if data:
http_request._body_parts.append(data)
return self.v2_http_client.request(http_request=http_request)
if not isinstance(url, atom.url.Url):
if isinstance(url, types.StringTypes):
url = atom.url.parse_url(url)
else:
raise atom.http_interface.UnparsableUrlObject('Unable to parse url '
'parameter because it was not a string or atom.url.Url')
connection = self._prepare_connection(url, all_headers)
if self.debug:
connection.debuglevel = 1
connection.putrequest(operation, self._get_access_url(url),
skip_host=True)
if url.port is not None:
connection.putheader('Host', '%s:%s' % (url.host, url.port))
else:
connection.putheader('Host', url.host)
# Overcome a bug in Python 2.4 and 2.5
# httplib.HTTPConnection.putrequest adding
# HTTP request header 'Host: www.google.com:443' instead of
# 'Host: www.google.com', and thus resulting the error message
# 'Token invalid - AuthSub token has wrong scope' in the HTTP response.
if (url.protocol == 'https' and int(url.port or 443) == 443 and
hasattr(connection, '_buffer') and
isinstance(connection._buffer, list)):
header_line = 'Host: %s:443' % url.host
replacement_header_line = 'Host: %s' % url.host
try:
connection._buffer[connection._buffer.index(header_line)] = (
replacement_header_line)
except ValueError: # header_line missing from connection._buffer
pass
# Send the HTTP headers.
for header_name in all_headers:
connection.putheader(header_name, all_headers[header_name])
connection.endheaders()
# If there is data, send it in the request.
if data:
if isinstance(data, list):
for data_part in data:
_send_data_part(data_part, connection)
else:
_send_data_part(data, connection)
# Return the HTTP Response from the server.
return connection.getresponse()
def _prepare_connection(self, url, headers):
if not isinstance(url, atom.url.Url):
if isinstance(url, types.StringTypes):
url = atom.url.parse_url(url)
else:
raise atom.http_interface.UnparsableUrlObject('Unable to parse url '
'parameter because it was not a string or atom.url.Url')
if url.protocol == 'https':
if not url.port:
return httplib.HTTPSConnection(url.host)
return httplib.HTTPSConnection(url.host, int(url.port))
else:
if not url.port:
return httplib.HTTPConnection(url.host)
return httplib.HTTPConnection(url.host, int(url.port))
def _get_access_url(self, url):
return url.to_string()
class ProxiedHttpClient(HttpClient):
"""Performs an HTTP request through a proxy.
The proxy settings are obtained from enviroment variables. The URL of the
proxy server is assumed to be stored in the environment variables
'https_proxy' and 'http_proxy' respectively. If the proxy server requires
a Basic Auth authorization header, the username and password are expected to
be in the 'proxy-username' or 'proxy_username' variable and the
'proxy-password' or 'proxy_password' variable, or in 'http_proxy' or
'https_proxy' as "protocol://[username:password@]host:port".
After connecting to the proxy server, the request is completed as in
HttpClient.request.
"""
def _prepare_connection(self, url, headers):
proxy_settings = os.environ.get('%s_proxy' % url.protocol)
if not proxy_settings:
# The request was HTTP or HTTPS, but there was no appropriate proxy set.
return HttpClient._prepare_connection(self, url, headers)
else:
proxy_auth = _get_proxy_auth(proxy_settings)
proxy_netloc = _get_proxy_net_location(proxy_settings)
if url.protocol == 'https':
# Set any proxy auth headers
if proxy_auth:
proxy_auth = 'Proxy-authorization: %s' % proxy_auth
# Construct the proxy connect command.
port = url.port
if not port:
port = '443'
proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (url.host, port)
# Set the user agent to send to the proxy
if headers and 'User-Agent' in headers:
user_agent = 'User-Agent: %s\r\n' % (headers['User-Agent'])
else:
user_agent = 'User-Agent: python\r\n'
proxy_pieces = '%s%s%s\r\n' % (proxy_connect, proxy_auth, user_agent)
# Find the proxy host and port.
proxy_url = atom.url.parse_url(proxy_netloc)
if not proxy_url.port:
proxy_url.port = '80'
# Connect to the proxy server, very simple recv and error checking
p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
p_sock.connect((proxy_url.host, int(proxy_url.port)))
p_sock.sendall(proxy_pieces)
response = ''
# Wait for the full response.
while response.find("\r\n\r\n") == -1:
response += p_sock.recv(8192)
p_status = response.split()[1]
if p_status != str(200):
raise ProxyError('Error status=%s' % str(p_status))
# Trivial setup for ssl socket.
sslobj = None
if ssl_imported:
sslobj = ssl.wrap_socket(p_sock, None, None)
else:
sock_ssl = socket.ssl(p_sock, None, None)
sslobj = httplib.FakeSocket(p_sock, sock_ssl)
# Initalize httplib and replace with the proxy socket.
connection = httplib.HTTPConnection(proxy_url.host)
connection.sock = sslobj
return connection
else:
# If protocol was not https.
# Find the proxy host and port.
proxy_url = atom.url.parse_url(proxy_netloc)
if not proxy_url.port:
proxy_url.port = '80'
if proxy_auth:
headers['Proxy-Authorization'] = proxy_auth.strip()
return httplib.HTTPConnection(proxy_url.host, int(proxy_url.port))
def _get_access_url(self, url):
return url.to_string()
def _get_proxy_auth(proxy_settings):
"""Returns proxy authentication string for header.
Will check environment variables for proxy authentication info, starting with
proxy(_/-)username and proxy(_/-)password before checking the given
proxy_settings for a [protocol://]username:password@host[:port] string.
Args:
proxy_settings: String from http_proxy or https_proxy environment variable.
Returns:
Authentication string for proxy, or empty string if no proxy username was
found.
"""
proxy_username = None
proxy_password = None
proxy_username = os.environ.get('proxy-username')
if not proxy_username:
proxy_username = os.environ.get('proxy_username')
proxy_password = os.environ.get('proxy-password')
if not proxy_password:
proxy_password = os.environ.get('proxy_password')
if not proxy_username:
if '@' in proxy_settings:
protocol_and_proxy_auth = proxy_settings.split('@')[0].split(':')
if len(protocol_and_proxy_auth) == 3:
# 3 elements means we have [<protocol>, //<user>, <password>]
proxy_username = protocol_and_proxy_auth[1].lstrip('/')
proxy_password = protocol_and_proxy_auth[2]
elif len(protocol_and_proxy_auth) == 2:
# 2 elements means we have [<user>, <password>]
proxy_username = protocol_and_proxy_auth[0]
proxy_password = protocol_and_proxy_auth[1]
if proxy_username:
user_auth = base64.encodestring('%s:%s' % (proxy_username,
proxy_password))
return 'Basic %s\r\n' % (user_auth.strip())
else:
return ''
def _get_proxy_net_location(proxy_settings):
"""Returns proxy host and port.
Args:
proxy_settings: String from http_proxy or https_proxy environment variable.
Must be in the form of protocol://[username:password@]host:port
Returns:
String in the form of protocol://host:port
"""
if '@' in proxy_settings:
protocol = proxy_settings.split(':')[0]
netloc = proxy_settings.split('@')[1]
return '%s://%s' % (protocol, netloc)
else:
return proxy_settings
def _send_data_part(data, connection):
if isinstance(data, types.StringTypes):
connection.send(data)
return
# Check to see if data is a file-like object that has a read method.
elif hasattr(data, 'read'):
# Read the file and send it a chunk at a time.
while 1:
binarydata = data.read(100000)
if binarydata == '': break
connection.send(binarydata)
return
else:
# The data object was not a file.
# Try to convert to a string and send the data.
connection.send(str(data))
return
| 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.
__author__ = 'j.s@google.com (Jeff Scudder)'
import StringIO
import pickle
import os.path
import tempfile
import atom.http_core
class Error(Exception):
pass
class NoRecordingFound(Error):
pass
class MockHttpClient(object):
debug = None
real_client = None
last_request_was_live = False
# The following members are used to construct the session cache temp file
# name.
# These are combined to form the file name
# /tmp/cache_prefix.cache_case_name.cache_test_name
cache_name_prefix = 'gdata_live_test'
cache_case_name = ''
cache_test_name = ''
def __init__(self, recordings=None, real_client=None):
self._recordings = recordings or []
if real_client is not None:
self.real_client = real_client
def add_response(self, http_request, status, reason, headers=None,
body=None):
response = MockHttpResponse(status, reason, headers, body)
# TODO Scrub the request and the response.
self._recordings.append((http_request._copy(), response))
AddResponse = add_response
def request(self, http_request):
"""Provide a recorded response, or record a response for replay.
If the real_client is set, the request will be made using the
real_client, and the response from the server will be recorded.
If the real_client is None (the default), this method will examine
the recordings and find the first which matches.
"""
request = http_request._copy()
_scrub_request(request)
if self.real_client is None:
self.last_request_was_live = False
for recording in self._recordings:
if _match_request(recording[0], request):
return recording[1]
else:
# Pass along the debug settings to the real client.
self.real_client.debug = self.debug
# Make an actual request since we can use the real HTTP client.
self.last_request_was_live = True
response = self.real_client.request(http_request)
scrubbed_response = _scrub_response(response)
self.add_response(request, scrubbed_response.status,
scrubbed_response.reason,
dict(atom.http_core.get_headers(scrubbed_response)),
scrubbed_response.read())
# Return the recording which we just added.
return self._recordings[-1][1]
raise NoRecordingFound('No recoding was found for request: %s %s' % (
request.method, str(request.uri)))
Request = request
def _save_recordings(self, filename):
recording_file = open(os.path.join(tempfile.gettempdir(), filename),
'wb')
pickle.dump(self._recordings, recording_file)
recording_file.close()
def _load_recordings(self, filename):
recording_file = open(os.path.join(tempfile.gettempdir(), filename),
'rb')
self._recordings = pickle.load(recording_file)
recording_file.close()
def _delete_recordings(self, filename):
full_path = os.path.join(tempfile.gettempdir(), filename)
if os.path.exists(full_path):
os.remove(full_path)
def _load_or_use_client(self, filename, http_client):
if os.path.exists(os.path.join(tempfile.gettempdir(), filename)):
self._load_recordings(filename)
else:
self.real_client = http_client
def use_cached_session(self, name=None, real_http_client=None):
"""Attempts to load recordings from a previous live request.
If a temp file with the recordings exists, then it is used to fulfill
requests. If the file does not exist, then a real client is used to
actually make the desired HTTP requests. Requests and responses are
recorded and will be written to the desired temprary cache file when
close_session is called.
Args:
name: str (optional) The file name of session file to be used. The file
is loaded from the temporary directory of this machine. If no name
is passed in, a default name will be constructed using the
cache_name_prefix, cache_case_name, and cache_test_name of this
object.
real_http_client: atom.http_core.HttpClient the real client to be used
if the cached recordings are not found. If the default
value is used, this will be an
atom.http_core.HttpClient.
"""
if real_http_client is None:
real_http_client = atom.http_core.HttpClient()
if name is None:
self._recordings_cache_name = self.get_cache_file_name()
else:
self._recordings_cache_name = name
self._load_or_use_client(self._recordings_cache_name, real_http_client)
def close_session(self):
"""Saves recordings in the temporary file named in use_cached_session."""
if self.real_client is not None:
self._save_recordings(self._recordings_cache_name)
def delete_session(self, name=None):
"""Removes recordings from a previous live request."""
if name is None:
self._delete_recordings(self._recordings_cache_name)
else:
self._delete_recordings(name)
def get_cache_file_name(self):
return '%s.%s.%s' % (self.cache_name_prefix, self.cache_case_name,
self.cache_test_name)
def _dump(self):
"""Provides debug information in a string."""
output = 'MockHttpClient\n real_client: %s\n cache file name: %s\n' % (
self.real_client, self.get_cache_file_name())
output += ' recordings:\n'
i = 0
for recording in self._recordings:
output += ' recording %i is for: %s %s\n' % (
i, recording[0].method, str(recording[0].uri))
i += 1
return output
def _match_request(http_request, stored_request):
"""Determines whether a request is similar enough to a stored request
to cause the stored response to be returned."""
# Check to see if the host names match.
if (http_request.uri.host is not None
and http_request.uri.host != stored_request.uri.host):
return False
# Check the request path in the URL (/feeds/private/full/x)
elif http_request.uri.path != stored_request.uri.path:
return False
# Check the method used in the request (GET, POST, etc.)
elif http_request.method != stored_request.method:
return False
# If there is a gsession ID in either request, make sure that it is matched
# exactly.
elif ('gsessionid' in http_request.uri.query
or 'gsessionid' in stored_request.uri.query):
if 'gsessionid' not in stored_request.uri.query:
return False
elif 'gsessionid' not in http_request.uri.query:
return False
elif (http_request.uri.query['gsessionid']
!= stored_request.uri.query['gsessionid']):
return False
# Ignores differences in the query params (?start-index=5&max-results=20),
# the body of the request, the port number, HTTP headers, just to name a
# few.
return True
def _scrub_request(http_request):
""" Removes email address and password from a client login request.
Since the mock server saves the request and response in plantext, sensitive
information like the password should be removed before saving the
recordings. At the moment only requests sent to a ClientLogin url are
scrubbed.
"""
if (http_request and http_request.uri and http_request.uri.path and
http_request.uri.path.endswith('ClientLogin')):
# Remove the email and password from a ClientLogin request.
http_request._body_parts = []
http_request.add_form_inputs(
{'form_data': 'client login request has been scrubbed'})
else:
# We can remove the body of the post from the recorded request, since
# the request body is not used when finding a matching recording.
http_request._body_parts = []
return http_request
def _scrub_response(http_response):
return http_response
class EchoHttpClient(object):
"""Sends the request data back in the response.
Used to check the formatting of the request as it was sent. Always responds
with a 200 OK, and some information from the HTTP request is returned in
special Echo-X headers in the response. The following headers are added
in the response:
'Echo-Host': The host name and port number to which the HTTP connection is
made. If no port was passed in, the header will contain
host:None.
'Echo-Uri': The path portion of the URL being requested. /example?x=1&y=2
'Echo-Scheme': The beginning of the URL, usually 'http' or 'https'
'Echo-Method': The HTTP method being used, 'GET', 'POST', 'PUT', etc.
"""
def request(self, http_request):
return self._http_request(http_request.uri, http_request.method,
http_request.headers, http_request._body_parts)
def _http_request(self, uri, method, headers=None, body_parts=None):
body = StringIO.StringIO()
response = atom.http_core.HttpResponse(status=200, reason='OK', body=body)
if headers is None:
response._headers = {}
else:
# Copy headers from the request to the response but convert values to
# strings. Server response headers always come in as strings, so an int
# should be converted to a corresponding string when echoing.
for header, value in headers.iteritems():
response._headers[header] = str(value)
response._headers['Echo-Host'] = '%s:%s' % (uri.host, str(uri.port))
response._headers['Echo-Uri'] = uri._get_relative_path()
response._headers['Echo-Scheme'] = uri.scheme
response._headers['Echo-Method'] = method
for part in body_parts:
if isinstance(part, str):
body.write(part)
elif hasattr(part, 'read'):
body.write(part.read())
body.seek(0)
return response
class SettableHttpClient(object):
"""An HTTP Client which responds with the data given in set_response."""
def __init__(self, status, reason, body, headers):
"""Configures the response for the server.
See set_response for details on the arguments to the constructor.
"""
self.set_response(status, reason, body, headers)
self.last_request = None
def set_response(self, status, reason, body, headers):
"""Determines the response which will be sent for each request.
Args:
status: An int for the HTTP status code, example: 200, 404, etc.
reason: String for the HTTP reason, example: OK, NOT FOUND, etc.
body: The body of the HTTP response as a string or a file-like
object (something with a read method).
headers: dict of strings containing the HTTP headers in the response.
"""
self.response = atom.http_core.HttpResponse(status=status, reason=reason,
body=body)
self.response._headers = headers.copy()
def request(self, http_request):
self.last_request = http_request
return self.response
class MockHttpResponse(atom.http_core.HttpResponse):
def __init__(self, status=None, reason=None, headers=None, body=None):
self._headers = headers or {}
if status is not None:
self.status = status
if reason is not None:
self.reason = reason
if body is not None:
# Instead of using a file-like object for the body, store as a string
# so that reads can be repeated.
if hasattr(body, 'read'):
self._body = body.read()
else:
self._body = body
def read(self):
return self._body
| 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.
"""MockService provides CRUD ops. for mocking calls to AtomPub services.
MockService: Exposes the publicly used methods of AtomService to provide
a mock interface which can be used in unit tests.
"""
import atom.service
import pickle
__author__ = 'api.jscudder (Jeffrey Scudder)'
# Recordings contains pairings of HTTP MockRequest objects with MockHttpResponse objects.
recordings = []
# If set, the mock service HttpRequest are actually made through this object.
real_request_handler = None
def ConcealValueWithSha(source):
import sha
return sha.new(source[:-5]).hexdigest()
def DumpRecordings(conceal_func=ConcealValueWithSha):
if conceal_func:
for recording_pair in recordings:
recording_pair[0].ConcealSecrets(conceal_func)
return pickle.dumps(recordings)
def LoadRecordings(recordings_file_or_string):
if isinstance(recordings_file_or_string, str):
atom.mock_service.recordings = pickle.loads(recordings_file_or_string)
elif hasattr(recordings_file_or_string, 'read'):
atom.mock_service.recordings = pickle.loads(
recordings_file_or_string.read())
def HttpRequest(service, operation, data, uri, extra_headers=None,
url_params=None, escape_params=True, content_type='application/atom+xml'):
"""Simulates an HTTP call to the server, makes an actual HTTP request if
real_request_handler is set.
This function operates in two different modes depending on if
real_request_handler is set or not. If real_request_handler is not set,
HttpRequest will look in this module's recordings list to find a response
which matches the parameters in the function call. If real_request_handler
is set, this function will call real_request_handler.HttpRequest, add the
response to the recordings list, and respond with the actual response.
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: ElementTree, 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, uri) = atom.service.ProcessUrl(service, uri)
current_request = MockRequest(operation, full_uri, host=server, ssl=ssl,
data=data, extra_headers=extra_headers, url_params=url_params,
escape_params=escape_params, content_type=content_type)
# If the request handler is set, we should actually make the request using
# the request handler and record the response to replay later.
if real_request_handler:
response = real_request_handler.HttpRequest(service, operation, data, uri,
extra_headers=extra_headers, url_params=url_params,
escape_params=escape_params, content_type=content_type)
# TODO: need to copy the HTTP headers from the real response into the
# recorded_response.
recorded_response = MockHttpResponse(body=response.read(),
status=response.status, reason=response.reason)
# Insert a tuple which maps the request to the response object returned
# when making an HTTP call using the real_request_handler.
recordings.append((current_request, recorded_response))
return recorded_response
else:
# Look through available recordings to see if one matches the current
# request.
for request_response_pair in recordings:
if request_response_pair[0].IsMatch(current_request):
return request_response_pair[1]
return None
class MockRequest(object):
"""Represents a request made to an AtomPub server.
These objects are used to determine if a client request matches a recorded
HTTP request to determine what the mock server's response will be.
"""
def __init__(self, operation, uri, host=None, ssl=False, port=None,
data=None, extra_headers=None, url_params=None, escape_params=True,
content_type='application/atom+xml'):
"""Constructor for a MockRequest
Args:
operation: str One of 'GET', 'POST', 'PUT', or 'DELETE' this is the
HTTP operation requested on the resource.
uri: str The URL describing the resource to be modified or feed to be
retrieved. This should include the protocol (http/https) and the host
(aka domain). For example, these are some valud full_uris:
'http://example.com', 'https://www.google.com/accounts/ClientLogin'
host: str (optional) The server name which will be placed at the
beginning of the URL if the uri parameter does not begin with 'http'.
Examples include 'example.com', 'www.google.com', 'www.blogger.com'.
ssl: boolean (optional) If true, the request URL will begin with https
instead of http.
data: ElementTree, filestream, list of parts, or other object which can be
converted to a string. (optional)
Should be set to None when performing a GET or PUT.
If data is a file-like object which can be read, the constructor
will read the entire file into memory. If the data is a list of
parts to be sent, each part will be evaluated and stored.
extra_headers: dict (optional) HTTP headers included in the request.
url_params: dict (optional) Key value pairs which should be added to
the URL as URL parameters in the request. For example uri='/',
url_parameters={'foo':'1','bar':'2'} could become '/?foo=1&bar=2'.
escape_params: boolean (optional) Perform URL escaping on the keys and
values specified in url_params. Defaults to True.
content_type: str (optional) Provides the MIME type of the data being
sent.
"""
self.operation = operation
self.uri = _ConstructFullUrlBase(uri, host=host, ssl=ssl)
self.data = data
self.extra_headers = extra_headers
self.url_params = url_params or {}
self.escape_params = escape_params
self.content_type = content_type
def ConcealSecrets(self, conceal_func):
"""Conceal secret data in this request."""
if self.extra_headers.has_key('Authorization'):
self.extra_headers['Authorization'] = conceal_func(
self.extra_headers['Authorization'])
def IsMatch(self, other_request):
"""Check to see if the other_request is equivalent to this request.
Used to determine if a recording matches an incoming request so that a
recorded response should be sent to the client.
The matching is not exact, only the operation and URL are examined
currently.
Args:
other_request: MockRequest The request which we want to check this
(self) MockRequest against to see if they are equivalent.
"""
# More accurate matching logic will likely be required.
return (self.operation == other_request.operation and self.uri ==
other_request.uri)
def _ConstructFullUrlBase(uri, host=None, ssl=False):
"""Puts URL components into the form http(s)://full.host.strinf/uri/path
Used to construct a roughly canonical URL so that URLs which begin with
'http://example.com/' can be compared to a uri of '/' when the host is
set to 'example.com'
If the uri contains 'http://host' already, the host and ssl parameters
are ignored.
Args:
uri: str The path component of the URL, examples include '/'
host: str (optional) The host name which should prepend the URL. Example:
'example.com'
ssl: boolean (optional) If true, the returned URL will begin with https
instead of http.
Returns:
String which has the form http(s)://example.com/uri/string/contents
"""
if uri.startswith('http'):
return uri
if ssl:
return 'https://%s%s' % (host, uri)
else:
return 'http://%s%s' % (host, uri)
class MockHttpResponse(object):
"""Returned from MockService crud methods as the server's response."""
def __init__(self, body=None, status=None, reason=None, headers=None):
"""Construct a mock HTTPResponse and set members.
Args:
body: str (optional) The HTTP body of the server's response.
status: int (optional)
reason: str (optional)
headers: dict (optional)
"""
self.body = body
self.status = status
self.reason = reason
self.headers = headers or {}
def read(self):
return self.body
def getheader(self, header_name):
return self.headers[header_name]
| 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.
"""This module provides a TokenStore class which is designed to manage
auth tokens required for different services.
Each token is valid for a set of scopes which is the start of a URL. An HTTP
client will use a token store to find a valid Authorization header to send
in requests to the specified URL. If the HTTP client determines that a token
has expired or been revoked, it can remove the token from the store so that
it will not be used in future requests.
"""
__author__ = 'api.jscudder (Jeff Scudder)'
import atom.http_interface
import atom.url
SCOPE_ALL = 'http'
class TokenStore(object):
"""Manages Authorization tokens which will be sent in HTTP headers."""
def __init__(self, scoped_tokens=None):
self._tokens = scoped_tokens or {}
def add_token(self, token):
"""Adds a new token to the store (replaces tokens with the same scope).
Args:
token: A subclass of http_interface.GenericToken. The token object is
responsible for adding the Authorization header to the HTTP request.
The scopes defined in the token are used to determine if the token
is valid for a requested scope when find_token is called.
Returns:
True if the token was added, False if the token was not added becase
no scopes were provided.
"""
if not hasattr(token, 'scopes') or not token.scopes:
return False
for scope in token.scopes:
self._tokens[str(scope)] = token
return True
def find_token(self, url):
"""Selects an Authorization header token which can be used for the URL.
Args:
url: str or atom.url.Url or a list containing the same.
The URL which is going to be requested. All
tokens are examined to see if any scopes begin match the beginning
of the URL. The first match found is returned.
Returns:
The token object which should execute the HTTP request. If there was
no token for the url (the url did not begin with any of the token
scopes available), then the atom.http_interface.GenericToken will be
returned because the GenericToken calls through to the http client
without adding an Authorization header.
"""
if url is None:
return None
if isinstance(url, (str, unicode)):
url = atom.url.parse_url(url)
if url in self._tokens:
token = self._tokens[url]
if token.valid_for_scope(url):
return token
else:
del self._tokens[url]
for scope, token in self._tokens.iteritems():
if token.valid_for_scope(url):
return token
return atom.http_interface.GenericToken()
def remove_token(self, token):
"""Removes the token from the token_store.
This method is used when a token is determined to be invalid. If the
token was found by find_token, but resulted in a 401 or 403 error stating
that the token was invlid, then the token should be removed to prevent
future use.
Returns:
True if a token was found and then removed from the token
store. False if the token was not in the TokenStore.
"""
token_found = False
scopes_to_delete = []
for scope, stored_token in self._tokens.iteritems():
if stored_token == token:
scopes_to_delete.append(scope)
token_found = True
for scope in scopes_to_delete:
del self._tokens[scope]
return token_found
def remove_all_tokens(self):
self._tokens = {}
| 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 (Jeff Scudder)'
import urlparse
import urllib
DEFAULT_PROTOCOL = 'http'
DEFAULT_PORT = 80
def parse_url(url_string):
"""Creates a Url object which corresponds to the URL string.
This method can accept partial URLs, but it will leave missing
members of the Url unset.
"""
parts = urlparse.urlparse(url_string)
url = Url()
if parts[0]:
url.protocol = parts[0]
if parts[1]:
host_parts = parts[1].split(':')
if host_parts[0]:
url.host = host_parts[0]
if len(host_parts) > 1:
url.port = host_parts[1]
if parts[2]:
url.path = parts[2]
if parts[4]:
param_pairs = parts[4].split('&')
for pair in param_pairs:
pair_parts = pair.split('=')
if len(pair_parts) > 1:
url.params[urllib.unquote_plus(pair_parts[0])] = (
urllib.unquote_plus(pair_parts[1]))
elif len(pair_parts) == 1:
url.params[urllib.unquote_plus(pair_parts[0])] = None
return url
class Url(object):
"""Represents a URL and implements comparison logic.
URL strings which are not identical can still be equivalent, so this object
provides a better interface for comparing and manipulating URLs than
strings. URL parameters are represented as a dictionary of strings, and
defaults are used for the protocol (http) and port (80) if not provided.
"""
def __init__(self, protocol=None, host=None, port=None, path=None,
params=None):
self.protocol = protocol
self.host = host
self.port = port
self.path = path
self.params = params or {}
def to_string(self):
url_parts = ['', '', '', '', '', '']
if self.protocol:
url_parts[0] = self.protocol
if self.host:
if self.port:
url_parts[1] = ':'.join((self.host, str(self.port)))
else:
url_parts[1] = self.host
if self.path:
url_parts[2] = self.path
if self.params:
url_parts[4] = self.get_param_string()
return urlparse.urlunparse(url_parts)
def get_param_string(self):
param_pairs = []
for key, value in self.params.iteritems():
param_pairs.append('='.join((urllib.quote_plus(key),
urllib.quote_plus(str(value)))))
return '&'.join(param_pairs)
def get_request_uri(self):
"""Returns the path with the parameters escaped and appended."""
param_string = self.get_param_string()
if param_string:
return '?'.join([self.path, param_string])
else:
return self.path
def __cmp__(self, other):
if not isinstance(other, Url):
return cmp(self.to_string(), str(other))
difference = 0
# Compare the protocol
if self.protocol and other.protocol:
difference = cmp(self.protocol, other.protocol)
elif self.protocol and not other.protocol:
difference = cmp(self.protocol, DEFAULT_PROTOCOL)
elif not self.protocol and other.protocol:
difference = cmp(DEFAULT_PROTOCOL, other.protocol)
if difference != 0:
return difference
# Compare the host
difference = cmp(self.host, other.host)
if difference != 0:
return difference
# Compare the port
if self.port and other.port:
difference = cmp(self.port, other.port)
elif self.port and not other.port:
difference = cmp(self.port, DEFAULT_PORT)
elif not self.port and other.port:
difference = cmp(DEFAULT_PORT, other.port)
if difference != 0:
return difference
# Compare the path
difference = cmp(self.path, other.path)
if difference != 0:
return difference
# Compare the parameters
return cmp(self.params, other.params)
def __str__(self):
return self.to_string()
| 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.
# TODO: add proxy handling.
__author__ = 'j.s@google.com (Jeff Scudder)'
import os
import StringIO
import urlparse
import urllib
import httplib
ssl = None
try:
import ssl
except ImportError:
pass
class Error(Exception):
pass
class UnknownSize(Error):
pass
class ProxyError(Error):
pass
MIME_BOUNDARY = 'END_OF_PART'
def get_headers(http_response):
"""Retrieves all HTTP headers from an HTTP response from the server.
This method is provided for backwards compatibility for Python2.2 and 2.3.
The httplib.HTTPResponse object in 2.2 and 2.3 does not have a getheaders
method so this function will use getheaders if available, but if not it
will retrieve a few using getheader.
"""
if hasattr(http_response, 'getheaders'):
return http_response.getheaders()
else:
headers = []
for header in (
'location', 'content-type', 'content-length', 'age', 'allow',
'cache-control', 'content-location', 'content-encoding', 'date',
'etag', 'expires', 'last-modified', 'pragma', 'server',
'set-cookie', 'transfer-encoding', 'vary', 'via', 'warning',
'www-authenticate', 'gdata-version'):
value = http_response.getheader(header, None)
if value is not None:
headers.append((header, value))
return headers
class HttpRequest(object):
"""Contains all of the parameters for an HTTP 1.1 request.
The HTTP headers are represented by a dictionary, and it is the
responsibility of the user to ensure that duplicate field names are combined
into one header value according to the rules in section 4.2 of RFC 2616.
"""
method = None
uri = None
def __init__(self, uri=None, method=None, headers=None):
"""Construct an HTTP request.
Args:
uri: The full path or partial path as a Uri object or a string.
method: The HTTP method for the request, examples include 'GET', 'POST',
etc.
headers: dict of strings The HTTP headers to include in the request.
"""
self.headers = headers or {}
self._body_parts = []
if method is not None:
self.method = method
if isinstance(uri, (str, unicode)):
uri = Uri.parse_uri(uri)
self.uri = uri or Uri()
def add_body_part(self, data, mime_type, size=None):
"""Adds data to the HTTP request body.
If more than one part is added, this is assumed to be a mime-multipart
request. This method is designed to create MIME 1.0 requests as specified
in RFC 1341.
Args:
data: str or a file-like object containing a part of the request body.
mime_type: str The MIME type describing the data
size: int Required if the data is a file like object. If the data is a
string, the size is calculated so this parameter is ignored.
"""
if isinstance(data, str):
size = len(data)
if size is None:
# TODO: support chunked transfer if some of the body is of unknown size.
raise UnknownSize('Each part of the body must have a known size.')
if 'Content-Length' in self.headers:
content_length = int(self.headers['Content-Length'])
else:
content_length = 0
# If this is the first part added to the body, then this is not a multipart
# request.
if len(self._body_parts) == 0:
self.headers['Content-Type'] = mime_type
content_length = size
self._body_parts.append(data)
elif len(self._body_parts) == 1:
# This is the first member in a mime-multipart request, so change the
# _body_parts list to indicate a multipart payload.
self._body_parts.insert(0, 'Media multipart posting')
boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,)
content_length += len(boundary_string) + size
self._body_parts.insert(1, boundary_string)
content_length += len('Media multipart posting')
# Put the content type of the first part of the body into the multipart
# payload.
original_type_string = 'Content-Type: %s\r\n\r\n' % (
self.headers['Content-Type'],)
self._body_parts.insert(2, original_type_string)
content_length += len(original_type_string)
boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,)
self._body_parts.append(boundary_string)
content_length += len(boundary_string)
# Change the headers to indicate this is now a mime multipart request.
self.headers['Content-Type'] = 'multipart/related; boundary="%s"' % (
MIME_BOUNDARY,)
self.headers['MIME-version'] = '1.0'
# Include the mime type of this part.
type_string = 'Content-Type: %s\r\n\r\n' % (mime_type)
self._body_parts.append(type_string)
content_length += len(type_string)
self._body_parts.append(data)
ending_boundary_string = '\r\n--%s--' % (MIME_BOUNDARY,)
self._body_parts.append(ending_boundary_string)
content_length += len(ending_boundary_string)
else:
# This is a mime multipart request.
boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,)
self._body_parts.insert(-1, boundary_string)
content_length += len(boundary_string) + size
# Include the mime type of this part.
type_string = 'Content-Type: %s\r\n\r\n' % (mime_type)
self._body_parts.insert(-1, type_string)
content_length += len(type_string)
self._body_parts.insert(-1, data)
self.headers['Content-Length'] = str(content_length)
# I could add an "append_to_body_part" method as well.
AddBodyPart = add_body_part
def add_form_inputs(self, form_data,
mime_type='application/x-www-form-urlencoded'):
"""Form-encodes and adds data to the request body.
Args:
form_data: dict or sequnce or two member tuples which contains the
form keys and values.
mime_type: str The MIME type of the form data being sent. Defaults
to 'application/x-www-form-urlencoded'.
"""
body = urllib.urlencode(form_data)
self.add_body_part(body, mime_type)
AddFormInputs = add_form_inputs
def _copy(self):
"""Creates a deep copy of this request."""
copied_uri = Uri(self.uri.scheme, self.uri.host, self.uri.port,
self.uri.path, self.uri.query.copy())
new_request = HttpRequest(uri=copied_uri, method=self.method,
headers=self.headers.copy())
new_request._body_parts = self._body_parts[:]
return new_request
def _dump(self):
"""Converts to a printable string for debugging purposes.
In order to preserve the request, it does not read from file-like objects
in the body.
"""
output = 'HTTP Request\n method: %s\n url: %s\n headers:\n' % (
self.method, str(self.uri))
for header, value in self.headers.iteritems():
output += ' %s: %s\n' % (header, value)
output += ' body sections:\n'
i = 0
for part in self._body_parts:
if isinstance(part, (str, unicode)):
output += ' %s: %s\n' % (i, part)
else:
output += ' %s: <file like object>\n' % i
i += 1
return output
def _apply_defaults(http_request):
if http_request.uri.scheme is None:
if http_request.uri.port == 443:
http_request.uri.scheme = 'https'
else:
http_request.uri.scheme = 'http'
class Uri(object):
"""A URI as used in HTTP 1.1"""
scheme = None
host = None
port = None
path = None
def __init__(self, scheme=None, host=None, port=None, path=None, query=None):
"""Constructor for a URI.
Args:
scheme: str This is usually 'http' or 'https'.
host: str The host name or IP address of the desired server.
post: int The server's port number.
path: str The path of the resource following the host. This begins with
a /, example: '/calendar/feeds/default/allcalendars/full'
query: dict of strings The URL query parameters. The keys and values are
both escaped so this dict should contain the unescaped values.
For example {'my key': 'val', 'second': '!!!'} will become
'?my+key=val&second=%21%21%21' which is appended to the path.
"""
self.query = query or {}
if scheme is not None:
self.scheme = scheme
if host is not None:
self.host = host
if port is not None:
self.port = port
if path:
self.path = path
def _get_query_string(self):
param_pairs = []
for key, value in self.query.iteritems():
param_pairs.append('='.join((urllib.quote_plus(key),
urllib.quote_plus(str(value)))))
return '&'.join(param_pairs)
def _get_relative_path(self):
"""Returns the path with the query parameters escaped and appended."""
param_string = self._get_query_string()
if self.path is None:
path = '/'
else:
path = self.path
if param_string:
return '?'.join([path, param_string])
else:
return path
def _to_string(self):
if self.scheme is None and self.port == 443:
scheme = 'https'
elif self.scheme is None:
scheme = 'http'
else:
scheme = self.scheme
if self.path is None:
path = '/'
else:
path = self.path
if self.port is None:
return '%s://%s%s' % (scheme, self.host, self._get_relative_path())
else:
return '%s://%s:%s%s' % (scheme, self.host, str(self.port),
self._get_relative_path())
def __str__(self):
return self._to_string()
def modify_request(self, http_request=None):
"""Sets HTTP request components based on the URI."""
if http_request is None:
http_request = HttpRequest()
if http_request.uri is None:
http_request.uri = Uri()
# Determine the correct scheme.
if self.scheme:
http_request.uri.scheme = self.scheme
if self.port:
http_request.uri.port = self.port
if self.host:
http_request.uri.host = self.host
# Set the relative uri path
if self.path:
http_request.uri.path = self.path
if self.query:
http_request.uri.query = self.query.copy()
return http_request
ModifyRequest = modify_request
def parse_uri(uri_string):
"""Creates a Uri object which corresponds to the URI string.
This method can accept partial URIs, but it will leave missing
members of the Uri unset.
"""
parts = urlparse.urlparse(uri_string)
uri = Uri()
if parts[0]:
uri.scheme = parts[0]
if parts[1]:
host_parts = parts[1].split(':')
if host_parts[0]:
uri.host = host_parts[0]
if len(host_parts) > 1:
uri.port = int(host_parts[1])
if parts[2]:
uri.path = parts[2]
if parts[4]:
param_pairs = parts[4].split('&')
for pair in param_pairs:
pair_parts = pair.split('=')
if len(pair_parts) > 1:
uri.query[urllib.unquote_plus(pair_parts[0])] = (
urllib.unquote_plus(pair_parts[1]))
elif len(pair_parts) == 1:
uri.query[urllib.unquote_plus(pair_parts[0])] = None
return uri
parse_uri = staticmethod(parse_uri)
ParseUri = parse_uri
parse_uri = Uri.parse_uri
ParseUri = Uri.parse_uri
class HttpResponse(object):
status = None
reason = None
_body = None
def __init__(self, status=None, reason=None, headers=None, body=None):
self._headers = headers or {}
if status is not None:
self.status = status
if reason is not None:
self.reason = reason
if body is not None:
if hasattr(body, 'read'):
self._body = body
else:
self._body = StringIO.StringIO(body)
def getheader(self, name, default=None):
if name in self._headers:
return self._headers[name]
else:
return default
def getheaders(self):
return self._headers
def read(self, amt=None):
if self._body is None:
return None
if not amt:
return self._body.read()
else:
return self._body.read(amt)
def _dump_response(http_response):
"""Converts to a string for printing debug messages.
Does not read the body since that may consume the content.
"""
output = 'HttpResponse\n status: %s\n reason: %s\n headers:' % (
http_response.status, http_response.reason)
headers = get_headers(http_response)
if isinstance(headers, dict):
for header, value in headers.iteritems():
output += ' %s: %s\n' % (header, value)
else:
for pair in headers:
output += ' %s: %s\n' % (pair[0], pair[1])
return output
class HttpClient(object):
"""Performs HTTP requests using httplib."""
debug = None
def request(self, http_request):
return self._http_request(http_request.method, http_request.uri,
http_request.headers, http_request._body_parts)
Request = request
def _get_connection(self, uri, headers=None):
"""Opens a socket connection to the server to set up an HTTP request.
Args:
uri: The full URL for the request as a Uri object.
headers: A dict of string pairs containing the HTTP headers for the
request.
"""
connection = None
if uri.scheme == 'https':
if not uri.port:
connection = httplib.HTTPSConnection(uri.host)
else:
connection = httplib.HTTPSConnection(uri.host, int(uri.port))
else:
if not uri.port:
connection = httplib.HTTPConnection(uri.host)
else:
connection = httplib.HTTPConnection(uri.host, int(uri.port))
return connection
def _http_request(self, method, uri, headers=None, body_parts=None):
"""Makes an HTTP request using httplib.
Args:
method: str example: 'GET', 'POST', 'PUT', 'DELETE', etc.
uri: str or atom.http_core.Uri
headers: dict of strings mapping to strings which will be sent as HTTP
headers in the request.
body_parts: list of strings, objects with a read method, or objects
which can be converted to strings using str. Each of these
will be sent in order as the body of the HTTP request.
"""
if isinstance(uri, (str, unicode)):
uri = Uri.parse_uri(uri)
connection = self._get_connection(uri, headers=headers)
if self.debug:
connection.debuglevel = 1
if connection.host != uri.host:
connection.putrequest(method, str(uri))
else:
connection.putrequest(method, uri._get_relative_path())
# Overcome a bug in Python 2.4 and 2.5
# httplib.HTTPConnection.putrequest adding
# HTTP request header 'Host: www.google.com:443' instead of
# 'Host: www.google.com', and thus resulting the error message
# 'Token invalid - AuthSub token has wrong scope' in the HTTP response.
if (uri.scheme == 'https' and int(uri.port or 443) == 443 and
hasattr(connection, '_buffer') and
isinstance(connection._buffer, list)):
header_line = 'Host: %s:443' % uri.host
replacement_header_line = 'Host: %s' % uri.host
try:
connection._buffer[connection._buffer.index(header_line)] = (
replacement_header_line)
except ValueError: # header_line missing from connection._buffer
pass
# Send the HTTP headers.
for header_name, value in headers.iteritems():
connection.putheader(header_name, value)
connection.endheaders()
# If there is data, send it in the request.
if body_parts and filter(lambda x: x != '', body_parts):
for part in body_parts:
_send_data_part(part, connection)
# Return the HTTP Response from the server.
return connection.getresponse()
def _send_data_part(data, connection):
if isinstance(data, (str, unicode)):
# I might want to just allow str, not unicode.
connection.send(data)
return
# Check to see if data is a file-like object that has a read method.
elif hasattr(data, 'read'):
# Read the file and send it a chunk at a time.
while 1:
binarydata = data.read(100000)
if binarydata == '': break
connection.send(binarydata)
return
else:
# The data object was not a file.
# Try to convert to a string and send the data.
connection.send(str(data))
return
class ProxiedHttpClient(HttpClient):
def _get_connection(self, uri, headers=None):
# Check to see if there are proxy settings required for this request.
proxy = None
if uri.scheme == 'https':
proxy = os.environ.get('https_proxy')
elif uri.scheme == 'http':
proxy = os.environ.get('http_proxy')
if not proxy:
return HttpClient._get_connection(self, uri, headers=headers)
# Now we have the URL of the appropriate proxy server.
# Get a username and password for the proxy if required.
proxy_auth = _get_proxy_auth()
if uri.scheme == 'https':
import socket
if proxy_auth:
proxy_auth = 'Proxy-authorization: %s' % proxy_auth
# Construct the proxy connect command.
port = uri.port
if not port:
port = 443
proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (uri.host, port)
# Set the user agent to send to the proxy
user_agent = ''
if headers and 'User-Agent' in headers:
user_agent = 'User-Agent: %s\r\n' % (headers['User-Agent'])
proxy_pieces = '%s%s%s\r\n' % (proxy_connect, proxy_auth, user_agent)
# Find the proxy host and port.
proxy_uri = Uri.parse_uri(proxy)
if not proxy_uri.port:
proxy_uri.port = '80'
# Connect to the proxy server, very simple recv and error checking
p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
p_sock.connect((proxy_uri.host, int(proxy_uri.port)))
p_sock.sendall(proxy_pieces)
response = ''
# Wait for the full response.
while response.find("\r\n\r\n") == -1:
response += p_sock.recv(8192)
p_status = response.split()[1]
if p_status != str(200):
raise ProxyError('Error status=%s' % str(p_status))
# Trivial setup for ssl socket.
sslobj = None
if ssl is not None:
sslobj = ssl.wrap_socket(p_sock, None, None)
else:
sock_ssl = socket.ssl(p_sock, None, Nonesock_)
sslobj = httplib.FakeSocket(p_sock, sock_ssl)
# Initalize httplib and replace with the proxy socket.
connection = httplib.HTTPConnection(proxy_uri.host)
connection.sock = sslobj
return connection
elif uri.scheme == 'http':
proxy_uri = Uri.parse_uri(proxy)
if not proxy_uri.port:
proxy_uri.port = '80'
if proxy_auth:
headers['Proxy-Authorization'] = proxy_auth.strip()
return httplib.HTTPConnection(proxy_uri.host, int(proxy_uri.port))
return None
def _get_proxy_auth():
import base64
proxy_username = os.environ.get('proxy-username')
if not proxy_username:
proxy_username = os.environ.get('proxy_username')
proxy_password = os.environ.get('proxy-password')
if not proxy_password:
proxy_password = os.environ.get('proxy_password')
if proxy_username:
user_auth = base64.b64encode('%s:%s' % (proxy_username,
proxy_password))
return 'Basic %s\r\n' % (user_auth.strip())
else:
return ''
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains classes representing Atom elements.
Module objective: provide data classes for Atom constructs. These classes hide
the XML-ness of Atom and provide a set of native Python classes to interact
with.
Conversions to and from XML should only be necessary when the Atom classes
"touch the wire" and are sent over HTTP. For this reason this module
provides methods and functions to convert Atom classes to and from strings.
For more information on the Atom data model, see RFC 4287
(http://www.ietf.org/rfc/rfc4287.txt)
AtomBase: A foundation class on which Atom classes are built. It
handles the parsing of attributes and children which are common to all
Atom classes. By default, the AtomBase class translates all XML child
nodes into ExtensionElements.
ExtensionElement: Atom allows Atom objects to contain XML which is not part
of the Atom specification, these are called extension elements. If a
classes parser encounters an unexpected XML construct, it is translated
into an ExtensionElement instance. ExtensionElement is designed to fully
capture the information in the XML. Child nodes in an XML extension are
turned into ExtensionElements as well.
"""
__author__ = 'api.jscudder (Jeffrey Scudder)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import warnings
# XML namespaces which are often used in Atom entities.
ATOM_NAMESPACE = 'http://www.w3.org/2005/Atom'
ELEMENT_TEMPLATE = '{http://www.w3.org/2005/Atom}%s'
APP_NAMESPACE = 'http://purl.org/atom/app#'
APP_TEMPLATE = '{http://purl.org/atom/app#}%s'
# This encoding is used for converting strings before translating the XML
# into an object.
XML_STRING_ENCODING = 'utf-8'
# The desired string encoding for object members. set or monkey-patch to
# unicode if you want object members to be Python unicode strings, instead of
# encoded strings
MEMBER_STRING_ENCODING = 'utf-8'
#MEMBER_STRING_ENCODING = unicode
# If True, all methods which are exclusive to v1 will raise a
# DeprecationWarning
ENABLE_V1_WARNINGS = False
def v1_deprecated(warning=None):
"""Shows a warning if ENABLE_V1_WARNINGS is True.
Function decorator used to mark methods used in v1 classes which
may be removed in future versions of the library.
"""
warning = warning or ''
# This closure is what is returned from the deprecated function.
def mark_deprecated(f):
# The deprecated_function wraps the actual call to f.
def optional_warn_function(*args, **kwargs):
if ENABLE_V1_WARNINGS:
warnings.warn(warning, DeprecationWarning, stacklevel=2)
return f(*args, **kwargs)
# Preserve the original name to avoid masking all decorated functions as
# 'deprecated_function'
try:
optional_warn_function.func_name = f.func_name
except TypeError:
pass # In Python2.3 we can't set the func_name
return optional_warn_function
return mark_deprecated
def CreateClassFromXMLString(target_class, xml_string, string_encoding=None):
"""Creates an instance of the target class from the string contents.
Args:
target_class: class The class which will be instantiated and populated
with the contents of the XML. This class must have a _tag and a
_namespace class variable.
xml_string: str A string which contains valid XML. The root element
of the XML string should match the tag and namespace of the desired
class.
string_encoding: str The character encoding which the xml_string should
be converted to before it is interpreted and translated into
objects. The default is None in which case the string encoding
is not changed.
Returns:
An instance of the target class with members assigned according to the
contents of the XML - or None if the root XML tag and namespace did not
match those of the target class.
"""
encoding = string_encoding or XML_STRING_ENCODING
if encoding and isinstance(xml_string, unicode):
xml_string = xml_string.encode(encoding)
tree = ElementTree.fromstring(xml_string)
return _CreateClassFromElementTree(target_class, tree)
CreateClassFromXMLString = v1_deprecated(
'Please use atom.core.parse with atom.data classes instead.')(
CreateClassFromXMLString)
def _CreateClassFromElementTree(target_class, tree, namespace=None, tag=None):
"""Instantiates the class and populates members according to the tree.
Note: Only use this function with classes that have _namespace and _tag
class members.
Args:
target_class: class The class which will be instantiated and populated
with the contents of the XML.
tree: ElementTree An element tree whose contents will be converted into
members of the new target_class instance.
namespace: str (optional) The namespace which the XML tree's root node must
match. If omitted, the namespace defaults to the _namespace of the
target class.
tag: str (optional) The tag which the XML tree's root node must match. If
omitted, the tag defaults to the _tag class member of the target
class.
Returns:
An instance of the target class - or None if the tag and namespace of
the XML tree's root node did not match the desired namespace and tag.
"""
if namespace is None:
namespace = target_class._namespace
if tag is None:
tag = target_class._tag
if tree.tag == '{%s}%s' % (namespace, tag):
target = target_class()
target._HarvestElementTree(tree)
return target
else:
return None
class ExtensionContainer(object):
def __init__(self, extension_elements=None, extension_attributes=None,
text=None):
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
__init__ = v1_deprecated(
'Please use data model classes in atom.data instead.')(
__init__)
# Three methods to create an object from an ElementTree
def _HarvestElementTree(self, tree):
# Fill in the instance members from the contents of the XML tree.
for child in tree:
self._ConvertElementTreeToMember(child)
for attribute, value in tree.attrib.iteritems():
self._ConvertElementAttributeToMember(attribute, value)
# Encode the text string according to the desired encoding type. (UTF-8)
if tree.text:
if MEMBER_STRING_ENCODING is unicode:
self.text = tree.text
else:
self.text = tree.text.encode(MEMBER_STRING_ENCODING)
def _ConvertElementTreeToMember(self, child_tree, current_class=None):
self.extension_elements.append(_ExtensionElementFromElementTree(
child_tree))
def _ConvertElementAttributeToMember(self, attribute, value):
# Encode the attribute value's string with the desired type Default UTF-8
if value:
if MEMBER_STRING_ENCODING is unicode:
self.extension_attributes[attribute] = value
else:
self.extension_attributes[attribute] = value.encode(
MEMBER_STRING_ENCODING)
# One method to create an ElementTree from an object
def _AddMembersToElementTree(self, tree):
for child in self.extension_elements:
child._BecomeChildElement(tree)
for attribute, value in self.extension_attributes.iteritems():
if value:
if isinstance(value, unicode) or MEMBER_STRING_ENCODING is unicode:
tree.attrib[attribute] = value
else:
# Decode the value from the desired encoding (default UTF-8).
tree.attrib[attribute] = value.decode(MEMBER_STRING_ENCODING)
if self.text:
if isinstance(self.text, unicode) or MEMBER_STRING_ENCODING is unicode:
tree.text = self.text
else:
tree.text = self.text.decode(MEMBER_STRING_ENCODING)
def FindExtensions(self, tag=None, namespace=None):
"""Searches extension elements for child nodes with the desired name.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all extensions in
a particular namespace, specify the namespace but not the tag name.
If you specify only the tag, the result list may contain extension
elements in multiple namespaces.
Args:
tag: str (optional) The desired tag
namespace: str (optional) The desired namespace
Returns:
A list of elements whose tag and/or namespace match the parameters
values
"""
results = []
if tag and namespace:
for element in self.extension_elements:
if element.tag == tag and element.namespace == namespace:
results.append(element)
elif tag and not namespace:
for element in self.extension_elements:
if element.tag == tag:
results.append(element)
elif namespace and not tag:
for element in self.extension_elements:
if element.namespace == namespace:
results.append(element)
else:
for element in self.extension_elements:
results.append(element)
return results
class AtomBase(ExtensionContainer):
_children = {}
_attributes = {}
def __init__(self, extension_elements=None, extension_attributes=None,
text=None):
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
__init__ = v1_deprecated(
'Please use data model classes in atom.data instead.')(
__init__)
def _ConvertElementTreeToMember(self, child_tree):
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(_CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
_CreateClassFromElementTree(member_class, child_tree))
else:
ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
def _ConvertElementAttributeToMember(self, attribute, value):
# Find the attribute in this class's list of attributes.
if self.__class__._attributes.has_key(attribute):
# Find the member of this class which corresponds to the XML attribute
# (lookup in current_class._attributes) and set this member to the
# desired value (using self.__dict__).
if value:
# Encode the string to capture non-ascii characters (default UTF-8)
if MEMBER_STRING_ENCODING is unicode:
setattr(self, self.__class__._attributes[attribute], value)
else:
setattr(self, self.__class__._attributes[attribute],
value.encode(MEMBER_STRING_ENCODING))
else:
ExtensionContainer._ConvertElementAttributeToMember(
self, attribute, value)
# Three methods to create an ElementTree from an object
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
if isinstance(member, unicode) or MEMBER_STRING_ENCODING is unicode:
tree.attrib[xml_attribute] = member
else:
tree.attrib[xml_attribute] = member.decode(MEMBER_STRING_ENCODING)
# Lastly, call the ExtensionContainers's _AddMembersToElementTree to
# convert any extension attributes.
ExtensionContainer._AddMembersToElementTree(self, tree)
def _BecomeChildElement(self, tree):
"""
Note: Only for use with classes that have a _tag and _namespace class
member. It is in AtomBase so that it can be inherited but it should
not be called on instances of AtomBase.
"""
new_child = ElementTree.Element('')
tree.append(new_child)
new_child.tag = '{%s}%s' % (self.__class__._namespace,
self.__class__._tag)
self._AddMembersToElementTree(new_child)
def _ToElementTree(self):
"""
Note, this method is designed to be used only with classes that have a
_tag and _namespace. It is placed in AtomBase for inheritance but should
not be called on this class.
"""
new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace,
self.__class__._tag))
self._AddMembersToElementTree(new_tree)
return new_tree
def ToString(self, string_encoding='UTF-8'):
"""Converts the Atom object to a string containing XML."""
return ElementTree.tostring(self._ToElementTree(), encoding=string_encoding)
def __str__(self):
return self.ToString()
class Name(AtomBase):
"""The atom:name element"""
_tag = 'name'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Name
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def NameFromString(xml_string):
return CreateClassFromXMLString(Name, xml_string)
class Email(AtomBase):
"""The atom:email element"""
_tag = 'email'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Email
Args:
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def EmailFromString(xml_string):
return CreateClassFromXMLString(Email, xml_string)
class Uri(AtomBase):
"""The atom:uri element"""
_tag = 'uri'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Uri
Args:
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def UriFromString(xml_string):
return CreateClassFromXMLString(Uri, xml_string)
class Person(AtomBase):
"""A foundation class from which atom:author and atom:contributor extend.
A person contains information like name, email address, and web page URI for
an author or contributor to an Atom feed.
"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}name' % (ATOM_NAMESPACE)] = ('name', Name)
_children['{%s}email' % (ATOM_NAMESPACE)] = ('email', Email)
_children['{%s}uri' % (ATOM_NAMESPACE)] = ('uri', Uri)
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Foundation from which author and contributor are derived.
The constructor is provided for illustrative purposes, you should not
need to instantiate a Person.
Args:
name: Name The person's name
email: Email The person's email address
uri: Uri The URI of the person's webpage
extension_elements: list A list of ExtensionElement instances which are
children of this element.
extension_attributes: dict A dictionary of strings which are the values
for additional XML attributes of this element.
text: String The text contents of the element. This is the contents
of the Entry's XML text node. (Example: <foo>This is the text</foo>)
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
class Author(Person):
"""The atom:author element
An author is a required element in Feed.
"""
_tag = 'author'
_namespace = ATOM_NAMESPACE
_children = Person._children.copy()
_attributes = Person._attributes.copy()
#_children = {}
#_attributes = {}
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Author
Args:
name: Name
email: Email
uri: Uri
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def AuthorFromString(xml_string):
return CreateClassFromXMLString(Author, xml_string)
class Contributor(Person):
"""The atom:contributor element"""
_tag = 'contributor'
_namespace = ATOM_NAMESPACE
_children = Person._children.copy()
_attributes = Person._attributes.copy()
def __init__(self, name=None, email=None, uri=None,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for Contributor
Args:
name: Name
email: Email
uri: Uri
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.name = name
self.email = email
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
self.text = text
def ContributorFromString(xml_string):
return CreateClassFromXMLString(Contributor, xml_string)
class Link(AtomBase):
"""The atom:link element"""
_tag = 'link'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['href'] = 'href'
_attributes['type'] = 'type'
_attributes['title'] = 'title'
_attributes['length'] = 'length'
_attributes['hreflang'] = 'hreflang'
def __init__(self, href=None, rel=None, link_type=None, hreflang=None,
title=None, length=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Link
Args:
href: string The href attribute of the link
rel: string
type: string
hreflang: string The language for the href
title: string
length: string The length of the href's destination
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
text: str The text data in the this element
"""
self.href = href
self.rel = rel
self.type = link_type
self.hreflang = hreflang
self.title = title
self.length = length
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LinkFromString(xml_string):
return CreateClassFromXMLString(Link, xml_string)
class Generator(AtomBase):
"""The atom:generator element"""
_tag = 'generator'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['uri'] = 'uri'
_attributes['version'] = 'version'
def __init__(self, uri=None, version=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Generator
Args:
uri: string
version: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.uri = uri
self.version = version
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GeneratorFromString(xml_string):
return CreateClassFromXMLString(Generator, xml_string)
class Text(AtomBase):
"""A foundation class from which atom:title, summary, etc. extend.
This class should never be instantiated.
"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['type'] = 'type'
def __init__(self, text_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Text
Args:
text_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = text_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Title(Text):
"""The atom:title element"""
_tag = 'title'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, title_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Title
Args:
title_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = title_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def TitleFromString(xml_string):
return CreateClassFromXMLString(Title, xml_string)
class Subtitle(Text):
"""The atom:subtitle element"""
_tag = 'subtitle'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, subtitle_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Subtitle
Args:
subtitle_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = subtitle_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SubtitleFromString(xml_string):
return CreateClassFromXMLString(Subtitle, xml_string)
class Rights(Text):
"""The atom:rights element"""
_tag = 'rights'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, rights_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Rights
Args:
rights_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = rights_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def RightsFromString(xml_string):
return CreateClassFromXMLString(Rights, xml_string)
class Summary(Text):
"""The atom:summary element"""
_tag = 'summary'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
def __init__(self, summary_type=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Summary
Args:
summary_type: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = summary_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SummaryFromString(xml_string):
return CreateClassFromXMLString(Summary, xml_string)
class Content(Text):
"""The atom:content element"""
_tag = 'content'
_namespace = ATOM_NAMESPACE
_children = Text._children.copy()
_attributes = Text._attributes.copy()
_attributes['src'] = 'src'
def __init__(self, content_type=None, src=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Content
Args:
content_type: string
src: string
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.type = content_type
self.src = src
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ContentFromString(xml_string):
return CreateClassFromXMLString(Content, xml_string)
class Category(AtomBase):
"""The atom:category element"""
_tag = 'category'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_attributes['term'] = 'term'
_attributes['scheme'] = 'scheme'
_attributes['label'] = 'label'
def __init__(self, term=None, scheme=None, label=None, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Category
Args:
term: str
scheme: str
label: str
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.term = term
self.scheme = scheme
self.label = label
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def CategoryFromString(xml_string):
return CreateClassFromXMLString(Category, xml_string)
class Id(AtomBase):
"""The atom:id element."""
_tag = 'id'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Id
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def IdFromString(xml_string):
return CreateClassFromXMLString(Id, xml_string)
class Icon(AtomBase):
"""The atom:icon element."""
_tag = 'icon'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Icon
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def IconFromString(xml_string):
return CreateClassFromXMLString(Icon, xml_string)
class Logo(AtomBase):
"""The atom:logo element."""
_tag = 'logo'
_namespace = ATOM_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Logo
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def LogoFromString(xml_string):
return CreateClassFromXMLString(Logo, xml_string)
class Draft(AtomBase):
"""The app:draft element which indicates if this entry should be public."""
_tag = 'draft'
_namespace = APP_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for app:draft
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def DraftFromString(xml_string):
return CreateClassFromXMLString(Draft, xml_string)
class Control(AtomBase):
"""The app:control element indicating restrictions on publication.
The APP control element may contain a draft element indicating whether or
not this entry should be publicly available.
"""
_tag = 'control'
_namespace = APP_NAMESPACE
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}draft' % APP_NAMESPACE] = ('draft', Draft)
def __init__(self, draft=None, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for app:control"""
self.draft = draft
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def ControlFromString(xml_string):
return CreateClassFromXMLString(Control, xml_string)
class Date(AtomBase):
"""A parent class for atom:updated, published, etc."""
#TODO Add text to and from time conversion methods to allow users to set
# the contents of a Date to a python DateTime object.
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Updated(Date):
"""The atom:updated element."""
_tag = 'updated'
_namespace = ATOM_NAMESPACE
_children = Date._children.copy()
_attributes = Date._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Updated
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def UpdatedFromString(xml_string):
return CreateClassFromXMLString(Updated, xml_string)
class Published(Date):
"""The atom:published element."""
_tag = 'published'
_namespace = ATOM_NAMESPACE
_children = Date._children.copy()
_attributes = Date._attributes.copy()
def __init__(self, text=None, extension_elements=None,
extension_attributes=None):
"""Constructor for Published
Args:
text: str The text data in the this element
extension_elements: list A list of ExtensionElement instances
extension_attributes: dict A dictionary of attribute value string pairs
"""
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def PublishedFromString(xml_string):
return CreateClassFromXMLString(Published, xml_string)
class LinkFinder(object):
"""An "interface" providing methods to find link elements
Entry elements often contain multiple links which differ in the rel
attribute or content type. Often, developers are interested in a specific
type of link so this class provides methods to find specific classes of
links.
This class is used as a mixin in Atom entries and feeds.
"""
def GetSelfLink(self):
"""Find the first link with rel set to 'self'
Returns:
An atom.Link or none if none of the links had rel equal to 'self'
"""
for a_link in self.link:
if a_link.rel == 'self':
return a_link
return None
def GetEditLink(self):
for a_link in self.link:
if a_link.rel == 'edit':
return a_link
return None
def GetEditMediaLink(self):
for a_link in self.link:
if a_link.rel == 'edit-media':
return a_link
return None
def GetNextLink(self):
for a_link in self.link:
if a_link.rel == 'next':
return a_link
return None
def GetLicenseLink(self):
for a_link in self.link:
if a_link.rel == 'license':
return a_link
return None
def GetAlternateLink(self):
for a_link in self.link:
if a_link.rel == 'alternate':
return a_link
return None
class FeedEntryParent(AtomBase, LinkFinder):
"""A super class for atom:feed and entry, contains shared attributes"""
_children = AtomBase._children.copy()
_attributes = AtomBase._attributes.copy()
_children['{%s}author' % ATOM_NAMESPACE] = ('author', [Author])
_children['{%s}category' % ATOM_NAMESPACE] = ('category', [Category])
_children['{%s}contributor' % ATOM_NAMESPACE] = ('contributor', [Contributor])
_children['{%s}id' % ATOM_NAMESPACE] = ('id', Id)
_children['{%s}link' % ATOM_NAMESPACE] = ('link', [Link])
_children['{%s}rights' % ATOM_NAMESPACE] = ('rights', Rights)
_children['{%s}title' % ATOM_NAMESPACE] = ('title', Title)
_children['{%s}updated' % ATOM_NAMESPACE] = ('updated', Updated)
def __init__(self, author=None, category=None, contributor=None,
atom_id=None, link=None, rights=None, title=None, updated=None,
text=None, extension_elements=None, extension_attributes=None):
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.rights = rights
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Source(FeedEntryParent):
"""The atom:source element"""
_tag = 'source'
_namespace = ATOM_NAMESPACE
_children = FeedEntryParent._children.copy()
_attributes = FeedEntryParent._attributes.copy()
_children['{%s}generator' % ATOM_NAMESPACE] = ('generator', Generator)
_children['{%s}icon' % ATOM_NAMESPACE] = ('icon', Icon)
_children['{%s}logo' % ATOM_NAMESPACE] = ('logo', Logo)
_children['{%s}subtitle' % ATOM_NAMESPACE] = ('subtitle', Subtitle)
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, text=None,
extension_elements=None, extension_attributes=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def SourceFromString(xml_string):
return CreateClassFromXMLString(Source, xml_string)
class Entry(FeedEntryParent):
"""The atom:entry element"""
_tag = 'entry'
_namespace = ATOM_NAMESPACE
_children = FeedEntryParent._children.copy()
_attributes = FeedEntryParent._attributes.copy()
_children['{%s}content' % ATOM_NAMESPACE] = ('content', Content)
_children['{%s}published' % ATOM_NAMESPACE] = ('published', Published)
_children['{%s}source' % ATOM_NAMESPACE] = ('source', Source)
_children['{%s}summary' % ATOM_NAMESPACE] = ('summary', Summary)
_children['{%s}control' % APP_NAMESPACE] = ('control', Control)
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,
extension_elements=None, extension_attributes=None, text=None):
"""Constructor for atom:entry
Args:
author: list A list of Author instances which belong to this class.
category: list A list of Category instances
content: Content The entry's Content
contributor: list A list on Contributor instances
id: Id The entry's Id element
link: list A list of Link instances
published: Published The entry's Published element
rights: Rights The entry's Rights element
source: Source the entry's source element
summary: Summary the entry's summary element
title: Title the entry's title element
updated: Updated the entry's updated element
control: The entry's app:control element which can be used to mark an
entry as a draft which should not be publicly viewable.
text: String 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 A list of ExtensionElement instances which are
children of this element.
extension_attributes: dict A dictionary of strings which are the values
for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.content = content
self.contributor = contributor or []
self.id = atom_id
self.link = link or []
self.published = published
self.rights = rights
self.source = source
self.summary = summary
self.title = title
self.updated = updated
self.control = control
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
__init__ = v1_deprecated('Please use atom.data.Entry instead.')(__init__)
def EntryFromString(xml_string):
return CreateClassFromXMLString(Entry, xml_string)
class Feed(Source):
"""The atom:feed element"""
_tag = 'feed'
_namespace = ATOM_NAMESPACE
_children = Source._children.copy()
_attributes = Source._attributes.copy()
_children['{%s}entry' % ATOM_NAMESPACE] = ('entry', [Entry])
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,
text=None, extension_elements=None, extension_attributes=None):
"""Constructor for Source
Args:
author: list (optional) A list of Author instances which belong to this
class.
category: list (optional) A list of Category instances
contributor: list (optional) A list on Contributor instances
generator: Generator (optional)
icon: Icon (optional)
id: Id (optional) The entry's Id element
link: list (optional) A list of Link instances
logo: Logo (optional)
rights: Rights (optional) The entry's Rights element
subtitle: Subtitle (optional) The entry's subtitle element
title: Title (optional) the entry's title element
updated: Updated (optional) the entry's updated element
entry: list (optional) A list of the Entry instances contained in the
feed.
text: String (optional) The text contents of the element. This is the
contents of the Entry's XML text node.
(Example: <foo>This is the text</foo>)
extension_elements: list (optional) A list of ExtensionElement instances
which are children of this element.
extension_attributes: dict (optional) A dictionary of strings which are
the values for additional XML attributes of this element.
"""
self.author = author or []
self.category = category or []
self.contributor = contributor or []
self.generator = generator
self.icon = icon
self.id = atom_id
self.link = link or []
self.logo = logo
self.rights = rights
self.subtitle = subtitle
self.title = title
self.updated = updated
self.entry = entry or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
__init__ = v1_deprecated('Please use atom.data.Feed instead.')(__init__)
def FeedFromString(xml_string):
return CreateClassFromXMLString(Feed, xml_string)
class ExtensionElement(object):
"""Represents extra XML elements contained in Atom classes."""
def __init__(self, tag, namespace=None, attributes=None,
children=None, text=None):
"""Constructor for EtensionElement
Args:
namespace: string (optional) The XML namespace for this element.
tag: string (optional) The tag (without the namespace qualifier) for
this element. To reconstruct the full qualified name of the element,
combine this tag with the namespace.
attributes: dict (optinal) The attribute value string pairs for the XML
attributes of this element.
children: list (optional) A list of ExtensionElements which represent
the XML child nodes of this element.
"""
self.namespace = namespace
self.tag = tag
self.attributes = attributes or {}
self.children = children or []
self.text = text
def ToString(self):
element_tree = self._TransferToElementTree(ElementTree.Element(''))
return ElementTree.tostring(element_tree, encoding="UTF-8")
def _TransferToElementTree(self, element_tree):
if self.tag is None:
return None
if self.namespace is not None:
element_tree.tag = '{%s}%s' % (self.namespace, self.tag)
else:
element_tree.tag = self.tag
for key, value in self.attributes.iteritems():
element_tree.attrib[key] = value
for child in self.children:
child._BecomeChildElement(element_tree)
element_tree.text = self.text
return element_tree
def _BecomeChildElement(self, element_tree):
"""Converts this object into an etree element and adds it as a child node.
Adds self to the ElementTree. This method is required to avoid verbose XML
which constantly redefines the namespace.
Args:
element_tree: ElementTree._Element The element to which this object's XML
will be added.
"""
new_element = ElementTree.Element('')
element_tree.append(new_element)
self._TransferToElementTree(new_element)
def FindChildren(self, tag=None, namespace=None):
"""Searches child nodes for objects with the desired tag/namespace.
Returns a list of extension elements within this object whose tag
and/or namespace match those passed in. To find all children in
a particular namespace, specify the namespace but not the tag name.
If you specify only the tag, the result list may contain extension
elements in multiple namespaces.
Args:
tag: str (optional) The desired tag
namespace: str (optional) The desired namespace
Returns:
A list of elements whose tag and/or namespace match the parameters
values
"""
results = []
if tag and namespace:
for element in self.children:
if element.tag == tag and element.namespace == namespace:
results.append(element)
elif tag and not namespace:
for element in self.children:
if element.tag == tag:
results.append(element)
elif namespace and not tag:
for element in self.children:
if element.namespace == namespace:
results.append(element)
else:
for element in self.children:
results.append(element)
return results
def ExtensionElementFromString(xml_string):
element_tree = ElementTree.fromstring(xml_string)
return _ExtensionElementFromElementTree(element_tree)
def _ExtensionElementFromElementTree(element_tree):
element_tag = element_tree.tag
if '}' in element_tag:
namespace = element_tag[1:element_tag.index('}')]
tag = element_tag[element_tag.index('}')+1:]
else:
namespace = None
tag = element_tag
extension = ExtensionElement(namespace=namespace, tag=tag)
for key, value in element_tree.attrib.iteritems():
extension.attributes[key] = value
for child in element_tree:
extension.children.append(_ExtensionElementFromElementTree(child))
extension.text = element_tree.text
return extension
def deprecated(warning=None):
"""Decorator to raise warning each time the function is called.
Args:
warning: The warning message to be displayed as a string (optinoal).
"""
warning = warning or ''
# This closure is what is returned from the deprecated function.
def mark_deprecated(f):
# The deprecated_function wraps the actual call to f.
def deprecated_function(*args, **kwargs):
warnings.warn(warning, DeprecationWarning, stacklevel=2)
return f(*args, **kwargs)
# Preserve the original name to avoid masking all decorated functions as
# 'deprecated_function'
try:
deprecated_function.func_name = f.func_name
except TypeError:
# Setting the func_name is not allowed in Python2.3.
pass
return deprecated_function
return mark_deprecated
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006, 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.
"""AtomService provides CRUD ops. in line with the Atom Publishing Protocol.
AtomService: Encapsulates the ability to perform insert, update and delete
operations with the Atom Publishing Protocol on which GData is
based. An instance can perform query, insertion, deletion, and
update.
HttpRequest: Function that performs a GET, POST, PUT, or DELETE HTTP request
to the specified end point. An AtomService object or a subclass can be
used to specify information about the request.
"""
__author__ = 'api.jscudder (Jeff Scudder)'
import atom.http_interface
import atom.url
import atom.http
import atom.token_store
import os
import httplib
import urllib
import re
import base64
import socket
import warnings
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
class AtomService(object):
"""Performs Atom Publishing Protocol CRUD operations.
The AtomService contains methods to perform HTTP CRUD operations.
"""
# Default values for members
port = 80
ssl = False
# Set the current_token to force the AtomService to use this token
# instead of searching for an appropriate token in the token_store.
current_token = None
auto_store_tokens = True
auto_set_current_token = True
def _get_override_token(self):
return self.current_token
def _set_override_token(self, token):
self.current_token = token
override_token = property(_get_override_token, _set_override_token)
#@atom.v1_deprecated('Please use atom.client.AtomPubClient instead.')
def __init__(self, server=None, additional_headers=None,
application_name='', http_client=None, token_store=None):
"""Creates a new AtomService client.
Args:
server: string (optional) The start of a URL for the server
to which all operations should be directed. Example:
'www.google.com'
additional_headers: dict (optional) Any additional HTTP headers which
should be included with CRUD operations.
http_client: An object responsible for making HTTP requests using a
request method. If none is provided, a new instance of
atom.http.ProxiedHttpClient will be used.
token_store: Keeps a collection of authorization tokens which can be
applied to requests for a specific URLs. Critical methods are
find_token based on a URL (atom.url.Url or a string), add_token,
and remove_token.
"""
self.http_client = http_client or atom.http.ProxiedHttpClient()
self.token_store = token_store or atom.token_store.TokenStore()
self.server = server
self.additional_headers = additional_headers or {}
self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % (
application_name,)
# If debug is True, the HTTPConnection will display debug information
self._set_debug(False)
__init__ = atom.v1_deprecated(
'Please use atom.client.AtomPubClient instead.')(
__init__)
def _get_debug(self):
return self.http_client.debug
def _set_debug(self, value):
self.http_client.debug = value
debug = property(_get_debug, _set_debug,
doc='If True, HTTP debug information is printed.')
def use_basic_auth(self, username, password, scopes=None):
if username is not None and password is not None:
if scopes is None:
scopes = [atom.token_store.SCOPE_ALL]
base_64_string = base64.encodestring('%s:%s' % (username, password))
token = BasicAuthToken('Basic %s' % base_64_string.strip(),
scopes=[atom.token_store.SCOPE_ALL])
if self.auto_set_current_token:
self.current_token = token
if self.auto_store_tokens:
return self.token_store.add_token(token)
return True
return False
def UseBasicAuth(self, username, password, for_proxy=False):
"""Sets an Authenticaiton: Basic HTTP header containing plaintext.
Deprecated, use use_basic_auth instead.
The username and password are base64 encoded and added to an HTTP header
which will be included in each request. Note that your username and
password are sent in plaintext.
Args:
username: str
password: str
"""
self.use_basic_auth(username, password)
#@atom.v1_deprecated('Please use atom.client.AtomPubClient for requests.')
def request(self, operation, url, data=None, headers=None,
url_params=None):
if isinstance(url, (str, unicode)):
if url.startswith('http:') and self.ssl:
# Force all requests to be https if self.ssl is True.
url = atom.url.parse_url('https:' + url[5:])
elif not url.startswith('http') and self.ssl:
url = atom.url.parse_url('https://%s%s' % (self.server, url))
elif not url.startswith('http'):
url = atom.url.parse_url('http://%s%s' % (self.server, url))
else:
url = atom.url.parse_url(url)
if url_params:
for name, value in url_params.iteritems():
url.params[name] = value
all_headers = self.additional_headers.copy()
if headers:
all_headers.update(headers)
# 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:
content_length = CalculateDataLength(data)
if content_length:
all_headers['Content-Length'] = str(content_length)
# Find an Authorization token for this URL if one is available.
if self.override_token:
auth_token = self.override_token
else:
auth_token = self.token_store.find_token(url)
return auth_token.perform_request(self.http_client, operation, url,
data=data, headers=all_headers)
request = atom.v1_deprecated(
'Please use atom.client.AtomPubClient for requests.')(
request)
# CRUD operations
def Get(self, uri, extra_headers=None, url_params=None, escape_params=True):
"""Query the APP server with the given URI
The uri is the portion of the URI after the server value
(server example: 'www.google.com').
Example use:
To perform a query against Google Base, set the server to
'base.google.com' and set the uri to '/base/feeds/...', where ... is
your query. For example, to find snippets for all digital cameras uri
should be set to: '/base/feeds/snippets?bq=digital+camera'
Args:
uri: string The query in the form of a URI. Example:
'/base/feeds/snippets?bq=digital+camera'.
extra_headers: dicty (optional) Extra HTTP headers to be included
in the GET request. These headers are in addition to
those stored in the client's additional_headers property.
The client automatically sets the Content-Type and
Authorization headers.
url_params: dict (optional) Additional URL parameters to be included
in the query. These are translated into query arguments
in the form '&dict_key=value&...'.
Example: {'max-results': '250'} becomes &max-results=250
escape_params: boolean (optional) If false, the calling code has already
ensured that the query will form a valid URL (all
reserved characters have been escaped). If true, this
method will escape the query and any URL parameters
provided.
Returns:
httplib.HTTPResponse The server's response to the GET request.
"""
return self.request('GET', uri, data=None, headers=extra_headers,
url_params=url_params)
def Post(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, content_type='application/atom+xml'):
"""Insert data into an APP server at the given URI.
Args:
data: string, ElementTree._Element, or something with a __str__ method
The XML to be sent to the uri.
uri: string The location (feed) to which the data should be inserted.
Example: '/base/feeds/items'.
extra_headers: dict (optional) HTTP headers which are to be included.
The client automatically sets the Content-Type,
Authorization, and Content-Length headers.
url_params: dict (optional) Additional URL parameters to be included
in the URI. These are translated into query arguments
in the form '&dict_key=value&...'.
Example: {'max-results': '250'} becomes &max-results=250
escape_params: boolean (optional) If false, the calling code has already
ensured that the query will form a valid URL (all
reserved characters have been escaped). If true, this
method will escape the query and any URL parameters
provided.
Returns:
httplib.HTTPResponse Server's response to the POST request.
"""
if extra_headers is None:
extra_headers = {}
if content_type:
extra_headers['Content-Type'] = content_type
return self.request('POST', uri, data=data, headers=extra_headers,
url_params=url_params)
def Put(self, data, uri, extra_headers=None, url_params=None,
escape_params=True, content_type='application/atom+xml'):
"""Updates an entry at the given URI.
Args:
data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The
XML containing the updated data.
uri: string A URI indicating entry to which the update will be applied.
Example: '/base/feeds/items/ITEM-ID'
extra_headers: dict (optional) HTTP headers which are to be included.
The client automatically sets the Content-Type,
Authorization, and Content-Length headers.
url_params: dict (optional) Additional URL parameters to be included
in the URI. These are translated into query arguments
in the form '&dict_key=value&...'.
Example: {'max-results': '250'} becomes &max-results=250
escape_params: boolean (optional) If false, the calling code has already
ensured that the query will form a valid URL (all
reserved characters have been escaped). If true, this
method will escape the query and any URL parameters
provided.
Returns:
httplib.HTTPResponse Server's response to the PUT request.
"""
if extra_headers is None:
extra_headers = {}
if content_type:
extra_headers['Content-Type'] = content_type
return self.request('PUT', uri, data=data, headers=extra_headers,
url_params=url_params)
def Delete(self, uri, extra_headers=None, url_params=None,
escape_params=True):
"""Deletes the entry at the given URI.
Args:
uri: string The URI of the entry to be deleted. Example:
'/base/feeds/items/ITEM-ID'
extra_headers: dict (optional) HTTP headers which are to be included.
The client automatically sets the Content-Type and
Authorization headers.
url_params: dict (optional) Additional URL parameters to be included
in the URI. These are translated into query arguments
in the form '&dict_key=value&...'.
Example: {'max-results': '250'} becomes &max-results=250
escape_params: boolean (optional) If false, the calling code has already
ensured that the query will form a valid URL (all
reserved characters have been escaped). If true, this
method will escape the query and any URL parameters
provided.
Returns:
httplib.HTTPResponse Server's response to the DELETE request.
"""
return self.request('DELETE', uri, data=None, headers=extra_headers,
url_params=url_params)
class BasicAuthToken(atom.http_interface.GenericToken):
def __init__(self, auth_header, scopes=None):
"""Creates a token used to add Basic Auth headers to HTTP requests.
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'
"""
self.auth_header = auth_header
self.scopes = scopes or []
def perform_request(self, http_client, operation, url, data=None,
headers=None):
"""Sets the Authorization header to the basic auth string."""
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 __str__(self):
return self.auth_header
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
def PrepareConnection(service, full_uri):
"""Opens a connection to the server based on the full URI.
This method is deprecated, instead use atom.http.HttpClient.request.
Examines the target URI and the proxy settings, which are set as
environment variables, to open a connection with the server. This
connection is used to make an HTTP request.
Args:
service: atom.AtomService or a subclass. It must have a server string which
represents the server host to which the request should be made. It may also
have a dictionary of additional_headers to send in the HTTP request.
full_uri: str Which is the target relative (lacks protocol and host) or
absolute URL to be opened. Example:
'https://www.google.com/accounts/ClientLogin' or
'base/feeds/snippets' where the server is set to www.google.com.
Returns:
A tuple containing the httplib.HTTPConnection and the full_uri for the
request.
"""
deprecation('calling deprecated function PrepareConnection')
(server, port, ssl, partial_uri) = ProcessUrl(service, full_uri)
if ssl:
# destination is https
proxy = os.environ.get('https_proxy')
if proxy:
(p_server, p_port, p_ssl, p_uri) = ProcessUrl(service, proxy, True)
proxy_username = os.environ.get('proxy-username')
if not proxy_username:
proxy_username = os.environ.get('proxy_username')
proxy_password = os.environ.get('proxy-password')
if not proxy_password:
proxy_password = os.environ.get('proxy_password')
if proxy_username:
user_auth = base64.encodestring('%s:%s' % (proxy_username,
proxy_password))
proxy_authorization = ('Proxy-authorization: Basic %s\r\n' % (
user_auth.strip()))
else:
proxy_authorization = ''
proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (server, port)
user_agent = 'User-Agent: %s\r\n' % (
service.additional_headers['User-Agent'])
proxy_pieces = (proxy_connect + proxy_authorization + user_agent
+ '\r\n')
#now connect, very simple recv and error checking
p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
p_sock.connect((p_server,p_port))
p_sock.sendall(proxy_pieces)
response = ''
# Wait for the full response.
while response.find("\r\n\r\n") == -1:
response += p_sock.recv(8192)
p_status=response.split()[1]
if p_status!=str(200):
raise atom.http.ProxyError('Error status=%s' % p_status)
# Trivial setup for ssl socket.
ssl = socket.ssl(p_sock, None, None)
fake_sock = httplib.FakeSocket(p_sock, ssl)
# Initalize httplib and replace with the proxy socket.
connection = httplib.HTTPConnection(server)
connection.sock=fake_sock
full_uri = partial_uri
else:
connection = httplib.HTTPSConnection(server, port)
full_uri = partial_uri
else:
# destination is http
proxy = os.environ.get('http_proxy')
if proxy:
(p_server, p_port, p_ssl, p_uri) = ProcessUrl(service.server, proxy, True)
proxy_username = os.environ.get('proxy-username')
if not proxy_username:
proxy_username = os.environ.get('proxy_username')
proxy_password = os.environ.get('proxy-password')
if not proxy_password:
proxy_password = os.environ.get('proxy_password')
if proxy_username:
UseBasicAuth(service, proxy_username, proxy_password, True)
connection = httplib.HTTPConnection(p_server, p_port)
if not full_uri.startswith("http://"):
if full_uri.startswith("/"):
full_uri = "http://%s%s" % (service.server, full_uri)
else:
full_uri = "http://%s/%s" % (service.server, full_uri)
else:
connection = httplib.HTTPConnection(server, port)
full_uri = partial_uri
return (connection, full_uri)
def UseBasicAuth(service, username, password, for_proxy=False):
"""Sets an Authenticaiton: Basic HTTP header containing plaintext.
Deprecated, use AtomService.use_basic_auth insread.
The username and password are base64 encoded and added to an HTTP header
which will be included in each request. Note that your username and
password are sent in plaintext. The auth header is added to the
additional_headers dictionary in the service object.
Args:
service: atom.AtomService or a subclass which has an
additional_headers dict as a member.
username: str
password: str
"""
deprecation('calling deprecated function UseBasicAuth')
base_64_string = base64.encodestring('%s:%s' % (username, password))
base_64_string = base_64_string.strip()
if for_proxy:
header_name = 'Proxy-Authorization'
else:
header_name = 'Authorization'
service.additional_headers[header_name] = 'Basic %s' % (base_64_string,)
def ProcessUrl(service, url, for_proxy=False):
"""Processes a passed URL. If the URL does not begin with https?, then
the default value for server is used
This method is deprecated, use atom.url.parse_url instead.
"""
if not isinstance(url, atom.url.Url):
url = atom.url.parse_url(url)
server = url.host
ssl = False
port = 80
if not server:
if hasattr(service, 'server'):
server = service.server
else:
server = service
if not url.protocol and hasattr(service, 'ssl'):
ssl = service.ssl
if hasattr(service, 'port'):
port = service.port
else:
if url.protocol == 'https':
ssl = True
elif url.protocol == 'http':
ssl = False
if url.port:
port = int(url.port)
elif port == 80 and ssl:
port = 443
return (server, port, ssl, url.get_request_uri())
def DictionaryToParamList(url_parameters, escape_params=True):
"""Convert a dictionary of URL arguments into a URL parameter string.
This function is deprcated, use atom.url.Url instead.
Args:
url_parameters: The dictionaty of key-value pairs which will be converted
into URL parameters. For example,
{'dry-run': 'true', 'foo': 'bar'}
will become ['dry-run=true', 'foo=bar'].
Returns:
A list which contains a string for each key-value pair. The strings are
ready to be incorporated into a URL by using '&'.join([] + parameter_list)
"""
# Choose which function to use when modifying the query and parameters.
# Use quote_plus when escape_params is true.
transform_op = [str, urllib.quote_plus][bool(escape_params)]
# Create a list of tuples containing the escaped version of the
# parameter-value pairs.
parameter_tuples = [(transform_op(param), transform_op(value))
for param, value in (url_parameters or {}).items()]
# Turn parameter-value tuples into a list of strings in the form
# 'PARAMETER=VALUE'.
return ['='.join(x) for x in parameter_tuples]
def BuildUri(uri, url_params=None, escape_params=True):
"""Converts a uri string and a collection of parameters into a URI.
This function is deprcated, use atom.url.Url instead.
Args:
uri: string
url_params: dict (optional)
escape_params: boolean (optional)
uri: string The start of the desired URI. This string can alrady contain
URL parameters. Examples: '/base/feeds/snippets',
'/base/feeds/snippets?bq=digital+camera'
url_parameters: dict (optional) Additional URL parameters to be included
in the query. These are translated into query arguments
in the form '&dict_key=value&...'.
Example: {'max-results': '250'} becomes &max-results=250
escape_params: boolean (optional) If false, the calling code has already
ensured that the query will form a valid URL (all
reserved characters have been escaped). If true, this
method will escape the query and any URL parameters
provided.
Returns:
string The URI consisting of the escaped URL parameters appended to the
initial uri string.
"""
# Prepare URL parameters for inclusion into the GET request.
parameter_list = DictionaryToParamList(url_params, escape_params)
# Append the URL parameters to the URL.
if parameter_list:
if uri.find('?') != -1:
# If there are already URL parameters in the uri string, add the
# parameters after a new & character.
full_uri = '&'.join([uri] + parameter_list)
else:
# The uri string did not have any URL parameters (no ? character)
# so put a ? between the uri and URL parameters.
full_uri = '%s%s' % (uri, '?%s' % ('&'.join([] + parameter_list)))
else:
full_uri = uri
return full_uri
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 method is deprecated, use atom.http.HttpClient.request instead.
Usage example, perform and HTTP GET on http://www.google.com/:
import atom.service
client = atom.service.AtomService()
http_response = client.Get('http://www.google.com/')
or you could set the client.server to 'www.google.com' and use the
following:
client.server = 'www.google.com'
http_response = client.Get('/')
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: ElementTree, 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.
"""
deprecation('call to deprecated function HttpRequest')
full_uri = BuildUri(uri, url_params, escape_params)
(connection, full_uri) = PrepareConnection(service, full_uri)
if extra_headers is None:
extra_headers = {}
# Turn on debug mode if the debug member is set.
if service.debug:
connection.debuglevel = 1
connection.putrequest(operation, full_uri)
# If the list of headers does not include a Content-Length, attempt to
# calculate it based on the data object.
if (data and not service.additional_headers.has_key('Content-Length') and
not extra_headers.has_key('Content-Length')):
content_length = CalculateDataLength(data)
if content_length:
extra_headers['Content-Length'] = str(content_length)
if content_type:
extra_headers['Content-Type'] = content_type
# Send the HTTP headers.
if isinstance(service.additional_headers, dict):
for header in service.additional_headers:
connection.putheader(header, service.additional_headers[header])
if isinstance(extra_headers, dict):
for header in extra_headers:
connection.putheader(header, extra_headers[header])
connection.endheaders()
# If there is data, send it in the request.
if data:
if isinstance(data, list):
for data_part in data:
__SendDataPart(data_part, connection)
else:
__SendDataPart(data, connection)
# Return the HTTP Response from the server.
return connection.getresponse()
def __SendDataPart(data, connection):
"""This method is deprecated, use atom.http._send_data_part"""
deprecated('call to deprecated function __SendDataPart')
if isinstance(data, str):
#TODO add handling for unicode.
connection.send(data)
return
elif ElementTree.iselement(data):
connection.send(ElementTree.tostring(data))
return
# Check to see if data is a file-like object that has a read method.
elif hasattr(data, 'read'):
# Read the file and send it a chunk at a time.
while 1:
binarydata = data.read(100000)
if binarydata == '': break
connection.send(binarydata)
return
else:
# The data object was not a file.
# Try to convert to a string and send the data.
connection.send(str(data))
return
def CalculateDataLength(data):
"""Attempts to determine the length of the data to send.
This method will respond with a length only if the data is a string or
and ElementTree element.
Args:
data: object If this is not a string or ElementTree element this funtion
will return None.
"""
if isinstance(data, str):
return len(data)
elif isinstance(data, list):
return None
elif ElementTree.iselement(data):
return len(ElementTree.tostring(data))
elif hasattr(data, 'read'):
# If this is a file-like object, don't try to guess the length.
return None
else:
return len(str(data))
def deprecation(message):
warnings.warn(message, DeprecationWarning, stacklevel=2)
| 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.
"""This module provides a common interface for all HTTP requests.
HttpResponse: Represents the server's response to an HTTP request. Provides
an interface identical to httplib.HTTPResponse which is the response
expected from higher level classes which use HttpClient.request.
GenericHttpClient: Provides an interface (superclass) for an object
responsible for making HTTP requests. Subclasses of this object are
used in AtomService and GDataService to make requests to the server. By
changing the http_client member object, the AtomService is able to make
HTTP requests using different logic (for example, when running on
Google App Engine, the http_client makes requests using the App Engine
urlfetch API).
"""
__author__ = 'api.jscudder (Jeff Scudder)'
import StringIO
USER_AGENT = '%s GData-Python/2.0.16'
class Error(Exception):
pass
class UnparsableUrlObject(Error):
pass
class ContentLengthRequired(Error):
pass
class HttpResponse(object):
def __init__(self, body=None, status=None, reason=None, headers=None):
"""Constructor for an HttpResponse object.
HttpResponse represents the server's response to an HTTP request from
the client. The HttpClient.request method returns a httplib.HTTPResponse
object and this HttpResponse class is designed to mirror the interface
exposed by httplib.HTTPResponse.
Args:
body: A file like object, with a read() method. The body could also
be a string, and the constructor will wrap it so that
HttpResponse.read(self) will return the full string.
status: The HTTP status code as an int. Example: 200, 201, 404.
reason: The HTTP status message which follows the code. Example:
OK, Created, Not Found
headers: A dictionary containing the HTTP headers in the server's
response. A common header in the response is Content-Length.
"""
if body:
if hasattr(body, 'read'):
self._body = body
else:
self._body = StringIO.StringIO(body)
else:
self._body = None
if status is not None:
self.status = int(status)
else:
self.status = None
self.reason = reason
self._headers = headers or {}
def getheader(self, name, default=None):
if name in self._headers:
return self._headers[name]
else:
return default
def read(self, amt=None):
if not amt:
return self._body.read()
else:
return self._body.read(amt)
class GenericHttpClient(object):
debug = False
def __init__(self, http_client, headers=None):
"""
Args:
http_client: An object which provides a request method to make an HTTP
request. The request method in GenericHttpClient performs a
call-through to the contained HTTP client object.
headers: A dictionary containing HTTP headers which should be included
in every HTTP request. Common persistent headers include
'User-Agent'.
"""
self.http_client = http_client
self.headers = headers or {}
def request(self, operation, url, data=None, headers=None):
all_headers = self.headers.copy()
if headers:
all_headers.update(headers)
return self.http_client.request(operation, url, data=data,
headers=all_headers)
def get(self, url, headers=None):
return self.request('GET', url, headers=headers)
def post(self, url, data, headers=None):
return self.request('POST', url, data=data, headers=headers)
def put(self, url, data, headers=None):
return self.request('PUT', url, data=data, headers=headers)
def delete(self, url, headers=None):
return self.request('DELETE', url, headers=headers)
class GenericToken(object):
"""Represents an Authorization token to be added to HTTP requests.
Some Authorization headers included calculated fields (digital
signatures for example) which are based on the parameters of the HTTP
request. Therefore the token is responsible for signing the request
and adding the Authorization header.
"""
def perform_request(self, http_client, operation, url, data=None,
headers=None):
"""For the GenericToken, no Authorization token is set."""
return http_client.request(operation, url, data=data, headers=headers)
def valid_for_scope(self, url):
"""Tells the caller if the token authorizes access to the desired URL.
Since the generic token doesn't add an auth header, it is not valid for
any scope.
"""
return False
| Python |
#!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This module is used for version 2 of the Google Data APIs.
"""Provides classes and constants for the XML in the Google Spreadsheets API.
Documentation for the raw XML which these classes represent can be found here:
http://code.google.com/apis/spreadsheets/docs/3.0/reference.html#Elements
"""
__author__ = 'j.s@google.com (Jeff Scudder)'
import atom.core
import gdata.data
GS_TEMPLATE = '{http://schemas.google.com/spreadsheets/2006}%s'
GSX_NAMESPACE = 'http://schemas.google.com/spreadsheets/2006/extended'
INSERT_MODE = 'insert'
OVERWRITE_MODE = 'overwrite'
WORKSHEETS_REL = 'http://schemas.google.com/spreadsheets/2006#worksheetsfeed'
BATCH_POST_ID_TEMPLATE = ('https://spreadsheets.google.com/feeds/cells'
'/%s/%s/private/full')
BATCH_ENTRY_ID_TEMPLATE = '%s/R%sC%s'
BATCH_EDIT_LINK_TEMPLATE = '%s/batch'
class Error(Exception):
pass
class FieldMissing(Exception):
pass
class HeaderNotSet(Error):
"""The desired column header had no value for the row in the list feed."""
class Cell(atom.core.XmlElement):
"""The gs:cell element.
A cell in the worksheet. The <gs:cell> element can appear only as a child
of <atom:entry>.
"""
_qname = GS_TEMPLATE % 'cell'
col = 'col'
input_value = 'inputValue'
numeric_value = 'numericValue'
row = 'row'
class ColCount(atom.core.XmlElement):
"""The gs:colCount element.
Indicates the number of columns in the worksheet, including columns that
contain only empty cells. The <gs:colCount> element can appear as a child
of <atom:entry> or <atom:feed>
"""
_qname = GS_TEMPLATE % 'colCount'
class Field(atom.core.XmlElement):
"""The gs:field element.
A field single cell within a record. Contained in an <atom:entry>.
"""
_qname = GS_TEMPLATE % 'field'
index = 'index'
name = 'name'
class Column(Field):
"""The gs:column element."""
_qname = GS_TEMPLATE % 'column'
class Data(atom.core.XmlElement):
"""The gs:data element.
A data region of a table. Contained in an <atom:entry> element.
"""
_qname = GS_TEMPLATE % 'data'
column = [Column]
insertion_mode = 'insertionMode'
num_rows = 'numRows'
start_row = 'startRow'
class Header(atom.core.XmlElement):
"""The gs:header element.
Indicates which row is the header row. Contained in an <atom:entry>.
"""
_qname = GS_TEMPLATE % 'header'
row = 'row'
class RowCount(atom.core.XmlElement):
"""The gs:rowCount element.
Indicates the number of total rows in the worksheet, including rows that
contain only empty cells. The <gs:rowCount> element can appear as a
child of <atom:entry> or <atom:feed>.
"""
_qname = GS_TEMPLATE % 'rowCount'
class Worksheet(atom.core.XmlElement):
"""The gs:worksheet element.
The worksheet where the table lives.Contained in an <atom:entry>.
"""
_qname = GS_TEMPLATE % 'worksheet'
name = 'name'
class Spreadsheet(gdata.data.GDEntry):
"""An Atom entry which represents a Google Spreadsheet."""
def find_worksheets_feed(self):
return self.find_url(WORKSHEETS_REL)
FindWorksheetsFeed = find_worksheets_feed
def get_spreadsheet_key(self):
"""Extracts the spreadsheet key unique to this spreadsheet."""
return self.get_id().split('/')[-1]
GetSpreadsheetKey = get_spreadsheet_key
class SpreadsheetsFeed(gdata.data.GDFeed):
"""An Atom feed listing a user's Google Spreadsheets."""
entry = [Spreadsheet]
class WorksheetEntry(gdata.data.GDEntry):
"""An Atom entry representing a single worksheet in a spreadsheet."""
row_count = RowCount
col_count = ColCount
def get_worksheet_id(self):
"""The worksheet ID identifies this worksheet in its spreadsheet."""
return self.get_id().split('/')[-1]
GetWorksheetId = get_worksheet_id
class WorksheetsFeed(gdata.data.GDFeed):
"""A feed containing the worksheets in a single spreadsheet."""
entry = [WorksheetEntry]
class Table(gdata.data.GDEntry):
"""An Atom entry that represents a subsection of a worksheet.
A table allows you to treat part or all of a worksheet somewhat like a
table in a database that is, as a set of structured data items. Tables
don't exist until you explicitly create them before you can use a table
feed, you have to explicitly define where the table data comes from.
"""
data = Data
header = Header
worksheet = Worksheet
def get_table_id(self):
if self.id.text:
return self.id.text.split('/')[-1]
return None
GetTableId = get_table_id
class TablesFeed(gdata.data.GDFeed):
"""An Atom feed containing the tables defined within a worksheet."""
entry = [Table]
class Record(gdata.data.GDEntry):
"""An Atom entry representing a single record in a table.
Note that the order of items in each record is the same as the order of
columns in the table definition, which may not match the order of
columns in the GUI.
"""
field = [Field]
def value_for_index(self, column_index):
for field in self.field:
if field.index == column_index:
return field.text
raise FieldMissing('There is no field for %s' % column_index)
ValueForIndex = value_for_index
def value_for_name(self, name):
for field in self.field:
if field.name == name:
return field.text
raise FieldMissing('There is no field for %s' % name)
ValueForName = value_for_name
def get_record_id(self):
if self.id.text:
return self.id.text.split('/')[-1]
return None
class RecordsFeed(gdata.data.GDFeed):
"""An Atom feed containing the individuals records in a table."""
entry = [Record]
class ListRow(atom.core.XmlElement):
"""A gsx column value within a row.
The local tag in the _qname is blank and must be set to the column
name. For example, when adding to a ListEntry, do:
col_value = ListRow(text='something')
col_value._qname = col_value._qname % 'mycolumnname'
"""
_qname = '{http://schemas.google.com/spreadsheets/2006/extended}%s'
class ListEntry(gdata.data.GDEntry):
"""An Atom entry representing a worksheet row in the list feed.
The values for a particular column can be get and set using
x.get_value('columnheader') and x.set_value('columnheader', 'value').
See also the explanation of column names in the ListFeed class.
"""
def get_value(self, column_name):
"""Returns the displayed text for the desired column in this row.
The formula or input which generated the displayed value is not accessible
through the list feed, to see the user's input, use the cells feed.
If a column is not present in this spreadsheet, or there is no value
for a column in this row, this method will return None.
"""
values = self.get_elements(column_name, GSX_NAMESPACE)
if len(values) == 0:
return None
return values[0].text
def set_value(self, column_name, value):
"""Changes the value of cell in this row under the desired column name.
Warning: if the cell contained a formula, it will be wiped out by setting
the value using the list feed since the list feed only works with
displayed values.
No client side checking is performed on the column_name, you need to
ensure that the column_name is the local tag name in the gsx tag for the
column. For example, the column_name will not contain special characters,
spaces, uppercase letters, etc.
"""
# Try to find the column in this row to change an existing value.
values = self.get_elements(column_name, GSX_NAMESPACE)
if len(values) > 0:
values[0].text = value
else:
# There is no value in this row for the desired column, so add a new
# gsx:column_name element.
new_value = ListRow(text=value)
new_value._qname = new_value._qname % (column_name,)
self._other_elements.append(new_value)
def to_dict(self):
"""Converts this row to a mapping of column names to their values."""
result = {}
values = self.get_elements(namespace=GSX_NAMESPACE)
for item in values:
result[item._get_tag()] = item.text
return result
def from_dict(self, values):
"""Sets values for this row from the dictionary.
Old values which are already in the entry will not be removed unless
they are overwritten with new values from the dict.
"""
for column, value in values.iteritems():
self.set_value(column, value)
class ListsFeed(gdata.data.GDFeed):
"""An Atom feed in which each entry represents a row in a worksheet.
The first row in the worksheet is used as the column names for the values
in each row. If a header cell is empty, then a unique column ID is used
for the gsx element name.
Spaces in a column name are removed from the name of the corresponding
gsx element.
Caution: The columnNames are case-insensitive. For example, if you see
a <gsx:e-mail> element in a feed, you can't know whether the column
heading in the original worksheet was "e-mail" or "E-Mail".
Note: If two or more columns have the same name, then subsequent columns
of the same name have _n appended to the columnName. For example, if the
first column name is "e-mail", followed by columns named "E-Mail" and
"E-mail", then the columnNames will be gsx:e-mail, gsx:e-mail_2, and
gsx:e-mail_3 respectively.
"""
entry = [ListEntry]
class CellEntry(gdata.data.BatchEntry):
"""An Atom entry representing a single cell in a worksheet."""
cell = Cell
class CellsFeed(gdata.data.BatchFeed):
"""An Atom feed contains one entry per cell in a worksheet.
The cell feed supports batch operations, you can send multiple cell
operations in one HTTP request.
"""
entry = [CellEntry]
def add_set_cell(self, row, col, input_value):
"""Adds a request to change the contents of a cell to this batch request.
Args:
row: int, The row number for this cell. Numbering starts at 1.
col: int, The column number for this cell. Starts at 1.
input_value: str, The desired formula/content this cell should contain.
"""
self.add_update(CellEntry(
id=atom.data.Id(text=BATCH_ENTRY_ID_TEMPLATE % (
self.id.text, row, col)),
cell=Cell(col=str(col), row=str(row), input_value=input_value)))
return self
AddSetCell = add_set_cell
def build_batch_cells_update(spreadsheet_key, worksheet_id):
"""Creates an empty cells feed for adding batch cell updates to.
Call batch_set_cell on the resulting CellsFeed instance then send the batch
request TODO: fill in
Args:
spreadsheet_key: The ID of the spreadsheet
worksheet_id:
"""
feed_id_text = BATCH_POST_ID_TEMPLATE % (spreadsheet_key, worksheet_id)
return CellsFeed(
id=atom.data.Id(text=feed_id_text),
link=[atom.data.Link(
rel='edit', href=BATCH_EDIT_LINK_TEMPLATE % (feed_id_text,))])
BuildBatchCellsUpdate = build_batch_cells_update
| 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 Google Spreadsheets servers.
For documentation on the Spreadsheets API, see:
http://code.google.com/apis/spreadsheets/
"""
__author__ = 'j.s@google.com (Jeff Scudder)'
import gdata.client
import gdata.gauth
import gdata.spreadsheets.data
import atom.data
import atom.http_core
SPREADSHEETS_URL = ('https://spreadsheets.google.com/feeds/spreadsheets'
'/private/full')
WORKSHEETS_URL = ('https://spreadsheets.google.com/feeds/worksheets/'
'%s/private/full')
WORKSHEET_URL = ('https://spreadsheets.google.com/feeds/worksheets/'
'%s/private/full/%s')
TABLES_URL = 'https://spreadsheets.google.com/feeds/%s/tables'
RECORDS_URL = 'https://spreadsheets.google.com/feeds/%s/records/%s'
RECORD_URL = 'https://spreadsheets.google.com/feeds/%s/records/%s/%s'
CELLS_URL = 'https://spreadsheets.google.com/feeds/cells/%s/%s/private/full'
CELL_URL = ('https://spreadsheets.google.com/feeds/cells/%s/%s/private/full/'
'R%sC%s')
LISTS_URL = 'https://spreadsheets.google.com/feeds/list/%s/%s/private/full'
class SpreadsheetsClient(gdata.client.GDClient):
api_version = '3'
auth_service = 'wise'
auth_scopes = gdata.gauth.AUTH_SCOPES['wise']
ssl = True
def get_spreadsheets(self, auth_token=None,
desired_class=gdata.spreadsheets.data.SpreadsheetsFeed,
**kwargs):
"""Obtains a feed with the spreadsheets belonging to the current user.
Args:
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (converter=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.spreadsheets.data.SpreadsheetsFeed.
"""
return self.get_feed(SPREADSHEETS_URL, auth_token=auth_token,
desired_class=desired_class, **kwargs)
GetSpreadsheets = get_spreadsheets
def get_worksheets(self, spreadsheet_key, auth_token=None,
desired_class=gdata.spreadsheets.data.WorksheetsFeed,
**kwargs):
"""Finds the worksheets within a given spreadsheet.
Args:
spreadsheet_key: str, The unique ID of this containing spreadsheet. This
can be the ID from the URL or as provided in a
Spreadsheet entry.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (converter=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.spreadsheets.data.WorksheetsFeed.
"""
return self.get_feed(WORKSHEETS_URL % spreadsheet_key,
auth_token=auth_token, desired_class=desired_class,
**kwargs)
GetWorksheets = get_worksheets
def add_worksheet(self, spreadsheet_key, title, rows, cols,
auth_token=None, **kwargs):
"""Creates a new worksheet entry in the spreadsheet.
Args:
spreadsheet_key: str, The unique ID of this containing spreadsheet. This
can be the ID from the URL or as provided in a
Spreadsheet entry.
title: str, The title to be used in for the worksheet.
rows: str or int, The number of rows this worksheet should start with.
cols: str or int, The number of columns this worksheet should start with.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
new_worksheet = gdata.spreadsheets.data.WorksheetEntry(
title=atom.data.Title(text=title),
row_count=gdata.spreadsheets.data.RowCount(text=str(rows)),
col_count=gdata.spreadsheets.data.ColCount(text=str(cols)))
return self.post(new_worksheet, WORKSHEETS_URL % spreadsheet_key,
auth_token=auth_token, **kwargs)
AddWorksheet = add_worksheet
def get_worksheet(self, spreadsheet_key, worksheet_id,
desired_class=gdata.spreadsheets.data.WorksheetEntry,
auth_token=None, **kwargs):
"""Retrieves a single worksheet.
Args:
spreadsheet_key: str, The unique ID of this containing spreadsheet. This
can be the ID from the URL or as provided in a
Spreadsheet entry.
worksheet_id: str, The unique ID for the worksheet withing the desired
spreadsheet.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (converter=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.spreadsheets.data.WorksheetEntry.
"""
return self.get_entry(WORKSHEET_URL % (spreadsheet_key, worksheet_id,),
auth_token=auth_token, desired_class=desired_class,
**kwargs)
GetWorksheet = get_worksheet
def add_table(self, spreadsheet_key, title, summary, worksheet_name,
header_row, num_rows, start_row, insertion_mode,
column_headers, auth_token=None, **kwargs):
"""Creates a new table within the worksheet.
Args:
spreadsheet_key: str, The unique ID of this containing spreadsheet. This
can be the ID from the URL or as provided in a
Spreadsheet entry.
title: str, The title for the new table within a worksheet.
summary: str, A description of the table.
worksheet_name: str The name of the worksheet in which this table
should live.
header_row: int or str, The number of the row in the worksheet which
will contain the column names for the data in this table.
num_rows: int or str, The number of adjacent rows in this table.
start_row: int or str, The number of the row at which the data begins.
insertion_mode: str
column_headers: dict of strings, maps the column letters (A, B, C) to
the desired name which will be viewable in the
worksheet.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
data = gdata.spreadsheets.data.Data(
insertion_mode=insertion_mode, num_rows=str(num_rows),
start_row=str(start_row))
for index, name in column_headers.iteritems():
data.column.append(gdata.spreadsheets.data.Column(
index=index, name=name))
new_table = gdata.spreadsheets.data.Table(
title=atom.data.Title(text=title), summary=atom.data.Summary(summary),
worksheet=gdata.spreadsheets.data.Worksheet(name=worksheet_name),
header=gdata.spreadsheets.data.Header(row=str(header_row)), data=data)
return self.post(new_table, TABLES_URL % spreadsheet_key,
auth_token=auth_token, **kwargs)
AddTable = add_table
def get_tables(self, spreadsheet_key,
desired_class=gdata.spreadsheets.data.TablesFeed,
auth_token=None, **kwargs):
"""Retrieves a feed listing the tables in this spreadsheet.
Args:
spreadsheet_key: str, The unique ID of this containing spreadsheet. This
can be the ID from the URL or as provided in a
Spreadsheet entry.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (converter=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.spreadsheets.data.TablesFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_feed(TABLES_URL % spreadsheet_key,
desired_class=desired_class, auth_token=auth_token,
**kwargs)
GetTables = get_tables
def add_record(self, spreadsheet_key, table_id, fields,
title=None, auth_token=None, **kwargs):
"""Adds a new row to the table.
Args:
spreadsheet_key: str, The unique ID of this containing spreadsheet. This
can be the ID from the URL or as provided in a
Spreadsheet entry.
table_id: str, The ID of the table within the worksheet which should
receive this new record. The table ID can be found using the
get_table_id method of a gdata.spreadsheets.data.Table.
fields: dict of strings mapping column names to values.
title: str, optional The title for this row.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
new_record = gdata.spreadsheets.data.Record()
if title is not None:
new_record.title = atom.data.Title(text=title)
for name, value in fields.iteritems():
new_record.field.append(gdata.spreadsheets.data.Field(
name=name, text=value))
return self.post(new_record, RECORDS_URL % (spreadsheet_key, table_id),
auth_token=auth_token, **kwargs)
AddRecord = add_record
def get_records(self, spreadsheet_key, table_id,
desired_class=gdata.spreadsheets.data.RecordsFeed,
auth_token=None, **kwargs):
"""Retrieves the records in a table.
Args:
spreadsheet_key: str, The unique ID of this containing spreadsheet. This
can be the ID from the URL or as provided in a
Spreadsheet entry.
table_id: str, The ID of the table within the worksheet whose records
we would like to fetch. The table ID can be found using the
get_table_id method of a gdata.spreadsheets.data.Table.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (converter=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.spreadsheets.data.RecordsFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_feed(RECORDS_URL % (spreadsheet_key, table_id),
desired_class=desired_class, auth_token=auth_token,
**kwargs)
GetRecords = get_records
def get_record(self, spreadsheet_key, table_id, record_id,
desired_class=gdata.spreadsheets.data.Record,
auth_token=None, **kwargs):
"""Retrieves a single record from the table.
Args:
spreadsheet_key: str, The unique ID of this containing spreadsheet. This
can be the ID from the URL or as provided in a
Spreadsheet entry.
table_id: str, The ID of the table within the worksheet whose records
we would like to fetch. The table ID can be found using the
get_table_id method of a gdata.spreadsheets.data.Table.
record_id: str, The ID of the record within this table which we want to
fetch. You can find the record ID using get_record_id() on
an instance of the gdata.spreadsheets.data.Record class.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (converter=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.spreadsheets.data.RecordsFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_entry(RECORD_URL % (spreadsheet_key, table_id, record_id),
desired_class=desired_class, auth_token=auth_token,
**kwargs)
GetRecord = get_record
def get_cells(self, spreadsheet_key, worksheet_id,
desired_class=gdata.spreadsheets.data.CellsFeed,
auth_token=None, **kwargs):
"""Retrieves the cells which have values in this spreadsheet.
Blank cells are not included.
Args:
spreadsheet_key: str, The unique ID of this containing spreadsheet. This
can be the ID from the URL or as provided in a
Spreadsheet entry.
worksheet_id: str, The unique ID of the worksheet in this spreadsheet
whose cells we want. This can be obtained using
WorksheetEntry's get_worksheet_id method.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (converter=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.spreadsheets.data.CellsFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_feed(CELLS_URL % (spreadsheet_key, worksheet_id),
auth_token=auth_token, desired_class=desired_class,
**kwargs)
GetCells = get_cells
def get_cell(self, spreadsheet_key, worksheet_id, row_num, col_num,
desired_class=gdata.spreadsheets.data.CellEntry,
auth_token=None, **kwargs):
"""Retrieves a single cell from the worksheet.
Indexes are 1 based so the first cell in the worksheet is 1, 1.
Args:
spreadsheet_key: str, The unique ID of this containing spreadsheet. This
can be the ID from the URL or as provided in a
Spreadsheet entry.
worksheet_id: str, The unique ID of the worksheet in this spreadsheet
whose cells we want. This can be obtained using
WorksheetEntry's get_worksheet_id method.
row_num: int, The row of the cell that we want. Numbering starts with 1.
col_num: int, The column of the cell we want. Numbering starts with 1.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (converter=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.spreadsheets.data.CellEntry.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_entry(
CELL_URL % (spreadsheet_key, worksheet_id, row_num, col_num),
auth_token=auth_token, desired_class=desired_class, **kwargs)
GetCell = get_cell
def get_list_feed(self, spreadsheet_key, worksheet_id,
desired_class=gdata.spreadsheets.data.ListsFeed,
auth_token=None, **kwargs):
"""Retrieves the value rows from the worksheet's list feed.
The list feed is a view of the spreadsheet in which the first row is used
for column names and subsequent rows up to the first blank line are
records.
Args:
spreadsheet_key: str, The unique ID of this containing spreadsheet. This
can be the ID from the URL or as provided in a
Spreadsheet entry.
worksheet_id: str, The unique ID of the worksheet in this spreadsheet
whose cells we want. This can be obtained using
WorksheetEntry's get_worksheet_id method.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (converter=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.spreadsheets.data.ListsFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_feed(LISTS_URL % (spreadsheet_key, worksheet_id),
auth_token=auth_token, desired_class=desired_class,
**kwargs)
GetListFeed = get_list_feed
def add_list_entry(self, list_entry, spreadsheet_key, worksheet_id,
auth_token=None, **kwargs):
"""Adds a new row to the worksheet's list feed.
Args:
list_entry: gdata.spreadsheets.data.ListsEntry An entry which contains
the values which should be set for the columns in this
record.
spreadsheet_key: str, The unique ID of this containing spreadsheet. This
can be the ID from the URL or as provided in a
Spreadsheet entry.
worksheet_id: str, The unique ID of the worksheet in this spreadsheet
whose cells we want. This can be obtained using
WorksheetEntry's get_worksheet_id method.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.post(list_entry, LISTS_URL % (spreadsheet_key, worksheet_id),
auth_token=auth_token, **kwargs)
AddListEntry = add_list_entry
class SpreadsheetQuery(gdata.client.Query):
def __init__(self, title=None, title_exact=None, **kwargs):
"""Adds Spreadsheets feed query parameters to a request.
Args:
title: str Specifies the search terms for the title of a document.
This parameter used without title-exact will only submit partial
queries, not exact queries.
title_exact: str Specifies whether the title query should be taken as an
exact string. Meaningless without title. Possible values are
'true' and 'false'.
"""
gdata.client.Query.__init__(self, **kwargs)
self.title = title
self.title_exact = title_exact
def modify_request(self, http_request):
gdata.client._add_query_param('title', self.title, http_request)
gdata.client._add_query_param('title-exact', self.title_exact,
http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request
class WorksheetQuery(SpreadsheetQuery):
pass
class ListQuery(gdata.client.Query):
def __init__(self, order_by=None, reverse=None, sq=None, **kwargs):
"""Adds List-feed specific query parameters to a request.
Args:
order_by: str Specifies what column to use in ordering the entries in
the feed. By position (the default): 'position' returns
rows in the order in which they appear in the GUI. Row 1, then
row 2, then row 3, and so on. By column:
'column:columnName' sorts rows in ascending order based on the
values in the column with the given columnName, where
columnName is the value in the header row for that column.
reverse: str Specifies whether to sort in descending or ascending order.
Reverses default sort order: 'true' results in a descending
sort; 'false' (the default) results in an ascending sort.
sq: str Structured query on the full text in the worksheet.
[columnName][binaryOperator][value]
Supported binaryOperators are:
- (), for overriding order of operations
- = or ==, for strict equality
- <> or !=, for strict inequality
- and or &&, for boolean and
- or or ||, for boolean or
"""
gdata.client.Query.__init__(self, **kwargs)
self.order_by = order_by
self.reverse = reverse
self.sq = sq
def modify_request(self, http_request):
gdata.client._add_query_param('orderby', self.order_by, http_request)
gdata.client._add_query_param('reverse', self.reverse, http_request)
gdata.client._add_query_param('sq', self.sq, http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request
class TableQuery(ListQuery):
pass
class CellQuery(gdata.client.Query):
def __init__(self, min_row=None, max_row=None, min_col=None, max_col=None,
range=None, return_empty=None, **kwargs):
"""Adds Cells-feed specific query parameters to a request.
Args:
min_row: str or int Positional number of minimum row returned in query.
max_row: str or int Positional number of maximum row returned in query.
min_col: str or int Positional number of minimum column returned in query.
max_col: str or int Positional number of maximum column returned in query.
range: str A single cell or a range of cells. Use standard spreadsheet
cell-range notations, using a colon to separate start and end of
range. Examples:
- 'A1' and 'R1C1' both specify only cell A1.
- 'D1:F3' and 'R1C4:R3C6' both specify the rectangle of cells with
corners at D1 and F3.
return_empty: str If 'true' then empty cells will be returned in the feed.
If omitted, the default is 'false'.
"""
gdata.client.Query.__init__(self, **kwargs)
self.min_row = min_row
self.max_row = max_row
self.min_col = min_col
self.max_col = max_col
self.range = range
self.return_empty = return_empty
def modify_request(self, http_request):
gdata.client._add_query_param('min-row', self.min_row, http_request)
gdata.client._add_query_param('max-row', self.max_row, http_request)
gdata.client._add_query_param('min-col', self.min_col, http_request)
gdata.client._add_query_param('max-col', self.max_col, http_request)
gdata.client._add_query_param('range', self.range, http_request)
gdata.client._add_query_param('return-empty', self.return_empty,
http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request
| 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
try:
import gdata.tlslite.utils.keyfactory as keyfactory
except ImportError:
from tlslite.tlslite.utils import keyfactory
try:
import gdata.tlslite.utils.cryptomath as cryptomath
except ImportError:
from tlslite.tlslite.utils import 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 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 |
#!/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.
"""Data model for parsing and generating XML for the Calendar Resource API."""
__author__ = 'Vic Fryzel <vf@google.com>'
import atom.core
import atom.data
import gdata.apps
import gdata.apps_property
import gdata.data
# This is required to work around a naming conflict between the Google
# Spreadsheets API and Python's built-in property function
pyproperty = property
# The apps:property name of the resourceId property
RESOURCE_ID_NAME = 'resourceId'
# The apps:property name of the resourceCommonName property
RESOURCE_COMMON_NAME_NAME = 'resourceCommonName'
# The apps:property name of the resourceDescription property
RESOURCE_DESCRIPTION_NAME = 'resourceDescription'
# The apps:property name of the resourceType property
RESOURCE_TYPE_NAME = 'resourceType'
# The apps:property name of the resourceEmail property
RESOURCE_EMAIL_NAME = 'resourceEmail'
class CalendarResourceEntry(gdata.data.GDEntry):
"""Represents a Calendar Resource entry in object form."""
property = [gdata.apps_property.AppsProperty]
def _GetProperty(self, name):
"""Get the apps:property value with the given name.
Args:
name: string Name of the apps:property value to get.
Returns:
The apps:property value with the given name, or None if the name was
invalid.
"""
for p in self.property:
if p.name == name:
return p.value
return None
def _SetProperty(self, name, value):
"""Set the apps:property value with the given name to the given value.
Args:
name: string Name of the apps:property value to set.
value: string Value to give the apps:property value with the given name.
"""
for i in range(len(self.property)):
if self.property[i].name == name:
self.property[i].value = value
return
self.property.append(gdata.apps_property.AppsProperty(name=name, value=value))
def GetResourceId(self):
"""Get the resource ID of this Calendar Resource object.
Returns:
The resource ID of this Calendar Resource object as a string or None.
"""
return self._GetProperty(RESOURCE_ID_NAME)
def SetResourceId(self, value):
"""Set the resource ID of this Calendar Resource object.
Args:
value: string The new resource ID value to give this object.
"""
self._SetProperty(RESOURCE_ID_NAME, value)
resource_id = pyproperty(GetResourceId, SetResourceId)
def GetResourceCommonName(self):
"""Get the common name of this Calendar Resource object.
Returns:
The common name of this Calendar Resource object as a string or None.
"""
return self._GetProperty(RESOURCE_COMMON_NAME_NAME)
def SetResourceCommonName(self, value):
"""Set the common name of this Calendar Resource object.
Args:
value: string The new common name value to give this object.
"""
self._SetProperty(RESOURCE_COMMON_NAME_NAME, value)
resource_common_name = pyproperty(
GetResourceCommonName,
SetResourceCommonName)
def GetResourceDescription(self):
"""Get the description of this Calendar Resource object.
Returns:
The description of this Calendar Resource object as a string or None.
"""
return self._GetProperty(RESOURCE_DESCRIPTION_NAME)
def SetResourceDescription(self, value):
"""Set the description of this Calendar Resource object.
Args:
value: string The new description value to give this object.
"""
self._SetProperty(RESOURCE_DESCRIPTION_NAME, value)
resource_description = pyproperty(
GetResourceDescription,
SetResourceDescription)
def GetResourceType(self):
"""Get the type of this Calendar Resource object.
Returns:
The type of this Calendar Resource object as a string or None.
"""
return self._GetProperty(RESOURCE_TYPE_NAME)
def SetResourceType(self, value):
"""Set the type value of this Calendar Resource object.
Args:
value: string The new type value to give this object.
"""
self._SetProperty(RESOURCE_TYPE_NAME, value)
resource_type = pyproperty(GetResourceType, SetResourceType)
def GetResourceEmail(self):
"""Get the email of this Calendar Resource object.
Returns:
The email of this Calendar Resource object as a string or None.
"""
return self._GetProperty(RESOURCE_EMAIL_NAME)
resource_email = pyproperty(GetResourceEmail)
def __init__(self, resource_id=None, resource_common_name=None,
resource_description=None, resource_type=None, *args, **kwargs):
"""Constructs a new CalendarResourceEntry object with the given arguments.
Args:
resource_id: string (optional) The resource ID to give this new object.
resource_common_name: string (optional) The common name to give this new
object.
resource_description: string (optional) The description to give this new
object.
resource_type: string (optional) The type to give this new object.
args: The other parameters to pass to gdata.entry.GDEntry constructor.
kwargs: The other parameters to pass to gdata.entry.GDEntry constructor.
"""
super(CalendarResourceEntry, self).__init__(*args, **kwargs)
if resource_id:
self.resource_id = resource_id
if resource_common_name:
self.resource_common_name = resource_common_name
if resource_description:
self.resource_description = resource_description
if resource_type:
self.resource_type = resource_type
class CalendarResourceFeed(gdata.data.GDFeed):
"""Represents a feed of CalendarResourceEntry objects."""
# Override entry so that this feed knows how to type its list of entries.
entry = [CalendarResourceEntry]
| Python |
#!/usr/bin/python
#
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""CalendarResourceClient simplifies Calendar Resources API calls.
CalendarResourceClient extends gdata.client.GDClient to ease interaction with
the Google Apps Calendar Resources API. These interactions include the ability
to create, retrieve, update, and delete calendar resources in a Google Apps
domain.
"""
__author__ = 'Vic Fryzel <vf@google.com>'
import gdata.calendar_resource.data
import gdata.client
import urllib
# Feed URI template. This must end with a /
# The strings in this template are eventually replaced with the API version
# and Google Apps domain name, respectively.
RESOURCE_FEED_TEMPLATE = '/a/feeds/calendar/resource/%s/%s/'
class CalendarResourceClient(gdata.client.GDClient):
"""Client extension for the Google Calendar Resource API service.
Attributes:
host: string The hostname for the Calendar Resouce API service.
api_version: string The version of the Calendar Resource API.
"""
host = 'apps-apis.google.com'
api_version = '2.0'
auth_service = 'apps'
auth_scopes = gdata.gauth.AUTH_SCOPES['apps']
ssl = True
def __init__(self, domain, auth_token=None, **kwargs):
"""Constructs a new client for the Calendar Resource API.
Args:
domain: string The Google Apps domain with Calendar Resources.
auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or
OAuthToken which authorizes this client to edit the calendar resource
data.
kwargs: The other parameters to pass to the gdata.client.GDClient
constructor.
"""
gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs)
self.domain = domain
def make_resource_feed_uri(self, resource_id=None, params=None):
"""Creates a resource feed URI for the Calendar Resource API.
Using this client's Google Apps domain, create a feed URI for calendar
resources in that domain. If a resource_id is provided, return a URI
for that specific resource. If params are provided, append them as GET
params.
Args:
resource_id: string (optional) The ID of the calendar resource for which
to make a feed URI.
params: dict (optional) key -> value params to append as GET vars to the
URI. Example: params={'start': 'my-resource-id'}
Returns:
A string giving the URI for calendar resources for this client's Google
Apps domain.
"""
uri = RESOURCE_FEED_TEMPLATE % (self.api_version, self.domain)
if resource_id:
uri += resource_id
if params:
uri += '?' + urllib.urlencode(params)
return uri
MakeResourceFeedUri = make_resource_feed_uri
def get_resource_feed(self, uri=None, **kwargs):
"""Fetches a ResourceFeed of calendar resources at the given URI.
Args:
uri: string The URI of the feed to pull.
kwargs: The other parameters to pass to gdata.client.GDClient.get_feed().
Returns:
A ResourceFeed object representing the feed at the given URI.
"""
if uri is None:
uri = self.MakeResourceFeedUri()
return self.get_feed(
uri,
desired_class=gdata.calendar_resource.data.CalendarResourceFeed,
**kwargs)
GetResourceFeed = get_resource_feed
def get_resource(self, uri=None, resource_id=None, **kwargs):
"""Fetches a single calendar resource by resource ID.
Args:
uri: string The base URI of the feed from which to fetch the resource.
resource_id: string The string ID of the Resource to fetch.
kwargs: The other parameters to pass to gdata.client.GDClient.get_entry().
Returns:
A Resource object representing the calendar resource with the given
base URI and resource ID.
"""
if uri is None:
uri = self.MakeResourceFeedUri(resource_id)
return self.get_entry(
uri,
desired_class=gdata.calendar_resource.data.CalendarResourceEntry,
**kwargs)
GetResource = get_resource
def create_resource(self, resource_id, resource_common_name=None,
resource_description=None, resource_type=None, **kwargs):
"""Creates a calendar resource with the given properties.
Args:
resource_id: string The resource ID of the calendar resource.
resource_common_name: string (optional) The common name of the resource.
resource_description: string (optional) The description of the resource.
resource_type: string (optional) The type of the resource.
kwargs: The other parameters to pass to gdata.client.GDClient.post().
Returns:
gdata.calendar_resource.data.CalendarResourceEntry of the new resource.
"""
new_resource = gdata.calendar_resource.data.CalendarResourceEntry(
resource_id=resource_id,
resource_common_name=resource_common_name,
resource_description=resource_description,
resource_type=resource_type)
return self.post(new_resource, self.MakeResourceFeedUri(), **kwargs)
CreateResource = create_resource
def update_resource(self, resource_id, resource_common_name=None,
resource_description=None, resource_type=None, **kwargs):
"""Updates the calendar resource with the given resource ID.
Args:
resource_id: string The resource ID of the calendar resource to update.
resource_common_name: string (optional) The common name to give the
resource.
resource_description: string (optional) The description to give the
resource.
resource_type: string (optional) The type to give the resource.
kwargs: The other parameters to pass to gdata.client.GDClient.update().
Returns:
gdata.calendar_resource.data.CalendarResourceEntry of the updated
resource.
"""
new_resource = gdata.calendar_resource.data.CalendarResourceEntry(
resource_id=resource_id,
resource_common_name=resource_common_name,
resource_description=resource_description,
resource_type=resource_type)
return self.update(new_resource, uri=self.MakeResourceFeedUri(resource_id),
**kwargs)
UpdateResource = update_resource
def delete_resource(self, resource_id, **kwargs):
"""Deletes the calendar resource with the given resource ID.
Args:
resource_id: string The resource ID of the calendar resource to delete.
kwargs: The other parameters to pass to gdata.client.GDClient.delete()
Returns:
An HTTP response object. See gdata.client.request().
"""
return self.delete(self.MakeResourceFeedUri(resource_id), **kwargs)
DeleteResource = delete_resource
| Python |
#!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This module is used for version 2 of the Google Data APIs.
"""Provides classes and constants for the XML in the Google Data namespace.
Documentation for the raw XML which these classes represent can be found here:
http://code.google.com/apis/gdata/docs/2.0/elements.html
"""
__author__ = 'j.s@google.com (Jeff Scudder)'
import os
import atom.core
import atom.data
GDATA_TEMPLATE = '{http://schemas.google.com/g/2005}%s'
GD_TEMPLATE = GDATA_TEMPLATE
OPENSEARCH_TEMPLATE_V1 = '{http://a9.com/-/spec/opensearchrss/1.0/}%s'
OPENSEARCH_TEMPLATE_V2 = '{http://a9.com/-/spec/opensearch/1.1/}%s'
BATCH_TEMPLATE = '{http://schemas.google.com/gdata/batch}%s'
# Labels used in batch request entries to specify the desired CRUD operation.
BATCH_INSERT = 'insert'
BATCH_UPDATE = 'update'
BATCH_DELETE = 'delete'
BATCH_QUERY = 'query'
EVENT_LOCATION = 'http://schemas.google.com/g/2005#event'
ALTERNATE_LOCATION = 'http://schemas.google.com/g/2005#event.alternate'
PARKING_LOCATION = 'http://schemas.google.com/g/2005#event.parking'
CANCELED_EVENT = 'http://schemas.google.com/g/2005#event.canceled'
CONFIRMED_EVENT = 'http://schemas.google.com/g/2005#event.confirmed'
TENTATIVE_EVENT = 'http://schemas.google.com/g/2005#event.tentative'
CONFIDENTIAL_EVENT = 'http://schemas.google.com/g/2005#event.confidential'
DEFAULT_EVENT = 'http://schemas.google.com/g/2005#event.default'
PRIVATE_EVENT = 'http://schemas.google.com/g/2005#event.private'
PUBLIC_EVENT = 'http://schemas.google.com/g/2005#event.public'
OPAQUE_EVENT = 'http://schemas.google.com/g/2005#event.opaque'
TRANSPARENT_EVENT = 'http://schemas.google.com/g/2005#event.transparent'
CHAT_MESSAGE = 'http://schemas.google.com/g/2005#message.chat'
INBOX_MESSAGE = 'http://schemas.google.com/g/2005#message.inbox'
SENT_MESSAGE = 'http://schemas.google.com/g/2005#message.sent'
SPAM_MESSAGE = 'http://schemas.google.com/g/2005#message.spam'
STARRED_MESSAGE = 'http://schemas.google.com/g/2005#message.starred'
UNREAD_MESSAGE = 'http://schemas.google.com/g/2005#message.unread'
BCC_RECIPIENT = 'http://schemas.google.com/g/2005#message.bcc'
CC_RECIPIENT = 'http://schemas.google.com/g/2005#message.cc'
SENDER = 'http://schemas.google.com/g/2005#message.from'
REPLY_TO = 'http://schemas.google.com/g/2005#message.reply-to'
TO_RECIPIENT = 'http://schemas.google.com/g/2005#message.to'
ASSISTANT_REL = 'http://schemas.google.com/g/2005#assistant'
CALLBACK_REL = 'http://schemas.google.com/g/2005#callback'
CAR_REL = 'http://schemas.google.com/g/2005#car'
COMPANY_MAIN_REL = 'http://schemas.google.com/g/2005#company_main'
FAX_REL = 'http://schemas.google.com/g/2005#fax'
HOME_REL = 'http://schemas.google.com/g/2005#home'
HOME_FAX_REL = 'http://schemas.google.com/g/2005#home_fax'
ISDN_REL = 'http://schemas.google.com/g/2005#isdn'
MAIN_REL = 'http://schemas.google.com/g/2005#main'
MOBILE_REL = 'http://schemas.google.com/g/2005#mobile'
OTHER_REL = 'http://schemas.google.com/g/2005#other'
OTHER_FAX_REL = 'http://schemas.google.com/g/2005#other_fax'
PAGER_REL = 'http://schemas.google.com/g/2005#pager'
RADIO_REL = 'http://schemas.google.com/g/2005#radio'
TELEX_REL = 'http://schemas.google.com/g/2005#telex'
TTL_TDD_REL = 'http://schemas.google.com/g/2005#tty_tdd'
WORK_REL = 'http://schemas.google.com/g/2005#work'
WORK_FAX_REL = 'http://schemas.google.com/g/2005#work_fax'
WORK_MOBILE_REL = 'http://schemas.google.com/g/2005#work_mobile'
WORK_PAGER_REL = 'http://schemas.google.com/g/2005#work_pager'
NETMEETING_REL = 'http://schemas.google.com/g/2005#netmeeting'
OVERALL_REL = 'http://schemas.google.com/g/2005#overall'
PRICE_REL = 'http://schemas.google.com/g/2005#price'
QUALITY_REL = 'http://schemas.google.com/g/2005#quality'
EVENT_REL = 'http://schemas.google.com/g/2005#event'
EVENT_ALTERNATE_REL = 'http://schemas.google.com/g/2005#event.alternate'
EVENT_PARKING_REL = 'http://schemas.google.com/g/2005#event.parking'
AIM_PROTOCOL = 'http://schemas.google.com/g/2005#AIM'
MSN_PROTOCOL = 'http://schemas.google.com/g/2005#MSN'
YAHOO_MESSENGER_PROTOCOL = 'http://schemas.google.com/g/2005#YAHOO'
SKYPE_PROTOCOL = 'http://schemas.google.com/g/2005#SKYPE'
QQ_PROTOCOL = 'http://schemas.google.com/g/2005#QQ'
GOOGLE_TALK_PROTOCOL = 'http://schemas.google.com/g/2005#GOOGLE_TALK'
ICQ_PROTOCOL = 'http://schemas.google.com/g/2005#ICQ'
JABBER_PROTOCOL = 'http://schemas.google.com/g/2005#JABBER'
REGULAR_COMMENTS = 'http://schemas.google.com/g/2005#regular'
REVIEW_COMMENTS = 'http://schemas.google.com/g/2005#reviews'
MAIL_BOTH = 'http://schemas.google.com/g/2005#both'
MAIL_LETTERS = 'http://schemas.google.com/g/2005#letters'
MAIL_PARCELS = 'http://schemas.google.com/g/2005#parcels'
MAIL_NEITHER = 'http://schemas.google.com/g/2005#neither'
GENERAL_ADDRESS = 'http://schemas.google.com/g/2005#general'
LOCAL_ADDRESS = 'http://schemas.google.com/g/2005#local'
OPTIONAL_ATENDEE = 'http://schemas.google.com/g/2005#event.optional'
REQUIRED_ATENDEE = 'http://schemas.google.com/g/2005#event.required'
ATTENDEE_ACCEPTED = 'http://schemas.google.com/g/2005#event.accepted'
ATTENDEE_DECLINED = 'http://schemas.google.com/g/2005#event.declined'
ATTENDEE_INVITED = 'http://schemas.google.com/g/2005#event.invited'
ATTENDEE_TENTATIVE = 'http://schemas.google.com/g/2005#event.tentative'
FULL_PROJECTION = 'full'
VALUES_PROJECTION = 'values'
BASIC_PROJECTION = 'basic'
PRIVATE_VISIBILITY = 'private'
PUBLIC_VISIBILITY = 'public'
OPAQUE_TRANSPARENCY = 'http://schemas.google.com/g/2005#event.opaque'
TRANSPARENT_TRANSPARENCY = 'http://schemas.google.com/g/2005#event.transparent'
CONFIDENTIAL_EVENT_VISIBILITY = 'http://schemas.google.com/g/2005#event.confidential'
DEFAULT_EVENT_VISIBILITY = 'http://schemas.google.com/g/2005#event.default'
PRIVATE_EVENT_VISIBILITY = 'http://schemas.google.com/g/2005#event.private'
PUBLIC_EVENT_VISIBILITY = 'http://schemas.google.com/g/2005#event.public'
CANCELED_EVENT_STATUS = 'http://schemas.google.com/g/2005#event.canceled'
CONFIRMED_EVENT_STATUS = 'http://schemas.google.com/g/2005#event.confirmed'
TENTATIVE_EVENT_STATUS = 'http://schemas.google.com/g/2005#event.tentative'
ACL_REL = 'http://schemas.google.com/acl/2007#accessControlList'
class Error(Exception):
pass
class MissingRequiredParameters(Error):
pass
class LinkFinder(atom.data.LinkFinder):
"""Mixin used in Feed and Entry classes to simplify link lookups by type.
Provides lookup methods for edit, edit-media, post, ACL and other special
links which are common across Google Data APIs.
"""
def find_html_link(self):
"""Finds the first link with rel of alternate and type of text/html."""
for link in self.link:
if link.rel == 'alternate' and link.type == 'text/html':
return link.href
return None
FindHtmlLink = find_html_link
def get_html_link(self):
for a_link in self.link:
if a_link.rel == 'alternate' and a_link.type == 'text/html':
return a_link
return None
GetHtmlLink = get_html_link
def find_post_link(self):
"""Get the URL to which new entries should be POSTed.
The POST target URL is used to insert new entries.
Returns:
A str for the URL in the link with a rel matching the POST type.
"""
return self.find_url('http://schemas.google.com/g/2005#post')
FindPostLink = find_post_link
def get_post_link(self):
return self.get_link('http://schemas.google.com/g/2005#post')
GetPostLink = get_post_link
def find_acl_link(self):
acl_link = self.get_acl_link()
if acl_link:
return acl_link.href
return None
FindAclLink = find_acl_link
def get_acl_link(self):
"""Searches for a link or feed_link (if present) with the rel for ACL."""
acl_link = self.get_link(ACL_REL)
if acl_link:
return acl_link
elif hasattr(self, 'feed_link'):
for a_feed_link in self.feed_link:
if a_feed_link.rel == ACL_REL:
return a_feed_link
return None
GetAclLink = get_acl_link
def find_feed_link(self):
return self.find_url('http://schemas.google.com/g/2005#feed')
FindFeedLink = find_feed_link
def get_feed_link(self):
return self.get_link('http://schemas.google.com/g/2005#feed')
GetFeedLink = get_feed_link
def find_previous_link(self):
return self.find_url('previous')
FindPreviousLink = find_previous_link
def get_previous_link(self):
return self.get_link('previous')
GetPreviousLink = get_previous_link
class TotalResults(atom.core.XmlElement):
"""opensearch:TotalResults for a GData feed."""
_qname = (OPENSEARCH_TEMPLATE_V1 % 'totalResults',
OPENSEARCH_TEMPLATE_V2 % 'totalResults')
class StartIndex(atom.core.XmlElement):
"""The opensearch:startIndex element in GData feed."""
_qname = (OPENSEARCH_TEMPLATE_V1 % 'startIndex',
OPENSEARCH_TEMPLATE_V2 % 'startIndex')
class ItemsPerPage(atom.core.XmlElement):
"""The opensearch:itemsPerPage element in GData feed."""
_qname = (OPENSEARCH_TEMPLATE_V1 % 'itemsPerPage',
OPENSEARCH_TEMPLATE_V2 % 'itemsPerPage')
class ExtendedProperty(atom.core.XmlElement):
"""The Google Data extendedProperty element.
Used to store arbitrary key-value information specific to your
application. The value can either be a text string stored as an XML
attribute (.value), or an XML node (XmlBlob) as a child element.
This element is used in the Google Calendar data API and the Google
Contacts data API.
"""
_qname = GDATA_TEMPLATE % 'extendedProperty'
name = 'name'
value = 'value'
def get_xml_blob(self):
"""Returns the XML blob as an atom.core.XmlElement.
Returns:
An XmlElement representing the blob's XML, or None if no
blob was set.
"""
if self._other_elements:
return self._other_elements[0]
else:
return None
GetXmlBlob = get_xml_blob
def set_xml_blob(self, blob):
"""Sets the contents of the extendedProperty to XML as a child node.
Since the extendedProperty is only allowed one child element as an XML
blob, setting the XML blob will erase any preexisting member elements
in this object.
Args:
blob: str or atom.core.XmlElement representing the XML blob stored in
the extendedProperty.
"""
# Erase any existing extension_elements, clears the child nodes from the
# extendedProperty.
if isinstance(blob, atom.core.XmlElement):
self._other_elements = [blob]
else:
self._other_elements = [atom.core.parse(str(blob))]
SetXmlBlob = set_xml_blob
class GDEntry(atom.data.Entry, LinkFinder):
"""Extends Atom Entry to provide data processing"""
etag = '{http://schemas.google.com/g/2005}etag'
def get_id(self):
if self.id is not None and self.id.text is not None:
return self.id.text.strip()
return None
GetId = get_id
def is_media(self):
if self.find_edit_media_link():
return True
return False
IsMedia = is_media
def find_media_link(self):
"""Returns the URL to the media content, if the entry is a media entry.
Otherwise returns None.
"""
if self.is_media():
return self.content.src
return None
FindMediaLink = find_media_link
class GDFeed(atom.data.Feed, LinkFinder):
"""A Feed from a GData service."""
etag = '{http://schemas.google.com/g/2005}etag'
total_results = TotalResults
start_index = StartIndex
items_per_page = ItemsPerPage
entry = [GDEntry]
def get_id(self):
if self.id is not None and self.id.text is not None:
return self.id.text.strip()
return None
GetId = get_id
def get_generator(self):
if self.generator and self.generator.text:
return self.generator.text.strip()
return None
class BatchId(atom.core.XmlElement):
"""Identifies a single operation in a batch request."""
_qname = BATCH_TEMPLATE % 'id'
class BatchOperation(atom.core.XmlElement):
"""The CRUD operation which this batch entry represents."""
_qname = BATCH_TEMPLATE % 'operation'
type = 'type'
class BatchStatus(atom.core.XmlElement):
"""The batch:status element present in a batch response entry.
A status element contains the code (HTTP response code) and
reason as elements. In a single request these fields would
be part of the HTTP response, but in a batch request each
Entry operation has a corresponding Entry in the response
feed which includes status information.
See http://code.google.com/apis/gdata/batch.html#Handling_Errors
"""
_qname = BATCH_TEMPLATE % 'status'
code = 'code'
reason = 'reason'
content_type = 'content-type'
class BatchEntry(GDEntry):
"""An atom:entry for use in batch requests.
The BatchEntry contains additional members to specify the operation to be
performed on this entry and a batch ID so that the server can reference
individual operations in the response feed. For more information, see:
http://code.google.com/apis/gdata/batch.html
"""
batch_operation = BatchOperation
batch_id = BatchId
batch_status = BatchStatus
class BatchInterrupted(atom.core.XmlElement):
"""The batch:interrupted element sent if batch request was interrupted.
Only appears in a feed if some of the batch entries could not be processed.
See: http://code.google.com/apis/gdata/batch.html#Handling_Errors
"""
_qname = BATCH_TEMPLATE % 'interrupted'
reason = 'reason'
success = 'success'
failures = 'failures'
parsed = 'parsed'
class BatchFeed(GDFeed):
"""A feed containing a list of batch request entries."""
interrupted = BatchInterrupted
entry = [BatchEntry]
def add_batch_entry(self, entry=None, id_url_string=None,
batch_id_string=None, operation_string=None):
"""Logic for populating members of a BatchEntry and adding to the feed.
If the entry is not a BatchEntry, it is converted to a BatchEntry so
that the batch specific members will be present.
The id_url_string can be used in place of an entry if the batch operation
applies to a URL. For example query and delete operations require just
the URL of an entry, no body is sent in the HTTP request. If an
id_url_string is sent instead of an entry, a BatchEntry is created and
added to the feed.
This method also assigns the desired batch id to the entry so that it
can be referenced in the server's response. If the batch_id_string is
None, this method will assign a batch_id to be the index at which this
entry will be in the feed's entry list.
Args:
entry: BatchEntry, atom.data.Entry, or another Entry flavor (optional)
The entry which will be sent to the server as part of the batch
request. The item must have a valid atom id so that the server
knows which entry this request references.
id_url_string: str (optional) The URL of the entry to be acted on. You
can find this URL in the text member of the atom id for an entry.
If an entry is not sent, this id will be used to construct a new
BatchEntry which will be added to the request feed.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. Note that batch_ids should either always be specified or
never, mixing could potentially result in duplicate batch ids.
operation_string: str (optional) The desired batch operation which will
set the batch_operation.type member of the entry. Options are
'insert', 'update', 'delete', and 'query'
Raises:
MissingRequiredParameters: Raised if neither an id_ url_string nor an
entry are provided in the request.
Returns:
The added entry.
"""
if entry is None and id_url_string is None:
raise MissingRequiredParameters('supply either an entry or URL string')
if entry is None and id_url_string is not None:
entry = BatchEntry(id=atom.data.Id(text=id_url_string))
if batch_id_string is not None:
entry.batch_id = BatchId(text=batch_id_string)
elif entry.batch_id is None or entry.batch_id.text is None:
entry.batch_id = BatchId(text=str(len(self.entry)))
if operation_string is not None:
entry.batch_operation = BatchOperation(type=operation_string)
self.entry.append(entry)
return entry
AddBatchEntry = add_batch_entry
def add_insert(self, entry, batch_id_string=None):
"""Add an insert request to the operations in this batch request feed.
If the entry doesn't yet have an operation or a batch id, these will
be set to the insert operation and a batch_id specified as a parameter.
Args:
entry: BatchEntry The entry which will be sent in the batch feed as an
insert request.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. Note that batch_ids should either always be specified or
never, mixing could potentially result in duplicate batch ids.
"""
self.add_batch_entry(entry=entry, batch_id_string=batch_id_string,
operation_string=BATCH_INSERT)
AddInsert = add_insert
def add_update(self, entry, batch_id_string=None):
"""Add an update request to the list of batch operations in this feed.
Sets the operation type of the entry to insert if it is not already set
and assigns the desired batch id to the entry so that it can be
referenced in the server's response.
Args:
entry: BatchEntry The entry which will be sent to the server as an
update (HTTP PUT) request. The item must have a valid atom id
so that the server knows which entry to replace.
batch_id_string: str (optional) The batch ID to be used to reference
this batch operation in the results feed. If this parameter is None,
the current length of the feed's entry array will be used as a
count. See also comments for AddInsert.
"""
self.add_batch_entry(entry=entry, batch_id_string=batch_id_string,
operation_string=BATCH_UPDATE)
AddUpdate = add_update
def add_delete(self, url_string=None, entry=None, batch_id_string=None):
"""Adds a delete request to the batch request feed.
This method takes either the url_string which is the atom id of the item
to be deleted, or the entry itself. The atom id of the entry must be
present so that the server knows which entry should be deleted.
Args:
url_string: str (optional) The URL of the entry to be deleted. You can
find this URL in the text member of the atom id for an entry.
entry: BatchEntry (optional) The entry to be deleted.
batch_id_string: str (optional)
Raises:
MissingRequiredParameters: Raised if neither a url_string nor an entry
are provided in the request.
"""
self.add_batch_entry(entry=entry, id_url_string=url_string,
batch_id_string=batch_id_string, operation_string=BATCH_DELETE)
AddDelete = add_delete
def add_query(self, url_string=None, entry=None, batch_id_string=None):
"""Adds a query request to the batch request feed.
This method takes either the url_string which is the query URL
whose results will be added to the result feed. The query URL will
be encapsulated in a BatchEntry, and you may pass in the BatchEntry
with a query URL instead of sending a url_string.
Args:
url_string: str (optional)
entry: BatchEntry (optional)
batch_id_string: str (optional)
Raises:
MissingRequiredParameters
"""
self.add_batch_entry(entry=entry, id_url_string=url_string,
batch_id_string=batch_id_string, operation_string=BATCH_QUERY)
AddQuery = add_query
def find_batch_link(self):
return self.find_url('http://schemas.google.com/g/2005#batch')
FindBatchLink = find_batch_link
class EntryLink(atom.core.XmlElement):
"""The gd:entryLink element.
Represents a logically nested entry. For example, a <gd:who>
representing a contact might have a nested entry from a contact feed.
"""
_qname = GDATA_TEMPLATE % 'entryLink'
entry = GDEntry
rel = 'rel'
read_only = 'readOnly'
href = 'href'
class FeedLink(atom.core.XmlElement):
"""The gd:feedLink element.
Represents a logically nested feed. For example, a calendar feed might
have a nested feed representing all comments on entries.
"""
_qname = GDATA_TEMPLATE % 'feedLink'
feed = GDFeed
rel = 'rel'
read_only = 'readOnly'
count_hint = 'countHint'
href = 'href'
class AdditionalName(atom.core.XmlElement):
"""The gd:additionalName element.
Specifies additional (eg. middle) name of the person.
Contains an attribute for the phonetic representaton of the name.
"""
_qname = GDATA_TEMPLATE % 'additionalName'
yomi = 'yomi'
class Comments(atom.core.XmlElement):
"""The gd:comments element.
Contains a comments feed for the enclosing entry (such as a calendar event).
"""
_qname = GDATA_TEMPLATE % 'comments'
rel = 'rel'
feed_link = FeedLink
class Country(atom.core.XmlElement):
"""The gd:country element.
Country name along with optional country code. The country code is
given in accordance with ISO 3166-1 alpha-2:
http://www.iso.org/iso/iso-3166-1_decoding_table
"""
_qname = GDATA_TEMPLATE % 'country'
code = 'code'
class EmailImParent(atom.core.XmlElement):
address = 'address'
label = 'label'
rel = 'rel'
primary = 'primary'
class Email(EmailImParent):
"""The gd:email element.
An email address associated with the containing entity (which is
usually an entity representing a person or a location).
"""
_qname = GDATA_TEMPLATE % 'email'
display_name = 'displayName'
class FamilyName(atom.core.XmlElement):
"""The gd:familyName element.
Specifies family name of the person, eg. "Smith".
"""
_qname = GDATA_TEMPLATE % 'familyName'
yomi = 'yomi'
class Im(EmailImParent):
"""The gd:im element.
An instant messaging address associated with the containing entity.
"""
_qname = GDATA_TEMPLATE % 'im'
protocol = 'protocol'
class GivenName(atom.core.XmlElement):
"""The gd:givenName element.
Specifies given name of the person, eg. "John".
"""
_qname = GDATA_TEMPLATE % 'givenName'
yomi = 'yomi'
class NamePrefix(atom.core.XmlElement):
"""The gd:namePrefix element.
Honorific prefix, eg. 'Mr' or 'Mrs'.
"""
_qname = GDATA_TEMPLATE % 'namePrefix'
class NameSuffix(atom.core.XmlElement):
"""The gd:nameSuffix element.
Honorific suffix, eg. 'san' or 'III'.
"""
_qname = GDATA_TEMPLATE % 'nameSuffix'
class FullName(atom.core.XmlElement):
"""The gd:fullName element.
Unstructured representation of the name.
"""
_qname = GDATA_TEMPLATE % 'fullName'
class Name(atom.core.XmlElement):
"""The gd:name element.
Allows storing person's name in a structured way. Consists of
given name, additional name, family name, prefix, suffix and full name.
"""
_qname = GDATA_TEMPLATE % 'name'
given_name = GivenName
additional_name = AdditionalName
family_name = FamilyName
name_prefix = NamePrefix
name_suffix = NameSuffix
full_name = FullName
class OrgDepartment(atom.core.XmlElement):
"""The gd:orgDepartment element.
Describes a department within an organization. Must appear within a
gd:organization element.
"""
_qname = GDATA_TEMPLATE % 'orgDepartment'
class OrgJobDescription(atom.core.XmlElement):
"""The gd:orgJobDescription element.
Describes a job within an organization. Must appear within a
gd:organization element.
"""
_qname = GDATA_TEMPLATE % 'orgJobDescription'
class OrgName(atom.core.XmlElement):
"""The gd:orgName element.
The name of the organization. Must appear within a gd:organization
element.
Contains a Yomigana attribute (Japanese reading aid) for the
organization name.
"""
_qname = GDATA_TEMPLATE % 'orgName'
yomi = 'yomi'
class OrgSymbol(atom.core.XmlElement):
"""The gd:orgSymbol element.
Provides a symbol of an organization. Must appear within a
gd:organization element.
"""
_qname = GDATA_TEMPLATE % 'orgSymbol'
class OrgTitle(atom.core.XmlElement):
"""The gd:orgTitle element.
The title of a person within an organization. Must appear within a
gd:organization element.
"""
_qname = GDATA_TEMPLATE % 'orgTitle'
class Organization(atom.core.XmlElement):
"""The gd:organization element.
An organization, typically associated with a contact.
"""
_qname = GDATA_TEMPLATE % 'organization'
label = 'label'
primary = 'primary'
rel = 'rel'
department = OrgDepartment
job_description = OrgJobDescription
name = OrgName
symbol = OrgSymbol
title = OrgTitle
class When(atom.core.XmlElement):
"""The gd:when element.
Represents a period of time or an instant.
"""
_qname = GDATA_TEMPLATE % 'when'
end = 'endTime'
start = 'startTime'
value = 'valueString'
class OriginalEvent(atom.core.XmlElement):
"""The gd:originalEvent element.
Equivalent to the Recurrence ID property specified in section 4.8.4.4
of RFC 2445. Appears in every instance of a recurring event, to identify
the original event.
Contains a <gd:when> element specifying the original start time of the
instance that has become an exception.
"""
_qname = GDATA_TEMPLATE % 'originalEvent'
id = 'id'
href = 'href'
when = When
class PhoneNumber(atom.core.XmlElement):
"""The gd:phoneNumber element.
A phone number associated with the containing entity (which is usually
an entity representing a person or a location).
"""
_qname = GDATA_TEMPLATE % 'phoneNumber'
label = 'label'
rel = 'rel'
uri = 'uri'
primary = 'primary'
class PostalAddress(atom.core.XmlElement):
"""The gd:postalAddress element."""
_qname = GDATA_TEMPLATE % 'postalAddress'
label = 'label'
rel = 'rel'
uri = 'uri'
primary = 'primary'
class Rating(atom.core.XmlElement):
"""The gd:rating element.
Represents a numeric rating of the enclosing entity, such as a
comment. Each rating supplies its own scale, although it may be
normalized by a service; for example, some services might convert all
ratings to a scale from 1 to 5.
"""
_qname = GDATA_TEMPLATE % 'rating'
average = 'average'
max = 'max'
min = 'min'
num_raters = 'numRaters'
rel = 'rel'
value = 'value'
class Recurrence(atom.core.XmlElement):
"""The gd:recurrence element.
Represents the dates and times when a recurring event takes place.
The string that defines the recurrence consists of a set of properties,
each of which is defined in the iCalendar standard (RFC 2445).
Specifically, the string usually begins with a DTSTART property that
indicates the starting time of the first instance of the event, and
often a DTEND property or a DURATION property to indicate when the
first instance ends. Next come RRULE, RDATE, EXRULE, and/or EXDATE
properties, which collectively define a recurring event and its
exceptions (but see below). (See section 4.8.5 of RFC 2445 for more
information about these recurrence component properties.) Last comes a
VTIMEZONE component, providing detailed timezone rules for any timezone
ID mentioned in the preceding properties.
Google services like Google Calendar don't generally generate EXRULE
and EXDATE properties to represent exceptions to recurring events;
instead, they generate <gd:recurrenceException> elements. However,
Google services may include EXRULE and/or EXDATE properties anyway;
for example, users can import events and exceptions into Calendar, and
if those imported events contain EXRULE or EXDATE properties, then
Calendar will provide those properties when it sends a <gd:recurrence>
element.
Note the the use of <gd:recurrenceException> means that you can't be
sure just from examining a <gd:recurrence> element whether there are
any exceptions to the recurrence description. To ensure that you find
all exceptions, look for <gd:recurrenceException> elements in the feed,
and use their <gd:originalEvent> elements to match them up with
<gd:recurrence> elements.
"""
_qname = GDATA_TEMPLATE % 'recurrence'
class RecurrenceException(atom.core.XmlElement):
"""The gd:recurrenceException element.
Represents an event that's an exception to a recurring event-that is,
an instance of a recurring event in which one or more aspects of the
recurring event (such as attendance list, time, or location) have been
changed.
Contains a <gd:originalEvent> element that specifies the original
recurring event that this event is an exception to.
When you change an instance of a recurring event, that instance becomes
an exception. Depending on what change you made to it, the exception
behaves in either of two different ways when the original recurring
event is changed:
- If you add, change, or remove comments, attendees, or attendee
responses, then the exception remains tied to the original event, and
changes to the original event also change the exception.
- If you make any other changes to the exception (such as changing the
time or location) then the instance becomes "specialized," which means
that it's no longer as tightly tied to the original event. If you
change the original event, specialized exceptions don't change. But
see below.
For example, say you have a meeting every Tuesday and Thursday at
2:00 p.m. If you change the attendance list for this Thursday's meeting
(but not for the regularly scheduled meeting), then it becomes an
exception. If you change the time for this Thursday's meeting (but not
for the regularly scheduled meeting), then it becomes specialized.
Regardless of whether an exception is specialized or not, if you do
something that deletes the instance that the exception was derived from,
then the exception is deleted. Note that changing the day or time of a
recurring event deletes all instances, and creates new ones.
For example, after you've specialized this Thursday's meeting, say you
change the recurring meeting to happen on Monday, Wednesday, and Friday.
That change deletes all of the recurring instances of the
Tuesday/Thursday meeting, including the specialized one.
If a particular instance of a recurring event is deleted, then that
instance appears as a <gd:recurrenceException> containing a
<gd:entryLink> that has its <gd:eventStatus> set to
"http://schemas.google.com/g/2005#event.canceled". (For more
information about canceled events, see RFC 2445.)
"""
_qname = GDATA_TEMPLATE % 'recurrenceException'
specialized = 'specialized'
entry_link = EntryLink
original_event = OriginalEvent
class Reminder(atom.core.XmlElement):
"""The gd:reminder element.
A time interval, indicating how long before the containing entity's start
time or due time attribute a reminder should be issued. Alternatively,
may specify an absolute time at which a reminder should be issued. Also
specifies a notification method, indicating what medium the system
should use to remind the user.
"""
_qname = GDATA_TEMPLATE % 'reminder'
absolute_time = 'absoluteTime'
method = 'method'
days = 'days'
hours = 'hours'
minutes = 'minutes'
class Transparency(atom.core.XmlElement):
"""The gd:transparency element:
Extensible enum corresponding to the TRANSP property defined in RFC 244.
"""
_qname = GDATA_TEMPLATE % 'transparency'
value = 'value'
class Agent(atom.core.XmlElement):
"""The gd:agent element.
The agent who actually receives the mail. Used in work addresses.
Also for 'in care of' or 'c/o'.
"""
_qname = GDATA_TEMPLATE % 'agent'
class HouseName(atom.core.XmlElement):
"""The gd:housename element.
Used in places where houses or buildings have names (and not
necessarily numbers), eg. "The Pillars".
"""
_qname = GDATA_TEMPLATE % 'housename'
class Street(atom.core.XmlElement):
"""The gd:street element.
Can be street, avenue, road, etc. This element also includes the
house number and room/apartment/flat/floor number.
"""
_qname = GDATA_TEMPLATE % 'street'
class PoBox(atom.core.XmlElement):
"""The gd:pobox element.
Covers actual P.O. boxes, drawers, locked bags, etc. This is usually
but not always mutually exclusive with street.
"""
_qname = GDATA_TEMPLATE % 'pobox'
class Neighborhood(atom.core.XmlElement):
"""The gd:neighborhood element.
This is used to disambiguate a street address when a city contains more
than one street with the same name, or to specify a small place whose
mail is routed through a larger postal town. In China it could be a
county or a minor city.
"""
_qname = GDATA_TEMPLATE % 'neighborhood'
class City(atom.core.XmlElement):
"""The gd:city element.
Can be city, village, town, borough, etc. This is the postal town and
not necessarily the place of residence or place of business.
"""
_qname = GDATA_TEMPLATE % 'city'
class Subregion(atom.core.XmlElement):
"""The gd:subregion element.
Handles administrative districts such as U.S. or U.K. counties that are
not used for mail addressing purposes. Subregion is not intended for
delivery addresses.
"""
_qname = GDATA_TEMPLATE % 'subregion'
class Region(atom.core.XmlElement):
"""The gd:region element.
A state, province, county (in Ireland), Land (in Germany),
departement (in France), etc.
"""
_qname = GDATA_TEMPLATE % 'region'
class Postcode(atom.core.XmlElement):
"""The gd:postcode element.
Postal code. Usually country-wide, but sometimes specific to the
city (e.g. "2" in "Dublin 2, Ireland" addresses).
"""
_qname = GDATA_TEMPLATE % 'postcode'
class Country(atom.core.XmlElement):
"""The gd:country element.
The name or code of the country.
"""
_qname = GDATA_TEMPLATE % 'country'
class FormattedAddress(atom.core.XmlElement):
"""The gd:formattedAddress element.
The full, unstructured postal address.
"""
_qname = GDATA_TEMPLATE % 'formattedAddress'
class StructuredPostalAddress(atom.core.XmlElement):
"""The gd:structuredPostalAddress element.
Postal address split into components. It allows to store the address
in locale independent format. The fields can be interpreted and used
to generate formatted, locale dependent address. The following elements
reperesent parts of the address: agent, house name, street, P.O. box,
neighborhood, city, subregion, region, postal code, country. The
subregion element is not used for postal addresses, it is provided for
extended uses of addresses only. In order to store postal address in an
unstructured form formatted address field is provided.
"""
_qname = GDATA_TEMPLATE % 'structuredPostalAddress'
rel = 'rel'
mail_class = 'mailClass'
usage = 'usage'
label = 'label'
primary = 'primary'
agent = Agent
house_name = HouseName
street = Street
po_box = PoBox
neighborhood = Neighborhood
city = City
subregion = Subregion
region = Region
postcode = Postcode
country = Country
formatted_address = FormattedAddress
class Where(atom.core.XmlElement):
"""The gd:where element.
A place (such as an event location) associated with the containing
entity. The type of the association is determined by the rel attribute;
the details of the location are contained in an embedded or linked-to
Contact entry.
A <gd:where> element is more general than a <gd:geoPt> element. The
former identifies a place using a text description and/or a Contact
entry, while the latter identifies a place using a specific geographic
location.
"""
_qname = GDATA_TEMPLATE % 'where'
label = 'label'
rel = 'rel'
value = 'valueString'
entry_link = EntryLink
class AttendeeType(atom.core.XmlElement):
"""The gd:attendeeType element."""
_qname = GDATA_TEMPLATE % 'attendeeType'
value = 'value'
class AttendeeStatus(atom.core.XmlElement):
"""The gd:attendeeStatus element."""
_qname = GDATA_TEMPLATE % 'attendeeStatus'
value = 'value'
class EventStatus(atom.core.XmlElement):
"""The gd:eventStatus element."""
_qname = GDATA_TEMPLATE % 'eventStatus'
value = 'value'
class Visibility(atom.core.XmlElement):
"""The gd:visibility element."""
_qname = GDATA_TEMPLATE % 'visibility'
value = 'value'
class Who(atom.core.XmlElement):
"""The gd:who element.
A person associated with the containing entity. The type of the
association is determined by the rel attribute; the details about the
person are contained in an embedded or linked-to Contact entry.
The <gd:who> element can be used to specify email senders and
recipients, calendar event organizers, and so on.
"""
_qname = GDATA_TEMPLATE % 'who'
email = 'email'
rel = 'rel'
value = 'valueString'
attendee_status = AttendeeStatus
attendee_type = AttendeeType
entry_link = EntryLink
class Deleted(atom.core.XmlElement):
"""gd:deleted when present, indicates the containing entry is deleted."""
_qname = GD_TEMPLATE % 'deleted'
class Money(atom.core.XmlElement):
"""Describes money"""
_qname = GD_TEMPLATE % 'money'
amount = 'amount'
currency_code = 'currencyCode'
class MediaSource(object):
"""GData Entries can refer to media sources, so this class provides a
place to store references to these objects along with some metadata.
"""
def __init__(self, file_handle=None, content_type=None, content_length=None,
file_path=None, file_name=None):
"""Creates an object of type MediaSource.
Args:
file_handle: A file handle pointing to the file to be encapsulated in the
MediaSource.
content_type: string The MIME type of the file. Required if a file_handle
is given.
content_length: int The size of the file. Required if a file_handle is
given.
file_path: string (optional) A full path name to the file. Used in
place of a file_handle.
file_name: string The name of the file without any path information.
Required if a file_handle is given.
"""
self.file_handle = file_handle
self.content_type = content_type
self.content_length = content_length
self.file_name = file_name
if (file_handle is None and content_type is not None and
file_path is not None):
self.set_file_handle(file_path, content_type)
def set_file_handle(self, file_name, content_type):
"""A helper function which can create a file handle from a given filename
and set the content type and length all at once.
Args:
file_name: string The path and file name to the file containing the media
content_type: string A MIME type representing the type of the media
"""
self.file_handle = open(file_name, 'rb')
self.content_type = content_type
self.content_length = os.path.getsize(file_name)
self.file_name = os.path.basename(file_name)
SetFileHandle = set_file_handle
def modify_request(self, http_request):
http_request.add_body_part(self.file_handle, self.content_type,
self.content_length)
return http_request
ModifyRequest = modify_request
| Python |
#!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Data model classes for parsing and generating XML for the Contacts API."""
__author__ = 'vinces1979@gmail.com (Vince Spicer)'
import atom.core
import gdata
import gdata.data
PHOTO_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#photo'
PHOTO_EDIT_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#edit-photo'
EXTERNAL_ID_ORGANIZATION = 'organization'
RELATION_MANAGER = 'manager'
CONTACTS_NAMESPACE = 'http://schemas.google.com/contact/2008'
CONTACTS_TEMPLATE = '{%s}%%s' % CONTACTS_NAMESPACE
class BillingInformation(atom.core.XmlElement):
"""
gContact:billingInformation
Specifies billing information of the entity represented by the contact. The element cannot be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'billingInformation'
class Birthday(atom.core.XmlElement):
"""
Stores birthday date of the person represented by the contact. The element cannot be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'birthday'
when = 'when'
class ContactLink(atom.data.Link):
"""
Extends atom.data.Link to add gd:etag attribute for photo link.
"""
etag = gdata.data.GD_TEMPLATE % 'etag'
class CalendarLink(atom.core.XmlElement):
"""
Storage for URL of the contact's calendar. The element can be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'calendarLink'
rel = 'rel'
label = 'label'
primary = 'primary'
href = 'href'
class DirectoryServer(atom.core.XmlElement):
"""
A directory server associated with this contact.
May not be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'directoryServer'
class Event(atom.core.XmlElement):
"""
These elements describe events associated with a contact.
They may be repeated
"""
_qname = CONTACTS_TEMPLATE % 'event'
label = 'label'
rel = 'rel'
when = gdata.data.When
class ExternalId(atom.core.XmlElement):
"""
Describes an ID of the contact in an external system of some kind.
This element may be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'externalId'
label = 'label'
rel = 'rel'
value = 'value'
def ExternalIdFromString(xml_string):
return atom.core.parse(ExternalId, xml_string)
class Gender(atom.core.XmlElement):
"""
Specifies the gender of the person represented by the contact.
The element cannot be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'gender'
value = 'value'
class Hobby(atom.core.XmlElement):
"""
Describes an ID of the contact in an external system of some kind.
This element may be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'hobby'
class Initials(atom.core.XmlElement):
""" Specifies the initials of the person represented by the contact. The
element cannot be repeated. """
_qname = CONTACTS_TEMPLATE % 'initials'
class Jot(atom.core.XmlElement):
"""
Storage for arbitrary pieces of information about the contact. Each jot
has a type specified by the rel attribute and a text value.
The element can be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'jot'
rel = 'rel'
class Language(atom.core.XmlElement):
"""
Specifies the preferred languages of the contact.
The element can be repeated.
The language must be specified using one of two mutually exclusive methods:
using the freeform @label attribute, or using the @code attribute, whose value
must conform to the IETF BCP 47 specification.
"""
_qname = CONTACTS_TEMPLATE % 'language'
code = 'code'
label = 'label'
class MaidenName(atom.core.XmlElement):
"""
Specifies maiden name of the person represented by the contact.
The element cannot be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'maidenName'
class Mileage(atom.core.XmlElement):
"""
Specifies the mileage for the entity represented by the contact.
Can be used for example to document distance needed for reimbursement
purposes. The value is not interpreted. The element cannot be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'mileage'
class NickName(atom.core.XmlElement):
"""
Specifies the nickname of the person represented by the contact.
The element cannot be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'nickname'
class Occupation(atom.core.XmlElement):
"""
Specifies the occupation/profession of the person specified by the contact.
The element cannot be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'occupation'
class Priority(atom.core.XmlElement):
"""
Classifies importance of the contact into 3 categories:
* Low
* Normal
* High
The priority element cannot be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'priority'
class Relation(atom.core.XmlElement):
"""
This element describe another entity (usually a person) that is in a
relation of some kind with the contact.
"""
_qname = CONTACTS_TEMPLATE % 'relation'
rel = 'rel'
label = 'label'
class Sensitivity(atom.core.XmlElement):
"""
Classifies sensitivity of the contact into the following categories:
* Confidential
* Normal
* Personal
* Private
The sensitivity element cannot be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'sensitivity'
rel = 'rel'
class UserDefinedField(atom.core.XmlElement):
"""
Represents an arbitrary key-value pair attached to the contact.
"""
_qname = CONTACTS_TEMPLATE % 'userDefinedField'
key = 'key'
value = 'value'
def UserDefinedFieldFromString(xml_string):
return atom.core.parse(UserDefinedField, xml_string)
class Website(atom.core.XmlElement):
"""
Describes websites associated with the contact, including links.
May be repeated.
"""
_qname = CONTACTS_TEMPLATE % 'website'
href = 'href'
label = 'label'
primary = 'primary'
rel = 'rel'
def WebsiteFromString(xml_string):
return atom.core.parse(Website, xml_string)
class HouseName(atom.core.XmlElement):
"""
Used in places where houses or buildings have names (and
not necessarily numbers), eg. "The Pillars".
"""
_qname = CONTACTS_TEMPLATE % 'housename'
class Street(atom.core.XmlElement):
"""
Can be street, avenue, road, etc. This element also includes the house
number and room/apartment/flat/floor number.
"""
_qname = CONTACTS_TEMPLATE % 'street'
class POBox(atom.core.XmlElement):
"""
Covers actual P.O. boxes, drawers, locked bags, etc. This is usually but not
always mutually exclusive with street
"""
_qname = CONTACTS_TEMPLATE % 'pobox'
class Neighborhood(atom.core.XmlElement):
"""
This is used to disambiguate a street address when a city contains more than
one street with the same name, or to specify a small place whose mail is
routed through a larger postal town. In China it could be a county or a
minor city.
"""
_qname = CONTACTS_TEMPLATE % 'neighborhood'
class City(atom.core.XmlElement):
"""
Can be city, village, town, borough, etc. This is the postal town and not
necessarily the place of residence or place of business.
"""
_qname = CONTACTS_TEMPLATE % 'city'
class SubRegion(atom.core.XmlElement):
"""
Handles administrative districts such as U.S. or U.K. counties that are not
used for mail addressing purposes. Subregion is not intended for
delivery addresses.
"""
_qname = CONTACTS_TEMPLATE % 'subregion'
class Region(atom.core.XmlElement):
"""
A state, province, county (in Ireland), Land (in Germany),
departement (in France), etc.
"""
_qname = CONTACTS_TEMPLATE % 'region'
class PostalCode(atom.core.XmlElement):
"""
Postal code. Usually country-wide, but sometimes specific to the
city (e.g. "2" in "Dublin 2, Ireland" addresses).
"""
_qname = CONTACTS_TEMPLATE % 'postcode'
class Country(atom.core.XmlElement):
""" The name or code of the country. """
_qname = CONTACTS_TEMPLATE % 'country'
class Status(atom.core.XmlElement):
"""Person's status element."""
_qname = CONTACTS_TEMPLATE % 'status'
indexed = 'indexed'
class PersonEntry(gdata.data.BatchEntry):
"""Represents a google contact"""
link = [ContactLink]
billing_information = BillingInformation
birthday = Birthday
calendar_link = [CalendarLink]
directory_server = DirectoryServer
event = [Event]
external_id = [ExternalId]
gender = Gender
hobby = [Hobby]
initials = Initials
jot = [Jot]
language= [Language]
maiden_name = MaidenName
mileage = Mileage
nickname = NickName
occupation = Occupation
priority = Priority
relation = [Relation]
sensitivity = Sensitivity
user_defined_field = [UserDefinedField]
website = [Website]
name = gdata.data.Name
phone_number = [gdata.data.PhoneNumber]
organization = gdata.data.Organization
postal_address = [gdata.data.PostalAddress]
email = [gdata.data.Email]
im = [gdata.data.Im]
structured_postal_address = [gdata.data.StructuredPostalAddress]
extended_property = [gdata.data.ExtendedProperty]
status = Status
class Deleted(atom.core.XmlElement):
"""If present, indicates that this contact has been deleted."""
_qname = gdata.GDATA_TEMPLATE % 'deleted'
class GroupMembershipInfo(atom.core.XmlElement):
"""
Identifies the group to which the contact belongs or belonged.
The group is referenced by its id.
"""
_qname = CONTACTS_TEMPLATE % 'groupMembershipInfo'
href = 'href'
deleted = 'deleted'
class ContactEntry(PersonEntry):
"""A Google Contacts flavor of an Atom Entry."""
deleted = Deleted
group_membership_info = [GroupMembershipInfo]
organization = gdata.data.Organization
def GetPhotoLink(self):
for a_link in self.link:
if a_link.rel == PHOTO_LINK_REL:
return a_link
return None
def GetPhotoEditLink(self):
for a_link in self.link:
if a_link.rel == PHOTO_EDIT_LINK_REL:
return a_link
return None
class ContactsFeed(gdata.data.BatchFeed):
"""A collection of Contacts."""
entry = [ContactEntry]
class SystemGroup(atom.core.XmlElement):
"""The contacts systemGroup element.
When used within a contact group entry, indicates that the group in
question is one of the predefined system groups."""
_qname = CONTACTS_TEMPLATE % 'systemGroup'
id = 'id'
class GroupEntry(gdata.data.BatchEntry):
"""Represents a contact group."""
extended_property = [gdata.data.ExtendedProperty]
system_group = SystemGroup
class GroupsFeed(gdata.data.BatchFeed):
"""A Google contact groups feed flavor of an Atom Feed."""
entry = [GroupEntry]
class ProfileEntry(PersonEntry):
"""A Google Profiles flavor of an Atom Entry."""
def ProfileEntryFromString(xml_string):
"""Converts an XML string into a ProfileEntry object.
Args:
xml_string: string The XML describing a Profile entry.
Returns:
A ProfileEntry object corresponding to the given XML.
"""
return atom.core.parse(ProfileEntry, xml_string)
class ProfilesFeed(gdata.data.BatchFeed):
"""A Google Profiles feed flavor of an Atom Feed."""
_qname = atom.data.ATOM_TEMPLATE % 'feed'
entry = [ProfileEntry]
def ProfilesFeedFromString(xml_string):
"""Converts an XML string into a ProfilesFeed object.
Args:
xml_string: string The XML describing a Profiles feed.
Returns:
A ProfilesFeed object corresponding to the given XML.
"""
return atom.core.parse(ProfilesFeed, xml_string)
| Python |
#!/usr/bin/env python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from types import ListType, DictionaryType
"""Contains a client to communicate with the Contacts servers.
For documentation on the Contacts API, see:
http://code.google.com/apis/contatcs/
"""
__author__ = 'vinces1979@gmail.com (Vince Spicer)'
import gdata.client
import gdata.contacts.data
import atom.client
import atom.data
import atom.http_core
import gdata.gauth
DEFAULT_BATCH_URL = ('https://www.google.com/m8/feeds/contacts/default/full'
'/batch')
DEFAULT_PROFILES_BATCH_URL = ('https://www.google.com/m8/feeds/profiles/domain/'
'%s/full/batch')
class ContactsClient(gdata.client.GDClient):
api_version = '3'
auth_service = 'cp'
server = "www.google.com"
contact_list = "default"
auth_scopes = gdata.gauth.AUTH_SCOPES['cp']
ssl = True
def __init__(self, domain=None, auth_token=None, **kwargs):
"""Constructs a new client for the Email Settings API.
Args:
domain: string The Google Apps domain (if any).
kwargs: The other parameters to pass to the gdata.client.GDClient
constructor.
"""
gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs)
self.domain = domain
def get_feed_uri(self, kind='contacts', contact_list=None, projection='full',
scheme="https"):
"""Builds a feed URI.
Args:
kind: The type of feed to return, typically 'groups' or 'contacts'.
Default value: 'contacts'.
contact_list: The contact list to return a feed for.
Default value: self.contact_list.
projection: The projection to apply to the feed contents, for example
'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.
scheme: The URL scheme such as 'http' or 'https', None to return a
relative URI without hostname.
Returns:
A feed URI using the given kind, contact list, and projection.
Example: '/m8/feeds/contacts/default/full'.
"""
contact_list = contact_list or self.contact_list
if kind == 'profiles':
contact_list = 'domain/%s' % self.domain
prefix = scheme and '%s://%s' % (scheme, self.server) or ''
return '%s/m8/feeds/%s/%s/%s' % (prefix, kind, contact_list, projection)
GetFeedUri = get_feed_uri
def get_contact(self, uri, desired_class=gdata.contacts.data.ContactEntry,
auth_token=None, **kwargs):
return self.get_entry(uri, auth_token=auth_token,
desired_class=desired_class, **kwargs)
GetContact = get_contact
def create_contact(self, new_contact, insert_uri=None, auth_token=None, **kwargs):
"""Adds an new contact to Google Contacts.
Args:
new_contact: atom.Entry or subclass A new contact which is to be added to
Google Contacts.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = insert_uri or self.GetFeedUri()
return self.Post(new_contact, insert_uri,
auth_token=auth_token, **kwargs)
CreateContact = create_contact
def add_contact(self, new_contact, insert_uri=None, auth_token=None,
billing_information=None, birthday=None, calendar_link=None, **kwargs):
"""Adds an new contact to Google Contacts.
Args:
new_contact: atom.Entry or subclass A new contact which is to be added to
Google Contacts.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
contact = gdata.contacts.data.ContactEntry()
if billing_information is not None:
if not isinstance(billing_information, gdata.contacts.data.BillingInformation):
billing_information = gdata.contacts.data.BillingInformation(text=billing_information)
contact.billing_information = billing_information
if birthday is not None:
if not isinstance(birthday, gdata.contacts.data.Birthday):
birthday = gdata.contacts.data.Birthday(when=birthday)
contact.birthday = birthday
if calendar_link is not None:
if type(calendar_link) is not ListType:
calendar_link = [calendar_link]
for link in calendar_link:
if not isinstance(link, gdata.contacts.data.CalendarLink):
if type(link) is not DictionaryType:
raise TypeError, "calendar_link Requires dictionary not %s" % type(link)
link = gdata.contacts.data.CalendarLink(
rel=link.get("rel", None),
label=link.get("label", None),
primary=link.get("primary", None),
href=link.get("href", None),
)
contact.calendar_link.append(link)
insert_uri = insert_uri or self.GetFeedUri()
return self.Post(contact, insert_uri,
auth_token=auth_token, **kwargs)
AddContact = add_contact
def get_contacts(self, uri=None, desired_class=gdata.contacts.data.ContactsFeed,
auth_token=None, **kwargs):
"""Obtains a feed with the contacts belonging to the current user.
Args:
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.spreadsheets.data.SpreadsheetsFeed.
"""
uri = uri or self.GetFeedUri()
return self.get_feed(uri, auth_token=auth_token,
desired_class=desired_class, **kwargs)
GetContacts = get_contacts
def get_group(self, uri=None, desired_class=gdata.contacts.data.GroupEntry,
auth_token=None, **kwargs):
""" Get a single groups details
Args:
uri: the group uri or id
"""
return self.get_entry(uri, desired_class=desired_class, auth_token=auth_token, **kwargs)
GetGroup = get_group
def get_groups(self, uri=None, desired_class=gdata.contacts.data.GroupsFeed,
auth_token=None, **kwargs):
uri = uri or self.GetFeedUri('groups')
return self.get_feed(uri, desired_class=desired_class, auth_token=auth_token, **kwargs)
GetGroups = get_groups
def create_group(self, new_group, insert_uri=None, url_params=None,
desired_class=None, **kwargs):
insert_uri = insert_uri or self.GetFeedUri('groups')
return self.Post(new_group, insert_uri, url_params=url_params,
desired_class=desired_class, **kwargs)
CreateGroup = create_group
def update_group(self, edit_uri, updated_group, url_params=None,
escape_params=True, desired_class=None, auth_token=None, **kwargs):
return self.Put(updated_group, self._CleanUri(edit_uri),
url_params=url_params,
escape_params=escape_params,
desired_class=desired_class,
auth_token=auth_token, **kwargs)
UpdateGroup = update_group
def delete_group(self, group_object, auth_token=None, force=False, **kws):
return self.Delete(group_object, auth_token=auth_token, force=force, **kws)
DeleteGroup = delete_group
def change_photo(self, media, contact_entry_or_url, content_type=None,
content_length=None, auth_token=None, **kwargs):
"""Change the photo for the contact by uploading a new photo.
Performs a PUT against the photo edit URL to send the binary data for the
photo.
Args:
media: filename, file-like-object, or a gdata.data.MediaSource object to send.
contact_entry_or_url: ContactEntry or str If it is a ContactEntry, this
method will search for an edit photo link URL and
perform a PUT to the URL.
content_type: str (optional) the mime type for the photo data. This is
necessary if media is a file or file name, but if media
is a MediaSource object then the media object can contain
the mime type. If media_type is set, it will override the
mime type in the media object.
content_length: int or str (optional) Specifying the content length is
only required if media is a file-like object. If media
is a filename, the length is determined using
os.path.getsize. If media is a MediaSource object, it is
assumed that it already contains the content length.
"""
ifmatch_header = None
if isinstance(contact_entry_or_url, gdata.contacts.data.ContactEntry):
photo_link = contact_entry_or_url.GetPhotoLink()
uri = photo_link.href
ifmatch_header = atom.client.CustomHeaders(
**{'if-match': photo_link.etag})
else:
uri = contact_entry_or_url
if isinstance(media, gdata.data.MediaSource):
payload = media
# If the media object is a file-like object, then use it as the file
# handle in the in the MediaSource.
elif hasattr(media, 'read'):
payload = gdata.data.MediaSource(file_handle=media,
content_type=content_type, content_length=content_length)
# Assume that the media object is a file name.
else:
payload = gdata.data.MediaSource(content_type=content_type,
content_length=content_length, file_path=media)
return self.Put(uri=uri, data=payload, auth_token=auth_token,
ifmatch_header=ifmatch_header, **kwargs)
ChangePhoto = change_photo
def get_photo(self, contact_entry_or_url, auth_token=None, **kwargs):
"""Retrives the binary data for the contact's profile photo as a string.
Args:
contact_entry_or_url: a gdata.contacts.ContactEntry object or a string
containing the photo link's URL. If the contact entry does not
contain a photo link, the image will not be fetched and this method
will return None.
"""
# TODO: add the ability to write out the binary image data to a file,
# reading and writing a chunk at a time to avoid potentially using up
# large amounts of memory.
url = None
if isinstance(contact_entry_or_url, gdata.contacts.data.ContactEntry):
photo_link = contact_entry_or_url.GetPhotoLink()
if photo_link:
url = photo_link.href
else:
url = contact_entry_or_url
if url:
return self.Get(url, auth_token=auth_token, **kwargs).read()
else:
return None
GetPhoto = get_photo
def delete_photo(self, contact_entry_or_url, auth_token=None, **kwargs):
"""Delete the contact's profile photo.
Args:
contact_entry_or_url: a gdata.contacts.ContactEntry object or a string
containing the photo link's URL.
"""
uri = None
ifmatch_header = None
if isinstance(contact_entry_or_url, gdata.contacts.data.ContactEntry):
photo_link = contact_entry_or_url.GetPhotoLink()
if photo_link.etag:
uri = photo_link.href
ifmatch_header = atom.client.CustomHeaders(
**{'if-match': photo_link.etag})
else:
# No etag means no photo has been assigned to this contact.
return
else:
uri = contact_entry_or_url
if uri:
self.Delete(entry_or_uri=uri, auth_token=auth_token,
ifmatch_header=ifmatch_header, **kwargs)
DeletePhoto = delete_photo
def get_profiles_feed(self, uri=None, auth_token=None, **kwargs):
"""Retrieves a feed containing all domain's profiles.
Args:
uri: string (optional) the URL to retrieve the profiles feed,
for example /m8/feeds/profiles/default/full
Returns:
On success, a ProfilesFeed containing the profiles.
On failure, raises a RequestError.
"""
uri = uri or self.GetFeedUri('profiles')
return self.get_feed(uri, auth_token=auth_token,
desired_class=gdata.contacts.data.ProfilesFeed, **kwargs)
GetProfilesFeed = get_profiles_feed
def get_profile(self, uri, auth_token=None, **kwargs):
"""Retrieves a domain's profile for the user.
Args:
uri: string the URL to retrieve the profiles feed,
for example /m8/feeds/profiles/default/full/username
Returns:
On success, a ProfileEntry containing the profile for the user.
On failure, raises a RequestError
"""
return self.get_entry(uri,
desired_class=gdata.contacts.data.ProfileEntry,
auth_token=auth_token, **kwargs)
GetProfile = get_profile
def update_profile(self, updated_profile, auth_token=None, force=False, **kwargs):
"""Updates an existing profile.
Args:
updated_profile: atom.Entry or subclass containing
the Atom Entry which will replace the profile which is
stored at the edit_url.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of ContactsClient.
force: boolean stating whether an update should be forced. Defaults to
False. Normally, if a change has been made since the passed in
entry was obtained, the server will not overwrite the entry since
the changes were based on an obsolete version of the entry.
Setting force to True will cause the update to silently
overwrite whatever version is present.
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, raises a RequestError.
"""
return self.Update(updated_profile, auth_token=auth_token, force=force, **kwargs)
UpdateProfile = update_profile
def execute_batch(self, batch_feed, url=DEFAULT_BATCH_URL, desired_class=None,
auth_token=None, **kwargs):
"""Sends a batch request feed to the server.
Args:
batch_feed: gdata.contacts.ContactFeed A feed containing batch
request entries. Each entry contains the operation to be performed
on the data contained in the entry. For example an entry with an
operation type of insert will be used as if the individual entry
had been inserted.
url: str The batch URL to which these operations should be applied.
converter: Function (optional) The function used to convert the server's
response to an object.
Returns:
The results of the batch request's execution on the server. If the
default converter is used, this is stored in a ContactsFeed.
"""
return self.Post(batch_feed, url, desired_class=desired_class,
auth_token=None, **kwargs)
ExecuteBatch = execute_batch
def execute_batch_profiles(self, batch_feed, url=None,
desired_class=gdata.contacts.data.ProfilesFeed,
auth_token=None, **kwargs):
"""Sends a batch request feed to the server.
Args:
batch_feed: gdata.profiles.ProfilesFeed A feed containing batch
request entries. Each entry contains the operation to be performed
on the data contained in the entry. For example an entry with an
operation type of insert will be used as if the individual entry
had been inserted.
url: string The batch URL to which these operations should be applied.
converter: Function (optional) The function used to convert the server's
response to an object. The default value is
gdata.profiles.ProfilesFeedFromString.
Returns:
The results of the batch request's execution on the server. If the
default converter is used, this is stored in a ProfilesFeed.
"""
url = url or (DEFAULT_PROFILES_BATCH_URL % self.domain)
return self.Post(batch_feed, url, desired_class=desired_class,
auth_token=auth_token, **kwargs)
ExecuteBatchProfiles = execute_batch_profiles
def _CleanUri(self, uri):
"""Sanitizes a feed URI.
Args:
uri: The URI to sanitize, can be relative or absolute.
Returns:
The given URI without its http://server prefix, if any.
Keeps the leading slash of the URI.
"""
url_prefix = 'http://%s' % self.server
if uri.startswith(url_prefix):
uri = uri[len(url_prefix):]
return uri
class ContactsQuery(gdata.client.Query):
"""
Create a custom Contacts Query
Full specs can be found at: U{Contacts query parameters reference
<http://code.google.com/apis/contacts/docs/3.0/reference.html#Parameters>}
"""
def __init__(self, feed=None, group=None, orderby=None, showdeleted=None,
sortorder=None, requirealldeleted=None, **kwargs):
"""
@param max_results: The maximum number of entries to return. If you want
to receive all of the contacts, rather than only the default maximum, you
can specify a very large number for max-results.
@param start-index: The 1-based index of the first result to be retrieved.
@param updated-min: The lower bound on entry update dates.
@param group: Constrains the results to only the contacts belonging to the
group specified. Value of this parameter specifies group ID
@param orderby: Sorting criterion. The only supported value is
lastmodified.
@param showdeleted: Include deleted contacts in the returned contacts feed
@pram sortorder: Sorting order direction. Can be either ascending or
descending.
@param requirealldeleted: Only relevant if showdeleted and updated-min
are also provided. It dictates the behavior of the server in case it
detects that placeholders of some entries deleted since the point in
time specified as updated-min may have been lost.
"""
gdata.client.Query.__init__(self, **kwargs)
self.group = group
self.orderby = orderby
self.sortorder = sortorder
self.showdeleted = showdeleted
def modify_request(self, http_request):
if self.group:
gdata.client._add_query_param('group', self.group, http_request)
if self.orderby:
gdata.client._add_query_param('orderby', self.orderby, http_request)
if self.sortorder:
gdata.client._add_query_param('sortorder', self.sortorder, http_request)
if self.showdeleted:
gdata.client._add_query_param('showdeleted', self.showdeleted, http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request
class ProfilesQuery(gdata.client.Query):
"""
Create a custom Profiles Query
Full specs can be found at: U{Profiless query parameters reference
<http://code.google.com/apis/apps/profiles/reference.html#Parameters>}
"""
def __init__(self, feed=None, start_key=None, **kwargs):
"""
@param start_key: Opaque key of the first element to retrieve. Present in
the next link of an earlier request, if further pages of response are
available.
"""
gdata.client.Query.__init__(self, **kwargs)
self.feed = feed or 'https://www.google.com/m8/feeds/profiles/default/full'
self.start_key = start_key
def modify_request(self, http_request):
if self.start_key:
gdata.client._add_query_param('start-key', self.start_key, http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request
| Python |
#!/usr/bin/env python
#
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to ElementWrapper objects used with Google Contacts."""
__author__ = 'dbrattli (Dag Brattli)'
import atom
import gdata
## Constants from http://code.google.com/apis/gdata/elements.html ##
REL_HOME = 'http://schemas.google.com/g/2005#home'
REL_WORK = 'http://schemas.google.com/g/2005#work'
REL_OTHER = 'http://schemas.google.com/g/2005#other'
# AOL Instant Messenger protocol
IM_AIM = 'http://schemas.google.com/g/2005#AIM'
IM_MSN = 'http://schemas.google.com/g/2005#MSN' # MSN Messenger protocol
IM_YAHOO = 'http://schemas.google.com/g/2005#YAHOO' # Yahoo Messenger protocol
IM_SKYPE = 'http://schemas.google.com/g/2005#SKYPE' # Skype protocol
IM_QQ = 'http://schemas.google.com/g/2005#QQ' # QQ protocol
# Google Talk protocol
IM_GOOGLE_TALK = 'http://schemas.google.com/g/2005#GOOGLE_TALK'
IM_ICQ = 'http://schemas.google.com/g/2005#ICQ' # ICQ protocol
IM_JABBER = 'http://schemas.google.com/g/2005#JABBER' # Jabber protocol
IM_NETMEETING = 'http://schemas.google.com/g/2005#netmeeting' # NetMeeting
PHOTO_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#photo'
PHOTO_EDIT_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#edit-photo'
# Different phone types, for more info see:
# http://code.google.com/apis/gdata/docs/2.0/elements.html#gdPhoneNumber
PHONE_CAR = 'http://schemas.google.com/g/2005#car'
PHONE_FAX = 'http://schemas.google.com/g/2005#fax'
PHONE_GENERAL = 'http://schemas.google.com/g/2005#general'
PHONE_HOME = REL_HOME
PHONE_HOME_FAX = 'http://schemas.google.com/g/2005#home_fax'
PHONE_INTERNAL = 'http://schemas.google.com/g/2005#internal-extension'
PHONE_MOBILE = 'http://schemas.google.com/g/2005#mobile'
PHONE_OTHER = REL_OTHER
PHONE_PAGER = 'http://schemas.google.com/g/2005#pager'
PHONE_SATELLITE = 'http://schemas.google.com/g/2005#satellite'
PHONE_VOIP = 'http://schemas.google.com/g/2005#voip'
PHONE_WORK = REL_WORK
PHONE_WORK_FAX = 'http://schemas.google.com/g/2005#work_fax'
PHONE_WORK_MOBILE = 'http://schemas.google.com/g/2005#work_mobile'
PHONE_WORK_PAGER = 'http://schemas.google.com/g/2005#work_pager'
PHONE_MAIN = 'http://schemas.google.com/g/2005#main'
PHONE_ASSISTANT = 'http://schemas.google.com/g/2005#assistant'
PHONE_CALLBACK = 'http://schemas.google.com/g/2005#callback'
PHONE_COMPANY_MAIN = 'http://schemas.google.com/g/2005#company_main'
PHONE_ISDN = 'http://schemas.google.com/g/2005#isdn'
PHONE_OTHER_FAX = 'http://schemas.google.com/g/2005#other_fax'
PHONE_RADIO = 'http://schemas.google.com/g/2005#radio'
PHONE_TELEX = 'http://schemas.google.com/g/2005#telex'
PHONE_TTY_TDD = 'http://schemas.google.com/g/2005#tty_tdd'
EXTERNAL_ID_ORGANIZATION = 'organization'
RELATION_MANAGER = 'manager'
CONTACTS_NAMESPACE = 'http://schemas.google.com/contact/2008'
class GDataBase(atom.AtomBase):
"""The Google Contacts intermediate class from atom.AtomBase."""
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, text=None,
extension_elements=None, extension_attributes=None):
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class ContactsBase(GDataBase):
"""The Google Contacts intermediate class for Contacts namespace."""
_namespace = CONTACTS_NAMESPACE
class OrgName(GDataBase):
"""The Google Contacts OrgName element."""
_tag = 'orgName'
class OrgTitle(GDataBase):
"""The Google Contacts OrgTitle element."""
_tag = 'orgTitle'
class OrgDepartment(GDataBase):
"""The Google Contacts OrgDepartment element."""
_tag = 'orgDepartment'
class OrgJobDescription(GDataBase):
"""The Google Contacts OrgJobDescription element."""
_tag = 'orgJobDescription'
class Where(GDataBase):
"""The Google Contacts Where element."""
_tag = 'where'
_children = GDataBase._children.copy()
_attributes = GDataBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['label'] = 'label'
_attributes['valueString'] = 'value_string'
def __init__(self, value_string=None, rel=None, label=None,
text=None, extension_elements=None, extension_attributes=None):
GDataBase.__init__(self, text=text, extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.rel = rel
self.label = label
self.value_string = value_string
class When(GDataBase):
"""The Google Contacts When element."""
_tag = 'when'
_children = GDataBase._children.copy()
_attributes = GDataBase._attributes.copy()
_attributes['startTime'] = 'start_time'
_attributes['endTime'] = 'end_time'
_attributes['label'] = 'label'
def __init__(self, start_time=None, end_time=None, label=None,
text=None, extension_elements=None, extension_attributes=None):
GDataBase.__init__(self, text=text, extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.start_time = start_time
self.end_time = end_time
self.label = label
class Organization(GDataBase):
"""The Google Contacts Organization element."""
_tag = 'organization'
_children = GDataBase._children.copy()
_attributes = GDataBase._attributes.copy()
_attributes['label'] = 'label'
_attributes['rel'] = 'rel'
_attributes['primary'] = 'primary'
_children['{%s}orgName' % GDataBase._namespace] = (
'org_name', OrgName)
_children['{%s}orgTitle' % GDataBase._namespace] = (
'org_title', OrgTitle)
_children['{%s}orgDepartment' % GDataBase._namespace] = (
'org_department', OrgDepartment)
_children['{%s}orgJobDescription' % GDataBase._namespace] = (
'org_job_description', OrgJobDescription)
#_children['{%s}where' % GDataBase._namespace] = ('where', Where)
def __init__(self, label=None, rel=None, primary='false', org_name=None,
org_title=None, org_department=None, org_job_description=None,
where=None, text=None,
extension_elements=None, extension_attributes=None):
GDataBase.__init__(self, text=text, extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.label = label
self.rel = rel or REL_OTHER
self.primary = primary
self.org_name = org_name
self.org_title = org_title
self.org_department = org_department
self.org_job_description = org_job_description
self.where = where
class PostalAddress(GDataBase):
"""The Google Contacts PostalAddress element."""
_tag = 'postalAddress'
_children = GDataBase._children.copy()
_attributes = GDataBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['primary'] = 'primary'
def __init__(self, primary=None, rel=None, text=None,
extension_elements=None, extension_attributes=None):
GDataBase.__init__(self, text=text, extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.rel = rel or REL_OTHER
self.primary = primary
class FormattedAddress(GDataBase):
"""The Google Contacts FormattedAddress element."""
_tag = 'formattedAddress'
class StructuredPostalAddress(GDataBase):
"""The Google Contacts StructuredPostalAddress element."""
_tag = 'structuredPostalAddress'
_children = GDataBase._children.copy()
_attributes = GDataBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['primary'] = 'primary'
_children['{%s}formattedAddress' % GDataBase._namespace] = (
'formatted_address', FormattedAddress)
def __init__(self, rel=None, primary=None,
formatted_address=None, text=None,
extension_elements=None, extension_attributes=None):
GDataBase.__init__(self, text=text, extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.rel = rel or REL_OTHER
self.primary = primary
self.formatted_address = formatted_address
class IM(GDataBase):
"""The Google Contacts IM element."""
_tag = 'im'
_children = GDataBase._children.copy()
_attributes = GDataBase._attributes.copy()
_attributes['address'] = 'address'
_attributes['primary'] = 'primary'
_attributes['protocol'] = 'protocol'
_attributes['label'] = 'label'
_attributes['rel'] = 'rel'
def __init__(self, primary='false', rel=None, address=None, protocol=None,
label=None, text=None,
extension_elements=None, extension_attributes=None):
GDataBase.__init__(self, text=text, extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.protocol = protocol
self.address = address
self.primary = primary
self.rel = rel or REL_OTHER
self.label = label
class Email(GDataBase):
"""The Google Contacts Email element."""
_tag = 'email'
_children = GDataBase._children.copy()
_attributes = GDataBase._attributes.copy()
_attributes['address'] = 'address'
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
_attributes['label'] = 'label'
def __init__(self, label=None, rel=None, address=None, primary='false',
text=None, extension_elements=None, extension_attributes=None):
GDataBase.__init__(self, text=text, extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.label = label
self.rel = rel or REL_OTHER
self.address = address
self.primary = primary
class PhoneNumber(GDataBase):
"""The Google Contacts PhoneNumber element."""
_tag = 'phoneNumber'
_children = GDataBase._children.copy()
_attributes = GDataBase._attributes.copy()
_attributes['label'] = 'label'
_attributes['rel'] = 'rel'
_attributes['uri'] = 'uri'
_attributes['primary'] = 'primary'
def __init__(self, label=None, rel=None, uri=None, primary='false',
text=None, extension_elements=None, extension_attributes=None):
GDataBase.__init__(self, text=text, extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.label = label
self.rel = rel or REL_OTHER
self.uri = uri
self.primary = primary
class Nickname(ContactsBase):
"""The Google Contacts Nickname element."""
_tag = 'nickname'
class Occupation(ContactsBase):
"""The Google Contacts Occupation element."""
_tag = 'occupation'
class Gender(ContactsBase):
"""The Google Contacts Gender element."""
_tag = 'gender'
_children = ContactsBase._children.copy()
_attributes = ContactsBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value=None,
text=None, extension_elements=None, extension_attributes=None):
ContactsBase.__init__(self, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.value = value
class Birthday(ContactsBase):
"""The Google Contacts Birthday element."""
_tag = 'birthday'
_children = ContactsBase._children.copy()
_attributes = ContactsBase._attributes.copy()
_attributes['when'] = 'when'
def __init__(self, when=None,
text=None, extension_elements=None, extension_attributes=None):
ContactsBase.__init__(self, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.when = when
class Relation(ContactsBase):
"""The Google Contacts Relation element."""
_tag = 'relation'
_children = ContactsBase._children.copy()
_attributes = ContactsBase._attributes.copy()
_attributes['label'] = 'label'
_attributes['rel'] = 'rel'
def __init__(self, label=None, rel=None,
text=None, extension_elements=None, extension_attributes=None):
ContactsBase.__init__(self, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.label = label
self.rel = rel
def RelationFromString(xml_string):
return atom.CreateClassFromXMLString(Relation, xml_string)
class UserDefinedField(ContactsBase):
"""The Google Contacts UserDefinedField element."""
_tag = 'userDefinedField'
_children = ContactsBase._children.copy()
_attributes = ContactsBase._attributes.copy()
_attributes['key'] = 'key'
_attributes['value'] = 'value'
def __init__(self, key=None, value=None,
text=None, extension_elements=None, extension_attributes=None):
ContactsBase.__init__(self, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.key = key
self.value = value
def UserDefinedFieldFromString(xml_string):
return atom.CreateClassFromXMLString(UserDefinedField, xml_string)
class Website(ContactsBase):
"""The Google Contacts Website element."""
_tag = 'website'
_children = ContactsBase._children.copy()
_attributes = ContactsBase._attributes.copy()
_attributes['href'] = 'href'
_attributes['label'] = 'label'
_attributes['primary'] = 'primary'
_attributes['rel'] = 'rel'
def __init__(self, href=None, label=None, primary='false', rel=None,
text=None, extension_elements=None, extension_attributes=None):
ContactsBase.__init__(self, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.href = href
self.label = label
self.primary = primary
self.rel = rel
def WebsiteFromString(xml_string):
return atom.CreateClassFromXMLString(Website, xml_string)
class ExternalId(ContactsBase):
"""The Google Contacts ExternalId element."""
_tag = 'externalId'
_children = ContactsBase._children.copy()
_attributes = ContactsBase._attributes.copy()
_attributes['label'] = 'label'
_attributes['rel'] = 'rel'
_attributes['value'] = 'value'
def __init__(self, label=None, rel=None, value=None,
text=None, extension_elements=None, extension_attributes=None):
ContactsBase.__init__(self, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.label = label
self.rel = rel
self.value = value
def ExternalIdFromString(xml_string):
return atom.CreateClassFromXMLString(ExternalId, xml_string)
class Event(ContactsBase):
"""The Google Contacts Event element."""
_tag = 'event'
_children = ContactsBase._children.copy()
_attributes = ContactsBase._attributes.copy()
_attributes['label'] = 'label'
_attributes['rel'] = 'rel'
_children['{%s}when' % ContactsBase._namespace] = ('when', When)
def __init__(self, label=None, rel=None, when=None,
text=None, extension_elements=None, extension_attributes=None):
ContactsBase.__init__(self, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.label = label
self.rel = rel
self.when = when
def EventFromString(xml_string):
return atom.CreateClassFromXMLString(Event, xml_string)
class Deleted(GDataBase):
"""The Google Contacts Deleted element."""
_tag = 'deleted'
class GroupMembershipInfo(ContactsBase):
"""The Google Contacts GroupMembershipInfo element."""
_tag = 'groupMembershipInfo'
_children = ContactsBase._children.copy()
_attributes = ContactsBase._attributes.copy()
_attributes['deleted'] = 'deleted'
_attributes['href'] = 'href'
def __init__(self, deleted=None, href=None, text=None,
extension_elements=None, extension_attributes=None):
ContactsBase.__init__(self, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes)
self.deleted = deleted
self.href = href
class PersonEntry(gdata.BatchEntry):
"""Base class for ContactEntry and ProfileEntry."""
_children = gdata.BatchEntry._children.copy()
_children['{%s}organization' % gdata.GDATA_NAMESPACE] = (
'organization', [Organization])
_children['{%s}phoneNumber' % gdata.GDATA_NAMESPACE] = (
'phone_number', [PhoneNumber])
_children['{%s}nickname' % CONTACTS_NAMESPACE] = ('nickname', Nickname)
_children['{%s}occupation' % CONTACTS_NAMESPACE] = ('occupation', Occupation)
_children['{%s}gender' % CONTACTS_NAMESPACE] = ('gender', Gender)
_children['{%s}birthday' % CONTACTS_NAMESPACE] = ('birthday', Birthday)
_children['{%s}postalAddress' % gdata.GDATA_NAMESPACE] = ('postal_address',
[PostalAddress])
_children['{%s}structuredPostalAddress' % gdata.GDATA_NAMESPACE] = (
'structured_postal_address', [StructuredPostalAddress])
_children['{%s}email' % gdata.GDATA_NAMESPACE] = ('email', [Email])
_children['{%s}im' % gdata.GDATA_NAMESPACE] = ('im', [IM])
_children['{%s}relation' % CONTACTS_NAMESPACE] = ('relation', [Relation])
_children['{%s}userDefinedField' % CONTACTS_NAMESPACE] = (
'user_defined_field', [UserDefinedField])
_children['{%s}website' % CONTACTS_NAMESPACE] = ('website', [Website])
_children['{%s}externalId' % CONTACTS_NAMESPACE] = (
'external_id', [ExternalId])
_children['{%s}event' % CONTACTS_NAMESPACE] = ('event', [Event])
# The following line should be removed once the Python support
# for GData 2.0 is mature.
_attributes = gdata.BatchEntry._attributes.copy()
_attributes['{%s}etag' % gdata.GDATA_NAMESPACE] = 'etag'
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None, organization=None, phone_number=None,
nickname=None, occupation=None, gender=None, birthday=None,
postal_address=None, structured_postal_address=None, email=None,
im=None, relation=None, user_defined_field=None, website=None,
external_id=None, event=None, batch_operation=None,
batch_id=None, batch_status=None, text=None,
extension_elements=None, extension_attributes=None, etag=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published,
batch_operation=batch_operation,
batch_id=batch_id, batch_status=batch_status,
title=title, updated=updated)
self.organization = organization or []
self.phone_number = phone_number or []
self.nickname = nickname
self.occupation = occupation
self.gender = gender
self.birthday = birthday
self.postal_address = postal_address or []
self.structured_postal_address = structured_postal_address or []
self.email = email or []
self.im = im or []
self.relation = relation or []
self.user_defined_field = user_defined_field or []
self.website = website or []
self.external_id = external_id or []
self.event = event or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
# The following line should be removed once the Python support
# for GData 2.0 is mature.
self.etag = etag
class ContactEntry(PersonEntry):
"""A Google Contact flavor of an Atom Entry."""
_children = PersonEntry._children.copy()
_children['{%s}deleted' % gdata.GDATA_NAMESPACE] = ('deleted', Deleted)
_children['{%s}groupMembershipInfo' % CONTACTS_NAMESPACE] = (
'group_membership_info', [GroupMembershipInfo])
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [gdata.ExtendedProperty])
# Overwrite the organization rule in PersonEntry so that a ContactEntry
# may only contain one <gd:organization> element.
_children['{%s}organization' % gdata.GDATA_NAMESPACE] = (
'organization', Organization)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None, organization=None, phone_number=None,
nickname=None, occupation=None, gender=None, birthday=None,
postal_address=None, structured_postal_address=None, email=None,
im=None, relation=None, user_defined_field=None, website=None,
external_id=None, event=None, batch_operation=None,
batch_id=None, batch_status=None, text=None,
extension_elements=None, extension_attributes=None, etag=None,
deleted=None, extended_property=None,
group_membership_info=None):
PersonEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title, updated=updated,
organization=organization, phone_number=phone_number,
nickname=nickname, occupation=occupation,
gender=gender, birthday=birthday,
postal_address=postal_address,
structured_postal_address=structured_postal_address,
email=email, im=im, relation=relation,
user_defined_field=user_defined_field,
website=website, external_id=external_id, event=event,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status, text=text,
extension_elements=extension_elements,
extension_attributes=extension_attributes, etag=etag)
self.deleted = deleted
self.extended_property = extended_property or []
self.group_membership_info = group_membership_info or []
def GetPhotoLink(self):
for a_link in self.link:
if a_link.rel == PHOTO_LINK_REL:
return a_link
return None
def GetPhotoEditLink(self):
for a_link in self.link:
if a_link.rel == PHOTO_EDIT_LINK_REL:
return a_link
return None
def ContactEntryFromString(xml_string):
return atom.CreateClassFromXMLString(ContactEntry, xml_string)
class ContactsFeed(gdata.BatchFeed, gdata.LinkFinder):
"""A Google Contacts feed flavor of an Atom Feed."""
_children = gdata.BatchFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [ContactEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def ContactsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(ContactsFeed, xml_string)
class GroupEntry(gdata.BatchEntry):
"""Represents a contact group."""
_children = gdata.BatchEntry._children.copy()
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [gdata.ExtendedProperty])
def __init__(self, author=None, category=None, content=None,
contributor=None, atom_id=None, link=None, published=None,
rights=None, source=None, summary=None, control=None,
title=None, updated=None,
extended_property=None, batch_operation=None, batch_id=None,
batch_status=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation,
batch_id=batch_id, batch_status=batch_status,
title=title, updated=updated)
self.extended_property = extended_property or []
def GroupEntryFromString(xml_string):
return atom.CreateClassFromXMLString(GroupEntry, xml_string)
class GroupsFeed(gdata.BatchFeed):
"""A Google contact groups feed flavor of an Atom Feed."""
_children = gdata.BatchFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GroupEntry])
def GroupsFeedFromString(xml_string):
return atom.CreateClassFromXMLString(GroupsFeed, xml_string)
class ProfileEntry(PersonEntry):
"""A Google Profiles flavor of an Atom Entry."""
def ProfileEntryFromString(xml_string):
"""Converts an XML string into a ProfileEntry object.
Args:
xml_string: string The XML describing a Profile entry.
Returns:
A ProfileEntry object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(ProfileEntry, xml_string)
class ProfilesFeed(gdata.BatchFeed, gdata.LinkFinder):
"""A Google Profiles feed flavor of an Atom Feed."""
_children = gdata.BatchFeed._children.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [ProfileEntry])
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None,
entry=None, total_results=None, start_index=None,
items_per_page=None, extension_elements=None,
extension_attributes=None, text=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
def ProfilesFeedFromString(xml_string):
"""Converts an XML string into a ProfilesFeed object.
Args:
xml_string: string The XML describing a Profiles feed.
Returns:
A ProfilesFeed object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(ProfilesFeed, xml_string)
| Python |
#!/usr/bin/env python
#
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""ContactsService extends the GDataService for Google Contacts operations.
ContactsService: Provides methods to query feeds and manipulate items.
Extends GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'dbrattli (Dag Brattli)'
import gdata
import gdata.calendar
import gdata.service
DEFAULT_BATCH_URL = ('http://www.google.com/m8/feeds/contacts/default/full'
'/batch')
DEFAULT_PROFILES_BATCH_URL = ('http://www.google.com'
'/m8/feeds/profiles/default/full/batch')
GDATA_VER_HEADER = 'GData-Version'
class Error(Exception):
pass
class RequestError(Error):
pass
class ContactsService(gdata.service.GDataService):
"""Client for the Google Contacts service."""
def __init__(self, email=None, password=None, source=None,
server='www.google.com', additional_headers=None,
contact_list='default', **kwargs):
"""Creates a client for the Contacts service.
Args:
email: string (optional) The user's email address, used for
authentication.
password: string (optional) The user's password.
source: string (optional) The name of the user's application.
server: string (optional) The name of the server to which a connection
will be opened. Default value: 'www.google.com'.
contact_list: string (optional) The name of the default contact list to
use when no URI is specified to the methods of the service.
Default value: 'default' (the logged in user's contact list).
**kwargs: The other parameters to pass to gdata.service.GDataService
constructor.
"""
self.contact_list = contact_list
gdata.service.GDataService.__init__(
self, email=email, password=password, service='cp', source=source,
server=server, additional_headers=additional_headers, **kwargs)
def GetFeedUri(self, kind='contacts', contact_list=None, projection='full',
scheme=None):
"""Builds a feed URI.
Args:
kind: The type of feed to return, typically 'groups' or 'contacts'.
Default value: 'contacts'.
contact_list: The contact list to return a feed for.
Default value: self.contact_list.
projection: The projection to apply to the feed contents, for example
'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.
scheme: The URL scheme such as 'http' or 'https', None to return a
relative URI without hostname.
Returns:
A feed URI using the given kind, contact list, and projection.
Example: '/m8/feeds/contacts/default/full'.
"""
contact_list = contact_list or self.contact_list
if kind == 'profiles':
contact_list = 'domain/%s' % contact_list
prefix = scheme and '%s://%s' % (scheme, self.server) or ''
return '%s/m8/feeds/%s/%s/%s' % (prefix, kind, contact_list, projection)
def GetContactsFeed(self, uri=None):
uri = uri or self.GetFeedUri()
return self.Get(uri, converter=gdata.contacts.ContactsFeedFromString)
def GetContact(self, uri):
return self.Get(uri, converter=gdata.contacts.ContactEntryFromString)
def CreateContact(self, new_contact, insert_uri=None, url_params=None,
escape_params=True):
"""Adds an new contact to Google Contacts.
Args:
new_contact: atom.Entry or subclass A new contact which is to be added to
Google Contacts.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = insert_uri or self.GetFeedUri()
return self.Post(new_contact, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.ContactEntryFromString)
def UpdateContact(self, edit_uri, updated_contact, url_params=None,
escape_params=True):
"""Updates an existing contact.
Args:
edit_uri: string The edit link URI for the element being updated
updated_contact: string, atom.Entry or subclass containing
the Atom Entry which will replace the contact which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Put(updated_contact, self._CleanUri(edit_uri),
url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.ContactEntryFromString)
def DeleteContact(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an contact with the specified ID from Google Contacts.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'/m8/feeds/contacts/default/full/xxx/yyy'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Delete(self._CleanUri(edit_uri),
url_params=url_params, escape_params=escape_params)
def GetGroupsFeed(self, uri=None):
uri = uri or self.GetFeedUri('groups')
return self.Get(uri, converter=gdata.contacts.GroupsFeedFromString)
def CreateGroup(self, new_group, insert_uri=None, url_params=None,
escape_params=True):
insert_uri = insert_uri or self.GetFeedUri('groups')
return self.Post(new_group, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.GroupEntryFromString)
def UpdateGroup(self, edit_uri, updated_group, url_params=None,
escape_params=True):
return self.Put(updated_group, self._CleanUri(edit_uri),
url_params=url_params,
escape_params=escape_params,
converter=gdata.contacts.GroupEntryFromString)
def DeleteGroup(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
return self.Delete(self._CleanUri(edit_uri),
url_params=url_params, escape_params=escape_params)
def ChangePhoto(self, media, contact_entry_or_url, content_type=None,
content_length=None):
"""Change the photo for the contact by uploading a new photo.
Performs a PUT against the photo edit URL to send the binary data for the
photo.
Args:
media: filename, file-like-object, or a gdata.MediaSource object to send.
contact_entry_or_url: ContactEntry or str If it is a ContactEntry, this
method will search for an edit photo link URL and
perform a PUT to the URL.
content_type: str (optional) the mime type for the photo data. This is
necessary if media is a file or file name, but if media
is a MediaSource object then the media object can contain
the mime type. If media_type is set, it will override the
mime type in the media object.
content_length: int or str (optional) Specifying the content length is
only required if media is a file-like object. If media
is a filename, the length is determined using
os.path.getsize. If media is a MediaSource object, it is
assumed that it already contains the content length.
"""
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
url = contact_entry_or_url.GetPhotoEditLink().href
else:
url = contact_entry_or_url
if isinstance(media, gdata.MediaSource):
payload = media
# If the media object is a file-like object, then use it as the file
# handle in the in the MediaSource.
elif hasattr(media, 'read'):
payload = gdata.MediaSource(file_handle=media,
content_type=content_type, content_length=content_length)
# Assume that the media object is a file name.
else:
payload = gdata.MediaSource(content_type=content_type,
content_length=content_length, file_path=media)
return self.Put(payload, url)
def GetPhoto(self, contact_entry_or_url):
"""Retrives the binary data for the contact's profile photo as a string.
Args:
contact_entry_or_url: a gdata.contacts.ContactEntry objecr or a string
containing the photo link's URL. If the contact entry does not
contain a photo link, the image will not be fetched and this method
will return None.
"""
# TODO: add the ability to write out the binary image data to a file,
# reading and writing a chunk at a time to avoid potentially using up
# large amounts of memory.
url = None
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
photo_link = contact_entry_or_url.GetPhotoLink()
if photo_link:
url = photo_link.href
else:
url = contact_entry_or_url
if url:
return self.Get(url, converter=str)
else:
return None
def DeletePhoto(self, contact_entry_or_url):
url = None
if isinstance(contact_entry_or_url, gdata.contacts.ContactEntry):
url = contact_entry_or_url.GetPhotoEditLink().href
else:
url = contact_entry_or_url
if url:
self.Delete(url)
def GetProfilesFeed(self, uri=None):
"""Retrieves a feed containing all domain's profiles.
Args:
uri: string (optional) the URL to retrieve the profiles feed,
for example /m8/feeds/profiles/default/full
Returns:
On success, a ProfilesFeed containing the profiles.
On failure, raises a RequestError.
"""
uri = uri or self.GetFeedUri('profiles')
return self.Get(uri,
converter=gdata.contacts.ProfilesFeedFromString)
def GetProfile(self, uri):
"""Retrieves a domain's profile for the user.
Args:
uri: string the URL to retrieve the profiles feed,
for example /m8/feeds/profiles/default/full/username
Returns:
On success, a ProfileEntry containing the profile for the user.
On failure, raises a RequestError
"""
return self.Get(uri,
converter=gdata.contacts.ProfileEntryFromString)
def UpdateProfile(self, edit_uri, updated_profile, url_params=None,
escape_params=True):
"""Updates an existing profile.
Args:
edit_uri: string The edit link URI for the element being updated
updated_profile: string atom.Entry or subclass containing
the Atom Entry which will replace the profile which is
stored at the edit_url.
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_params will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, raises a RequestError.
"""
return self.Put(updated_profile, self._CleanUri(edit_uri),
url_params=url_params, escape_params=escape_params,
converter=gdata.contacts.ProfileEntryFromString)
def ExecuteBatch(self, batch_feed, url,
converter=gdata.contacts.ContactsFeedFromString):
"""Sends a batch request feed to the server.
Args:
batch_feed: gdata.contacts.ContactFeed A feed containing batch
request entries. Each entry contains the operation to be performed
on the data contained in the entry. For example an entry with an
operation type of insert will be used as if the individual entry
had been inserted.
url: str The batch URL to which these operations should be applied.
converter: Function (optional) The function used to convert the server's
response to an object. The default value is ContactsFeedFromString.
Returns:
The results of the batch request's execution on the server. If the
default converter is used, this is stored in a ContactsFeed.
"""
return self.Post(batch_feed, url, converter=converter)
def ExecuteBatchProfiles(self, batch_feed, url,
converter=gdata.contacts.ProfilesFeedFromString):
"""Sends a batch request feed to the server.
Args:
batch_feed: gdata.profiles.ProfilesFeed A feed containing batch
request entries. Each entry contains the operation to be performed
on the data contained in the entry. For example an entry with an
operation type of insert will be used as if the individual entry
had been inserted.
url: string The batch URL to which these operations should be applied.
converter: Function (optional) The function used to convert the server's
response to an object. The default value is
gdata.profiles.ProfilesFeedFromString.
Returns:
The results of the batch request's execution on the server. If the
default converter is used, this is stored in a ProfilesFeed.
"""
return self.Post(batch_feed, url, converter=converter)
def _CleanUri(self, uri):
"""Sanitizes a feed URI.
Args:
uri: The URI to sanitize, can be relative or absolute.
Returns:
The given URI without its http://server prefix, if any.
Keeps the leading slash of the URI.
"""
url_prefix = 'http://%s' % self.server
if uri.startswith(url_prefix):
uri = uri[len(url_prefix):]
return uri
class ContactsQuery(gdata.service.Query):
def __init__(self, feed=None, text_query=None, params=None,
categories=None, group=None):
self.feed = feed or '/m8/feeds/contacts/default/full'
if group:
self._SetGroup(group)
gdata.service.Query.__init__(self, feed=self.feed, text_query=text_query,
params=params, categories=categories)
def _GetGroup(self):
if 'group' in self:
return self['group']
else:
return None
def _SetGroup(self, group_id):
self['group'] = group_id
group = property(_GetGroup, _SetGroup,
doc='The group query parameter to find only contacts in this group')
class GroupsQuery(gdata.service.Query):
def __init__(self, feed=None, text_query=None, params=None,
categories=None):
self.feed = feed or '/m8/feeds/groups/default/full'
gdata.service.Query.__init__(self, feed=self.feed, text_query=text_query,
params=params, categories=categories)
class ProfilesQuery(gdata.service.Query):
"""Constructs a query object for the profiles feed."""
def __init__(self, feed=None, text_query=None, params=None,
categories=None):
self.feed = feed or '/m8/feeds/profiles/default/full'
gdata.service.Query.__init__(self, feed=self.feed, text_query=text_query,
params=params, categories=categories)
| Python |
#!/usr/bin/python
#
# Copyright 2011 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 representing elements of the Documents List API."""
__author__ = 'vicfryzel@google.com (Vic Fryzel)'
import re
import atom.core
import atom.data
import gdata.acl.data
import gdata.data
DOCUMENTS_NS = 'http://schemas.google.com/docs/2007'
LABELS_NS = 'http://schemas.google.com/g/2005/labels'
DOCUMENTS_TEMPLATE = '{http://schemas.google.com/docs/2007}%s'
ACL_FEEDLINK_REL = 'http://schemas.google.com/acl/2007#accessControlList'
RESUMABLE_CREATE_MEDIA_LINK_REL = 'http://schemas.google.com/g/2005#resumable-create-media'
RESUMABLE_EDIT_MEDIA_LINK_REL = 'http://schemas.google.com/g/2005#resumable-edit-media'
REVISION_FEEDLINK_REL = DOCUMENTS_NS + '/revisions'
PARENT_LINK_REL = DOCUMENTS_NS + '#parent'
PUBLISH_LINK_REL = DOCUMENTS_NS + '#publish'
DATA_KIND_SCHEME = 'http://schemas.google.com/g/2005#kind'
LABELS_SCHEME = LABELS_NS
DOCUMENT_LABEL = 'document'
SPREADSHEET_LABEL = 'spreadsheet'
DRAWING_LABEL = 'drawing'
PRESENTATION_LABEL = 'presentation'
FILE_LABEL = 'file'
PDF_LABEL = 'pdf'
FORM_LABEL = 'form'
ITEM_LABEL = 'item'
COLLECTION_LABEL = 'folder'
STARRED_LABEL = 'starred'
VIEWED_LABEL = 'viewed'
HIDDEN_LABEL = 'hidden'
TRASHED_LABEL = 'trashed'
MINE_LABEL = 'mine'
PRIVATE_LABEL = 'private'
SHAREDWITHDOMAIN_LABEL = 'shared-with-domain'
RESTRICTEDDOWNLOAD_LABEL = 'restricted-download'
class ResourceId(atom.core.XmlElement):
"""The DocList gd:resourceId element."""
_qname = gdata.data.GDATA_TEMPLATE % 'resourceId'
class LastModifiedBy(atom.data.Person):
"""The DocList gd:lastModifiedBy element."""
_qname = gdata.data.GDATA_TEMPLATE % 'lastModifiedBy'
class LastViewed(atom.data.Person):
"""The DocList gd:lastViewed element."""
_qname = gdata.data.GDATA_TEMPLATE % 'lastViewed'
class WritersCanInvite(atom.core.XmlElement):
"""The DocList docs:writersCanInvite element."""
_qname = DOCUMENTS_TEMPLATE % 'writersCanInvite'
value = 'value'
class Deleted(atom.core.XmlElement):
"""The DocList gd:deleted element."""
_qname = gdata.data.GDATA_TEMPLATE % 'deleted'
class QuotaBytesUsed(atom.core.XmlElement):
"""The DocList gd:quotaBytesUsed element."""
_qname = gdata.data.GDATA_TEMPLATE % 'quotaBytesUsed'
class Publish(atom.core.XmlElement):
"""The DocList docs:publish element."""
_qname = DOCUMENTS_TEMPLATE % 'publish'
value = 'value'
class PublishAuto(atom.core.XmlElement):
"""The DocList docs:publishAuto element."""
_qname = DOCUMENTS_TEMPLATE % 'publishAuto'
value = 'value'
class PublishOutsideDomain(atom.core.XmlElement):
"""The DocList docs:publishOutsideDomain element."""
_qname = DOCUMENTS_TEMPLATE % 'publishOutsideDomain'
value = 'value'
class Filename(atom.core.XmlElement):
"""The DocList docs:filename element."""
_qname = DOCUMENTS_TEMPLATE % 'filename'
class SuggestedFilename(atom.core.XmlElement):
"""The DocList docs:suggestedFilename element."""
_qname = DOCUMENTS_TEMPLATE % 'suggestedFilename'
class CategoryFinder(object):
"""Mixin to provide category finding functionality.
Analogous to atom.data.LinkFinder, but a simpler API, specialized for
DocList categories.
"""
def add_category(self, scheme, term, label):
"""Add a category for a scheme, term and label.
Args:
scheme: The scheme for the category.
term: The term for the category.
label: The label for the category
Returns:
The newly created atom.data.Category.
"""
category = atom.data.Category(scheme=scheme, term=term, label=label)
self.category.append(category)
return category
AddCategory = add_category
def get_categories(self, scheme):
"""Fetch the category elements for a scheme.
Args:
scheme: The scheme to fetch the elements for.
Returns:
Generator of atom.data.Category elements.
"""
for category in self.category:
if category.scheme == scheme:
yield category
GetCategories = get_categories
def remove_categories(self, scheme):
"""Remove category elements for a scheme.
Args:
scheme: The scheme of category to remove.
"""
for category in list(self.get_categories(scheme)):
self.category.remove(category)
RemoveCategories = remove_categories
def get_first_category(self, scheme):
"""Fetch the first category element for a scheme.
Args:
scheme: The scheme of category to return.
Returns:
atom.data.Category if found or None.
"""
try:
return self.get_categories(scheme).next()
except StopIteration, e:
# The entry doesn't have the category
return None
GetFirstCategory = get_first_category
def set_resource_type(self, label):
"""Set the document type for an entry, by building the appropriate
atom.data.Category
Args:
label: str The value for the category entry. If None is passed the
category is removed and not set.
Returns:
An atom.data.Category or None if label is None.
"""
self.remove_categories(DATA_KIND_SCHEME)
if label is not None:
return self.add_category(scheme=DATA_KIND_SCHEME,
term='%s#%s' % (DOCUMENTS_NS, label),
label=label)
else:
return None
SetResourceType = set_resource_type
def get_resource_type(self):
"""Extracts the type of document this Resource is.
This method returns the type of document the Resource represents. Possible
values are document, presentation, drawing, spreadsheet, file, folder,
form, item, or pdf.
'folder' is a possible return value of this method because, for legacy
support, we have not yet renamed the folder keyword to collection in
the API itself.
Returns:
String representing the type of document.
"""
category = self.get_first_category(DATA_KIND_SCHEME)
if category is not None:
return category.label
else:
return None
GetResourceType = get_resource_type
def get_labels(self):
"""Extracts the labels for this Resource.
This method returns the labels as a set, for example: 'hidden', 'starred',
'viewed'.
Returns:
Set of string labels.
"""
return set(category.label for category in
self.get_categories(LABELS_SCHEME))
GetLabels = get_labels
def has_label(self, label):
"""Whether this Resource has a label.
Args:
label: The str label to test for
Returns:
Boolean value indicating presence of label.
"""
return label in self.get_labels()
HasLabel = has_label
def add_label(self, label):
"""Add a label, if it is not present.
Args:
label: The str label to set
"""
if not self.has_label(label):
self.add_category(scheme=LABELS_SCHEME,
term='%s#%s' % (LABELS_NS, label),
label=label)
AddLabel = add_label
def remove_label(self, label):
"""Remove a label, if it is present.
Args:
label: The str label to remove
"""
for category in self.get_categories(LABELS_SCHEME):
if category.label == label:
self.category.remove(category)
RemoveLabel = remove_label
def is_starred(self):
"""Whether this Resource is starred.
Returns:
Boolean value indicating that the resource is starred.
"""
return self.has_label(STARRED_LABEL)
IsStarred = is_starred
def is_hidden(self):
"""Whether this Resource is hidden.
Returns:
Boolean value indicating that the resource is hidden.
"""
return self.has_label(HIDDEN_LABEL)
IsHidden = is_hidden
def is_viewed(self):
"""Whether this Resource is viewed.
Returns:
Boolean value indicating that the resource is viewed.
"""
return self.has_label(VIEWED_LABEL)
IsViewed = is_viewed
def is_trashed(self):
"""Whether this resource is trashed.
Returns:
Boolean value indicating that the resource is trashed.
"""
return self.has_label(TRASHED_LABEL)
IsTrashed = is_trashed
def is_mine(self):
"""Whether this resource is marked as mine.
Returns:
Boolean value indicating that the resource is marked as mine.
"""
return self.has_label(MINE_LABEL)
IsMine = is_mine
def is_private(self):
"""Whether this resource is private.
Returns:
Boolean value indicating that the resource is private.
"""
return self.has_label(PRIVATE_LABEL)
IsPrivate = is_private
def is_shared_with_domain(self):
"""Whether this resource is shared with the domain.
Returns:
Boolean value indicating that the resource is shared with the domain.
"""
return self.has_label(SHAREDWITHDOMAIN_LABEL)
IsSharedWithDomain = is_shared_with_domain
def is_restricted_download(self):
"""Whether this resource is restricted download.
Returns:
Boolean value indicating whether the resource is restricted download.
"""
return self.has_label(RESTRICTEDDOWNLOAD_LABEL)
IsRestrictedDownload = is_restricted_download
class AclEntry(gdata.acl.data.AclEntry, gdata.data.BatchEntry):
"""Resource ACL entry."""
@staticmethod
def get_instance(role=None, scope_type=None, scope_value=None, key=False):
entry = AclEntry()
if role is not None:
if isinstance(role, basestring):
role = gdata.acl.data.AclRole(value=role)
if key:
entry.with_key = gdata.acl.data.AclWithKey(key='', role=role)
else:
entry.role = role
if scope_type is not None:
if scope_value is not None:
entry.scope = gdata.acl.data.AclScope(type=scope_type,
value=scope_value)
else:
entry.scope = gdata.acl.data.AclScope(type=scope_type)
return entry
GetInstance = get_instance
class AclFeed(gdata.acl.data.AclFeed):
"""Resource ACL feed."""
entry = [AclEntry]
class Resource(gdata.data.GDEntry, CategoryFinder):
"""DocList version of an Atom Entry."""
last_viewed = LastViewed
last_modified_by = LastModifiedBy
resource_id = ResourceId
deleted = Deleted
writers_can_invite = WritersCanInvite
quota_bytes_used = QuotaBytesUsed
feed_link = [gdata.data.FeedLink]
filename = Filename
suggested_filename = SuggestedFilename
# Only populated if you request /feeds/default/private/expandAcl
acl_feed = AclFeed
def __init__(self, type=None, title=None, **kwargs):
super(Resource, self).__init__(**kwargs)
if isinstance(type, basestring):
self.set_resource_type(type)
if title is not None:
if isinstance(title, basestring):
self.title = atom.data.Title(text=title)
else:
self.title = title
def get_acl_feed_link(self):
"""Extracts the Resource's ACL feed <gd:feedLink>.
Returns:
A gdata.data.FeedLink object.
"""
for feed_link in self.feed_link:
if feed_link.rel == ACL_FEEDLINK_REL:
return feed_link
return None
GetAclFeedLink = get_acl_feed_link
def get_revisions_feed_link(self):
"""Extracts the Resource's revisions feed <gd:feedLink>.
Returns:
A gdata.data.FeedLink object.
"""
for feed_link in self.feed_link:
if feed_link.rel == REVISION_FEEDLINK_REL:
return feed_link
return None
GetRevisionsFeedLink = get_revisions_feed_link
def get_resumable_create_media_link(self):
"""Extracts the Resource's resumable create link.
Returns:
A gdata.data.FeedLink object.
"""
return self.get_link(RESUMABLE_CREATE_MEDIA_LINK_REL)
GetResumableCreateMediaLink = get_resumable_create_media_link
def get_resumable_edit_media_link(self):
"""Extracts the Resource's resumable update link.
Returns:
A gdata.data.FeedLink object.
"""
return self.get_link(RESUMABLE_EDIT_MEDIA_LINK_REL)
GetResumableEditMediaLink = get_resumable_edit_media_link
def in_collections(self):
"""Returns the parents link(s) (collections) of this entry."""
links = []
for link in self.link:
if link.rel == PARENT_LINK_REL and link.href:
links.append(link)
return links
InCollections = in_collections
class ResourceFeed(gdata.data.GDFeed):
"""Main feed containing a list of resources."""
entry = [Resource]
class Revision(gdata.data.GDEntry):
"""Resource Revision entry."""
publish = Publish
publish_auto = PublishAuto
publish_outside_domain = PublishOutsideDomain
def find_publish_link(self):
"""Get the link that points to the published resource on the web.
Returns:
A str for the URL in the link with a rel ending in #publish.
"""
return self.find_url(PUBLISH_LINK_REL)
FindPublishLink = find_publish_link
def get_publish_link(self):
"""Get the link that points to the published resource on the web.
Returns:
A gdata.data.Link for the link with a rel ending in #publish.
"""
return self.get_link(PUBLISH_LINK_REL)
GetPublishLink = get_publish_link
class RevisionFeed(gdata.data.GDFeed):
"""A DocList Revision feed."""
entry = [Revision]
class ArchiveResourceId(atom.core.XmlElement):
"""The DocList docs:removed element."""
_qname = DOCUMENTS_TEMPLATE % 'archiveResourceId'
class ArchiveFailure(atom.core.XmlElement):
"""The DocList docs:archiveFailure element."""
_qname = DOCUMENTS_TEMPLATE % 'archiveFailure'
class ArchiveComplete(atom.core.XmlElement):
"""The DocList docs:archiveComplete element."""
_qname = DOCUMENTS_TEMPLATE % 'archiveComplete'
class ArchiveTotal(atom.core.XmlElement):
"""The DocList docs:archiveTotal element."""
_qname = DOCUMENTS_TEMPLATE % 'archiveTotal'
class ArchiveTotalComplete(atom.core.XmlElement):
"""The DocList docs:archiveTotalComplete element."""
_qname = DOCUMENTS_TEMPLATE % 'archiveTotalComplete'
class ArchiveTotalFailure(atom.core.XmlElement):
"""The DocList docs:archiveTotalFailure element."""
_qname = DOCUMENTS_TEMPLATE % 'archiveTotalFailure'
class ArchiveConversion(atom.core.XmlElement):
"""The DocList docs:removed element."""
_qname = DOCUMENTS_TEMPLATE % 'archiveConversion'
source = 'source'
target = 'target'
class ArchiveNotify(atom.core.XmlElement):
"""The DocList docs:archiveNotify element."""
_qname = DOCUMENTS_TEMPLATE % 'archiveNotify'
class ArchiveStatus(atom.core.XmlElement):
"""The DocList docs:archiveStatus element."""
_qname = DOCUMENTS_TEMPLATE % 'archiveStatus'
class ArchiveNotifyStatus(atom.core.XmlElement):
"""The DocList docs:archiveNotifyStatus element."""
_qname = DOCUMENTS_TEMPLATE % 'archiveNotifyStatus'
class Archive(gdata.data.GDEntry):
"""Archive entry."""
archive_resource_ids = [ArchiveResourceId]
status = ArchiveStatus
date_completed = ArchiveComplete
num_resources = ArchiveTotal
num_complete_resources = ArchiveTotalComplete
num_failed_resources = ArchiveTotalFailure
failed_resource_ids = [ArchiveFailure]
notify_status = ArchiveNotifyStatus
conversions = [ArchiveConversion]
notification_email = ArchiveNotify
size = QuotaBytesUsed
@staticmethod
def from_resource_list(resources):
resource_ids = []
for resource in resources:
id = ArchiveResourceId(text=resource.resource_id.text)
resource_ids.append(id)
return Archive(archive_resource_ids=resource_ids)
FromResourceList = from_resource_list
class Removed(atom.core.XmlElement):
"""The DocList docs:removed element."""
_qname = DOCUMENTS_TEMPLATE % 'removed'
class Changestamp(atom.core.XmlElement):
"""The DocList docs:changestamp element."""
_qname = DOCUMENTS_TEMPLATE % 'changestamp'
value = 'value'
class Change(Resource):
"""Change feed entry."""
changestamp = Changestamp
removed = Removed
class ChangeFeed(gdata.data.GDFeed):
"""DocList Changes feed."""
entry = [Change]
class QuotaBytesTotal(atom.core.XmlElement):
"""The DocList gd:quotaBytesTotal element."""
_qname = gdata.data.GDATA_TEMPLATE % 'quotaBytesTotal'
class QuotaBytesUsedInTrash(atom.core.XmlElement):
"""The DocList docs:quotaBytesUsedInTrash element."""
_qname = DOCUMENTS_TEMPLATE % 'quotaBytesUsedInTrash'
class ImportFormat(atom.core.XmlElement):
"""The DocList docs:importFormat element."""
_qname = DOCUMENTS_TEMPLATE % 'importFormat'
source = 'source'
target = 'target'
class ExportFormat(atom.core.XmlElement):
"""The DocList docs:exportFormat element."""
_qname = DOCUMENTS_TEMPLATE % 'exportFormat'
source = 'source'
target = 'target'
class FeatureName(atom.core.XmlElement):
"""The DocList docs:featureName element."""
_qname = DOCUMENTS_TEMPLATE % 'featureName'
class FeatureRate(atom.core.XmlElement):
"""The DocList docs:featureRate element."""
_qname = DOCUMENTS_TEMPLATE % 'featureRate'
class Feature(atom.core.XmlElement):
"""The DocList docs:feature element."""
_qname = DOCUMENTS_TEMPLATE % 'feature'
name = FeatureName
rate = FeatureRate
class MaxUploadSize(atom.core.XmlElement):
"""The DocList docs:maxUploadSize element."""
_qname = DOCUMENTS_TEMPLATE % 'maxUploadSize'
kind = 'kind'
class AdditionalRoleSet(atom.core.XmlElement):
"""The DocList docs:additionalRoleSet element."""
_qname = DOCUMENTS_TEMPLATE % 'additionalRoleSet'
primaryRole = 'primaryRole'
additional_role = [gdata.acl.data.AclAdditionalRole]
class AdditionalRoleInfo(atom.core.XmlElement):
"""The DocList docs:additionalRoleInfo element."""
_qname = DOCUMENTS_TEMPLATE % 'additionalRoleInfo'
kind = 'kind'
additional_role_set = [AdditionalRoleSet]
class Metadata(gdata.data.GDEntry):
"""Metadata entry for a user."""
quota_bytes_total = QuotaBytesTotal
quota_bytes_used = QuotaBytesUsed
quota_bytes_used_in_trash = QuotaBytesUsedInTrash
import_formats = [ImportFormat]
export_formats = [ExportFormat]
features = [Feature]
max_upload_sizes = [MaxUploadSize]
additional_role_info = [AdditionalRoleInfo]
| Python |
#!/usr/bin/python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DocsClient simplifies interactions with the Documents List API."""
__author__ = 'vicfryzel@google.com (Vic Fryzel)'
import copy
import mimetypes
import re
import urllib
import atom.data
import atom.http_core
import gdata.client
import gdata.docs.data
import gdata.gauth
# Feed URIs that are given by the API, but cannot be obtained without
# making a mostly unnecessary HTTP request.
RESOURCE_FEED_URI = '/feeds/default/private/full'
RESOURCE_SELF_LINK_TEMPLATE = RESOURCE_FEED_URI + '/%s'
RESOURCE_UPLOAD_URI = '/feeds/upload/create-session/default/private/full'
ARCHIVE_FEED_URI = '/feeds/default/private/archive'
METADATA_URI = '/feeds/metadata/default'
CHANGE_FEED_URI = '/feeds/default/private/changes'
class DocsClient(gdata.client.GDClient):
"""Client for all features of the Google Documents List API."""
host = 'docs.google.com'
api_version = '3.0'
auth_service = 'writely'
alt_auth_service = 'wise'
alt_auth_token = None
auth_scopes = gdata.gauth.AUTH_SCOPES['writely']
ssl = True
def request(self, method=None, uri=None, **kwargs):
"""Add support for imitating other users via 2-Legged OAuth.
Args:
uri: (optional) URI of the request in which to replace default with
self.xoauth_requestor_id.
Returns:
Result of super(DocsClient, self).request().
"""
if self.xoauth_requestor_id is not None and uri is not None:
if isinstance(uri, (str, unicode)):
uri = atom.http_core.Uri.parse_uri(uri)
uri.path.replace('/default', '/%s' % self.xoauth_requestor_id)
return super(DocsClient, self).request(method=method, uri=uri, **kwargs)
Request = request
def get_metadata(self, **kwargs):
"""Retrieves the metadata of a user account.
Args:
kwargs: Other parameters to pass to self.get_entry().
Returns:
gdata.docs.data.Metadata representing metadata of user's account.
"""
return self.get_entry(
METADATA_URI, desired_class=gdata.docs.data.Metadata, **kwargs)
GetMetadata = get_metadata
def get_changes(self, changestamp=None, max_results=None, show_root=None,
**kwargs):
"""Retrieves changes to a user's documents list.
Args:
changestamp: (optional) String changestamp value to query since.
If provided, returned changes will have a changestamp larger than
the given one.
max_results: (optional) Number of results to fetch. API will limit
this number to 100 at most.
show_root: (optional) True to include indications if a resource is in
the root collection.
kwargs: Other parameters to pass to self.get_feed().
Returns:
gdata.docs.data.ChangeFeed.
"""
uri = atom.http_core.Uri.parse_uri(CHANGE_FEED_URI)
if changestamp is not None:
uri.query['start-index'] = changestamp
if max_results is not None:
uri.query['max-results'] = max_results
if show_root is not None:
uri.query['showroot'] = str(show_root).lower()
return self.get_feed(
uri, desired_class=gdata.docs.data.ChangeFeed, **kwargs)
GetChanges = get_changes
def get_resources(self, uri=None, limit=None, show_root=None, **kwargs):
"""Retrieves the resources in a user's docslist, or the given URI.
Args:
uri: (optional) URI to query for resources. If None, then
gdata.docs.client.DocsClient.RESOURCE_FEED_URI is used, which will
query for all non-collections.
limit: int (optional) A maximum cap for the number of results to
return in the feed. By default, the API returns a maximum of 100
per page. Thus, if you set limit=5000, you will get <= 5000
documents (guarenteed no more than 5000), and will need to follow the
feed's next links (feed.GetNextLink()) to the rest. See
get_everything(). Similarly, if you set limit=50, only <= 50
documents are returned. Note: if the max-results parameter is set in
the uri parameter, it is chosen over a value set for limit.
show_root: (optional) True to include indications if a resource is in
the root collection.
kwargs: Other parameters to pass to self.get_feed().
Returns:
gdata.docs.data.ResourceFeed feed.
"""
if uri is None:
uri = RESOURCE_FEED_URI
if isinstance(uri, basestring):
uri = atom.http_core.Uri.parse_uri(uri)
# Add max-results param if it wasn't included in the uri.
if limit is not None and not 'max-results' in uri.query:
uri.query['max-results'] = limit
if show_root is not None:
uri.query['showroot'] = str(show_root).lower()
return self.get_feed(uri, desired_class=gdata.docs.data.ResourceFeed,
**kwargs)
GetResources = get_resources
def get_all_resources(self, uri=None, show_root=None, **kwargs):
"""Retrieves all of a user's non-collections or everything at the given URI.
Folders are not included in this by default. Pass in a custom URI to
include collections in your query. The DocsQuery class is an easy way to
generate such a URI.
This method makes multiple HTTP requests (by following the feed's next
links) in order to fetch the user's entire document list.
Args:
uri: (optional) URI to query the doclist feed with. If None, then use
DocsClient.RESOURCE_FEED_URI, which will retrieve all
non-collections.
show_root: (optional) True to include indications if a resource is in
the root collection.
kwargs: Other parameters to pass to self.GetResources().
Returns:
List of gdata.docs.data.Resource objects representing the retrieved
entries.
"""
if uri is None:
uri = RESOURCE_FEED_URI
if isinstance(uri, basestring):
uri = atom.http_core.Uri.parse_uri(uri)
if show_root is not None:
uri.query['showroot'] = str(show_root).lower()
feed = self.GetResources(uri=uri, **kwargs)
entries = feed.entry
while feed.GetNextLink() is not None:
feed = self.GetResources(feed.GetNextLink().href, **kwargs)
entries.extend(feed.entry)
return entries
GetAllResources = get_all_resources
def get_resource(self, entry, **kwargs):
"""Retrieves a resource again given its entry.
Args:
entry: gdata.docs.data.Resource to fetch and return.
kwargs: Other args to pass to GetResourceBySelfLink().
Returns:
gdata.docs.data.Resource representing retrieved resource.
"""
return self.GetResourceBySelfLink(entry.GetSelfLink().href, **kwargs)
GetResource = get_resource
def get_resource_by_id(self, resource_id, **kwargs):
"""Retrieves a resource again given its resource ID.
Args:
resource_id: Typed or untyped resource ID of a resource.
kwargs: Other args to pass to GetResourceBySelfLink().
Returns:
gdata.docs.data.Resource representing retrieved resource.
"""
return self.GetResourceBySelfLink(
RESOURCE_SELF_LINK_TEMPLATE % resource_id, **kwargs)
GetResourceById = get_resource_by_id
def get_resource_by_self_link(self, uri, etag=None, show_root=None,
**kwargs):
"""Retrieves a particular resource by its self link.
Args:
uri: str URI at which to query for given resource. This can be found
using entry.GetSelfLink().
etag: str (optional) The document/item's etag value to be used in a
conditional GET. See http://code.google.com/apis/documents/docs/3.0/
developers_guide_protocol.html#RetrievingCached.
show_root: (optional) True to include indications if a resource is in
the root collection.
kwargs: Other parameters to pass to self.get_entry().
Returns:
gdata.docs.data.Resource representing the retrieved resource.
"""
if isinstance(uri, basestring):
uri = atom.http_core.Uri.parse_uri(uri)
if show_root is not None:
uri.query['showroot'] = str(show_root).lower()
return self.get_entry(
uri , etag=etag, desired_class=gdata.docs.data.Resource, **kwargs)
GetResourceBySelfLink = get_resource_by_self_link
def get_resource_acl(self, entry, **kwargs):
"""Retrieves the ACL sharing permissions for the given entry.
Args:
entry: gdata.docs.data.Resource for which to get ACL.
kwargs: Other parameters to pass to self.get_feed().
Returns:
gdata.docs.data.AclFeed representing the resource's ACL.
"""
self._check_entry_is_resource(entry)
return self.get_feed(entry.GetAclFeedLink().href,
desired_class=gdata.docs.data.AclFeed, **kwargs)
GetResourceAcl = get_resource_acl
def create_resource(self, entry, media=None, collection=None,
create_uri=None, **kwargs):
"""Creates new entries in Google Docs, and uploads their contents.
Args:
entry: gdata.docs.data.Resource representing initial version
of entry being created. If media is also provided, the entry will
first be created with the given metadata and content.
media: (optional) gdata.data.MediaSource containing the file to be
uploaded.
collection: (optional) gdata.docs.data.Resource representing a collection
in which this new entry should be created. If provided along
with create_uri, create_uri will win (e.g. entry will be created at
create_uri, not necessarily in given collection).
create_uri: (optional) String URI at which to create the given entry. If
collection, media and create_uri are None, use
gdata.docs.client.RESOURCE_FEED_URI. If collection and create_uri are
None, use gdata.docs.client.RESOURCE_UPLOAD_URI. If collection and
media are not None,
collection.GetResumableCreateMediaLink() is used,
with the collection's resource ID substituted in.
kwargs: Other parameters to pass to self.post() and self.update().
Returns:
gdata.docs.data.Resource containing information about new entry.
"""
if media is not None:
if create_uri is None and collection is not None:
create_uri = collection.GetResumableCreateMediaLink().href
elif create_uri is None:
create_uri = RESOURCE_UPLOAD_URI
uploader = gdata.client.ResumableUploader(
self, media.file_handle, media.content_type, media.content_length,
desired_class=gdata.docs.data.Resource)
return uploader.upload_file(create_uri, entry, **kwargs)
else:
if create_uri is None and collection is not None:
create_uri = collection.content.src
elif create_uri is None:
create_uri = RESOURCE_FEED_URI
return self.post(
entry, create_uri, desired_class=gdata.docs.data.Resource, **kwargs)
CreateResource = create_resource
def update_resource(self, entry, media=None, update_metadata=True,
new_revision=False, **kwargs):
"""Updates an entry in Google Docs with new metadata and/or new data.
Args:
entry: Entry to update. Make any metadata changes to this entry.
media: (optional) gdata.data.MediaSource object containing the file with
which to replace the entry's data.
update_metadata: (optional) True to update the metadata from the entry
itself. You might set this to False to only update an entry's
file content, and not its metadata.
new_revision: (optional) True to create a new revision with this update,
False otherwise.
kwargs: Other parameters to pass to self.post().
Returns:
gdata.docs.data.Resource representing the updated entry.
"""
uri_params = {}
if new_revision:
uri_params['new-revision'] = 'true'
if update_metadata and media is None:
uri = atom.http_core.parse_uri(entry.GetEditLink().href)
uri.query.update(uri_params)
return super(DocsClient, self).update(entry, **kwargs)
else:
uploader = gdata.client.ResumableUploader(
self, media.file_handle, media.content_type, media.content_length,
desired_class=gdata.docs.data.Resource)
return uploader.UpdateFile(entry_or_resumable_edit_link=entry,
update_metadata=update_metadata,
uri_params=uri_params, **kwargs)
UpdateResource = update_resource
def download_resource(self, entry, file_path, extra_params=None, **kwargs):
"""Downloads the contents of the given entry to disk.
Note: to download a file in memory, use the DownloadResourceToMemory()
method.
Args:
entry: gdata.docs.data.Resource whose contents to fetch.
file_path: str Full path to which to save file.
extra_params: dict (optional) A map of any further parameters to control
how the document is downloaded/exported. For example, exporting a
spreadsheet as a .csv: extra_params={'gid': 0, 'exportFormat': 'csv'}
kwargs: Other parameters to pass to self._download_file().
Raises:
gdata.client.RequestError if the download URL is malformed or the server's
response was not successful.
"""
self._check_entry_is_not_collection(entry)
self._check_entry_has_content(entry)
uri = self._get_download_uri(entry.content.src, extra_params)
self._download_file(uri, file_path, **kwargs)
DownloadResource = download_resource
def download_resource_to_memory(self, entry, extra_params=None, **kwargs):
"""Returns the contents of the given entry.
Args:
entry: gdata.docs.data.Resource whose contents to fetch.
extra_params: dict (optional) A map of any further parameters to control
how the document is downloaded/exported. For example, exporting a
spreadsheet as a .csv: extra_params={'gid': 0, 'exportFormat': 'csv'}
kwargs: Other parameters to pass to self._get_content().
Returns:
Content of given resource after being downloaded.
Raises:
gdata.client.RequestError if the download URL is malformed or the server's
response was not successful.
"""
self._check_entry_is_not_collection(entry)
self._check_entry_has_content(entry)
uri = self._get_download_uri(entry.content.src, extra_params)
return self._get_content(uri, **kwargs)
DownloadResourceToMemory = download_resource_to_memory
def _get_download_uri(self, base_uri, extra_params=None):
uri = base_uri.replace('&', '&')
if extra_params is not None:
if 'exportFormat' in extra_params and '/Export?' not in uri:
raise gdata.client.Error, ('This entry type cannot be exported '
'as a different format.')
if 'gid' in extra_params and uri.find('spreadsheets') == -1:
raise gdata.client.Error, 'gid param is not valid for this resource type.'
uri += '&' + urllib.urlencode(extra_params)
return uri
def _get_content(self, uri, extra_params=None, auth_token=None, **kwargs):
"""Fetches the given resource's content.
This method is useful for downloading/exporting a file within enviornments
like Google App Engine, where the user may not have the ability to write
the file to a local disk.
Be warned, this method will use as much memory as needed to store the
fetched content. This could cause issues in your environment or app. This
is only different from Download() in that you will probably retain an
open reference to the data returned from this method, where as the data
from Download() will be immediately written to disk and the memory
freed. This client library currently doesn't support reading server
responses into a buffer or yielding an open file pointer to responses.
Args:
entry: Resource to fetch.
extra_params: dict (optional) A map of any further parameters to control
how the document is downloaded/exported. For example, exporting a
spreadsheet as a .csv: extra_params={'gid': 0, 'exportFormat': 'csv'}
auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or
OAuthToken which authorizes this client to edit the user's data.
kwargs: Other parameters to pass to self.request().
Returns:
The binary file content.
Raises:
gdata.client.RequestError: on error response from server.
"""
server_response = None
token = auth_token
if 'spreadsheets' in uri and token is None \
and self.alt_auth_token is not None:
token = self.alt_auth_token
server_response = self.request(
'GET', uri, auth_token=token, **kwargs)
if server_response.status != 200:
raise gdata.client.RequestError, {'status': server_response.status,
'reason': server_response.reason,
'body': server_response.read()}
return server_response.read()
def _download_file(self, uri, file_path, **kwargs):
"""Downloads a file to disk from the specified URI.
Note: to download a file in memory, use the GetContent() method.
Args:
uri: str The full URL to download the file from.
file_path: str The full path to save the file to.
kwargs: Other parameters to pass to self.get_content().
Raises:
gdata.client.RequestError: on error response from server.
"""
f = open(file_path, 'wb')
try:
f.write(self._get_content(uri, **kwargs))
except gdata.client.RequestError, e:
f.close()
raise e
f.flush()
f.close()
_DownloadFile = _download_file
def copy_resource(self, entry, title, **kwargs):
"""Copies the given entry to a new entry with the given title.
Note: Files do not support this feature.
Args:
entry: gdata.docs.data.Resource to copy.
title: String title for the new entry.
kwargs: Other parameters to pass to self.post().
Returns:
gdata.docs.data.Resource representing duplicated resource.
"""
self._check_entry_is_resource(entry)
new_entry = gdata.docs.data.Resource(
title=atom.data.Title(text=title),
id=atom.data.Id(text=entry.GetSelfLink().href))
return self.post(new_entry, RESOURCE_FEED_URI, **kwargs)
CopyResource = copy_resource
def move_resource(self, entry, collection=None, keep_in_collections=False,
**kwargs):
"""Moves an item into a different collection (or out of all collections).
Args:
entry: gdata.docs.data.Resource to move.
collection: gdata.docs.data.Resource (optional) An object representing
the destination collection. If None, set keep_in_collections to
False to remove the item from all collections.
keep_in_collections: boolean (optional) If True, the given entry
is not removed from any existing collections it is already in.
kwargs: Other parameters to pass to self.post().
Returns:
gdata.docs.data.Resource of the moved entry.
"""
self._check_entry_is_resource(entry)
# Remove the item from any collections it is already in.
if not keep_in_collections:
for current_collection in entry.InCollections():
uri = '%s/contents/%s' % (
current_collection.href,
urllib.quote(entry.resource_id.text))
self.delete(uri, force=True)
if collection is not None:
self._check_entry_is_collection(collection)
entry = self.post(entry, collection.content.src, **kwargs)
return entry
MoveResource = move_resource
def delete_resource(self, entry, permanent=False, **kwargs):
"""Trashes or deletes the given entry.
Args:
entry: gdata.docs.data.Resource to trash or delete.
permanent: True to skip the trash and delete the entry forever.
kwargs: Other args to pass to gdata.client.GDClient.Delete()
Returns:
Result of delete request.
"""
uri = entry.GetEditLink().href
if permanent:
uri += '?delete=true'
return super(DocsClient, self).delete(uri, **kwargs)
DeleteResource = delete_resource
def _check_entry_is_resource(self, entry):
"""Ensures given entry is a gdata.docs.data.Resource.
Args:
entry: Entry to test.
Raises:
ValueError: If given entry is not a resource.
"""
if not isinstance(entry, gdata.docs.data.Resource):
raise ValueError('%s is not a gdata.docs.data.Resource' % str(entry))
def _check_entry_is_collection(self, entry):
"""Ensures given entry is a collection.
Args:
entry: Entry to test.
Raises:
ValueError: If given entry is a collection.
"""
self._check_entry_is_resource(entry)
if entry.get_resource_type() != gdata.docs.data.COLLECTION_LABEL:
raise ValueError('%s is not a collection' % str(entry))
def _check_entry_is_not_collection(self, entry):
"""Ensures given entry is not a collection.
Args:
entry: Entry to test.
Raises:
ValueError: If given entry is a collection.
"""
try:
self._check_entry_is_resource(entry)
except ValueError:
return
if entry.get_resource_type() == gdata.docs.data.COLLECTION_LABEL:
raise ValueError(
'%s is a collection, which is not valid in this method' % str(entry))
def _check_entry_has_content(self, entry):
"""Ensures given entry has a content element with src.
Args:
entry: Entry to test.
Raises:
ValueError: If given entry is not an entry or has no content src.
"""
# Don't use _check_entry_is_resource since could be Revision etc
if not (hasattr(entry, 'content') and entry.content and
entry.content.src):
raise ValueError('Entry %s has no downloadable content.' % entry)
def get_acl(self, entry, **kwargs):
"""Retrieves an AclFeed for the given resource.
Args:
entry: gdata.docs.data.Resource to fetch AclFeed for.
kwargs: Other args to pass to GetFeed().
Returns:
gdata.docs.data.AclFeed representing retrieved entries.
"""
self._check_entry_is_resource(entry)
return self.get_feed(
entry.GetAclFeedLink().href,
desired_class=gdata.docs.data.AclFeed, **kwargs)
GetAcl = get_acl
def get_acl_entry(self, entry, **kwargs):
"""Retrieves an AclEntry again.
This is useful if you need to poll for an ACL changing.
Args:
entry: gdata.docs.data.AclEntry to fetch and return.
kwargs: Other args to pass to GetAclEntryBySelfLink().
Returns:
gdata.docs.data.AclEntry representing retrieved entry.
"""
return self.GetAclEntryBySelfLink(entry.GetSelfLink().href, **kwargs)
GetAclEntry = get_acl_entry
def get_acl_entry_by_self_link(self, self_link, **kwargs):
"""Retrieves a particular AclEntry by its self link.
Args:
self_link: URI at which to query for given ACL entry. This can be found
using entry.GetSelfLink().
kwargs: Other parameters to pass to self.get_entry().
Returns:
gdata.docs.data.AclEntry representing the retrieved entry.
"""
if isinstance(self_link, atom.data.Link):
self_link = self_link.href
return self.get_entry(self_link, desired_class=gdata.docs.data.AclEntry,
**kwargs)
GetAclEntryBySelfLink = get_acl_entry_by_self_link
def add_acl_entry(self, resource, acl_entry, send_notifications=None,
**kwargs):
"""Adds the given AclEntry to the given Resource.
Args:
resource: gdata.docs.data.Resource to which to add AclEntry.
acl_entry: gdata.docs.data.AclEntry representing ACL entry to add.
send_notifications: True if users should be notified by email when
this AclEntry is added.
kwargs: Other parameters to pass to self.post().
Returns:
gdata.docs.data.AclEntry containing information about new entry.
Raises:
ValueError: If given resource has no ACL link.
"""
uri = resource.GetAclLink().href
if uri is None:
raise ValueError(('Given resource has no ACL link. Did you fetch this'
'resource from the API?'))
if send_notifications is not None:
if not send_notifications:
uri += '?send-notification-emails=false'
return self.post(acl_entry, uri, desired_class=gdata.docs.data.AclEntry,
**kwargs)
AddAclEntry = add_acl_entry
def update_acl_entry(self, entry, send_notifications=None, **kwargs):
"""Updates the given AclEntry with new metadata.
Args:
entry: AclEntry to update. Make any metadata changes to this entry.
send_notifications: True if users should be notified by email when
this AclEntry is updated.
kwargs: Other parameters to pass to super(DocsClient, self).update().
Returns:
gdata.docs.data.AclEntry representing the updated ACL entry.
"""
uri = entry.GetEditLink().href
if not send_notifications:
uri += '?send-notification-emails=false'
return super(DocsClient, self).update(entry, uri=uri, **kwargs)
UpdateAclEntry = update_acl_entry
def delete_acl_entry(self, entry, **kwargs):
"""Deletes the given AclEntry.
Args:
entry: gdata.docs.data.AclEntry to delete.
kwargs: Other args to pass to gdata.client.GDClient.Delete()
Returns:
Result of delete request.
"""
return super(DocsClient, self).delete(entry.GetEditLink().href,
**kwargs)
DeleteAclEntry = delete_acl_entry
def batch_process_acl_entries(self, resource, entries, **kwargs):
"""Applies the specified operation of each entry in a single request.
To use this, simply set acl_entry.batch_operation to one of
['query', 'insert', 'update', 'delete'], and optionally set
acl_entry.batch_id to a string of your choice.
Then, put all of your modified AclEntry objects into a list and pass
that list as the entries parameter.
Args:
resource: gdata.docs.data.Resource to which the given entries belong.
entries: [gdata.docs.data.AclEntry] to modify in some way.
kwargs: Other args to pass to gdata.client.GDClient.post()
Returns:
Resulting gdata.docs.data.AclFeed of changes.
"""
feed = gdata.docs.data.AclFeed()
feed.entry = entries
return super(DocsClient, self).post(
feed, uri=resource.GetAclLink().href + '/batch', **kwargs)
BatchProcessAclEntries = batch_process_acl_entries
def get_revisions(self, entry, **kwargs):
"""Retrieves the revision history for a resource.
Args:
entry: gdata.docs.data.Resource for which to get revisions.
kwargs: Other parameters to pass to self.get_feed().
Returns:
gdata.docs.data.RevisionFeed representing the resource's revisions.
"""
self._check_entry_is_resource(entry)
return self.get_feed(
entry.GetRevisionsFeedLink().href,
desired_class=gdata.docs.data.RevisionFeed, **kwargs)
GetRevisions = get_revisions
def get_revision(self, entry, **kwargs):
"""Retrieves a revision again given its entry.
Args:
entry: gdata.docs.data.Revision to fetch and return.
kwargs: Other args to pass to GetRevisionBySelfLink().
Returns:
gdata.docs.data.Revision representing retrieved revision.
"""
return self.GetRevisionBySelfLink(entry.GetSelfLink().href, **kwargs)
GetRevision = get_revision
def get_revision_by_self_link(self, self_link, **kwargs):
"""Retrieves a particular reivision by its self link.
Args:
self_link: URI at which to query for given revision. This can be found
using entry.GetSelfLink().
kwargs: Other parameters to pass to self.get_entry().
Returns:
gdata.docs.data.Revision representing the retrieved revision.
"""
if isinstance(self_link, atom.data.Link):
self_link = self_link.href
return self.get_entry(self_link, desired_class=gdata.docs.data.Revision,
**kwargs)
GetRevisionBySelfLink = get_revision_by_self_link
def download_revision(self, entry, file_path, extra_params=None, **kwargs):
"""Downloads the contents of the given revision to disk.
Note: to download a revision in memory, use the DownloadRevisionToMemory()
method.
Args:
entry: gdata.docs.data.Revision whose contents to fetch.
file_path: str Full path to which to save file.
extra_params: dict (optional) A map of any further parameters to control
how the document is downloaded.
kwargs: Other parameters to pass to self._download_file().
Raises:
gdata.client.RequestError if the download URL is malformed or the server's
response was not successful.
"""
self._check_entry_is_not_collection(entry)
self._check_entry_has_content(entry)
uri = self._get_download_uri(entry.content.src, extra_params)
self._download_file(uri, file_path, **kwargs)
DownloadRevision = download_revision
def download_revision_to_memory(self, entry, extra_params=None, **kwargs):
"""Returns the contents of the given revision.
Args:
entry: gdata.docs.data.Revision whose contents to fetch.
extra_params: dict (optional) A map of any further parameters to control
how the document is downloaded/exported.
kwargs: Other parameters to pass to self._get_content().
Returns:
Content of given revision after being downloaded.
Raises:
gdata.client.RequestError if the download URL is malformed or the server's
response was not successful.
"""
self._check_entry_is_not_collection(entry)
self._check_entry_has_content(entry)
uri = self._get_download_uri(entry.content.src, extra_params)
return self._get_content(uri, **kwargs)
DownloadRevisionToMemory = download_revision_to_memory
def publish_revision(self, entry, publish_auto=None,
publish_outside_domain=False, **kwargs):
"""Publishes the given revision.
This method can only be used for document revisions.
Args:
entry: Revision to update.
publish_auto: True to automatically publish future revisions of the
document. False to not automatically publish future revisions.
None to take no action and use the default value.
publish_outside_domain: True to make the published revision available
outside of a Google Apps domain. False to not publish outside
the domain. None to use the default value.
kwargs: Other parameters to pass to super(DocsClient, self).update().
Returns:
gdata.docs.data.Revision representing the updated revision.
"""
entry.publish = gdata.docs.data.Publish(value='true')
if publish_auto == True:
entry.publish_auto = gdata.docs.data.PublishAuto(value='true')
elif publish_auto == False:
entry.publish_auto = gdata.docs.data.PublishAuto(value='false')
if publish_outside_domain == True:
entry.publish_outside_domain = \
gdata.docs.data.PublishOutsideDomain(value='true')
elif publish_outside_domain == False:
entry.publish_outside_domain = \
gdata.docs.data.PublishOutsideDomain(value='false')
return super(DocsClient, self).update(entry, force=True, **kwargs)
PublishRevision = publish_revision
def unpublish_revision(self, entry, **kwargs):
"""Unpublishes the given revision.
This method can only be used for document revisions.
Args:
entry: Revision to update.
kwargs: Other parameters to pass to super(DocsClient, self).update().
Returns:
gdata.docs.data.Revision representing the updated revision.
"""
entry.publish = gdata.docs.data.Publish(value='false')
return super(DocsClient, self).update(entry, force=True, **kwargs)
UnpublishRevision = unpublish_revision
def delete_revision(self, entry, **kwargs):
"""Deletes the given Revision.
Args:
entry: gdata.docs.data.Revision to delete.
kwargs: Other args to pass to gdata.client.GDClient.Delete()
Returns:
Result of delete request.
"""
return super(DocsClient, self).delete(entry, force=True, **kwargs)
DeleteRevision = delete_revision
def get_archive(self, entry, **kwargs):
"""Retrieves an archive again given its entry.
This is useful if you need to poll for an archive completing.
Args:
entry: gdata.docs.data.Archive to fetch and return.
kwargs: Other args to pass to GetArchiveBySelfLink().
Returns:
gdata.docs.data.Archive representing retrieved archive.
"""
return self.GetArchiveBySelfLink(entry.GetSelfLink().href, **kwargs)
GetArchive = get_archive
def get_archive_by_self_link(self, self_link, **kwargs):
"""Retrieves a particular archive by its self link.
Args:
self_link: URI at which to query for given archive. This can be found
using entry.GetSelfLink().
kwargs: Other parameters to pass to self.get_entry().
Returns:
gdata.docs.data.Archive representing the retrieved archive.
"""
if isinstance(self_link, atom.data.Link):
self_link = self_link.href
return self.get_entry(self_link, desired_class=gdata.docs.data.Archive,
**kwargs)
GetArchiveBySelfLink = get_archive_by_self_link
def create_archive(self, entry, **kwargs):
"""Creates a new archive of resources.
Args:
entry: gdata.docs.data.Archive representing metadata of archive to
create.
kwargs: Other parameters to pass to self.post().
Returns:
gdata.docs.data.Archive containing information about new archive.
"""
return self.post(entry, ARCHIVE_FEED_URI,
desired_class=gdata.docs.data.Archive, **kwargs)
CreateArchive = create_archive
def update_archive(self, entry, **kwargs):
"""Updates the given Archive with new metadata.
This method is really only useful for updating the notification email
address of an archive that is being processed.
Args:
entry: Archive to update. Make any metadata changes to this entry.
kwargs: Other parameters to pass to super(DocsClient, self).update().
Returns:
gdata.docs.data.Archive representing the updated archive.
"""
return super(DocsClient, self).update(entry, **kwargs)
UpdateArchive = update_archive
download_archive = DownloadResource
DownloadArchive = download_archive
download_archive_to_memory = DownloadResourceToMemory
DownloadArchiveToMemory = download_archive_to_memory
def delete_archive(self, entry, **kwargs):
"""Aborts the given Archive operation, or deletes the Archive.
Args:
entry: gdata.docs.data.Archive to delete.
kwargs: Other args to pass to gdata.client.GDClient.Delete()
Returns:
Result of delete request.
"""
return super(DocsClient, self).delete(entry, force=True, **kwargs)
DeleteArchive = delete_archive
class DocsQuery(gdata.client.Query):
def __init__(self, title=None, title_exact=None, opened_min=None,
opened_max=None, edited_min=None, edited_max=None, owner=None,
writer=None, reader=None, show_collections=None, show_root=None,
show_deleted=None, ocr=None, target_language=None,
source_language=None, convert=None, query=None, **kwargs):
"""Constructs a query URL for the Google Documents List API.
Args:
title: str (optional) Specifies the search terms for the title of a
document. This parameter used without title_exact will only
submit partial queries, not exact queries.
title_exact: str (optional) Meaningless without title. Possible values
are 'true' and 'false'. Note: Matches are case-insensitive.
opened_min: str (optional) Lower bound on the last time a document was
opened by the current user. Use the RFC 3339 timestamp
format. For example: opened_min='2005-08-09T09:57:00-08:00'.
opened_max: str (optional) Upper bound on the last time a document was
opened by the current user. (See also opened_min.)
edited_min: str (optional) Lower bound on the last time a document was
edited by the current user. This value corresponds to the edited.text
value in the doc's entry object, which represents changes to the
document's content or metadata. Use the RFC 3339 timestamp format.
For example: edited_min='2005-08-09T09:57:00-08:00'
edited_max: str (optional) Upper bound on the last time a document was
edited by the user. (See also edited_min.)
owner: str (optional) Searches for documents with a specific owner. Use
the email address of the owner. For example: owner='user@gmail.com'
writer: str (optional) Searches for documents which can be written to
by specific users. Use a single email address or a comma separated list
of email addresses. For example: writer='user1@gmail.com,user@example.com'
reader: str (optional) Searches for documents which can be read by
specific users. (See also writer.)
show_collections: str (optional) Specifies whether the query should return
collections as well as documents and files. Possible values are 'true'
and 'false'. Default is 'false'.
show_root: (optional) 'true' to specify when an item is in the root
collection. Default is 'false'
show_deleted: str (optional) Specifies whether the query should return
documents which are in the trash as well as other documents.
Possible values are 'true' and 'false'. Default is false.
ocr: str (optional) Specifies whether to attempt OCR on a .jpg, .png, or
.gif upload. Possible values are 'true' and 'false'. Default is
false. See OCR in the Protocol Guide:
http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#OCR
target_language: str (optional) Specifies the language to translate a
document into. See Document Translation in the Protocol Guide for a
table of possible values:
http://code.google.com/apis/documents/docs/3.0/developers_guide_protocol.html#DocumentTranslation
source_language: str (optional) Specifies the source language of the
original document. Optional when using the translation service.
If not provided, Google will attempt to auto-detect the source
language. See Document Translation in the Protocol Guide for a table of
possible values (link in target_language).
convert: str (optional) Used when uploading files specify if document uploads
should convert to a native Google Docs format.
Possible values are 'true' and 'false'. The default is 'true'.
query: str (optional) Full-text query to use. See the 'q' parameter in
the documentation.
"""
gdata.client.Query.__init__(self, **kwargs)
self.convert = convert
self.title = title
self.title_exact = title_exact
self.opened_min = opened_min
self.opened_max = opened_max
self.edited_min = edited_min
self.edited_max = edited_max
self.owner = owner
self.writer = writer
self.reader = reader
self.show_collections = show_collections
self.show_root = show_root
self.show_deleted = show_deleted
self.ocr = ocr
self.target_language = target_language
self.source_language = source_language
self.query = query
def modify_request(self, http_request):
gdata.client._add_query_param('convert', self.convert, http_request)
gdata.client._add_query_param('title', self.title, http_request)
gdata.client._add_query_param('title-exact', self.title_exact,
http_request)
gdata.client._add_query_param('opened-min', self.opened_min, http_request)
gdata.client._add_query_param('opened-max', self.opened_max, http_request)
gdata.client._add_query_param('edited-min', self.edited_min, http_request)
gdata.client._add_query_param('edited-max', self.edited_max, http_request)
gdata.client._add_query_param('owner', self.owner, http_request)
gdata.client._add_query_param('writer', self.writer, http_request)
gdata.client._add_query_param('reader', self.reader, http_request)
gdata.client._add_query_param('query', self.query, http_request)
gdata.client._add_query_param('showfolders', self.show_collections,
http_request)
gdata.client._add_query_param('showroot', self.show_root, http_request)
gdata.client._add_query_param('showdeleted', self.show_deleted,
http_request)
gdata.client._add_query_param('ocr', self.ocr, http_request)
gdata.client._add_query_param('targetLanguage', self.target_language,
http_request)
gdata.client._add_query_param('sourceLanguage', self.source_language,
http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request
| Python |
#!/usr/bin/python
#
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to Atom objects used with Google Documents."""
__author__ = ('api.jfisher (Jeff Fisher), '
'api.eric@google.com (Eric Bidelman)')
import atom
import gdata
DOCUMENTS_NAMESPACE = 'http://schemas.google.com/docs/2007'
class Scope(atom.AtomBase):
"""The DocList ACL scope element"""
_tag = 'scope'
_namespace = gdata.GACL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
_attributes['type'] = 'type'
def __init__(self, value=None, type=None, extension_elements=None,
extension_attributes=None, text=None):
self.value = value
self.type = type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Role(atom.AtomBase):
"""The DocList ACL role element"""
_tag = 'role'
_namespace = gdata.GACL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class FeedLink(atom.AtomBase):
"""The DocList gd:feedLink element"""
_tag = 'feedLink'
_namespace = gdata.GDATA_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['rel'] = 'rel'
_attributes['href'] = 'href'
def __init__(self, href=None, rel=None, text=None, extension_elements=None,
extension_attributes=None):
self.href = href
self.rel = rel
atom.AtomBase.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
class ResourceId(atom.AtomBase):
"""The DocList gd:resourceId element"""
_tag = 'resourceId'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class LastModifiedBy(atom.Person):
"""The DocList gd:lastModifiedBy element"""
_tag = 'lastModifiedBy'
_namespace = gdata.GDATA_NAMESPACE
class LastViewed(atom.Person):
"""The DocList gd:lastViewed element"""
_tag = 'lastViewed'
_namespace = gdata.GDATA_NAMESPACE
class WritersCanInvite(atom.AtomBase):
"""The DocList docs:writersCanInvite element"""
_tag = 'writersCanInvite'
_namespace = DOCUMENTS_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
class DocumentListEntry(gdata.GDataEntry):
"""The Google Documents version of an Atom Entry"""
_tag = gdata.GDataEntry._tag
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feedLink', FeedLink)
_children['{%s}resourceId' % gdata.GDATA_NAMESPACE] = ('resourceId',
ResourceId)
_children['{%s}lastModifiedBy' % gdata.GDATA_NAMESPACE] = ('lastModifiedBy',
LastModifiedBy)
_children['{%s}lastViewed' % gdata.GDATA_NAMESPACE] = ('lastViewed',
LastViewed)
_children['{%s}writersCanInvite' % DOCUMENTS_NAMESPACE] = (
'writersCanInvite', WritersCanInvite)
def __init__(self, resourceId=None, feedLink=None, lastViewed=None,
lastModifiedBy=None, writersCanInvite=None, author=None,
category=None, content=None, atom_id=None, link=None,
published=None, title=None, updated=None, text=None,
extension_elements=None, extension_attributes=None):
self.feedLink = feedLink
self.lastViewed = lastViewed
self.lastModifiedBy = lastModifiedBy
self.resourceId = resourceId
self.writersCanInvite = writersCanInvite
gdata.GDataEntry.__init__(
self, author=author, category=category, content=content,
atom_id=atom_id, link=link, published=published, title=title,
updated=updated, extension_elements=extension_elements,
extension_attributes=extension_attributes, text=text)
def GetAclLink(self):
"""Extracts the DocListEntry's <gd:feedLink>.
Returns:
A FeedLink object.
"""
return self.feedLink
def GetDocumentType(self):
"""Extracts the type of document from the DocListEntry.
This method returns the type of document the DocListEntry
represents. Possible values are document, presentation,
spreadsheet, folder, or pdf.
Returns:
A string representing the type of document.
"""
if self.category:
for category in self.category:
if category.scheme == gdata.GDATA_NAMESPACE + '#kind':
return category.label
else:
return None
def DocumentListEntryFromString(xml_string):
"""Converts an XML string into a DocumentListEntry object.
Args:
xml_string: string The XML describing a Document List feed entry.
Returns:
A DocumentListEntry object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(DocumentListEntry, xml_string)
class DocumentListAclEntry(gdata.GDataEntry):
"""A DocList ACL Entry flavor of an Atom Entry"""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}scope' % gdata.GACL_NAMESPACE] = ('scope', Scope)
_children['{%s}role' % gdata.GACL_NAMESPACE] = ('role', Role)
def __init__(self, category=None, atom_id=None, link=None,
title=None, updated=None, scope=None, role=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=None, category=category,
content=None, atom_id=atom_id, link=link,
published=None, title=title,
updated=updated, text=None)
self.scope = scope
self.role = role
def DocumentListAclEntryFromString(xml_string):
"""Converts an XML string into a DocumentListAclEntry object.
Args:
xml_string: string The XML describing a Document List ACL feed entry.
Returns:
A DocumentListAclEntry object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(DocumentListAclEntry, xml_string)
class DocumentListFeed(gdata.GDataFeed):
"""A feed containing a list of Google Documents Items"""
_tag = gdata.GDataFeed._tag
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[DocumentListEntry])
def DocumentListFeedFromString(xml_string):
"""Converts an XML string into a DocumentListFeed object.
Args:
xml_string: string The XML describing a DocumentList feed.
Returns:
A DocumentListFeed object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(DocumentListFeed, xml_string)
class DocumentListAclFeed(gdata.GDataFeed):
"""A DocList ACL feed flavor of a Atom feed"""
_tag = gdata.GDataFeed._tag
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[DocumentListAclEntry])
def DocumentListAclFeedFromString(xml_string):
"""Converts an XML string into a DocumentListAclFeed object.
Args:
xml_string: string The XML describing a DocumentList feed.
Returns:
A DocumentListFeed object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(DocumentListAclFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright 2009 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""DocsService extends the GDataService to streamline Google Documents
operations.
DocsService: Provides methods to query feeds and manipulate items.
Extends GDataService.
DocumentQuery: Queries a Google Document list feed.
DocumentAclQuery: Queries a Google Document Acl feed.
"""
__author__ = ('api.jfisher (Jeff Fisher), '
'e.bidelman (Eric Bidelman)')
import re
import atom
import gdata.service
import gdata.docs
import urllib
# XML Namespaces used in Google Documents entities.
DATA_KIND_SCHEME = gdata.GDATA_NAMESPACE + '#kind'
DOCUMENT_LABEL = 'document'
SPREADSHEET_LABEL = 'spreadsheet'
PRESENTATION_LABEL = 'presentation'
FOLDER_LABEL = 'folder'
PDF_LABEL = 'pdf'
LABEL_SCHEME = gdata.GDATA_NAMESPACE + '/labels'
STARRED_LABEL_TERM = LABEL_SCHEME + '#starred'
TRASHED_LABEL_TERM = LABEL_SCHEME + '#trashed'
HIDDEN_LABEL_TERM = LABEL_SCHEME + '#hidden'
MINE_LABEL_TERM = LABEL_SCHEME + '#mine'
PRIVATE_LABEL_TERM = LABEL_SCHEME + '#private'
SHARED_WITH_DOMAIN_LABEL_TERM = LABEL_SCHEME + '#shared-with-domain'
VIEWED_LABEL_TERM = LABEL_SCHEME + '#viewed'
FOLDERS_SCHEME_PREFIX = gdata.docs.DOCUMENTS_NAMESPACE + '/folders/'
# File extensions of documents that are permitted to be uploaded or downloaded.
SUPPORTED_FILETYPES = {
'CSV': 'text/csv',
'TSV': 'text/tab-separated-values',
'TAB': 'text/tab-separated-values',
'DOC': 'application/msword',
'DOCX': ('application/vnd.openxmlformats-officedocument.'
'wordprocessingml.document'),
'ODS': 'application/x-vnd.oasis.opendocument.spreadsheet',
'ODT': 'application/vnd.oasis.opendocument.text',
'RTF': 'application/rtf',
'SXW': 'application/vnd.sun.xml.writer',
'TXT': 'text/plain',
'XLS': 'application/vnd.ms-excel',
'XLSX': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'PDF': 'application/pdf',
'PNG': 'image/png',
'PPT': 'application/vnd.ms-powerpoint',
'PPS': 'application/vnd.ms-powerpoint',
'HTM': 'text/html',
'HTML': 'text/html',
'ZIP': 'application/zip',
'SWF': 'application/x-shockwave-flash'
}
class DocsService(gdata.service.GDataService):
"""Client extension for the Google Documents service Document List feed."""
__FILE_EXT_PATTERN = re.compile('.*\.([a-zA-Z]{3,}$)')
__RESOURCE_ID_PATTERN = re.compile('^([a-z]*)(:|%3A)([\w-]*)$')
def __init__(self, email=None, password=None, source=None,
server='docs.google.com', additional_headers=None, **kwargs):
"""Creates a client for the Google Documents service.
Args:
email: string (optional) The user's email address, used for
authentication.
password: string (optional) The user's password.
source: string (optional) The name of the user's application.
server: string (optional) The name of the server to which a connection
will be opened. Default value: 'docs.google.com'.
**kwargs: The other parameters to pass to gdata.service.GDataService
constructor.
"""
gdata.service.GDataService.__init__(
self, email=email, password=password, service='writely', source=source,
server=server, additional_headers=additional_headers, **kwargs)
self.ssl = True
def _MakeKindCategory(self, label):
if label is None:
return None
return atom.Category(scheme=DATA_KIND_SCHEME,
term=gdata.docs.DOCUMENTS_NAMESPACE + '#' + label, label=label)
def _MakeContentLinkFromId(self, resource_id):
match = self.__RESOURCE_ID_PATTERN.match(resource_id)
label = match.group(1)
doc_id = match.group(3)
if label == DOCUMENT_LABEL:
return '/feeds/download/documents/Export?docId=%s' % doc_id
if label == PRESENTATION_LABEL:
return '/feeds/download/presentations/Export?docId=%s' % doc_id
if label == SPREADSHEET_LABEL:
return ('https://spreadsheets.google.com/feeds/download/spreadsheets/'
'Export?key=%s' % doc_id)
raise ValueError, 'Invalid resource id: %s' % resource_id
def _UploadFile(self, media_source, title, category, folder_or_uri=None):
"""Uploads a file to the Document List feed.
Args:
media_source: A gdata.MediaSource object containing the file to be
uploaded.
title: string The title of the document on the server after being
uploaded.
category: An atom.Category object specifying the appropriate document
type.
folder_or_uri: DocumentListEntry or string (optional) An object with a
link to a folder or a uri to a folder to upload to.
Note: A valid uri for a folder is of the form:
/feeds/folders/private/full/folder%3Afolder_id
Returns:
A DocumentListEntry containing information about the document created on
the Google Documents service.
"""
if folder_or_uri:
try:
uri = folder_or_uri.content.src
except AttributeError:
uri = folder_or_uri
else:
uri = '/feeds/documents/private/full'
entry = gdata.docs.DocumentListEntry()
entry.title = atom.Title(text=title)
if category is not None:
entry.category.append(category)
entry = self.Post(entry, uri, media_source=media_source,
extra_headers={'Slug': media_source.file_name},
converter=gdata.docs.DocumentListEntryFromString)
return entry
def _DownloadFile(self, uri, file_path):
"""Downloads a file.
Args:
uri: string The full Export URL to download the file from.
file_path: string The full path to save the file to.
Raises:
RequestError: on error response from server.
"""
server_response = self.request('GET', uri)
response_body = server_response.read()
timeout = 5
while server_response.status == 302 and timeout > 0:
server_response = self.request('GET',
server_response.getheader('Location'))
response_body = server_response.read()
timeout -= 1
if server_response.status != 200:
raise gdata.service.RequestError, {'status': server_response.status,
'reason': server_response.reason,
'body': response_body}
f = open(file_path, 'wb')
f.write(response_body)
f.flush()
f.close()
def MoveIntoFolder(self, source_entry, folder_entry):
"""Moves a document into a folder in the Document List Feed.
Args:
source_entry: DocumentListEntry An object representing the source
document/folder.
folder_entry: DocumentListEntry An object with a link to the destination
folder.
Returns:
A DocumentListEntry containing information about the document created on
the Google Documents service.
"""
entry = gdata.docs.DocumentListEntry()
entry.id = source_entry.id
entry = self.Post(entry, folder_entry.content.src,
converter=gdata.docs.DocumentListEntryFromString)
return entry
def Query(self, uri, converter=gdata.docs.DocumentListFeedFromString):
"""Queries the Document List feed and returns the resulting feed of
entries.
Args:
uri: string The full URI to be queried. This can contain query
parameters, a hostname, or simply the relative path to a Document
List feed. The DocumentQuery object is useful when constructing
query parameters.
converter: func (optional) A function which will be executed on the
retrieved item, generally to render it into a Python object.
By default the DocumentListFeedFromString function is used to
return a DocumentListFeed object. This is because most feed
queries will result in a feed and not a single entry.
"""
return self.Get(uri, converter=converter)
def QueryDocumentListFeed(self, uri):
"""Retrieves a DocumentListFeed by retrieving a URI based off the Document
List feed, including any query parameters. A DocumentQuery object can
be used to construct these parameters.
Args:
uri: string The URI of the feed being retrieved possibly with query
parameters.
Returns:
A DocumentListFeed object representing the feed returned by the server.
"""
return self.Get(uri, converter=gdata.docs.DocumentListFeedFromString)
def GetDocumentListEntry(self, uri):
"""Retrieves a particular DocumentListEntry by its unique URI.
Args:
uri: string The unique URI of an entry in a Document List feed.
Returns:
A DocumentListEntry object representing the retrieved entry.
"""
return self.Get(uri, converter=gdata.docs.DocumentListEntryFromString)
def GetDocumentListFeed(self, uri=None):
"""Retrieves a feed containing all of a user's documents.
Args:
uri: string A full URI to query the Document List feed.
"""
if not uri:
uri = gdata.docs.service.DocumentQuery().ToUri()
return self.QueryDocumentListFeed(uri)
def GetDocumentListAclEntry(self, uri):
"""Retrieves a particular DocumentListAclEntry by its unique URI.
Args:
uri: string The unique URI of an entry in a Document List feed.
Returns:
A DocumentListAclEntry object representing the retrieved entry.
"""
return self.Get(uri, converter=gdata.docs.DocumentListAclEntryFromString)
def GetDocumentListAclFeed(self, uri):
"""Retrieves a feed containing all of a user's documents.
Args:
uri: string The URI of a document's Acl feed to retrieve.
Returns:
A DocumentListAclFeed object representing the ACL feed
returned by the server.
"""
return self.Get(uri, converter=gdata.docs.DocumentListAclFeedFromString)
def Upload(self, media_source, title, folder_or_uri=None, label=None):
"""Uploads a document inside of a MediaSource object to the Document List
feed with the given title.
Args:
media_source: MediaSource The gdata.MediaSource object containing a
document file to be uploaded.
title: string The title of the document on the server after being
uploaded.
folder_or_uri: DocumentListEntry or string (optional) An object with a
link to a folder or a uri to a folder to upload to.
Note: A valid uri for a folder is of the form:
/feeds/folders/private/full/folder%3Afolder_id
label: optional label describing the type of the document to be created.
Returns:
A DocumentListEntry containing information about the document created
on the Google Documents service.
"""
return self._UploadFile(media_source, title, self._MakeKindCategory(label),
folder_or_uri)
def Download(self, entry_or_id_or_url, file_path, export_format=None,
gid=None, extra_params=None):
"""Downloads a document from the Document List.
Args:
entry_or_id_or_url: a DocumentListEntry, or the resource id of an entry,
or a url to download from (such as the content src).
file_path: string The full path to save the file to.
export_format: the format to convert to, if conversion is required.
gid: grid id, for downloading a single grid of a spreadsheet
extra_params: a map of any further parameters to control how the document
is downloaded
Raises:
RequestError if the service does not respond with success
"""
if isinstance(entry_or_id_or_url, gdata.docs.DocumentListEntry):
url = entry_or_id_or_url.content.src
else:
if self.__RESOURCE_ID_PATTERN.match(entry_or_id_or_url):
url = self._MakeContentLinkFromId(entry_or_id_or_url)
else:
url = entry_or_id_or_url
if export_format is not None:
if url.find('/Export?') == -1:
raise gdata.service.Error, ('This entry cannot be exported '
'as a different format')
url += '&exportFormat=%s' % export_format
if gid is not None:
if url.find('spreadsheets') == -1:
raise gdata.service.Error, 'grid id param is not valid for this entry'
url += '&gid=%s' % gid
if extra_params:
url += '&' + urllib.urlencode(extra_params)
self._DownloadFile(url, file_path)
def Export(self, entry_or_id_or_url, file_path, gid=None, extra_params=None):
"""Downloads a document from the Document List in a different format.
Args:
entry_or_id_or_url: a DocumentListEntry, or the resource id of an entry,
or a url to download from (such as the content src).
file_path: string The full path to save the file to. The export
format is inferred from the the file extension.
gid: grid id, for downloading a single grid of a spreadsheet
extra_params: a map of any further parameters to control how the document
is downloaded
Raises:
RequestError if the service does not respond with success
"""
ext = None
match = self.__FILE_EXT_PATTERN.match(file_path)
if match:
ext = match.group(1)
self.Download(entry_or_id_or_url, file_path, ext, gid, extra_params)
def CreateFolder(self, title, folder_or_uri=None):
"""Creates a folder in the Document List feed.
Args:
title: string The title of the folder on the server after being created.
folder_or_uri: DocumentListEntry or string (optional) An object with a
link to a folder or a uri to a folder to upload to.
Note: A valid uri for a folder is of the form:
/feeds/folders/private/full/folder%3Afolder_id
Returns:
A DocumentListEntry containing information about the folder created on
the Google Documents service.
"""
if folder_or_uri:
try:
uri = folder_or_uri.content.src
except AttributeError:
uri = folder_or_uri
else:
uri = '/feeds/documents/private/full'
folder_entry = gdata.docs.DocumentListEntry()
folder_entry.title = atom.Title(text=title)
folder_entry.category.append(self._MakeKindCategory(FOLDER_LABEL))
folder_entry = self.Post(folder_entry, uri,
converter=gdata.docs.DocumentListEntryFromString)
return folder_entry
def MoveOutOfFolder(self, source_entry):
"""Moves a document into a folder in the Document List Feed.
Args:
source_entry: DocumentListEntry An object representing the source
document/folder.
Returns:
True if the entry was moved out.
"""
return self.Delete(source_entry.GetEditLink().href)
# Deprecated methods
#@atom.deprecated('Please use Upload instead')
def UploadPresentation(self, media_source, title, folder_or_uri=None):
"""Uploads a presentation inside of a MediaSource object to the Document
List feed with the given title.
This method is deprecated, use Upload instead.
Args:
media_source: MediaSource The MediaSource object containing a
presentation file to be uploaded.
title: string The title of the presentation on the server after being
uploaded.
folder_or_uri: DocumentListEntry or string (optional) An object with a
link to a folder or a uri to a folder to upload to.
Note: A valid uri for a folder is of the form:
/feeds/folders/private/full/folder%3Afolder_id
Returns:
A DocumentListEntry containing information about the presentation created
on the Google Documents service.
"""
return self._UploadFile(
media_source, title, self._MakeKindCategory(PRESENTATION_LABEL),
folder_or_uri=folder_or_uri)
UploadPresentation = atom.deprecated('Please use Upload instead')(
UploadPresentation)
#@atom.deprecated('Please use Upload instead')
def UploadSpreadsheet(self, media_source, title, folder_or_uri=None):
"""Uploads a spreadsheet inside of a MediaSource object to the Document
List feed with the given title.
This method is deprecated, use Upload instead.
Args:
media_source: MediaSource The MediaSource object containing a spreadsheet
file to be uploaded.
title: string The title of the spreadsheet on the server after being
uploaded.
folder_or_uri: DocumentListEntry or string (optional) An object with a
link to a folder or a uri to a folder to upload to.
Note: A valid uri for a folder is of the form:
/feeds/folders/private/full/folder%3Afolder_id
Returns:
A DocumentListEntry containing information about the spreadsheet created
on the Google Documents service.
"""
return self._UploadFile(
media_source, title, self._MakeKindCategory(SPREADSHEET_LABEL),
folder_or_uri=folder_or_uri)
UploadSpreadsheet = atom.deprecated('Please use Upload instead')(
UploadSpreadsheet)
#@atom.deprecated('Please use Upload instead')
def UploadDocument(self, media_source, title, folder_or_uri=None):
"""Uploads a document inside of a MediaSource object to the Document List
feed with the given title.
This method is deprecated, use Upload instead.
Args:
media_source: MediaSource The gdata.MediaSource object containing a
document file to be uploaded.
title: string The title of the document on the server after being
uploaded.
folder_or_uri: DocumentListEntry or string (optional) An object with a
link to a folder or a uri to a folder to upload to.
Note: A valid uri for a folder is of the form:
/feeds/folders/private/full/folder%3Afolder_id
Returns:
A DocumentListEntry containing information about the document created
on the Google Documents service.
"""
return self._UploadFile(
media_source, title, self._MakeKindCategory(DOCUMENT_LABEL),
folder_or_uri=folder_or_uri)
UploadDocument = atom.deprecated('Please use Upload instead')(
UploadDocument)
"""Calling any of these functions is the same as calling Export"""
DownloadDocument = atom.deprecated('Please use Export instead')(Export)
DownloadPresentation = atom.deprecated('Please use Export instead')(Export)
DownloadSpreadsheet = atom.deprecated('Please use Export instead')(Export)
"""Calling any of these functions is the same as calling MoveIntoFolder"""
MoveDocumentIntoFolder = atom.deprecated(
'Please use MoveIntoFolder instead')(MoveIntoFolder)
MovePresentationIntoFolder = atom.deprecated(
'Please use MoveIntoFolder instead')(MoveIntoFolder)
MoveSpreadsheetIntoFolder = atom.deprecated(
'Please use MoveIntoFolder instead')(MoveIntoFolder)
MoveFolderIntoFolder = atom.deprecated(
'Please use MoveIntoFolder instead')(MoveIntoFolder)
class DocumentQuery(gdata.service.Query):
"""Object used to construct a URI to query the Google Document List feed"""
def __init__(self, feed='/feeds/documents', visibility='private',
projection='full', text_query=None, params=None,
categories=None):
"""Constructor for Document List Query
Args:
feed: string (optional) The path for the feed. (e.g. '/feeds/documents')
visibility: string (optional) The visibility chosen for the current feed.
projection: string (optional) The projection chosen for the current feed.
text_query: string (optional) The contents of the q query parameter. This
string is URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to
the query's items.
categories: list (optional) List of category strings which should be
included as query categories. See gdata.service.Query for
additional documentation.
Yields:
A DocumentQuery object used to construct a URI based on the Document
List feed.
"""
self.visibility = visibility
self.projection = projection
gdata.service.Query.__init__(self, feed, text_query, params, categories)
def ToUri(self):
"""Generates a URI from the query parameters set in the object.
Returns:
A string containing the URI used to retrieve entries from the Document
List feed.
"""
old_feed = self.feed
self.feed = '/'.join([old_feed, self.visibility, self.projection])
new_feed = gdata.service.Query.ToUri(self)
self.feed = old_feed
return new_feed
def AddNamedFolder(self, email, folder_name):
"""Adds a named folder category, qualified by a schema.
This function lets you query for documents that are contained inside a
named folder without fear of collision with other categories.
Args:
email: string The email of the user who owns the folder.
folder_name: string The name of the folder.
Returns:
The string of the category that was added to the object.
"""
category = '{%s%s}%s' % (FOLDERS_SCHEME_PREFIX, email, folder_name)
self.categories.append(category)
return category
def RemoveNamedFolder(self, email, folder_name):
"""Removes a named folder category, qualified by a schema.
Args:
email: string The email of the user who owns the folder.
folder_name: string The name of the folder.
Returns:
The string of the category that was removed to the object.
"""
category = '{%s%s}%s' % (FOLDERS_SCHEME_PREFIX, email, folder_name)
self.categories.remove(category)
return category
class DocumentAclQuery(gdata.service.Query):
"""Object used to construct a URI to query a Document's ACL feed"""
def __init__(self, resource_id, feed='/feeds/acl/private/full'):
"""Constructor for Document ACL Query
Args:
resource_id: string The resource id. (e.g. 'document%3Adocument_id',
'spreadsheet%3Aspreadsheet_id', etc.)
feed: string (optional) The path for the feed.
(e.g. '/feeds/acl/private/full')
Yields:
A DocumentAclQuery object used to construct a URI based on the Document
ACL feed.
"""
self.resource_id = resource_id
gdata.service.Query.__init__(self, feed)
def ToUri(self):
"""Generates a URI from the query parameters set in the object.
Returns:
A string containing the URI used to retrieve entries from the Document
ACL feed.
"""
return '%s/%s' % (gdata.service.Query.ToUri(self), self.resource_id)
| Python |
#!/usr/bin/python
#
# Copyright (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 |
#!/usr/bin/python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| Python |
#!/usr/bin/env python
#
# Copyright (C) 2010 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This module is used for version 2 of the Google Data APIs.
__author__ = 'j.s@google.com (Jeff Scudder)'
"""Provides classes and methods for working with JSON-C.
This module is experimental and subject to backwards incompatible changes.
Jsonc: Class which represents JSON-C data and provides pythonic member
access which is a bit cleaner than working with plain old dicts.
parse_json: Converts a JSON-C string into a Jsonc object.
jsonc_to_string: Converts a Jsonc object into a string of JSON-C.
"""
try:
import simplejson
except ImportError:
try:
# Try to import from django, should work on App Engine
from django.utils import simplejson
except ImportError:
# Should work for Python2.6 and higher.
import json as simplejson
def _convert_to_jsonc(x):
"""Builds a Jsonc objects which wraps the argument's members."""
if isinstance(x, dict):
jsonc_obj = Jsonc()
# Recursively transform all members of the dict.
# When converting a dict, we do not convert _name items into private
# Jsonc members.
for key, value in x.iteritems():
jsonc_obj._dict[key] = _convert_to_jsonc(value)
return jsonc_obj
elif isinstance(x, list):
# Recursively transform all members of the list.
members = []
for item in x:
members.append(_convert_to_jsonc(item))
return members
else:
# Return the base object.
return x
def parse_json(json_string):
"""Converts a JSON-C string into a Jsonc object.
Args:
json_string: str or unicode The JSON to be parsed.
Returns:
A new Jsonc object.
"""
return _convert_to_jsonc(simplejson.loads(json_string))
def parse_json_file(json_file):
return _convert_to_jsonc(simplejson.load(json_file))
def jsonc_to_string(jsonc_obj):
"""Converts a Jsonc object into a string of JSON-C."""
return simplejson.dumps(_convert_to_object(jsonc_obj))
def prettify_jsonc(jsonc_obj, indentation=2):
"""Converts a Jsonc object to a pretified (intented) JSON string."""
return simplejson.dumps(_convert_to_object(jsonc_obj), indent=indentation)
def _convert_to_object(jsonc_obj):
"""Creates a new dict or list which has the data in the Jsonc object.
Used to convert the Jsonc object to a plain old Python object to simplify
conversion to a JSON-C string.
Args:
jsonc_obj: A Jsonc object to be converted into simple Python objects
(dicts, lists, etc.)
Returns:
Either a dict, list, or other object with members converted from Jsonc
objects to the corresponding simple Python object.
"""
if isinstance(jsonc_obj, Jsonc):
plain = {}
for key, value in jsonc_obj._dict.iteritems():
plain[key] = _convert_to_object(value)
return plain
elif isinstance(jsonc_obj, list):
plain = []
for item in jsonc_obj:
plain.append(_convert_to_object(item))
return plain
else:
return jsonc_obj
def _to_jsonc_name(member_name):
"""Converts a Python style member name to a JSON-C style name.
JSON-C uses camelCaseWithLower while Python tends to use
lower_with_underscores so this method converts as follows:
spam becomes spam
spam_and_eggs becomes spamAndEggs
Args:
member_name: str or unicode The Python syle name which should be
converted to JSON-C style.
Returns:
The JSON-C style name as a str or unicode.
"""
characters = []
uppercase_next = False
for character in member_name:
if character == '_':
uppercase_next = True
elif uppercase_next:
characters.append(character.upper())
uppercase_next = False
else:
characters.append(character)
return ''.join(characters)
class Jsonc(object):
"""Represents JSON-C data in an easy to access object format.
To access the members of a JSON structure which looks like this:
{
"data": {
"totalItems": 800,
"items": [
{
"content": {
"1": "rtsp://v5.cache3.c.youtube.com/CiILENy.../0/0/0/video.3gp"
},
"viewCount": 220101,
"commentCount": 22,
"favoriteCount": 201
}
]
},
"apiVersion": "2.0"
}
You would do the following:
x = gdata.core.parse_json(the_above_string)
# Gives you 800
x.data.total_items
# Should be 22
x.data.items[0].comment_count
# The apiVersion is '2.0'
x.api_version
To create a Jsonc object which would produce the above JSON, you would do:
gdata.core.Jsonc(
api_version='2.0',
data=gdata.core.Jsonc(
total_items=800,
items=[
gdata.core.Jsonc(
view_count=220101,
comment_count=22,
favorite_count=201,
content={
'1': ('rtsp://v5.cache3.c.youtube.com'
'/CiILENy.../0/0/0/video.3gp')})]))
or
x = gdata.core.Jsonc()
x.api_version = '2.0'
x.data = gdata.core.Jsonc()
x.data.total_items = 800
x.data.items = []
# etc.
How it works:
The JSON-C data is stored in an internal dictionary (._dict) and the
getattr, setattr, and delattr methods rewrite the name which you provide
to mirror the expected format in JSON-C. (For more details on name
conversion see _to_jsonc_name.) You may also access members using
getitem, setitem, delitem as you would for a dictionary. For example
x.data.total_items is equivalent to x['data']['totalItems']
(Not all dict methods are supported so if you need something other than
the item operations, then you will want to use the ._dict member).
You may need to use getitem or the _dict member to access certain
properties in cases where the JSON-C syntax does not map neatly to Python
objects. For example the YouTube Video feed has some JSON like this:
"content": {"1": "rtsp://v5.cache3.c.youtube.com..."...}
You cannot do x.content.1 in Python, so you would use the getitem as
follows:
x.content['1']
or you could use the _dict member as follows:
x.content._dict['1']
If you need to create a new object with such a mapping you could use.
x.content = gdata.core.Jsonc(_dict={'1': 'rtsp://cache3.c.youtube.com...'})
"""
def __init__(self, _dict=None, **kwargs):
json = _dict or {}
for key, value in kwargs.iteritems():
if key.startswith('_'):
object.__setattr__(self, key, value)
else:
json[_to_jsonc_name(key)] = _convert_to_jsonc(value)
object.__setattr__(self, '_dict', json)
def __setattr__(self, name, value):
if name.startswith('_'):
object.__setattr__(self, name, value)
else:
object.__getattribute__(
self, '_dict')[_to_jsonc_name(name)] = _convert_to_jsonc(value)
def __getattr__(self, name):
if name.startswith('_'):
object.__getattribute__(self, name)
else:
try:
return object.__getattribute__(self, '_dict')[_to_jsonc_name(name)]
except KeyError:
raise AttributeError(
'No member for %s or [\'%s\']' % (name, _to_jsonc_name(name)))
def __delattr__(self, name):
if name.startswith('_'):
object.__delattr__(self, name)
else:
try:
del object.__getattribute__(self, '_dict')[_to_jsonc_name(name)]
except KeyError:
raise AttributeError(
'No member for %s (or [\'%s\'])' % (name, _to_jsonc_name(name)))
# For container methods pass-through to the underlying dict.
def __getitem__(self, key):
return self._dict[key]
def __setitem__(self, key, value):
self._dict[key] = value
def __delitem__(self, key):
del self._dict[key]
| Python |
#!/usr/bin/python
#
# Copyright (C) 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) 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 |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2007 Benoit Chesneau <benoitc@metavers.net>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""Contains extensions to Atom objects used by Google Codesearch"""
__author__ = 'Benoit Chesneau'
import atom
import gdata
CODESEARCH_NAMESPACE='http://schemas.google.com/codesearch/2006'
CODESEARCH_TEMPLATE='{http://shema.google.com/codesearch/2006}%s'
class Match(atom.AtomBase):
""" The Google Codesearch match element """
_tag = 'match'
_namespace = CODESEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['lineNumber'] = 'line_number'
_attributes['type'] = 'type'
def __init__(self, line_number=None, type=None, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.type = type
self.line_number = line_number
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class File(atom.AtomBase):
""" The Google Codesearch file element"""
_tag = 'file'
_namespace = CODESEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.name = name
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Package(atom.AtomBase):
""" The Google Codesearch package element"""
_tag = 'package'
_namespace = CODESEARCH_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
_attributes['uri'] = 'uri'
def __init__(self, name=None, uri=None, extension_elements=None,
extension_attributes=None, text=None):
self.text = text
self.name = name
self.uri = uri
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class CodesearchEntry(gdata.GDataEntry):
""" Google codesearch atom entry"""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}file' % CODESEARCH_NAMESPACE] = ('file', File)
_children['{%s}package' % CODESEARCH_NAMESPACE] = ('package', Package)
_children['{%s}match' % CODESEARCH_NAMESPACE] = ('match', [Match])
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
match=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=None)
self.match = match or []
def CodesearchEntryFromString(xml_string):
"""Converts an XML string into a CodesearchEntry object.
Args:
xml_string: string The XML describing a Codesearch feed entry.
Returns:
A CodesearchEntry object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(CodesearchEntry, xml_string)
class CodesearchFeed(gdata.GDataFeed):
"""feed containing list of Google codesearch Items"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CodesearchEntry])
def CodesearchFeedFromString(xml_string):
"""Converts an XML string into a CodesearchFeed object.
Args:
xml_string: string The XML describing a Codesearch feed.
Returns:
A CodeseartchFeed object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(CodesearchFeed, xml_string)
| Python |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2007 Benoit Chesneau <benoitc@metavers.net>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""CodesearchService extends GDataService to streamline Google Codesearch
operations"""
__author__ = 'Benoit Chesneau'
import atom
import gdata.service
import gdata.codesearch
class CodesearchService(gdata.service.GDataService):
"""Client extension for Google codesearch service"""
ssl = True
def __init__(self, email=None, password=None, source=None,
server='www.google.com', additional_headers=None, **kwargs):
"""Creates a client for the Google codesearch service.
Args:
email: string (optional) The user's email address, used for
authentication.
password: string (optional) The user's password.
source: string (optional) The name of the user's application.
server: string (optional) The name of the server to which a connection
will be opened. Default value: 'www.google.com'.
**kwargs: The other parameters to pass to gdata.service.GDataService
constructor.
"""
gdata.service.GDataService.__init__(
self, email=email, password=password, service='codesearch',
source=source, server=server, additional_headers=additional_headers,
**kwargs)
def Query(self, uri, converter=gdata.codesearch.CodesearchFeedFromString):
"""Queries the Codesearch feed and returns the resulting feed of
entries.
Args:
uri: string The full URI to be queried. This can contain query
parameters, a hostname, or simply the relative path to a Document
List feed. The DocumentQuery object is useful when constructing
query parameters.
converter: func (optional) A function which will be executed on the
retrieved item, generally to render it into a Python object.
By default the CodesearchFeedFromString function is used to
return a CodesearchFeed object. This is because most feed
queries will result in a feed and not a single entry.
Returns :
A CodesearchFeed objects representing the feed returned by the server
"""
return self.Get(uri, converter=converter)
def GetSnippetsFeed(self, text_query=None):
"""Retrieve Codesearch feed for a keyword
Args:
text_query : string (optional) The contents of the q query parameter. This
string is URL escaped upon conversion to a URI.
Returns:
A CodesearchFeed objects representing the feed returned by the server
"""
query=gdata.codesearch.service.CodesearchQuery(text_query=text_query)
feed = self.Query(query.ToUri())
return feed
class CodesearchQuery(gdata.service.Query):
"""Object used to construct the query to the Google Codesearch feed. here only as a shorcut"""
def __init__(self, feed='/codesearch/feeds/search', text_query=None,
params=None, categories=None):
"""Constructor for Codesearch Query.
Args:
feed: string (optional) The path for the feed. (e.g. '/codesearch/feeds/search')
text_query: string (optional) The contents of the q query parameter. This
string is URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to
the query's items.
categories: list (optional) List of category strings which should be
included as query categories. See gdata.service.Query for
additional documentation.
Yelds:
A CodesearchQuery object to construct a URI based on Codesearch feed
"""
gdata.service.Query.__init__(self, feed, text_query, params, categories)
| Python |
#!/usr/bin/env python
#
# Copyright (C) 2008, 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This module is used for version 2 of the Google Data APIs.
"""Provides a client to interact with Google Data API servers.
This module is used for version 2 of the Google Data APIs. The primary class
in this module is GDClient.
GDClient: handles auth and CRUD operations when communicating with servers.
GDataClient: deprecated client for version one services. Will be removed.
"""
__author__ = 'j.s@google.com (Jeff Scudder)'
import re
import atom.client
import atom.core
import atom.http_core
import gdata.gauth
import gdata.data
class Error(Exception):
pass
class RequestError(Error):
status = None
reason = None
body = None
headers = None
class RedirectError(RequestError):
pass
class CaptchaChallenge(RequestError):
captcha_url = None
captcha_token = None
class ClientLoginTokenMissing(Error):
pass
class MissingOAuthParameters(Error):
pass
class ClientLoginFailed(RequestError):
pass
class UnableToUpgradeToken(RequestError):
pass
class Unauthorized(Error):
pass
class BadAuthenticationServiceURL(RedirectError):
pass
class BadAuthentication(RequestError):
pass
class NotModified(RequestError):
pass
class NotImplemented(RequestError):
pass
def error_from_response(message, http_response, error_class,
response_body=None):
"""Creates a new exception and sets the HTTP information in the error.
Args:
message: str human readable message to be displayed if the exception is
not caught.
http_response: The response from the server, contains error information.
error_class: The exception to be instantiated and populated with
information from the http_response
response_body: str (optional) specify if the response has already been read
from the http_response object.
"""
if response_body is None:
body = http_response.read()
else:
body = response_body
error = error_class('%s: %i, %s' % (message, http_response.status, body))
error.status = http_response.status
error.reason = http_response.reason
error.body = body
error.headers = atom.http_core.get_headers(http_response)
return error
def get_xml_version(version):
"""Determines which XML schema to use based on the client API version.
Args:
version: string which is converted to an int. The version string is in
the form 'Major.Minor.x.y.z' and only the major version number
is considered. If None is provided assume version 1.
"""
if version is None:
return 1
return int(version.split('.')[0])
class GDClient(atom.client.AtomPubClient):
"""Communicates with Google Data servers to perform CRUD operations.
This class is currently experimental and may change in backwards
incompatible ways.
This class exists to simplify the following three areas involved in using
the Google Data APIs.
CRUD Operations:
The client provides a generic 'request' method for making HTTP requests.
There are a number of convenience methods which are built on top of
request, which include get_feed, get_entry, get_next, post, update, and
delete. These methods contact the Google Data servers.
Auth:
Reading user-specific private data requires authorization from the user as
do any changes to user data. An auth_token object can be passed into any
of the HTTP requests to set the Authorization header in the request.
You may also want to set the auth_token member to a an object which can
use modify_request to set the Authorization header in the HTTP request.
If you are authenticating using the email address and password, you can
use the client_login method to obtain an auth token and set the
auth_token member.
If you are using browser redirects, specifically AuthSub, you will want
to use gdata.gauth.AuthSubToken.from_url to obtain the token after the
redirect, and you will probably want to updgrade this since use token
to a multiple use (session) token using the upgrade_token method.
API Versions:
This client is multi-version capable and can be used with Google Data API
version 1 and version 2. The version should be specified by setting the
api_version member to a string, either '1' or '2'.
"""
# The gsessionid is used by Google Calendar to prevent redirects.
__gsessionid = None
api_version = None
# Name of the Google Data service when making a ClientLogin request.
auth_service = None
# URL prefixes which should be requested for AuthSub and OAuth.
auth_scopes = None
# Name of alternate auth service to use in certain cases
alt_auth_service = None
def request(self, method=None, uri=None, auth_token=None,
http_request=None, converter=None, desired_class=None,
redirects_remaining=4, **kwargs):
"""Make an HTTP request to the server.
See also documentation for atom.client.AtomPubClient.request.
If a 302 redirect is sent from the server to the client, this client
assumes that the redirect is in the form used by the Google Calendar API.
The same request URI and method will be used as in the original request,
but a gsessionid URL parameter will be added to the request URI with
the value provided in the server's 302 redirect response. If the 302
redirect is not in the format specified by the Google Calendar API, a
RedirectError will be raised containing the body of the server's
response.
The method calls the client's modify_request method to make any changes
required by the client before the request is made. For example, a
version 2 client could add a GData-Version: 2 header to the request in
its modify_request method.
Args:
method: str The HTTP verb for this request, usually 'GET', 'POST',
'PUT', or 'DELETE'
uri: atom.http_core.Uri, str, or unicode The URL being requested.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others.
http_request: (optional) atom.http_core.HttpRequest
converter: function which takes the body of the response as its only
argument and returns the desired object.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (converter=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned.
redirects_remaining: (optional) int, if this number is 0 and the
server sends a 302 redirect, the request method
will raise an exception. This parameter is used in
recursive request calls to avoid an infinite loop.
Any additional arguments are passed through to
atom.client.AtomPubClient.request.
Returns:
An HTTP response object (see atom.http_core.HttpResponse for a
description of the object's interface) if no converter was
specified and no desired_class was specified. If a converter function
was provided, the results of calling the converter are returned. If no
converter was specified but a desired_class was provided, the response
body will be converted to the class using
atom.core.parse.
"""
if isinstance(uri, (str, unicode)):
uri = atom.http_core.Uri.parse_uri(uri)
# Add the gsession ID to the URL to prevent further redirects.
# TODO: If different sessions are using the same client, there will be a
# multitude of redirects and session ID shuffling.
# If the gsession ID is in the URL, adopt it as the standard location.
if uri is not None and uri.query is not None and 'gsessionid' in uri.query:
self.__gsessionid = uri.query['gsessionid']
# The gsession ID could also be in the HTTP request.
elif (http_request is not None and http_request.uri is not None
and http_request.uri.query is not None
and 'gsessionid' in http_request.uri.query):
self.__gsessionid = http_request.uri.query['gsessionid']
# If the gsession ID is stored in the client, and was not present in the
# URI then add it to the URI.
elif self.__gsessionid is not None:
uri.query['gsessionid'] = self.__gsessionid
# The AtomPubClient should call this class' modify_request before
# performing the HTTP request.
#http_request = self.modify_request(http_request)
response = atom.client.AtomPubClient.request(self, method=method,
uri=uri, auth_token=auth_token, http_request=http_request, **kwargs)
# On success, convert the response body using the desired converter
# function if present.
if response is None:
return None
if response.status == 200 or response.status == 201:
if converter is not None:
return converter(response)
elif desired_class is not None:
if self.api_version is not None:
return atom.core.parse(response.read(), desired_class,
version=get_xml_version(self.api_version))
else:
# No API version was specified, so allow parse to
# use the default version.
return atom.core.parse(response.read(), desired_class)
else:
return response
# TODO: move the redirect logic into the Google Calendar client once it
# exists since the redirects are only used in the calendar API.
elif response.status == 302:
if redirects_remaining > 0:
location = (response.getheader('Location')
or response.getheader('location'))
if location is not None:
# Make a recursive call with the gsession ID in the URI to follow
# the redirect.
return self.request(method=method, uri=location,
auth_token=auth_token, http_request=http_request,
converter=converter, desired_class=desired_class,
redirects_remaining=redirects_remaining-1,
**kwargs)
else:
raise error_from_response('302 received without Location header',
response, RedirectError)
else:
raise error_from_response('Too many redirects from server',
response, RedirectError)
elif response.status == 401:
raise error_from_response('Unauthorized - Server responded with',
response, Unauthorized)
elif response.status == 304:
raise error_from_response('Entry Not Modified - Server responded with',
response, NotModified)
elif response.status == 501:
raise error_from_response(
'This API operation is not implemented. - Server responded with',
response, NotImplemented)
# If the server's response was not a 200, 201, 302, 304, 401, or 501, raise
# an exception.
else:
raise error_from_response('Server responded with', response,
RequestError)
Request = request
def request_client_login_token(
self, email, password, source, service=None,
account_type='HOSTED_OR_GOOGLE',
auth_url=atom.http_core.Uri.parse_uri(
'https://www.google.com/accounts/ClientLogin'),
captcha_token=None, captcha_response=None):
service = service or self.auth_service
# Set the target URL.
http_request = atom.http_core.HttpRequest(uri=auth_url, method='POST')
http_request.add_body_part(
gdata.gauth.generate_client_login_request_body(email=email,
password=password, service=service, source=source,
account_type=account_type, captcha_token=captcha_token,
captcha_response=captcha_response),
'application/x-www-form-urlencoded')
# Use the underlying http_client to make the request.
response = self.http_client.request(http_request)
response_body = response.read()
if response.status == 200:
token_string = gdata.gauth.get_client_login_token_string(response_body)
if token_string is not None:
return gdata.gauth.ClientLoginToken(token_string)
else:
raise ClientLoginTokenMissing(
'Recieved a 200 response to client login request,'
' but no token was present. %s' % (response_body,))
elif response.status == 403:
captcha_challenge = gdata.gauth.get_captcha_challenge(response_body)
if captcha_challenge:
challenge = CaptchaChallenge('CAPTCHA required')
challenge.captcha_url = captcha_challenge['url']
challenge.captcha_token = captcha_challenge['token']
raise challenge
elif response_body.splitlines()[0] == 'Error=BadAuthentication':
raise BadAuthentication('Incorrect username or password')
else:
raise error_from_response('Server responded with a 403 code',
response, RequestError, response_body)
elif response.status == 302:
# Google tries to redirect all bad URLs back to
# http://www.google.<locale>. If a redirect
# attempt is made, assume the user has supplied an incorrect
# authentication URL
raise error_from_response('Server responded with a redirect',
response, BadAuthenticationServiceURL,
response_body)
else:
raise error_from_response('Server responded to ClientLogin request',
response, ClientLoginFailed, response_body)
RequestClientLoginToken = request_client_login_token
def client_login(self, email, password, source, service=None,
account_type='HOSTED_OR_GOOGLE',
auth_url=atom.http_core.Uri.parse_uri(
'https://www.google.com/accounts/ClientLogin'),
captcha_token=None, captcha_response=None):
"""Performs an auth request using the user's email address and password.
In order to modify user specific data and read user private data, your
application must be authorized by the user. One way to demonstrage
authorization is by including a Client Login token in the Authorization
HTTP header of all requests. This method requests the Client Login token
by sending the user's email address, password, the name of the
application, and the service code for the service which will be accessed
by the application. If the username and password are correct, the server
will respond with the client login code and a new ClientLoginToken
object will be set in the client's auth_token member. With the auth_token
set, future requests from this client will include the Client Login
token.
For a list of service names, see
http://code.google.com/apis/gdata/faq.html#clientlogin
For more information on Client Login, see:
http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html
Args:
email: str The user's email address or username.
password: str The password for the user's account.
source: str The name of your application. This can be anything you
like but should should give some indication of which app is
making the request.
service: str The service code for the service you would like to access.
For example, 'cp' for contacts, 'cl' for calendar. For a full
list see
http://code.google.com/apis/gdata/faq.html#clientlogin
If you are using a subclass of the gdata.client.GDClient, the
service will usually be filled in for you so you do not need
to specify it. For example see BloggerClient,
SpreadsheetsClient, etc.
account_type: str (optional) The type of account which is being
authenticated. This can be either 'GOOGLE' for a Google
Account, 'HOSTED' for a Google Apps Account, or the
default 'HOSTED_OR_GOOGLE' which will select the Google
Apps Account if the same email address is used for both
a Google Account and a Google Apps Account.
auth_url: str (optional) The URL to which the login request should be
sent.
captcha_token: str (optional) If a previous login attempt was reponded
to with a CAPTCHA challenge, this is the token which
identifies the challenge (from the CAPTCHA's URL).
captcha_response: str (optional) If a previous login attempt was
reponded to with a CAPTCHA challenge, this is the
response text which was contained in the challenge.
Returns:
Generated token, which is also stored in this object.
Raises:
A RequestError or one of its suclasses: BadAuthentication,
BadAuthenticationServiceURL, ClientLoginFailed,
ClientLoginTokenMissing, or CaptchaChallenge
"""
service = service or self.auth_service
self.auth_token = self.request_client_login_token(email, password,
source, service=service, account_type=account_type, auth_url=auth_url,
captcha_token=captcha_token, captcha_response=captcha_response)
if self.alt_auth_service is not None:
self.alt_auth_token = self.request_client_login_token(
email, password, source, service=self.alt_auth_service,
account_type=account_type, auth_url=auth_url,
captcha_token=captcha_token, captcha_response=captcha_response)
return self.auth_token
ClientLogin = client_login
def upgrade_token(self, token=None, url=atom.http_core.Uri.parse_uri(
'https://www.google.com/accounts/AuthSubSessionToken')):
"""Asks the Google auth server for a multi-use AuthSub token.
For details on AuthSub, see:
http://code.google.com/apis/accounts/docs/AuthSub.html
Args:
token: gdata.gauth.AuthSubToken or gdata.gauth.SecureAuthSubToken
(optional) If no token is passed in, the client's auth_token member
is used to request the new token. The token object will be modified
to contain the new session token string.
url: str or atom.http_core.Uri (optional) The URL to which the token
upgrade request should be sent. Defaults to:
https://www.google.com/accounts/AuthSubSessionToken
Returns:
The upgraded gdata.gauth.AuthSubToken object.
"""
# Default to using the auth_token member if no token is provided.
if token is None:
token = self.auth_token
# We cannot upgrade a None token.
if token is None:
raise UnableToUpgradeToken('No token was provided.')
if not isinstance(token, gdata.gauth.AuthSubToken):
raise UnableToUpgradeToken(
'Cannot upgrade the token because it is not an AuthSubToken object.')
http_request = atom.http_core.HttpRequest(uri=url, method='GET')
token.modify_request(http_request)
# Use the lower level HttpClient to make the request.
response = self.http_client.request(http_request)
if response.status == 200:
token._upgrade_token(response.read())
return token
else:
raise UnableToUpgradeToken(
'Server responded to token upgrade request with %s: %s' % (
response.status, response.read()))
UpgradeToken = upgrade_token
def revoke_token(self, token=None, url=atom.http_core.Uri.parse_uri(
'https://www.google.com/accounts/AuthSubRevokeToken')):
"""Requests that the token be invalidated.
This method can be used for both AuthSub and OAuth tokens (to invalidate
a ClientLogin token, the user must change their password).
Returns:
True if the server responded with a 200.
Raises:
A RequestError if the server responds with a non-200 status.
"""
# Default to using the auth_token member if no token is provided.
if token is None:
token = self.auth_token
http_request = atom.http_core.HttpRequest(uri=url, method='GET')
token.modify_request(http_request)
response = self.http_client.request(http_request)
if response.status != 200:
raise error_from_response('Server sent non-200 to revoke token',
response, RequestError, response.read())
return True
RevokeToken = revoke_token
def get_oauth_token(self, scopes, next, consumer_key, consumer_secret=None,
rsa_private_key=None,
url=gdata.gauth.REQUEST_TOKEN_URL):
"""Obtains an OAuth request token to allow the user to authorize this app.
Once this client has a request token, the user can authorize the request
token by visiting the authorization URL in their browser. After being
redirected back to this app at the 'next' URL, this app can then exchange
the authorized request token for an access token.
For more information see the documentation on Google Accounts with OAuth:
http://code.google.com/apis/accounts/docs/OAuth.html#AuthProcess
Args:
scopes: list of strings or atom.http_core.Uri objects which specify the
URL prefixes which this app will be accessing. For example, to access
the Google Calendar API, you would want to use scopes:
['https://www.google.com/calendar/feeds/',
'http://www.google.com/calendar/feeds/']
next: str or atom.http_core.Uri object, The URL which the user's browser
should be sent to after they authorize access to their data. This
should be a URL in your application which will read the token
information from the URL and upgrade the request token to an access
token.
consumer_key: str This is the identifier for this application which you
should have received when you registered your application with Google
to use OAuth.
consumer_secret: str (optional) The shared secret between your app and
Google which provides evidence that this request is coming from you
application and not another app. If present, this libraries assumes
you want to use an HMAC signature to verify requests. Keep this data
a secret.
rsa_private_key: str (optional) The RSA private key which is used to
generate a digital signature which is checked by Google's server. If
present, this library assumes that you want to use an RSA signature
to verify requests. Keep this data a secret.
url: The URL to which a request for a token should be made. The default
is Google's OAuth request token provider.
"""
http_request = None
if rsa_private_key is not None:
http_request = gdata.gauth.generate_request_for_request_token(
consumer_key, gdata.gauth.RSA_SHA1, scopes,
rsa_key=rsa_private_key, auth_server_url=url, next=next)
elif consumer_secret is not None:
http_request = gdata.gauth.generate_request_for_request_token(
consumer_key, gdata.gauth.HMAC_SHA1, scopes,
consumer_secret=consumer_secret, auth_server_url=url, next=next)
else:
raise MissingOAuthParameters(
'To request an OAuth token, you must provide your consumer secret'
' or your private RSA key.')
response = self.http_client.request(http_request)
response_body = response.read()
if response.status != 200:
raise error_from_response('Unable to obtain OAuth request token',
response, RequestError, response_body)
if rsa_private_key is not None:
return gdata.gauth.rsa_token_from_body(response_body, consumer_key,
rsa_private_key,
gdata.gauth.REQUEST_TOKEN)
elif consumer_secret is not None:
return gdata.gauth.hmac_token_from_body(response_body, consumer_key,
consumer_secret,
gdata.gauth.REQUEST_TOKEN)
GetOAuthToken = get_oauth_token
def get_access_token(self, request_token,
url=gdata.gauth.ACCESS_TOKEN_URL):
"""Exchanges an authorized OAuth request token for an access token.
Contacts the Google OAuth server to upgrade a previously authorized
request token. Once the request token is upgraded to an access token,
the access token may be used to access the user's data.
For more details, see the Google Accounts OAuth documentation:
http://code.google.com/apis/accounts/docs/OAuth.html#AccessToken
Args:
request_token: An OAuth token which has been authorized by the user.
url: (optional) The URL to which the upgrade request should be sent.
Defaults to: https://www.google.com/accounts/OAuthAuthorizeToken
"""
http_request = gdata.gauth.generate_request_for_access_token(
request_token, auth_server_url=url)
response = self.http_client.request(http_request)
response_body = response.read()
if response.status != 200:
raise error_from_response(
'Unable to upgrade OAuth request token to access token',
response, RequestError, response_body)
return gdata.gauth.upgrade_to_access_token(request_token, response_body)
GetAccessToken = get_access_token
def modify_request(self, http_request):
"""Adds or changes request before making the HTTP request.
This client will add the API version if it is specified.
Subclasses may override this method to add their own request
modifications before the request is made.
"""
http_request = atom.client.AtomPubClient.modify_request(self,
http_request)
if self.api_version is not None:
http_request.headers['GData-Version'] = self.api_version
return http_request
ModifyRequest = modify_request
def get_feed(self, uri, auth_token=None, converter=None,
desired_class=gdata.data.GDFeed, **kwargs):
return self.request(method='GET', uri=uri, auth_token=auth_token,
converter=converter, desired_class=desired_class,
**kwargs)
GetFeed = get_feed
def get_entry(self, uri, auth_token=None, converter=None,
desired_class=gdata.data.GDEntry, etag=None, **kwargs):
http_request = atom.http_core.HttpRequest()
# Conditional retrieval
if etag is not None:
http_request.headers['If-None-Match'] = etag
return self.request(method='GET', uri=uri, auth_token=auth_token,
http_request=http_request, converter=converter,
desired_class=desired_class, **kwargs)
GetEntry = get_entry
def get_next(self, feed, auth_token=None, converter=None,
desired_class=None, **kwargs):
"""Fetches the next set of results from the feed.
When requesting a feed, the number of entries returned is capped at a
service specific default limit (often 25 entries). You can specify your
own entry-count cap using the max-results URL query parameter. If there
are more results than could fit under max-results, the feed will contain
a next link. This method performs a GET against this next results URL.
Returns:
A new feed object containing the next set of entries in this feed.
"""
if converter is None and desired_class is None:
desired_class = feed.__class__
return self.get_feed(feed.find_next_link(), auth_token=auth_token,
converter=converter, desired_class=desired_class,
**kwargs)
GetNext = get_next
# TODO: add a refresh method to re-fetch the entry/feed from the server
# if it has been updated.
def post(self, entry, uri, auth_token=None, converter=None,
desired_class=None, **kwargs):
if converter is None and desired_class is None:
desired_class = entry.__class__
http_request = atom.http_core.HttpRequest()
http_request.add_body_part(
entry.to_string(get_xml_version(self.api_version)),
'application/atom+xml')
return self.request(method='POST', uri=uri, auth_token=auth_token,
http_request=http_request, converter=converter,
desired_class=desired_class, **kwargs)
Post = post
def update(self, entry, auth_token=None, force=False, uri=None, **kwargs):
"""Edits the entry on the server by sending the XML for this entry.
Performs a PUT and converts the response to a new entry object with a
matching class to the entry passed in.
Args:
entry:
auth_token:
force: boolean stating whether an update should be forced. Defaults to
False. Normally, if a change has been made since the passed in
entry was obtained, the server will not overwrite the entry since
the changes were based on an obsolete version of the entry.
Setting force to True will cause the update to silently
overwrite whatever version is present.
uri: The uri to put to. If provided, this uri is PUT to rather than the
inferred uri from the entry's edit link.
Returns:
A new Entry object of a matching type to the entry which was passed in.
"""
http_request = atom.http_core.HttpRequest()
http_request.add_body_part(
entry.to_string(get_xml_version(self.api_version)),
'application/atom+xml')
# Include the ETag in the request if present.
if force:
http_request.headers['If-Match'] = '*'
elif hasattr(entry, 'etag') and entry.etag:
http_request.headers['If-Match'] = entry.etag
if uri is None:
uri = entry.find_edit_link()
return self.request(method='PUT', uri=uri, auth_token=auth_token,
http_request=http_request,
desired_class=entry.__class__, **kwargs)
Update = update
def delete(self, entry_or_uri, auth_token=None, force=False, **kwargs):
http_request = atom.http_core.HttpRequest()
# Include the ETag in the request if present.
if force:
http_request.headers['If-Match'] = '*'
elif hasattr(entry_or_uri, 'etag') and entry_or_uri.etag:
http_request.headers['If-Match'] = entry_or_uri.etag
# If the user passes in a URL, just delete directly, may not work as
# the service might require an ETag.
if isinstance(entry_or_uri, (str, unicode, atom.http_core.Uri)):
return self.request(method='DELETE', uri=entry_or_uri,
http_request=http_request, auth_token=auth_token,
**kwargs)
return self.request(method='DELETE', uri=entry_or_uri.find_edit_link(),
http_request=http_request, auth_token=auth_token,
**kwargs)
Delete = delete
def batch(self, feed, uri=None, force=False, auth_token=None, **kwargs):
"""Sends a batch request to the server to execute operation entries.
Args:
feed: A batch feed containing batch entries, each is an operation.
uri: (optional) The uri to which the batch request feed should be POSTed.
If none is provided, then the feed's edit link will be used.
force: (optional) boolean set to True if you want the batch update to
clobber all data. If False, the version in the information in the
feed object will cause the server to check to see that no changes
intervened between when you fetched the data and when you sent the
changes.
auth_token: (optional) An object which sets the Authorization HTTP header
in its modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others.
"""
http_request = atom.http_core.HttpRequest()
http_request.add_body_part(
feed.to_string(get_xml_version(self.api_version)),
'application/atom+xml')
if force:
http_request.headers['If-Match'] = '*'
elif hasattr(feed, 'etag') and feed.etag:
http_request.headers['If-Match'] = feed.etag
if uri is None:
uri = feed.find_edit_link()
return self.request(method='POST', uri=uri, auth_token=auth_token,
http_request=http_request,
desired_class=feed.__class__, **kwargs)
Batch = batch
# TODO: add a refresh method to request a conditional update to an entry
# or feed.
def _add_query_param(param_string, value, http_request):
if value:
http_request.uri.query[param_string] = value
class Query(object):
def __init__(self, text_query=None, categories=None, author=None, alt=None,
updated_min=None, updated_max=None, pretty_print=False,
published_min=None, published_max=None, start_index=None,
max_results=None, strict=False, **custom_parameters):
"""Constructs a Google Data Query to filter feed contents serverside.
Args:
text_query: Full text search str (optional)
categories: list of strings (optional). Each string is a required
category. To include an 'or' query, put a | in the string between
terms. For example, to find everything in the Fitz category and
the Laurie or Jane category (Fitz and (Laurie or Jane)) you would
set categories to ['Fitz', 'Laurie|Jane'].
author: str (optional) The service returns entries where the author
name and/or email address match your query string.
alt: str (optional) for the Alternative representation type you'd like
the feed in. If you don't specify an alt parameter, the service
returns an Atom feed. This is equivalent to alt='atom'.
alt='rss' returns an RSS 2.0 result feed.
alt='json' returns a JSON representation of the feed.
alt='json-in-script' Requests a response that wraps JSON in a script
tag.
alt='atom-in-script' Requests an Atom response that wraps an XML
string in a script tag.
alt='rss-in-script' Requests an RSS response that wraps an XML
string in a script tag.
updated_min: str (optional), RFC 3339 timestamp format, lower bounds.
For example: 2005-08-09T10:57:00-08:00
updated_max: str (optional) updated time must be earlier than timestamp.
pretty_print: boolean (optional) If True the server's XML response will
be indented to make it more human readable. Defaults to False.
published_min: str (optional), Similar to updated_min but for published
time.
published_max: str (optional), Similar to updated_max but for published
time.
start_index: int or str (optional) 1-based index of the first result to
be retrieved. Note that this isn't a general cursoring mechanism.
If you first send a query with ?start-index=1&max-results=10 and
then send another query with ?start-index=11&max-results=10, the
service cannot guarantee that the results are equivalent to
?start-index=1&max-results=20, because insertions and deletions
could have taken place in between the two queries.
max_results: int or str (optional) Maximum number of results to be
retrieved. Each service has a default max (usually 25) which can
vary from service to service. There is also a service-specific
limit to the max_results you can fetch in a request.
strict: boolean (optional) If True, the server will return an error if
the server does not recognize any of the parameters in the request
URL. Defaults to False.
custom_parameters: other query parameters that are not explicitly defined.
"""
self.text_query = text_query
self.categories = categories or []
self.author = author
self.alt = alt
self.updated_min = updated_min
self.updated_max = updated_max
self.pretty_print = pretty_print
self.published_min = published_min
self.published_max = published_max
self.start_index = start_index
self.max_results = max_results
self.strict = strict
self.custom_parameters = custom_parameters
def add_custom_parameter(self, key, value):
self.custom_parameters[key] = value
AddCustomParameter = add_custom_parameter
def modify_request(self, http_request):
_add_query_param('q', self.text_query, http_request)
if self.categories:
http_request.uri.query['category'] = ','.join(self.categories)
_add_query_param('author', self.author, http_request)
_add_query_param('alt', self.alt, http_request)
_add_query_param('updated-min', self.updated_min, http_request)
_add_query_param('updated-max', self.updated_max, http_request)
if self.pretty_print:
http_request.uri.query['prettyprint'] = 'true'
_add_query_param('published-min', self.published_min, http_request)
_add_query_param('published-max', self.published_max, http_request)
if self.start_index is not None:
http_request.uri.query['start-index'] = str(self.start_index)
if self.max_results is not None:
http_request.uri.query['max-results'] = str(self.max_results)
if self.strict:
http_request.uri.query['strict'] = 'true'
http_request.uri.query.update(self.custom_parameters)
ModifyRequest = modify_request
class GDQuery(atom.http_core.Uri):
def _get_text_query(self):
return self.query['q']
def _set_text_query(self, value):
self.query['q'] = value
text_query = property(_get_text_query, _set_text_query,
doc='The q parameter for searching for an exact text match on content')
class ResumableUploader(object):
"""Resumable upload helper for the Google Data protocol."""
DEFAULT_CHUNK_SIZE = 5242880 # 5MB
# Initial chunks which are smaller than 256KB might be dropped. The last
# chunk for a file can be smaller tan this.
MIN_CHUNK_SIZE = 262144 # 256KB
def __init__(self, client, file_handle, content_type, total_file_size,
chunk_size=None, desired_class=None):
"""Starts a resumable upload to a service that supports the protocol.
Args:
client: gdata.client.GDClient A Google Data API service.
file_handle: object A file-like object containing the file to upload.
content_type: str The mimetype of the file to upload.
total_file_size: int The file's total size in bytes.
chunk_size: int The size of each upload chunk. If None, the
DEFAULT_CHUNK_SIZE will be used.
desired_class: object (optional) The type of gdata.data.GDEntry to parse
the completed entry as. This should be specific to the API.
"""
self.client = client
self.file_handle = file_handle
self.content_type = content_type
self.total_file_size = total_file_size
self.chunk_size = chunk_size or self.DEFAULT_CHUNK_SIZE
if self.chunk_size < self.MIN_CHUNK_SIZE:
self.chunk_size = self.MIN_CHUNK_SIZE
self.desired_class = desired_class or gdata.data.GDEntry
self.upload_uri = None
# Send the entire file if the chunk size is less than fize's total size.
if self.total_file_size <= self.chunk_size:
self.chunk_size = total_file_size
def _init_session(self, resumable_media_link, entry=None, headers=None,
auth_token=None, method='POST'):
"""Starts a new resumable upload to a service that supports the protocol.
The method makes a request to initiate a new upload session. The unique
upload uri returned by the server (and set in this method) should be used
to send upload chunks to the server.
Args:
resumable_media_link: str The full URL for the #resumable-create-media or
#resumable-edit-media link for starting a resumable upload request or
updating media using a resumable PUT.
entry: A (optional) gdata.data.GDEntry containging metadata to create the
upload from.
headers: dict (optional) Additional headers to send in the initial request
to create the resumable upload request. These headers will override
any default headers sent in the request. For example:
headers={'Slug': 'MyTitle'}.
auth_token: (optional) An object which sets the Authorization HTTP header
in its modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others.
method: (optional) Type of HTTP request to start the session with.
Defaults to 'POST', but may also be 'PUT'.
Returns:
Result of HTTP request to intialize the session. See atom.client.request.
Raises:
RequestError if the unique upload uri is not set or the
server returns something other than an HTTP 308 when the upload is
incomplete.
"""
http_request = atom.http_core.HttpRequest()
# Send empty body if Atom XML wasn't specified.
if entry is None:
http_request.add_body_part('', self.content_type, size=0)
else:
http_request.add_body_part(str(entry), 'application/atom+xml',
size=len(str(entry)))
http_request.headers['X-Upload-Content-Type'] = self.content_type
http_request.headers['X-Upload-Content-Length'] = str(self.total_file_size)
if headers is not None:
http_request.headers.update(headers)
response = self.client.request(method=method,
uri=resumable_media_link,
auth_token=auth_token,
http_request=http_request)
self.upload_uri = (response.getheader('location') or
response.getheader('Location'))
return response
_InitSession = _init_session
def upload_chunk(self, start_byte, content_bytes):
"""Uploads a byte range (chunk) to the resumable upload server.
Args:
start_byte: int The byte offset of the total file where the byte range
passed in lives.
content_bytes: str The file contents of this chunk.
Returns:
The final Atom entry created on the server. The entry object's type will
be the class specified in self.desired_class.
Raises:
RequestError if the unique upload uri is not set or the
server returns something other than an HTTP 308 when the upload is
incomplete.
"""
if self.upload_uri is None:
raise RequestError('Resumable upload request not initialized.')
# Adjustment if last byte range is less than defined chunk size.
chunk_size = self.chunk_size
if len(content_bytes) <= chunk_size:
chunk_size = len(content_bytes)
http_request = atom.http_core.HttpRequest()
http_request.add_body_part(content_bytes, self.content_type,
size=len(content_bytes))
http_request.headers['Content-Range'] = ('bytes %s-%s/%s'
% (start_byte,
start_byte + chunk_size - 1,
self.total_file_size))
try:
response = self.client.request(method='PUT', uri=self.upload_uri,
http_request=http_request,
desired_class=self.desired_class)
return response
except RequestError, error:
if error.status == 308:
return None
else:
raise error
UploadChunk = upload_chunk
def upload_file(self, resumable_media_link, entry=None, headers=None,
auth_token=None, **kwargs):
"""Uploads an entire file in chunks using the resumable upload protocol.
If you are interested in pausing an upload or controlling the chunking
yourself, use the upload_chunk() method instead.
Args:
resumable_media_link: str The full URL for the #resumable-create-media for
starting a resumable upload request.
entry: A (optional) gdata.data.GDEntry containging metadata to create the
upload from.
headers: dict Additional headers to send in the initial request to create
the resumable upload request. These headers will override any default
headers sent in the request. For example: headers={'Slug': 'MyTitle'}.
auth_token: (optional) An object which sets the Authorization HTTP header
in its modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others.
kwargs: (optional) Other args to pass to self._init_session.
Returns:
The final Atom entry created on the server. The entry object's type will
be the class specified in self.desired_class.
Raises:
RequestError if anything other than a HTTP 308 is returned
when the request raises an exception.
"""
self._init_session(resumable_media_link, headers=headers,
auth_token=auth_token, entry=entry, **kwargs)
start_byte = 0
entry = None
while not entry:
entry = self.upload_chunk(
start_byte, self.file_handle.read(self.chunk_size))
start_byte += self.chunk_size
return entry
UploadFile = upload_file
def update_file(self, entry_or_resumable_edit_link, headers=None, force=False,
auth_token=None, update_metadata=False, uri_params=None):
"""Updates the contents of an existing file using the resumable protocol.
If you are interested in pausing an upload or controlling the chunking
yourself, use the upload_chunk() method instead.
Args:
entry_or_resumable_edit_link: object or string A gdata.data.GDEntry for
the entry/file to update or the full uri of the link with rel
#resumable-edit-media.
headers: dict Additional headers to send in the initial request to create
the resumable upload request. These headers will override any default
headers sent in the request. For example: headers={'Slug': 'MyTitle'}.
force boolean (optional) True to force an update and set the If-Match
header to '*'. If False and entry_or_resumable_edit_link is a
gdata.data.GDEntry object, its etag value is used. Otherwise this
parameter should be set to True to force the update.
auth_token: (optional) An object which sets the Authorization HTTP header
in its modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others.
update_metadata: (optional) True to also update the entry's metadata
with that in the given GDEntry object in entry_or_resumable_edit_link.
uri_params: (optional) Dict of additional parameters to attach to the URI.
Some non-dict types are valid here, too, like list of tuple pairs.
Returns:
The final Atom entry created on the server. The entry object's type will
be the class specified in self.desired_class.
Raises:
RequestError if anything other than a HTTP 308 is returned when the
request raises an exception.
"""
custom_headers = {}
if headers is not None:
custom_headers.update(headers)
uri = None
entry = None
if isinstance(entry_or_resumable_edit_link, gdata.data.GDEntry):
uri = entry_or_resumable_edit_link.find_url(
'http://schemas.google.com/g/2005#resumable-edit-media')
custom_headers['If-Match'] = entry_or_resumable_edit_link.etag
if update_metadata:
entry = entry_or_resumable_edit_link
else:
uri = entry_or_resumable_edit_link
uri = atom.http_core.parse_uri(uri)
if uri_params is not None:
uri.query.update(uri_params)
if force:
custom_headers['If-Match'] = '*'
return self.upload_file(str(uri), entry=entry, headers=custom_headers,
auth_token=auth_token, method='PUT')
UpdateFile = update_file
def query_upload_status(self, uri=None):
"""Queries the current status of a resumable upload request.
Args:
uri: str (optional) A resumable upload uri to query and override the one
that is set in this object.
Returns:
An integer representing the file position (byte) to resume the upload from
or True if the upload is complete.
Raises:
RequestError if anything other than a HTTP 308 is returned
when the request raises an exception.
"""
# Override object's unique upload uri.
if uri is None:
uri = self.upload_uri
http_request = atom.http_core.HttpRequest()
http_request.headers['Content-Length'] = '0'
http_request.headers['Content-Range'] = 'bytes */%s' % self.total_file_size
try:
response = self.client.request(
method='POST', uri=uri, http_request=http_request)
if response.status == 201:
return True
else:
raise error_from_response(
'%s returned by server' % response.status, response, RequestError)
except RequestError, error:
if error.status == 308:
for pair in error.headers:
if pair[0].capitalize() == 'Range':
return int(pair[1].split('-')[1]) + 1
else:
raise error
QueryUploadStatus = query_upload_status
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 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/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 = ['https://%s' % YOUTUBE_SERVER]
ssl = True
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) 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.
"""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 = 'https://uploads.gdata.youtube.com/feeds/api/users'
YOUTUBE_UPLOAD_TOKEN_URI = 'https://gdata.youtube.com/action/GetUploadToken'
YOUTUBE_VIDEO_URI = 'https://gdata.youtube.com/feeds/api/videos'
YOUTUBE_USER_FEED_URI = 'https://gdata.youtube.com/feeds/api/users'
YOUTUBE_PLAYLIST_FEED_URI = 'https://gdata.youtube.com/feeds/api/playlists'
YOUTUBE_STANDARD_FEEDS = 'https://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.
"""
ssl = True
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/python
#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Data model classes for parsing and generating XML for both the
Google Analytics Data Export and Management APIs. Although both APIs
operate on different parts of Google Analytics, they share common XML
elements and are released in the same module.
The Management API supports 5 feeds all using the same ManagementFeed
data class.
"""
__author__ = 'api.nickm@google.com (Nick Mihailovski)'
import gdata.data
import atom.core
import atom.data
# XML Namespace used in Google Analytics API entities.
DXP_NS = '{http://schemas.google.com/analytics/2009}%s'
GA_NS = '{http://schemas.google.com/ga/2009}%s'
GD_NS = '{http://schemas.google.com/g/2005}%s'
class GetProperty(object):
"""Utility class to simplify retrieving Property objects."""
def get_property(self, name):
"""Helper method to return a propery object by its name attribute.
Args:
name: string The name of the <dxp:property> element to retrieve.
Returns:
A property object corresponding to the matching <dxp:property> element.
if no property is found, None is returned.
"""
for prop in self.property:
if prop.name == name:
return prop
return None
GetProperty = get_property
class GetMetric(object):
"""Utility class to simplify retrieving Metric objects."""
def get_metric(self, name):
"""Helper method to return a propery value by its name attribute
Args:
name: string The name of the <dxp:metric> element to retrieve.
Returns:
A property object corresponding to the matching <dxp:metric> element.
if no property is found, None is returned.
"""
for met in self.metric:
if met.name == name:
return met
return None
GetMetric = get_metric
class GetDimension(object):
"""Utility class to simplify retrieving Dimension objects."""
def get_dimension(self, name):
"""Helper method to return a dimention object by its name attribute
Args:
name: string The name of the <dxp:dimension> element to retrieve.
Returns:
A dimension object corresponding to the matching <dxp:dimension> element.
if no dimension is found, None is returned.
"""
for dim in self.dimension:
if dim.name == name:
return dim
return None
GetDimension = get_dimension
class GaLinkFinder(object):
"""Utility class to return specific links in Google Analytics feeds."""
def get_parent_links(self):
"""Returns a list of all the parent links in an entry."""
links = []
for link in self.link:
if link.rel == link.parent():
links.append(link)
return links
GetParentLinks = get_parent_links
def get_child_links(self):
"""Returns a list of all the child links in an entry."""
links = []
for link in self.link:
if link.rel == link.child():
links.append(link)
return links
GetChildLinks = get_child_links
def get_child_link(self, target_kind):
"""Utility method to return one child link.
Returns:
A child link with the given target_kind. None if the target_kind was
not found.
"""
for link in self.link:
if link.rel == link.child() and link.target_kind == target_kind:
return link
return None
GetChildLink = get_child_link
class StartDate(atom.core.XmlElement):
"""Analytics Feed <dxp:startDate>"""
_qname = DXP_NS % 'startDate'
class EndDate(atom.core.XmlElement):
"""Analytics Feed <dxp:endDate>"""
_qname = DXP_NS % 'endDate'
class Metric(atom.core.XmlElement):
"""Analytics Feed <dxp:metric>"""
_qname = DXP_NS % 'metric'
name = 'name'
type = 'type'
value = 'value'
confidence_interval = 'confidenceInterval'
class Aggregates(atom.core.XmlElement, GetMetric):
"""Analytics Data Feed <dxp:aggregates>"""
_qname = DXP_NS % 'aggregates'
metric = [Metric]
class ContainsSampledData(atom.core.XmlElement):
"""Analytics Data Feed <dxp:containsSampledData>"""
_qname = DXP_NS % 'containsSampledData'
class TableId(atom.core.XmlElement):
"""Analytics Feed <dxp:tableId>"""
_qname = DXP_NS % 'tableId'
class TableName(atom.core.XmlElement):
"""Analytics Feed <dxp:tableName>"""
_qname = DXP_NS % 'tableName'
class Property(atom.core.XmlElement):
"""Analytics Feed <dxp:property>"""
_qname = DXP_NS % 'property'
name = 'name'
value = 'value'
class Definition(atom.core.XmlElement):
"""Analytics Feed <dxp:definition>"""
_qname = DXP_NS % 'definition'
class Segment(atom.core.XmlElement):
"""Analytics Feed <dxp:segment>"""
_qname = DXP_NS % 'segment'
id = 'id'
name = 'name'
definition = Definition
class Engagement(atom.core.XmlElement):
"""Analytics Feed <dxp:engagement>"""
_qname = GA_NS % 'engagement'
type = 'type'
comparison = 'comparison'
threshold_value = 'thresholdValue'
class Step(atom.core.XmlElement):
"""Analytics Feed <dxp:step>"""
_qname = GA_NS % 'step'
number = 'number'
name = 'name'
path = 'path'
class Destination(atom.core.XmlElement):
"""Analytics Feed <dxp:destination>"""
_qname = GA_NS % 'destination'
step = [Step]
expression = 'expression'
case_sensitive = 'caseSensitive'
match_type = 'matchType'
step1_required = 'step1Required'
class Goal(atom.core.XmlElement):
"""Analytics Feed <dxp:goal>"""
_qname = GA_NS % 'goal'
destination = Destination
engagement = Engagement
number = 'number'
name = 'name'
value = 'value'
active = 'active'
class CustomVariable(atom.core.XmlElement):
"""Analytics Data Feed <dxp:customVariable>"""
_qname = GA_NS % 'customVariable'
index = 'index'
name = 'name'
scope = 'scope'
class DataSource(atom.core.XmlElement, GetProperty):
"""Analytics Data Feed <dxp:dataSource>"""
_qname = DXP_NS % 'dataSource'
table_id = TableId
table_name = TableName
property = [Property]
class Dimension(atom.core.XmlElement):
"""Analytics Feed <dxp:dimension>"""
_qname = DXP_NS % 'dimension'
name = 'name'
value = 'value'
class AnalyticsLink(atom.data.Link):
"""Subclass of link <link>"""
target_kind = GD_NS % 'targetKind'
@classmethod
def parent(cls):
"""Parent target_kind"""
return '%s#parent' % GA_NS[1:-3]
@classmethod
def child(cls):
"""Child target_kind"""
return '%s#child' % GA_NS[1:-3]
# Account Feed.
class AccountEntry(gdata.data.GDEntry, GetProperty):
"""Analytics Account Feed <entry>"""
_qname = atom.data.ATOM_TEMPLATE % 'entry'
table_id = TableId
property = [Property]
goal = [Goal]
custom_variable = [CustomVariable]
class AccountFeed(gdata.data.GDFeed):
"""Analytics Account Feed <feed>"""
_qname = atom.data.ATOM_TEMPLATE % 'feed'
segment = [Segment]
entry = [AccountEntry]
# Data Feed.
class DataEntry(gdata.data.GDEntry, GetMetric, GetDimension):
"""Analytics Data Feed <entry>"""
_qname = atom.data.ATOM_TEMPLATE % 'entry'
dimension = [Dimension]
metric = [Metric]
def get_object(self, name):
"""Returns either a Dimension or Metric object with the same name as the
name parameter.
Args:
name: string The name of the object to retrieve.
Returns:
Either a Dimension or Object that has the same as the name parameter.
"""
output = self.GetDimension(name)
if not output:
output = self.GetMetric(name)
return output
GetObject = get_object
class DataFeed(gdata.data.GDFeed):
"""Analytics Data Feed <feed>.
Although there is only one datasource, it is stored in an array to replicate
the design of the Java client library and ensure backwards compatibility if
new data sources are added in the future.
"""
_qname = atom.data.ATOM_TEMPLATE % 'feed'
start_date = StartDate
end_date = EndDate
aggregates = Aggregates
contains_sampled_data = ContainsSampledData
data_source = [DataSource]
entry = [DataEntry]
segment = Segment
def has_sampled_data(self):
"""Returns whether this feed has sampled data."""
if (self.contains_sampled_data.text == 'true'):
return True
return False
HasSampledData = has_sampled_data
# Management Feed.
class ManagementEntry(gdata.data.GDEntry, GetProperty, GaLinkFinder):
"""Analytics Managememt Entry <entry>."""
_qname = atom.data.ATOM_TEMPLATE % 'entry'
kind = GD_NS % 'kind'
property = [Property]
goal = Goal
segment = Segment
link = [AnalyticsLink]
class ManagementFeed(gdata.data.GDFeed):
"""Analytics Management Feed <feed>.
This class holds the data for all 5 Management API feeds: Account,
Web Property, Profile, Goal, and Advanced Segment Feeds.
"""
_qname = atom.data.ATOM_TEMPLATE % 'feed'
entry = [ManagementEntry]
kind = GD_NS % 'kind'
| Python |
#!/usr/bin/python
#
# Copyright 2010 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Streamlines requests to the Google Analytics APIs."""
__author__ = 'api.nickm@google.com (Nick Mihailovski)'
import atom.data
import gdata.client
import gdata.analytics.data
import gdata.gauth
class AnalyticsClient(gdata.client.GDClient):
"""Client extension for the Google Analytics API service."""
api_version = '2'
auth_service = 'analytics'
auth_scopes = gdata.gauth.AUTH_SCOPES['analytics']
account_type = 'GOOGLE'
ssl = True
def __init__(self, auth_token=None, **kwargs):
"""Initializes a new client for the Google Analytics Data Export API.
Args:
auth_token: gdata.gauth.ClientLoginToken, AuthSubToken, or
OAuthToken (optional) Authorizes this client to edit the user's data.
kwargs: The other parameters to pass to gdata.client.GDClient
constructor.
"""
gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs)
def get_account_feed(self, feed_uri, auth_token=None, **kwargs):
"""Makes a request to the Analytics API Account Feed.
Args:
feed_uri: str or gdata.analytics.AccountFeedQuery The Analytics Account
Feed uri to define what data to retrieve from the API. Can also be
used with a gdata.analytics.AccountFeedQuery object.
"""
return self.get_feed(feed_uri,
desired_class=gdata.analytics.data.AccountFeed,
auth_token=auth_token,
**kwargs)
GetAccountFeed = get_account_feed
def get_data_feed(self, feed_uri, auth_token=None, **kwargs):
"""Makes a request to the Analytics API Data Feed.
Args:
feed_uri: str or gdata.analytics.AccountFeedQuery The Analytics Data
Feed uri to define what data to retrieve from the API. Can also be
used with a gdata.analytics.AccountFeedQuery object.
"""
return self.get_feed(feed_uri,
desired_class=gdata.analytics.data.DataFeed,
auth_token=auth_token,
**kwargs)
GetDataFeed = get_data_feed
def get_management_feed(self, feed_uri, auth_token=None, **kwargs):
"""Makes a request to the Google Analytics Management API.
The Management API provides read-only access to configuration data for
Google Analytics and supercedes the Data Export API Account Feed.
The Management API supports 5 feeds: account, web property, profile,
goal, advanced segment.
You can access each feed through the respective management query class
below. All requests return the same data object.
Args:
feed_uri: str or AccountQuery, WebPropertyQuery,
ProfileQuery, GoalQuery, MgmtAdvSegFeedQuery
The Management API Feed uri to define which feed to retrieve.
Either use a string or one of the wrapper classes.
"""
return self.get_feed(feed_uri,
desired_class=gdata.analytics.data.ManagementFeed,
auth_token=auth_token,
**kwargs)
GetMgmtFeed = GetManagementFeed = get_management_feed
class AnalyticsBaseQuery(gdata.client.GDQuery):
"""Abstracts common configuration across all query objects.
Attributes:
scheme: string The default scheme. Should always be https.
host: string The default host.
"""
scheme = 'https'
host = 'www.google.com'
class AccountFeedQuery(AnalyticsBaseQuery):
"""Account Feed query class to simplify constructing Account Feed Urls.
To use this class, you can either pass a dict in the constructor that has
all the data feed query parameters as keys:
queryUrl = AccountFeedQuery({'max-results': '10000'})
Alternatively you can add new parameters directly to the query object:
queryUrl = AccountFeedQuery()
queryUrl.query['max-results'] = '10000'
Args:
query: dict (optional) Contains all the GA Data Feed query parameters
as keys.
"""
path = '/analytics/feeds/accounts/default'
def __init__(self, query={}, **kwargs):
self.query = query
gdata.client.GDQuery(self, **kwargs)
class DataFeedQuery(AnalyticsBaseQuery):
"""Data Feed query class to simplify constructing Data Feed Urls.
To use this class, you can either pass a dict in the constructor that has
all the data feed query parameters as keys:
queryUrl = DataFeedQuery({'start-date': '2008-10-01'})
Alternatively you can add new parameters directly to the query object:
queryUrl = DataFeedQuery()
queryUrl.query['start-date'] = '2008-10-01'
Args:
query: dict (optional) Contains all the GA Data Feed query parameters
as keys.
"""
path = '/analytics/feeds/data'
def __init__(self, query={}, **kwargs):
self.query = query
gdata.client.GDQuery(self, **kwargs)
class AccountQuery(AnalyticsBaseQuery):
"""Management API Account Feed query class.
Example Usage:
queryUrl = AccountQuery()
queryUrl = AccountQuery({'max-results': 100})
queryUrl2 = AccountQuery()
queryUrl2.query['max-results'] = 100
Args:
query: dict (optional) A dictionary of query parameters.
"""
path = '/analytics/feeds/datasources/ga/accounts'
def __init__(self, query={}, **kwargs):
self.query = query
gdata.client.GDQuery(self, **kwargs)
class WebPropertyQuery(AnalyticsBaseQuery):
"""Management API Web Property Feed query class.
Example Usage:
queryUrl = WebPropertyQuery()
queryUrl = WebPropertyQuery('123', {'max-results': 100})
queryUrl = WebPropertyQuery(acct_id='123',
query={'max-results': 100})
queryUrl2 = WebPropertyQuery()
queryUrl2.acct_id = '1234'
queryUrl2.query['max-results'] = 100
Args:
acct_id: string (optional) The account ID to filter results.
Default is ~all.
query: dict (optional) A dictionary of query parameters.
"""
def __init__(self, acct_id='~all', query={}, **kwargs):
self.acct_id = acct_id
self.query = query
gdata.client.GDQuery(self, **kwargs)
@property
def path(self):
"""Wrapper for path attribute."""
return ('/analytics/feeds/datasources/ga/accounts/%s/webproperties' %
self.acct_id)
class ProfileQuery(AnalyticsBaseQuery):
"""Management API Profile Feed query class.
Example Usage:
queryUrl = ProfileQuery()
queryUrl = ProfileQuery('123', 'UA-123-1', {'max-results': 100})
queryUrl = ProfileQuery(acct_id='123',
web_prop_id='UA-123-1',
query={'max-results': 100})
queryUrl2 = ProfileQuery()
queryUrl2.acct_id = '123'
queryUrl2.web_prop_id = 'UA-123-1'
queryUrl2.query['max-results'] = 100
Args:
acct_id: string (optional) The account ID to filter results.
Default is ~all.
web_prop_id: string (optional) The web property ID to filter results.
Default is ~all.
query: dict (optional) A dictionary of query parameters.
"""
def __init__(self, acct_id='~all', web_prop_id='~all', query={}, **kwargs):
self.acct_id = acct_id
self.web_prop_id = web_prop_id
self.query = query
gdata.client.GDQuery(self, **kwargs)
@property
def path(self):
"""Wrapper for path attribute."""
return ('/analytics/feeds/datasources/ga/accounts/%s/webproperties'
'/%s/profiles' % (self.acct_id, self.web_prop_id))
class GoalQuery(AnalyticsBaseQuery):
"""Management API Goal Feed query class.
Example Usage:
queryUrl = GoalQuery()
queryUrl = GoalQuery('123', 'UA-123-1', '555',
{'max-results': 100})
queryUrl = GoalQuery(acct_id='123',
web_prop_id='UA-123-1',
profile_id='555',
query={'max-results': 100})
queryUrl2 = GoalQuery()
queryUrl2.acct_id = '123'
queryUrl2.web_prop_id = 'UA-123-1'
queryUrl2.query['max-results'] = 100
Args:
acct_id: string (optional) The account ID to filter results.
Default is ~all.
web_prop_id: string (optional) The web property ID to filter results.
Default is ~all.
profile_id: string (optional) The profile ID to filter results.
Default is ~all.
query: dict (optional) A dictionary of query parameters.
"""
def __init__(self, acct_id='~all', web_prop_id='~all', profile_id='~all',
query={}, **kwargs):
self.acct_id = acct_id
self.web_prop_id = web_prop_id
self.profile_id = profile_id
self.query = query or {}
gdata.client.GDQuery(self, **kwargs)
@property
def path(self):
"""Wrapper for path attribute."""
return ('/analytics/feeds/datasources/ga/accounts/%s/webproperties'
'/%s/profiles/%s/goals' % (self.acct_id, self.web_prop_id,
self.profile_id))
class AdvSegQuery(AnalyticsBaseQuery):
"""Management API Goal Feed query class.
Example Usage:
queryUrl = AdvSegQuery()
queryUrl = AdvSegQuery({'max-results': 100})
queryUrl1 = AdvSegQuery()
queryUrl1.query['max-results'] = 100
Args:
query: dict (optional) A dictionary of query parameters.
"""
path = '/analytics/feeds/datasources/ga/segments'
def __init__(self, query={}, **kwargs):
self.query = query
gdata.client.GDQuery(self, **kwargs)
| Python |
#!/usr/bin/python
#
# Original Copyright (C) 2006 Google Inc.
# Refactored in 2009 to work for Google Analytics by Sal Uryasev at Juice Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Note that this module will not function without specifically adding
# 'analytics': [ #Google Analytics
# 'https://www.google.com/analytics/feeds/'],
# to CLIENT_LOGIN_SCOPES in the gdata/service.py file
"""Contains extensions to Atom objects used with Google Analytics."""
__author__ = 'api.suryasev (Sal Uryasev)'
import atom
import gdata
GAN_NAMESPACE = 'http://schemas.google.com/analytics/2009'
class TableId(gdata.GDataEntry):
"""tableId element."""
_tag = 'tableId'
_namespace = GAN_NAMESPACE
class Property(gdata.GDataEntry):
_tag = 'property'
_namespace = GAN_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_attributes['name'] = 'name'
_attributes['value'] = 'value'
def __init__(self, name=None, value=None, *args, **kwargs):
self.name = name
self.value = value
super(Property, self).__init__(*args, **kwargs)
def __str__(self):
return self.value
def __repr__(self):
return self.value
class AccountListEntry(gdata.GDataEntry):
"""The Google Documents version of an Atom Entry"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}tableId' % GAN_NAMESPACE] = ('tableId',
[TableId])
_children['{%s}property' % GAN_NAMESPACE] = ('property',
[Property])
def __init__(self, tableId=None, property=None,
*args, **kwargs):
self.tableId = tableId
self.property = property
super(AccountListEntry, self).__init__(*args, **kwargs)
def AccountListEntryFromString(xml_string):
"""Converts an XML string into an AccountListEntry object.
Args:
xml_string: string The XML describing a Document List feed entry.
Returns:
A AccountListEntry object corresponding to the given XML.
"""
return atom.CreateClassFromXMLString(AccountListEntry, xml_string)
class AccountListFeed(gdata.GDataFeed):
"""A feed containing a list of Google Documents Items"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[AccountListEntry])
def AccountListFeedFromString(xml_string):
"""Converts an XML string into an AccountListFeed object.
Args:
xml_string: string The XML describing an AccountList feed.
Returns:
An AccountListFeed object corresponding to the given XML.
All properties are also linked to with a direct reference
from each entry object for convenience. (e.g. entry.AccountName)
"""
feed = atom.CreateClassFromXMLString(AccountListFeed, xml_string)
for entry in feed.entry:
for pro in entry.property:
entry.__dict__[pro.name.replace('ga:','')] = pro
for td in entry.tableId:
td.__dict__['value'] = td.text
return feed
class Dimension(gdata.GDataEntry):
_tag = 'dimension'
_namespace = GAN_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_attributes['name'] = 'name'
_attributes['value'] = 'value'
_attributes['type'] = 'type'
_attributes['confidenceInterval'] = 'confidence_interval'
def __init__(self, name=None, value=None, type=None,
confidence_interval = None, *args, **kwargs):
self.name = name
self.value = value
self.type = type
self.confidence_interval = confidence_interval
super(Dimension, self).__init__(*args, **kwargs)
def __str__(self):
return self.value
def __repr__(self):
return self.value
class Metric(gdata.GDataEntry):
_tag = 'metric'
_namespace = GAN_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_attributes['name'] = 'name'
_attributes['value'] = 'value'
_attributes['type'] = 'type'
_attributes['confidenceInterval'] = 'confidence_interval'
def __init__(self, name=None, value=None, type=None,
confidence_interval = None, *args, **kwargs):
self.name = name
self.value = value
self.type = type
self.confidence_interval = confidence_interval
super(Metric, self).__init__(*args, **kwargs)
def __str__(self):
return self.value
def __repr__(self):
return self.value
class AnalyticsDataEntry(gdata.GDataEntry):
"""The Google Analytics version of an Atom Entry"""
_tag = 'entry'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}dimension' % GAN_NAMESPACE] = ('dimension',
[Dimension])
_children['{%s}metric' % GAN_NAMESPACE] = ('metric',
[Metric])
def __init__(self, dimension=None, metric=None, *args, **kwargs):
self.dimension = dimension
self.metric = metric
super(AnalyticsDataEntry, self).__init__(*args, **kwargs)
class AnalyticsDataFeed(gdata.GDataFeed):
"""A feed containing a list of Google Analytics Data Feed"""
_tag = 'feed'
_namespace = atom.ATOM_NAMESPACE
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[AnalyticsDataEntry])
"""
Data Feed
"""
def AnalyticsDataFeedFromString(xml_string):
"""Converts an XML string into an AccountListFeed object.
Args:
xml_string: string The XML describing an AccountList feed.
Returns:
An AccountListFeed object corresponding to the given XML.
Each metric and dimension is also referenced directly from
the entry for easier access. (e.g. entry.keyword.value)
"""
feed = atom.CreateClassFromXMLString(AnalyticsDataFeed, xml_string)
if feed.entry:
for entry in feed.entry:
for met in entry.metric:
entry.__dict__[met.name.replace('ga:','')] = met
if entry.dimension is not None:
for dim in entry.dimension:
entry.__dict__[dim.name.replace('ga:','')] = dim
return feed
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
# Refactored in 2009 to work for Google Analytics by Sal Uryasev at Juice Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
AccountsService extends the GDataService to streamline Google Analytics
account information operations.
AnalyticsDataService: Provides methods to query google analytics data feeds.
Extends GDataService.
DataQuery: Queries a Google Analytics Data list feed.
AccountQuery: Queries a Google Analytics Account list feed.
"""
__author__ = 'api.suryasev (Sal Uryasev)'
import urllib
import atom
import gdata.service
import gdata.analytics
class AccountsService(gdata.service.GDataService):
"""Client extension for the Google Analytics Account List feed."""
def __init__(self, email="", password=None, source=None,
server='www.google.com/analytics', additional_headers=None,
**kwargs):
"""Creates a client for the Google Analytics service.
Args:
email: string (optional) The user's email address, used for
authentication.
password: string (optional) The user's password.
source: string (optional) The name of the user's application.
server: string (optional) The name of the server to which a connection
will be opened.
**kwargs: The other parameters to pass to gdata.service.GDataService
constructor.
"""
gdata.service.GDataService.__init__(
self, email=email, password=password, service='analytics',
source=source, server=server, additional_headers=additional_headers,
**kwargs)
def QueryAccountListFeed(self, uri):
"""Retrieves an AccountListFeed by retrieving a URI based off the Document
List feed, including any query parameters. An AccountListFeed object
can be used to construct these parameters.
Args:
uri: string The URI of the feed being retrieved possibly with query
parameters.
Returns:
An AccountListFeed object representing the feed returned by the server.
"""
return self.Get(uri, converter=gdata.analytics.AccountListFeedFromString)
def GetAccountListEntry(self, uri):
"""Retrieves a particular AccountListEntry by its unique URI.
Args:
uri: string The unique URI of an entry in an Account List feed.
Returns:
An AccountLisFeed object representing the retrieved entry.
"""
return self.Get(uri, converter=gdata.analytics.AccountListEntryFromString)
def GetAccountList(self, max_results=1000, text_query=None,
params=None, categories=None):
"""Retrieves a feed containing all of a user's accounts and profiles."""
q = gdata.analytics.service.AccountQuery(max_results=max_results,
text_query=text_query,
params=params,
categories=categories);
return self.QueryAccountListFeed(q.ToUri())
class AnalyticsDataService(gdata.service.GDataService):
"""Client extension for the Google Analytics service Data List feed."""
def __init__(self, email=None, password=None, source=None,
server='www.google.com/analytics', additional_headers=None,
**kwargs):
"""Creates a client for the Google Analytics service.
Args:
email: string (optional) The user's email address, used for
authentication.
password: string (optional) The user's password.
source: string (optional) The name of the user's application.
server: string (optional) The name of the server to which a connection
will be opened. Default value: 'docs.google.com'.
**kwargs: The other parameters to pass to gdata.service.GDataService
constructor.
"""
gdata.service.GDataService.__init__(self,
email=email, password=password, service='analytics', source=source,
server=server, additional_headers=additional_headers, **kwargs)
def GetData(self, ids='', dimensions='', metrics='',
sort='', filters='', start_date='',
end_date='', start_index='',
max_results=''):
"""Retrieves a feed containing a user's data
ids: comma-separated string of analytics accounts.
dimensions: comma-separated string of dimensions.
metrics: comma-separated string of metrics.
sort: comma-separated string of dimensions and metrics for sorting.
This may be previxed with a minus to sort in reverse order.
(e.g. '-ga:keyword')
If ommited, the first dimension passed in will be used.
filters: comma-separated string of filter parameters.
(e.g. 'ga:keyword==google')
start_date: start date for data pull.
end_date: end date for data pull.
start_index: used in combination with max_results to pull more than 1000
entries. This defaults to 1.
max_results: maximum results that the pull will return. This defaults
to, and maxes out at 1000.
"""
q = gdata.analytics.service.DataQuery(ids=ids,
dimensions=dimensions,
metrics=metrics,
filters=filters,
sort=sort,
start_date=start_date,
end_date=end_date,
start_index=start_index,
max_results=max_results);
return self.AnalyticsDataFeed(q.ToUri())
def AnalyticsDataFeed(self, uri):
"""Retrieves an AnalyticsListFeed by retrieving a URI based off the
Document List feed, including any query parameters. An
AnalyticsListFeed object can be used to construct these parameters.
Args:
uri: string The URI of the feed being retrieved possibly with query
parameters.
Returns:
An AnalyticsListFeed object representing the feed returned by the
server.
"""
return self.Get(uri,
converter=gdata.analytics.AnalyticsDataFeedFromString)
"""
Account Fetching
"""
def QueryAccountListFeed(self, uri):
"""Retrieves an Account ListFeed by retrieving a URI based off the Account
List feed, including any query parameters. A AccountQuery object can
be used to construct these parameters.
Args:
uri: string The URI of the feed being retrieved possibly with query
parameters.
Returns:
An AccountListFeed object representing the feed returned by the server.
"""
return self.Get(uri, converter=gdata.analytics.AccountListFeedFromString)
def GetAccountListEntry(self, uri):
"""Retrieves a particular AccountListEntry by its unique URI.
Args:
uri: string The unique URI of an entry in an Account List feed.
Returns:
An AccountListEntry object representing the retrieved entry.
"""
return self.Get(uri, converter=gdata.analytics.AccountListEntryFromString)
def GetAccountList(self, username="default", max_results=1000,
start_index=1):
"""Retrieves a feed containing all of a user's accounts and profiles.
The username parameter is soon to be deprecated, with 'default'
becoming the only allowed parameter.
"""
if not username:
raise Exception("username is a required parameter")
q = gdata.analytics.service.AccountQuery(username=username,
max_results=max_results,
start_index=start_index);
return self.QueryAccountListFeed(q.ToUri())
class DataQuery(gdata.service.Query):
"""Object used to construct a URI to a data feed"""
def __init__(self, feed='/feeds/data', text_query=None,
params=None, categories=None, ids="",
dimensions="", metrics="", sort="", filters="",
start_date="", end_date="", start_index="",
max_results=""):
"""Constructor for Analytics List Query
Args:
feed: string (optional) The path for the feed. (e.g. '/feeds/data')
text_query: string (optional) The contents of the q query parameter.
This string is URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to
the query's items.
categories: list (optional) List of category strings which should be
included as query categories. See gdata.service.Query for
additional documentation.
ids: comma-separated string of analytics accounts.
dimensions: comma-separated string of dimensions.
metrics: comma-separated string of metrics.
sort: comma-separated string of dimensions and metrics.
This may be previxed with a minus to sort in reverse order
(e.g. '-ga:keyword').
If ommited, the first dimension passed in will be used.
filters: comma-separated string of filter parameters
(e.g. 'ga:keyword==google').
start_date: start date for data pull.
end_date: end date for data pull.
start_index: used in combination with max_results to pull more than 1000
entries. This defaults to 1.
max_results: maximum results that the pull will return. This defaults
to, and maxes out at 1000.
Yields:
A DocumentQuery object used to construct a URI based on the Document
List feed.
"""
self.elements = {'ids': ids,
'dimensions': dimensions,
'metrics': metrics,
'sort': sort,
'filters': filters,
'start-date': start_date,
'end-date': end_date,
'start-index': start_index,
'max-results': max_results}
gdata.service.Query.__init__(self, feed, text_query, params, categories)
def ToUri(self):
"""Generates a URI from the query parameters set in the object.
Returns:
A string containing the URI used to retrieve entries from the Analytics
List feed.
"""
old_feed = self.feed
self.feed = '/'.join([old_feed]) + '?' + \
urllib.urlencode(dict([(key, value) for key, value in \
self.elements.iteritems() if value]))
new_feed = gdata.service.Query.ToUri(self)
self.feed = old_feed
return new_feed
class AccountQuery(gdata.service.Query):
"""Object used to construct a URI to query the Google Account List feed"""
def __init__(self, feed='/feeds/accounts', start_index=1,
max_results=1000, username='default', text_query=None,
params=None, categories=None):
"""Constructor for Account List Query
Args:
feed: string (optional) The path for the feed. (e.g. '/feeds/documents')
visibility: string (optional) The visibility chosen for the current
feed.
projection: string (optional) The projection chosen for the current
feed.
text_query: string (optional) The contents of the q query parameter.
This string is URL escaped upon conversion to a URI.
params: dict (optional) Parameter value string pairs which become URL
params when translated to a URI. These parameters are added to
the query's items.
categories: list (optional) List of category strings which should be
included as query categories. See gdata.service.Query for
additional documentation.
username: string (deprecated) This value should now always be passed as
'default'.
Yields:
A DocumentQuery object used to construct a URI based on the Document
List feed.
"""
self.max_results = max_results
self.start_index = start_index
self.username = username
gdata.service.Query.__init__(self, feed, text_query, params, categories)
def ToUri(self):
"""Generates a URI from the query parameters set in the object.
Returns:
A string containing the URI used to retrieve entries from the Account
List feed.
"""
old_feed = self.feed
self.feed = '/'.join([old_feed, self.username]) + '?' + \
'&'.join(['max-results=' + str(self.max_results),
'start-index=' + str(self.start_index)])
new_feed = self.feed
self.feed = old_feed
return new_feed
| Python |
#!/usr/bin/python
#
# Copyright (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.
"""
__author__ = 'api.jscudder (Jeff Scudder)'
import StringIO
import pickle
import atom.http_interface
import atom.token_store
from google.appengine.api import urlfetch
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import memcache
def run_on_appengine(gdata_service, store_tokens=True,
single_user_mode=False, deadline=None):
"""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 and a
token_store member.
store_tokens: Boolean, defaults to True. If True, the gdata_service
will attempt to add each token to it's token_store when
SetClientLoginToken or SetAuthSubToken is called. If False
the tokens will not automatically be added to the
token_store.
single_user_mode: Boolean, defaults to False. If True, the current_token
member of gdata_service will be set when
SetClientLoginToken or SetAuthTubToken is called. If set
to True, the current_token is set in the gdata_service
and anyone who accesses the object will use the same
token.
Note: If store_tokens is set to False and
single_user_mode is set to False, all tokens will be
ignored, since the library assumes: the tokens should not
be stored in the datastore and they should not be stored
in the gdata_service object. This will make it
impossible to make requests which require authorization.
deadline: int (optional) The number of seconds to wait for a response
before timing out on the HTTP request. If no deadline is
specified, the deafault deadline for HTTP requests from App
Engine is used. The maximum is currently 10 (for 10 seconds).
The default deadline for App Engine is 5 seconds.
"""
gdata_service.http_client = AppEngineHttpClient(deadline=deadline)
gdata_service.token_store = AppEngineTokenStore()
gdata_service.auto_store_tokens = store_tokens
gdata_service.auto_set_current_token = single_user_mode
return gdata_service
class AppEngineHttpClient(atom.http_interface.GenericHttpClient):
def __init__(self, headers=None, deadline=None):
self.debug = False
self.headers = headers or {}
self.deadline = deadline
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 = [_convert_data_part(x) for x in data]
data_str = ''.join(converted_parts)
else:
data_str = _convert_data_part(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'] = str(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
if self.deadline is None:
return HttpResponse(urlfetch.Fetch(url=str(url), payload=data_str,
method=method, headers=all_headers, follow_redirects=False))
return HttpResponse(urlfetch.Fetch(url=str(url), payload=data_str,
method=method, headers=all_headers, follow_redirects=False,
deadline=self.deadline))
def _convert_data_part(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]
class TokenCollection(db.Model):
"""Datastore Model which associates auth tokens with the current user."""
user = db.UserProperty()
pickled_tokens = db.BlobProperty()
class AppEngineTokenStore(atom.token_store.TokenStore):
"""Stores the user's auth tokens in the App Engine datastore.
Tokens are only written to the datastore if a user is signed in (if
users.get_current_user() returns a user object).
"""
def __init__(self):
self.user = None
def add_token(self, token):
"""Associates the token with the current user and stores it.
If there is no current user, the token will not be stored.
Returns:
False if the token was not stored.
"""
tokens = load_auth_tokens(self.user)
if not hasattr(token, 'scopes') or not token.scopes:
return False
for scope in token.scopes:
tokens[str(scope)] = token
key = save_auth_tokens(tokens, self.user)
if key:
return True
return False
def find_token(self, url):
"""Searches the current user's collection of token for a token which can
be used for a request to the url.
Returns:
The stored token which belongs to the current user and is valid for the
desired URL. If there is no current user, or there is no valid user
token in the datastore, a atom.http_interface.GenericToken is returned.
"""
if url is None:
return None
if isinstance(url, (str, unicode)):
url = atom.url.parse_url(url)
tokens = load_auth_tokens(self.user)
if url in tokens:
token = tokens[url]
if token.valid_for_scope(url):
return token
else:
del tokens[url]
save_auth_tokens(tokens, self.user)
for scope, token in tokens.iteritems():
if token.valid_for_scope(url):
return token
return atom.http_interface.GenericToken()
def remove_token(self, token):
"""Removes the token from the current user's collection in the datastore.
Returns:
False if the token was not removed, this could be because the token was
not in the datastore, or because there is no current user.
"""
token_found = False
scopes_to_delete = []
tokens = load_auth_tokens(self.user)
for scope, stored_token in tokens.iteritems():
if stored_token == token:
scopes_to_delete.append(scope)
token_found = True
for scope in scopes_to_delete:
del tokens[scope]
if token_found:
save_auth_tokens(tokens, self.user)
return token_found
def remove_all_tokens(self):
"""Removes all of the current user's tokens from the datastore."""
save_auth_tokens({}, self.user)
def save_auth_tokens(token_dict, user=None):
"""Associates the tokens with the current user and writes to the datastore.
If there us no current user, the tokens are not written and this function
returns None.
Returns:
The key of the datastore entity containing the user's tokens, or None if
there was no current user.
"""
if user is None:
user = users.get_current_user()
if user is None:
return None
memcache.set('gdata_pickled_tokens:%s' % user, pickle.dumps(token_dict))
user_tokens = TokenCollection.all().filter('user =', user).get()
if user_tokens:
user_tokens.pickled_tokens = pickle.dumps(token_dict)
return user_tokens.put()
else:
user_tokens = TokenCollection(
user=user,
pickled_tokens=pickle.dumps(token_dict))
return user_tokens.put()
def load_auth_tokens(user=None):
"""Reads a dictionary of the current user's tokens from the datastore.
If there is no current user (a user is not signed in to the app) or the user
does not have any tokens, an empty dictionary is returned.
"""
if user is None:
user = users.get_current_user()
if user is None:
return {}
pickled_tokens = memcache.get('gdata_pickled_tokens:%s' % user)
if pickled_tokens:
return pickle.loads(pickled_tokens)
user_tokens = TokenCollection.all().filter('user =', user).get()
if user_tokens:
memcache.set('gdata_pickled_tokens:%s' % user, user_tokens.pickled_tokens)
return pickle.loads(user_tokens.pickled_tokens)
return {}
| 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.
"""Provides functions to persist serialized auth tokens in the datastore.
The get_token and set_token functions should be used in conjunction with
gdata.gauth's token_from_blob and token_to_blob to allow auth token objects
to be reused across requests. It is up to your own code to ensure that the
token key's are unique.
"""
__author__ = 'j.s@google.com (Jeff Scudder)'
from google.appengine.ext import db
from google.appengine.api import memcache
class Token(db.Model):
"""Datastore Model which stores a serialized auth token."""
t = db.BlobProperty()
def get_token(unique_key):
"""Searches for a stored token with the desired key.
Checks memcache and then the datastore if required.
Args:
unique_key: str which uniquely identifies the desired auth token.
Returns:
A string encoding the auth token data. Use gdata.gauth.token_from_blob to
convert back into a usable token object. None if the token was not found
in memcache or the datastore.
"""
token_string = memcache.get(unique_key)
if token_string is None:
# The token wasn't in memcache, so look in the datastore.
token = Token.get_by_key_name(unique_key)
if token is None:
return None
return token.t
return token_string
def set_token(unique_key, token_str):
"""Saves the serialized auth token in the datastore.
The token is also stored in memcache to speed up retrieval on a cache hit.
Args:
unique_key: The unique name for this token as a string. It is up to your
code to ensure that this token value is unique in your application.
Previous values will be silently overwitten.
token_str: A serialized auth token as a string. I expect that this string
will be generated by gdata.gauth.token_to_blob.
Returns:
True if the token was stored sucessfully, False if the token could not be
safely cached (if an old value could not be cleared). If the token was
set in memcache, but not in the datastore, this function will return None.
However, in that situation an exception will likely be raised.
Raises:
Datastore exceptions may be raised from the App Engine SDK in the event of
failure.
"""
# First try to save in memcache.
result = memcache.set(unique_key, token_str)
# If memcache fails to save the value, clear the cached value.
if not result:
result = memcache.delete(unique_key)
# If we could not clear the cached value for this token, refuse to save.
if result == 0:
return False
# Save to the datastore.
if Token(key_name=unique_key, t=token_str).put():
return True
return None
def delete_token(unique_key):
# Clear from memcache.
memcache.delete(unique_key)
# Clear from the datastore.
Token(key_name=unique_key).delete()
| 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.
"""This package's modules adapt the gdata library to run in other environments
The first example is the appengine module which contains functions and
classes which modify a GDataService object to run on Google App Engine.
"""
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains the data classes of the Google Calendar Data API"""
__author__ = 'j.s@google.com (Jeff Scudder)'
import atom.core
import atom.data
import gdata.acl.data
import gdata.data
import gdata.geo.data
import gdata.opensearch.data
GCAL_NAMESPACE = 'http://schemas.google.com/gCal/2005'
GCAL_TEMPLATE = '{%s}%%s' % GCAL_NAMESPACE
WEB_CONTENT_LINK_REL = '%s/%s' % (GCAL_NAMESPACE, 'webContent')
class AccessLevelProperty(atom.core.XmlElement):
"""Describes how much a given user may do with an event or calendar"""
_qname = GCAL_TEMPLATE % 'accesslevel'
value = 'value'
class AllowGSync2Property(atom.core.XmlElement):
"""Whether the user is permitted to run Google Apps Sync"""
_qname = GCAL_TEMPLATE % 'allowGSync2'
value = 'value'
class AllowGSyncProperty(atom.core.XmlElement):
"""Whether the user is permitted to run Google Apps Sync"""
_qname = GCAL_TEMPLATE % 'allowGSync'
value = 'value'
class AnyoneCanAddSelfProperty(atom.core.XmlElement):
"""Whether anyone can add self as attendee"""
_qname = GCAL_TEMPLATE % 'anyoneCanAddSelf'
value = 'value'
class CalendarAclRole(gdata.acl.data.AclRole):
"""Describes the Calendar roles of an entry in the Calendar access control list"""
_qname = gdata.acl.data.GACL_TEMPLATE % 'role'
class CalendarCommentEntry(gdata.data.GDEntry):
"""Describes an entry in a feed of a Calendar event's comments"""
class CalendarCommentFeed(gdata.data.GDFeed):
"""Describes feed of a Calendar event's comments"""
entry = [CalendarCommentEntry]
class CalendarComments(gdata.data.Comments):
"""Describes a container of a feed link for Calendar comment entries"""
_qname = gdata.data.GD_TEMPLATE % 'comments'
class CalendarExtendedProperty(gdata.data.ExtendedProperty):
"""Defines a value for the realm attribute that is used only in the calendar API"""
_qname = gdata.data.GD_TEMPLATE % 'extendedProperty'
class CalendarWhere(gdata.data.Where):
"""Extends the base Where class with Calendar extensions"""
_qname = gdata.data.GD_TEMPLATE % 'where'
class ColorProperty(atom.core.XmlElement):
"""Describes the color of a calendar"""
_qname = GCAL_TEMPLATE % 'color'
value = 'value'
class GuestsCanInviteOthersProperty(atom.core.XmlElement):
"""Whether guests can invite others to the event"""
_qname = GCAL_TEMPLATE % 'guestsCanInviteOthers'
value = 'value'
class GuestsCanModifyProperty(atom.core.XmlElement):
"""Whether guests can modify event"""
_qname = GCAL_TEMPLATE % 'guestsCanModify'
value = 'value'
class GuestsCanSeeGuestsProperty(atom.core.XmlElement):
"""Whether guests can see other attendees"""
_qname = GCAL_TEMPLATE % 'guestsCanSeeGuests'
value = 'value'
class HiddenProperty(atom.core.XmlElement):
"""Describes whether a calendar is hidden"""
_qname = GCAL_TEMPLATE % 'hidden'
value = 'value'
class IcalUIDProperty(atom.core.XmlElement):
"""Describes the UID in the ical export of the event"""
_qname = GCAL_TEMPLATE % 'uid'
value = 'value'
class OverrideNameProperty(atom.core.XmlElement):
"""Describes the override name property of a calendar"""
_qname = GCAL_TEMPLATE % 'overridename'
value = 'value'
class PrivateCopyProperty(atom.core.XmlElement):
"""Indicates whether this is a private copy of the event, changes to which should not be sent to other calendars"""
_qname = GCAL_TEMPLATE % 'privateCopy'
value = 'value'
class QuickAddProperty(atom.core.XmlElement):
"""Describes whether gd:content is for quick-add processing"""
_qname = GCAL_TEMPLATE % 'quickadd'
value = 'value'
class ResourceProperty(atom.core.XmlElement):
"""Describes whether gd:who is a resource such as a conference room"""
_qname = GCAL_TEMPLATE % 'resource'
value = 'value'
id = 'id'
class EventWho(gdata.data.Who):
"""Extends the base Who class with Calendar extensions"""
_qname = gdata.data.GD_TEMPLATE % 'who'
resource = ResourceProperty
class SelectedProperty(atom.core.XmlElement):
"""Describes whether a calendar is selected"""
_qname = GCAL_TEMPLATE % 'selected'
value = 'value'
class SendAclNotificationsProperty(atom.core.XmlElement):
"""Describes whether to send ACL notifications to grantees"""
_qname = GCAL_TEMPLATE % 'sendAclNotifications'
value = 'value'
class CalendarAclEntry(gdata.acl.data.AclEntry):
"""Describes an entry in a feed of a Calendar access control list (ACL)"""
send_acl_notifications = SendAclNotificationsProperty
class CalendarAclFeed(gdata.data.GDFeed):
"""Describes a Calendar access contorl list (ACL) feed"""
entry = [CalendarAclEntry]
class SendEventNotificationsProperty(atom.core.XmlElement):
"""Describes whether to send event notifications to other participants of the event"""
_qname = GCAL_TEMPLATE % 'sendEventNotifications'
value = 'value'
class SequenceNumberProperty(atom.core.XmlElement):
"""Describes sequence number of an event"""
_qname = GCAL_TEMPLATE % 'sequence'
value = 'value'
class CalendarRecurrenceExceptionEntry(gdata.data.GDEntry):
"""Describes an entry used by a Calendar recurrence exception entry link"""
uid = IcalUIDProperty
sequence = SequenceNumberProperty
class CalendarRecurrenceException(gdata.data.RecurrenceException):
"""Describes an exception to a recurring Calendar event"""
_qname = gdata.data.GD_TEMPLATE % 'recurrenceException'
class SettingsProperty(atom.core.XmlElement):
"""User preference name-value pair"""
_qname = GCAL_TEMPLATE % 'settingsProperty'
name = 'name'
value = 'value'
class SettingsEntry(gdata.data.GDEntry):
"""Describes a Calendar Settings property entry"""
settings_property = SettingsProperty
class CalendarSettingsFeed(gdata.data.GDFeed):
"""Personal settings for Calendar application"""
entry = [SettingsEntry]
class SuppressReplyNotificationsProperty(atom.core.XmlElement):
"""Lists notification methods to be suppressed for this reply"""
_qname = GCAL_TEMPLATE % 'suppressReplyNotifications'
methods = 'methods'
class SyncEventProperty(atom.core.XmlElement):
"""Describes whether this is a sync scenario where the Ical UID and Sequence number are honored during inserts and updates"""
_qname = GCAL_TEMPLATE % 'syncEvent'
value = 'value'
class When(gdata.data.When):
"""Extends the gd:when element to add reminders"""
reminder = [gdata.data.Reminder]
class CalendarEventEntry(gdata.data.BatchEntry):
"""Describes a Calendar event entry"""
quick_add = QuickAddProperty
send_event_notifications = SendEventNotificationsProperty
sync_event = SyncEventProperty
anyone_can_add_self = AnyoneCanAddSelfProperty
extended_property = [CalendarExtendedProperty]
sequence = SequenceNumberProperty
guests_can_invite_others = GuestsCanInviteOthersProperty
guests_can_modify = GuestsCanModifyProperty
guests_can_see_guests = GuestsCanSeeGuestsProperty
georss_where = gdata.geo.data.GeoRssWhere
private_copy = PrivateCopyProperty
suppress_reply_notifications = SuppressReplyNotificationsProperty
uid = IcalUIDProperty
where = [gdata.data.Where]
when = [When]
who = [gdata.data.Who]
transparency = gdata.data.Transparency
comments = gdata.data.Comments
event_status = gdata.data.EventStatus
visibility = gdata.data.Visibility
recurrence = gdata.data.Recurrence
recurrence_exception = [gdata.data.RecurrenceException]
original_event = gdata.data.OriginalEvent
reminder = [gdata.data.Reminder]
class TimeZoneProperty(atom.core.XmlElement):
"""Describes the time zone of a calendar"""
_qname = GCAL_TEMPLATE % 'timezone'
value = 'value'
class TimesCleanedProperty(atom.core.XmlElement):
"""Describes how many times calendar was cleaned via Manage Calendars"""
_qname = GCAL_TEMPLATE % 'timesCleaned'
value = 'value'
class CalendarEntry(gdata.data.GDEntry):
"""Describes a Calendar entry in the feed of a user's calendars"""
timezone = TimeZoneProperty
overridename = OverrideNameProperty
hidden = HiddenProperty
selected = SelectedProperty
times_cleaned = TimesCleanedProperty
color = ColorProperty
where = [CalendarWhere]
accesslevel = AccessLevelProperty
class CalendarEventFeed(gdata.data.BatchFeed):
"""Describes a Calendar event feed"""
allow_g_sync2 = AllowGSync2Property
timezone = TimeZoneProperty
entry = [CalendarEventEntry]
times_cleaned = TimesCleanedProperty
allow_g_sync = AllowGSyncProperty
class CalendarFeed(gdata.data.GDFeed):
"""Describes a feed of Calendars"""
entry = [CalendarEntry]
class WebContentGadgetPref(atom.core.XmlElement):
"""Describes a single web content gadget preference"""
_qname = GCAL_TEMPLATE % 'webContentGadgetPref'
name = 'name'
value = 'value'
class WebContent(atom.core.XmlElement):
"""Describes a "web content" extension"""
_qname = GCAL_TEMPLATE % 'webContent'
height = 'height'
width = 'width'
web_content_gadget_pref = [WebContentGadgetPref]
url = 'url'
display = 'display'
class WebContentLink(atom.data.Link):
"""Describes a "web content" link"""
def __init__(self, title=None, href=None, link_type=None,
web_content=None):
atom.data.Link.__init__(self, rel=WEB_CONTENT_LINK_REL, title=title, href=href,
link_type=link_type)
web_content = WebContent
| Python |
#!/usr/bin/python
#
# Copyright (C) 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""CalendarClient extends the GDataService to streamline Google Calendar operations.
CalendarService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'alainv (Alain Vongsouvanh)'
import urllib
import gdata.client
import gdata.calendar.data
import atom.data
import atom.http_core
import gdata.gauth
DEFAULT_BATCH_URL = ('https://www.google.com/calendar/feeds/default/private'
'/full/batch')
class CalendarClient(gdata.client.GDClient):
"""Client for the Google Calendar service."""
api_version = '2'
auth_service = 'cl'
server = "www.google.com"
contact_list = "default"
auth_scopes = gdata.gauth.AUTH_SCOPES['cl']
def __init__(self, domain=None, auth_token=None, **kwargs):
"""Constructs a new client for the Calendar API.
Args:
domain: string The Google Apps domain (if any).
kwargs: The other parameters to pass to the gdata.client.GDClient
constructor.
"""
gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs)
self.domain = domain
def get_calendar_feed_uri(self, feed='', projection='full', scheme="https"):
"""Builds a feed URI.
Args:
projection: The projection to apply to the feed contents, for example
'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.
scheme: The URL scheme such as 'http' or 'https', None to return a
relative URI without hostname.
Returns:
A feed URI using the given scheme and projection.
Example: '/calendar/feeds/default/owncalendars/full'.
"""
prefix = scheme and '%s://%s' % (scheme, self.server) or ''
suffix = feed and '/%s/%s' % (feed, projection) or ''
return '%s/calendar/feeds/default%s' % (prefix, suffix)
GetCalendarFeedUri = get_calendar_feed_uri
def get_calendar_event_feed_uri(self, calendar='default', visibility='private',
projection='full', scheme="https"):
"""Builds a feed URI.
Args:
projection: The projection to apply to the feed contents, for example
'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'.
scheme: The URL scheme such as 'http' or 'https', None to return a
relative URI without hostname.
Returns:
A feed URI using the given scheme and projection.
Example: '/calendar/feeds/default/private/full'.
"""
prefix = scheme and '%s://%s' % (scheme, self.server) or ''
return '%s/calendar/feeds/%s/%s/%s' % (prefix, calendar,
visibility, projection)
GetCalendarEventFeedUri = get_calendar_event_feed_uri
def get_calendars_feed(self, uri,
desired_class=gdata.calendar.data.CalendarFeed,
auth_token=None, **kwargs):
"""Obtains a calendar feed.
Args:
uri: The uri of the calendar feed to request.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_feed(uri, auth_token=auth_token,
desired_class=desired_class, **kwargs)
GetCalendarsFeed = get_calendars_feed
def get_own_calendars_feed(self,
desired_class=gdata.calendar.data.CalendarFeed,
auth_token=None, **kwargs):
"""Obtains a feed containing the calendars owned by the current user.
Args:
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.GetCalendarsFeed(uri=self.GetCalendarFeedUri(feed='owncalendars'),
desired_class=desired_class, auth_token=auth_token,
**kwargs)
GetOwnCalendarsFeed = get_own_calendars_feed
def get_all_calendars_feed(self, desired_class=gdata.calendar.data.CalendarFeed,
auth_token=None, **kwargs):
"""Obtains a feed containing all the ccalendars the current user has access to.
Args:
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.GetCalendarsFeed(uri=self.GetCalendarFeedUri(feed='allcalendars'),
desired_class=desired_class, auth_token=auth_token,
**kwargs)
GetAllCalendarsFeed = get_all_calendars_feed
def get_calendar_entry(self, uri, desired_class=gdata.calendar.data.CalendarEntry,
auth_token=None, **kwargs):
"""Obtains a single calendar entry.
Args:
uri: The uri of the desired calendar entry.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarEntry.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class,
**kwargs)
GetCalendarEntry = get_calendar_entry
def get_calendar_event_feed(self, uri=None,
desired_class=gdata.calendar.data.CalendarEventFeed,
auth_token=None, **kwargs):
"""Obtains a feed of events for the desired calendar.
Args:
uri: The uri of the desired calendar entry.
Defaults to https://www.google.com/calendar/feeds/default/private/full.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarEventFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
uri = uri or self.GetCalendarEventFeedUri()
return self.get_feed(uri, auth_token=auth_token,
desired_class=desired_class, **kwargs)
GetCalendarEventFeed = get_calendar_event_feed
def get_event_entry(self, uri, desired_class=gdata.calendar.data.CalendarEventEntry,
auth_token=None, **kwargs):
"""Obtains a single event entry.
Args:
uri: The uri of the desired calendar event entry.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarEventEntry.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class,
**kwargs)
GetEventEntry = get_event_entry
def get_calendar_acl_feed(self, uri='https://www.google.com/calendar/feeds/default/acl/full',
desired_class=gdata.calendar.data.CalendarAclFeed,
auth_token=None, **kwargs):
"""Obtains an Access Control List feed.
Args:
uri: The uri of the desired Acl feed.
Defaults to https://www.google.com/calendar/feeds/default/acl/full.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarAclFeed.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_feed(uri, auth_token=auth_token, desired_class=desired_class,
**kwargs)
GetCalendarAclFeed = get_calendar_acl_feed
def get_calendar_acl_entry(self, uri, desired_class=gdata.calendar.data.CalendarAclEntry,
auth_token=None, **kwargs):
"""Obtains a single Access Control List entry.
Args:
uri: The uri of the desired Acl feed.
desired_class: class descended from atom.core.XmlElement to which a
successful response should be converted. If there is no
converter function specified (desired_class=None) then the
desired_class will be used in calling the
atom.core.parse function. If neither
the desired_class nor the converter is specified, an
HTTP reponse object will be returned. Defaults to
gdata.calendar.data.CalendarAclEntry.
auth_token: An object which sets the Authorization HTTP header in its
modify_request method. Recommended classes include
gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
among others. Represents the current user. Defaults to None
and if None, this method will look for a value in the
auth_token member of SpreadsheetsClient.
"""
return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class,
**kwargs)
GetCalendarAclEntry = get_calendar_acl_entry
def insert_calendar(self, new_calendar, insert_uri=None, auth_token=None, **kwargs):
"""Adds an new calendar to Google Calendar.
Args:
new_calendar: atom.Entry or subclass A new calendar which is to be added to
Google Calendar.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = insert_uri or self.GetCalendarFeedUri(feed='owncalendars')
return self.Post(new_calendar, insert_uri,
auth_token=auth_token, **kwargs)
InsertCalendar = insert_calendar
def insert_calendar_subscription(self, calendar, insert_uri=None,
auth_token=None, **kwargs):
"""Subscribes the authenticated user to the provided calendar.
Args:
calendar: The calendar to which the user should be subscribed.
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the subscription created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = insert_uri or self.GetCalendarFeedUri(feed='allcalendars')
return self.Post(calendar, insert_uri, auth_token=auth_token, **kwargs)
InsertCalendarSubscription = insert_calendar_subscription
def insert_event(self, new_event, insert_uri=None, auth_token=None, **kwargs):
"""Adds an new event to Google Calendar.
Args:
new_event: atom.Entry or subclass A new event which is to be added to
Google Calendar.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = insert_uri or self.GetCalendarEventFeedUri()
return self.Post(new_event, insert_uri,
auth_token=auth_token, **kwargs)
InsertEvent = insert_event
def insert_acl_entry(self, new_acl_entry,
insert_uri = 'https://www.google.com/calendar/feeds/default/acl/full',
auth_token=None, **kwargs):
"""Adds an new Acl entry to Google Calendar.
Args:
new_acl_event: atom.Entry or subclass A new acl which is to be added to
Google Calendar.
insert_uri: the URL to post new contacts to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the contact created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_acl_entry, insert_uri, auth_token=auth_token, **kwargs)
InsertAclEntry = insert_acl_entry
def execute_batch(self, batch_feed, url, desired_class=None):
"""Sends a batch request feed to the server.
Args:
batch_feed: gdata.contacts.CalendarEventFeed A feed containing batch
request entries. Each entry contains the operation to be performed
on the data contained in the entry. For example an entry with an
operation type of insert will be used as if the individual entry
had been inserted.
url: str The batch URL to which these operations should be applied.
converter: Function (optional) The function used to convert the server's
response to an object.
Returns:
The results of the batch request's execution on the server. If the
default converter is used, this is stored in a ContactsFeed.
"""
return self.Post(batch_feed, url, desired_class=desired_class)
ExecuteBatch = execute_batch
def update(self, entry, auth_token=None, **kwargs):
"""Edits the entry on the server by sending the XML for this entry.
Performs a PUT and converts the response to a new entry object with a
matching class to the entry passed in.
Args:
entry:
auth_token:
Returns:
A new Entry object of a matching type to the entry which was passed in.
"""
return gdata.client.GDClient.Update(self, entry, auth_token=auth_token,
force=True, **kwargs)
Update = update
class CalendarEventQuery(gdata.client.Query):
"""
Create a custom Calendar Query
Full specs can be found at: U{Calendar query parameters reference
<http://code.google.com/apis/calendar/data/2.0/reference.html#Parameters>}
"""
def __init__(self, feed=None, ctz=None, fields=None, futureevents=None,
max_attendees=None, orderby=None, recurrence_expansion_start=None,
recurrence_expansion_end=None, singleevents=None, showdeleted=None,
showhidden=None, sortorder=None, start_min=None, start_max=None,
updated_min=None, **kwargs):
"""
@param max_results: The maximum number of entries to return. If you want
to receive all of the contacts, rather than only the default maximum, you
can specify a very large number for max-results.
@param start-index: The 1-based index of the first result to be retrieved.
@param updated-min: The lower bound on entry update dates.
@param group: Constrains the results to only the contacts belonging to the
group specified. Value of this parameter specifies group ID
@param orderby: Sorting criterion. The only supported value is
lastmodified.
@param showdeleted: Include deleted contacts in the returned contacts feed
@pram sortorder: Sorting order direction. Can be either ascending or
descending.
@param requirealldeleted: Only relevant if showdeleted and updated-min
are also provided. It dictates the behavior of the server in case it
detects that placeholders of some entries deleted since the point in
time specified as updated-min may have been lost.
"""
gdata.client.Query.__init__(self, **kwargs)
self.ctz = ctz
self.fields = fields
self.futureevents = futureevents
self.max_attendees = max_attendees
self.orderby = orderby
self.recurrence_expansion_start = recurrence_expansion_start
self.recurrence_expansion_end = recurrence_expansion_end
self.singleevents = singleevents
self.showdeleted = showdeleted
self.showhidden = showhidden
self.sortorder = sortorder
self.start_min = start_min
self.start_max = start_max
self.updated_min = updated_min
def modify_request(self, http_request):
if self.ctz:
gdata.client._add_query_param('ctz', self.ctz, http_request)
if self.fields:
gdata.client._add_query_param('fields', self.fields, http_request)
if self.futureevents:
gdata.client._add_query_param('futureevents', self.futureevents, http_request)
if self.max_attendees:
gdata.client._add_query_param('max-attendees', self.max_attendees, http_request)
if self.orderby:
gdata.client._add_query_param('orderby', self.orderby, http_request)
if self.recurrence_expansion_start:
gdata.client._add_query_param('recurrence-expansion-start',
self.recurrence_expansion_start, http_request)
if self.recurrence_expansion_end:
gdata.client._add_query_param('recurrence-expansion-end',
self.recurrence_expansion_end, http_request)
if self.singleevents:
gdata.client._add_query_param('singleevents', self.singleevents, http_request)
if self.showdeleted:
gdata.client._add_query_param('showdeleted', self.showdeleted, http_request)
if self.showhidden:
gdata.client._add_query_param('showhidden', self.showhidden, http_request)
if self.sortorder:
gdata.client._add_query_param('sortorder', self.sortorder, http_request)
if self.start_min:
gdata.client._add_query_param('start-min', self.start_min, http_request)
if self.start_max:
gdata.client._add_query_param('start-max', self.start_max, http_request)
if self.updated_min:
gdata.client._add_query_param('updated-min', self.updated_min, http_request)
gdata.client.Query.modify_request(self, http_request)
ModifyRequest = modify_request
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains extensions to ElementWrapper objects used with Google Calendar."""
__author__ = 'api.vli (Vivian Li), api.rboyd (Ryan Boyd)'
try:
from xml.etree import cElementTree as ElementTree
except ImportError:
try:
import cElementTree as ElementTree
except ImportError:
try:
from xml.etree import ElementTree
except ImportError:
from elementtree import ElementTree
import atom
import gdata
# XML namespaces which are often used in Google Calendar entities.
GCAL_NAMESPACE = 'http://schemas.google.com/gCal/2005'
GCAL_TEMPLATE = '{http://schemas.google.com/gCal/2005}%s'
WEB_CONTENT_LINK_REL = '%s/%s' % (GCAL_NAMESPACE, 'webContent')
GACL_NAMESPACE = gdata.GACL_NAMESPACE
GACL_TEMPLATE = gdata.GACL_TEMPLATE
class ValueAttributeContainer(atom.AtomBase):
"""A parent class for all Calendar classes which have a value attribute.
Children include Color, AccessLevel, Hidden
"""
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Color(ValueAttributeContainer):
"""The Google Calendar color element"""
_tag = 'color'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class AccessLevel(ValueAttributeContainer):
"""The Google Calendar accesslevel element"""
_tag = 'accesslevel'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Hidden(ValueAttributeContainer):
"""The Google Calendar hidden element"""
_tag = 'hidden'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Selected(ValueAttributeContainer):
"""The Google Calendar selected element"""
_tag = 'selected'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Timezone(ValueAttributeContainer):
"""The Google Calendar timezone element"""
_tag = 'timezone'
_namespace = GCAL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class Where(atom.AtomBase):
"""The Google Calendar Where element"""
_tag = 'where'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['valueString'] = 'value_string'
def __init__(self, value_string=None, extension_elements=None,
extension_attributes=None, text=None):
self.value_string = value_string
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class CalendarListEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar meta Entry flavor of an Atom Entry """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}color' % GCAL_NAMESPACE] = ('color', Color)
_children['{%s}accesslevel' % GCAL_NAMESPACE] = ('access_level',
AccessLevel)
_children['{%s}hidden' % GCAL_NAMESPACE] = ('hidden', Hidden)
_children['{%s}selected' % GCAL_NAMESPACE] = ('selected', Selected)
_children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone)
_children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', Where)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
color=None, access_level=None, hidden=None, timezone=None,
selected=None,
where=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=None)
self.color = color
self.access_level = access_level
self.hidden = hidden
self.selected = selected
self.timezone = timezone
self.where = where
class CalendarListFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar meta feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarListEntry])
class Scope(atom.AtomBase):
"""The Google ACL scope element"""
_tag = 'scope'
_namespace = GACL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
_attributes['type'] = 'type'
def __init__(self, extension_elements=None, value=None, scope_type=None,
extension_attributes=None, text=None):
self.value = value
self.type = scope_type
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Role(ValueAttributeContainer):
"""The Google Calendar timezone element"""
_tag = 'role'
_namespace = GACL_NAMESPACE
_children = ValueAttributeContainer._children.copy()
_attributes = ValueAttributeContainer._attributes.copy()
class CalendarAclEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar ACL Entry flavor of an Atom Entry """
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
_children['{%s}scope' % GACL_NAMESPACE] = ('scope', Scope)
_children['{%s}role' % GACL_NAMESPACE] = ('role', Role)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
scope=None, role=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.GDataEntry.__init__(self, author=author, category=category,
content=content, atom_id=atom_id, link=link,
published=published, title=title,
updated=updated, text=None)
self.scope = scope
self.role = role
class CalendarAclFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar ACL feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarAclEntry])
class CalendarEventCommentEntry(gdata.GDataEntry, gdata.LinkFinder):
"""A Google Calendar event comments entry flavor of an Atom Entry"""
_tag = gdata.GDataEntry._tag
_namespace = gdata.GDataEntry._namespace
_children = gdata.GDataEntry._children.copy()
_attributes = gdata.GDataEntry._attributes.copy()
class CalendarEventCommentFeed(gdata.GDataFeed, gdata.LinkFinder):
"""A Google Calendar event comments feed flavor of an Atom Feed"""
_tag = gdata.GDataFeed._tag
_namespace = gdata.GDataFeed._namespace
_children = gdata.GDataFeed._children.copy()
_attributes = gdata.GDataFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[CalendarEventCommentEntry])
class ExtendedProperty(gdata.ExtendedProperty):
"""A transparent subclass of gdata.ExtendedProperty added to this module
for backwards compatibility."""
class Reminder(atom.AtomBase):
"""The Google Calendar reminder element"""
_tag = 'reminder'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['absoluteTime'] = 'absolute_time'
_attributes['days'] = 'days'
_attributes['hours'] = 'hours'
_attributes['minutes'] = 'minutes'
_attributes['method'] = 'method'
def __init__(self, absolute_time=None,
days=None, hours=None, minutes=None, method=None,
extension_elements=None,
extension_attributes=None, text=None):
self.absolute_time = absolute_time
if days is not None:
self.days = str(days)
else:
self.days = None
if hours is not None:
self.hours = str(hours)
else:
self.hours = None
if minutes is not None:
self.minutes = str(minutes)
else:
self.minutes = None
self.method = method
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class When(atom.AtomBase):
"""The Google Calendar When element"""
_tag = 'when'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}reminder' % gdata.GDATA_NAMESPACE] = ('reminder', [Reminder])
_attributes['startTime'] = 'start_time'
_attributes['endTime'] = 'end_time'
def __init__(self, start_time=None, end_time=None, reminder=None,
extension_elements=None, extension_attributes=None, text=None):
self.start_time = start_time
self.end_time = end_time
self.reminder = reminder or []
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Recurrence(atom.AtomBase):
"""The Google Calendar Recurrence element"""
_tag = 'recurrence'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
class UriEnumElement(atom.AtomBase):
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, tag, enum_map, attrib_name='value',
extension_elements=None, extension_attributes=None, text=None):
self.tag=tag
self.enum_map=enum_map
self.attrib_name=attrib_name
self.value=None
self.text=text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def findKey(self, value):
res=[item[0] for item in self.enum_map.items() if item[1] == value]
if res is None or len(res) == 0:
return None
return res[0]
def _ConvertElementAttributeToMember(self, attribute, value):
# Special logic to use the enum_map to set the value of the object's value member.
if attribute == self.attrib_name and value != '':
self.value = self.enum_map[value]
return
# Find the attribute in this class's list of attributes.
if self.__class__._attributes.has_key(attribute):
# Find the member of this class which corresponds to the XML attribute
# (lookup in current_class._attributes) and set this member to the
# desired value (using self.__dict__).
setattr(self, self.__class__._attributes[attribute], value)
else:
# The current class doesn't map this attribute, so try to parent class.
atom.ExtensionContainer._ConvertElementAttributeToMember(self,
attribute,
value)
def _AddMembersToElementTree(self, tree):
# Convert the members of this class which are XML child nodes.
# This uses the class's _children dictionary to find the members which
# should become XML child nodes.
member_node_names = [values[0] for tag, values in
self.__class__._children.iteritems()]
for member_name in member_node_names:
member = getattr(self, member_name)
if member is None:
pass
elif isinstance(member, list):
for instance in member:
instance._BecomeChildElement(tree)
else:
member._BecomeChildElement(tree)
# Special logic to set the desired XML attribute.
key = self.findKey(self.value)
if key is not None:
tree.attrib[self.attrib_name]=key
# Convert the members of this class which are XML attributes.
for xml_attribute, member_name in self.__class__._attributes.iteritems():
member = getattr(self, member_name)
if member is not None:
tree.attrib[xml_attribute] = member
# Lastly, call the parent's _AddMembersToElementTree to get any
# extension elements.
atom.ExtensionContainer._AddMembersToElementTree(self, tree)
class AttendeeStatus(UriEnumElement):
"""The Google Calendar attendeeStatus element"""
_tag = 'attendeeStatus'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
attendee_enum = {
'http://schemas.google.com/g/2005#event.accepted' : 'ACCEPTED',
'http://schemas.google.com/g/2005#event.declined' : 'DECLINED',
'http://schemas.google.com/g/2005#event.invited' : 'INVITED',
'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'}
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'attendeeStatus', AttendeeStatus.attendee_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class AttendeeType(UriEnumElement):
"""The Google Calendar attendeeType element"""
_tag = 'attendeeType'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
attendee_type_enum = {
'http://schemas.google.com/g/2005#event.optional' : 'OPTIONAL',
'http://schemas.google.com/g/2005#event.required' : 'REQUIRED' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'attendeeType',
AttendeeType.attendee_type_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,text=text)
class Visibility(UriEnumElement):
"""The Google Calendar Visibility element"""
_tag = 'visibility'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
visibility_enum = {
'http://schemas.google.com/g/2005#event.confidential' : 'CONFIDENTIAL',
'http://schemas.google.com/g/2005#event.default' : 'DEFAULT',
'http://schemas.google.com/g/2005#event.private' : 'PRIVATE',
'http://schemas.google.com/g/2005#event.public' : 'PUBLIC' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'visibility', Visibility.visibility_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Transparency(UriEnumElement):
"""The Google Calendar Transparency element"""
_tag = 'transparency'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
transparency_enum = {
'http://schemas.google.com/g/2005#event.opaque' : 'OPAQUE',
'http://schemas.google.com/g/2005#event.transparent' : 'TRANSPARENT' }
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, tag='transparency',
enum_map=Transparency.transparency_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Comments(atom.AtomBase):
"""The Google Calendar comments element"""
_tag = 'comments'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
gdata.FeedLink)
_attributes['rel'] = 'rel'
def __init__(self, rel=None, feed_link=None, extension_elements=None,
extension_attributes=None, text=None):
self.rel = rel
self.feed_link = feed_link
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class EventStatus(UriEnumElement):
"""The Google Calendar eventStatus element"""
_tag = 'eventStatus'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
status_enum = { 'http://schemas.google.com/g/2005#event.canceled' : 'CANCELED',
'http://schemas.google.com/g/2005#event.confirmed' : 'CONFIRMED',
'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'}
def __init__(self, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, tag='eventStatus',
enum_map=EventStatus.status_enum,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
class Who(UriEnumElement):
"""The Google Calendar Who element"""
_tag = 'who'
_namespace = gdata.GDATA_NAMESPACE
_children = UriEnumElement._children.copy()
_attributes = UriEnumElement._attributes.copy()
_children['{%s}attendeeStatus' % gdata.GDATA_NAMESPACE] = (
'attendee_status', AttendeeStatus)
_children['{%s}attendeeType' % gdata.GDATA_NAMESPACE] = ('attendee_type',
AttendeeType)
_attributes['valueString'] = 'name'
_attributes['email'] = 'email'
relEnum = { 'http://schemas.google.com/g/2005#event.attendee' : 'ATTENDEE',
'http://schemas.google.com/g/2005#event.organizer' : 'ORGANIZER',
'http://schemas.google.com/g/2005#event.performer' : 'PERFORMER',
'http://schemas.google.com/g/2005#event.speaker' : 'SPEAKER',
'http://schemas.google.com/g/2005#message.bcc' : 'BCC',
'http://schemas.google.com/g/2005#message.cc' : 'CC',
'http://schemas.google.com/g/2005#message.from' : 'FROM',
'http://schemas.google.com/g/2005#message.reply-to' : 'REPLY_TO',
'http://schemas.google.com/g/2005#message.to' : 'TO' }
def __init__(self, name=None, email=None, attendee_status=None,
attendee_type=None, rel=None, extension_elements=None,
extension_attributes=None, text=None):
UriEnumElement.__init__(self, 'who', Who.relEnum, attrib_name='rel',
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.name = name
self.email = email
self.attendee_status = attendee_status
self.attendee_type = attendee_type
self.rel = rel
class OriginalEvent(atom.AtomBase):
"""The Google Calendar OriginalEvent element"""
_tag = 'originalEvent'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
# TODO: The when tag used to map to a EntryLink, make sure it should really be a When.
_children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', When)
_attributes['id'] = 'id'
_attributes['href'] = 'href'
def __init__(self, id=None, href=None, when=None,
extension_elements=None, extension_attributes=None, text=None):
self.id = id
self.href = href
self.when = when
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def GetCalendarEventEntryClass():
return CalendarEventEntry
# This class is not completely defined here, because of a circular reference
# in which CalendarEventEntryLink and CalendarEventEntry refer to one another.
class CalendarEventEntryLink(gdata.EntryLink):
"""An entryLink which contains a calendar event entry
Within an event's recurranceExceptions, an entry link
points to a calendar event entry. This class exists
to capture the calendar specific extensions in the entry.
"""
_tag = 'entryLink'
_namespace = gdata.GDATA_NAMESPACE
_children = gdata.EntryLink._children.copy()
_attributes = gdata.EntryLink._attributes.copy()
# The CalendarEventEntryLink should like CalendarEventEntry as a child but
# that class hasn't been defined yet, so we will wait until after defining
# CalendarEventEntry to list it in _children.
class RecurrenceException(atom.AtomBase):
"""The Google Calendar RecurrenceException element"""
_tag = 'recurrenceException'
_namespace = gdata.GDATA_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}entryLink' % gdata.GDATA_NAMESPACE] = ('entry_link',
CalendarEventEntryLink)
_children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event',
OriginalEvent)
_attributes['specialized'] = 'specialized'
def __init__(self, specialized=None, entry_link=None,
original_event=None, extension_elements=None,
extension_attributes=None, text=None):
self.specialized = specialized
self.entry_link = entry_link
self.original_event = original_event
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class SendEventNotifications(atom.AtomBase):
"""The Google Calendar sendEventNotifications element"""
_tag = 'sendEventNotifications'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, extension_elements=None,
value=None, extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class QuickAdd(atom.AtomBase):
"""The Google Calendar quickadd element"""
_tag = 'quickadd'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, extension_elements=None,
value=None, extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
def _TransferToElementTree(self, element_tree):
if self.value:
element_tree.attrib['value'] = self.value
element_tree.tag = GCAL_TEMPLATE % 'quickadd'
atom.AtomBase._TransferToElementTree(self, element_tree)
return element_tree
def _TakeAttributeFromElementTree(self, attribute, element_tree):
if attribute == 'value':
self.value = element_tree.attrib[attribute]
del element_tree.attrib[attribute]
else:
atom.AtomBase._TakeAttributeFromElementTree(self, attribute,
element_tree)
class SyncEvent(atom.AtomBase):
_tag = 'syncEvent'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value='false', extension_elements=None,
extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class UID(atom.AtomBase):
_tag = 'uid'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Sequence(atom.AtomBase):
_tag = 'sequence'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class WebContentGadgetPref(atom.AtomBase):
_tag = 'webContentGadgetPref'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_attributes['name'] = 'name'
_attributes['value'] = 'value'
"""The Google Calendar Web Content Gadget Preferences element"""
def __init__(self, name=None, value=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.value = value
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class WebContent(atom.AtomBase):
_tag = 'webContent'
_namespace = GCAL_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
_children['{%s}webContentGadgetPref' % GCAL_NAMESPACE] = ('gadget_pref',
[WebContentGadgetPref])
_attributes['url'] = 'url'
_attributes['width'] = 'width'
_attributes['height'] = 'height'
def __init__(self, url=None, width=None, height=None, text=None,
gadget_pref=None, extension_elements=None, extension_attributes=None):
self.url = url
self.width = width
self.height = height
self.text = text
self.gadget_pref = gadget_pref or []
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class WebContentLink(atom.Link):
_tag = 'link'
_namespace = atom.ATOM_NAMESPACE
_children = atom.Link._children.copy()
_attributes = atom.Link._attributes.copy()
_children['{%s}webContent' % GCAL_NAMESPACE] = ('web_content', WebContent)
def __init__(self, title=None, href=None, link_type=None,
web_content=None):
atom.Link.__init__(self, rel=WEB_CONTENT_LINK_REL, title=title, href=href,
link_type=link_type)
self.web_content = web_content
class GuestsCanInviteOthers(atom.AtomBase):
"""Indicates whether event attendees may invite others to the event.
This element may only be changed by the organizer of the event. If not
included as part of the event entry, this element will default to true
during a POST request, and will inherit its previous value during a PUT
request.
"""
_tag = 'guestsCanInviteOthers'
_namespace = GCAL_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value='true', *args, **kwargs):
atom.AtomBase.__init__(self, *args, **kwargs)
self.value = value
class GuestsCanSeeGuests(atom.AtomBase):
"""Indicates whether attendees can see other people invited to the event.
The organizer always sees all attendees. Guests always see themselves. This
property affects what attendees see in the event's guest list via both the
Calendar UI and API feeds.
This element may only be changed by the organizer of the event.
If not included as part of the event entry, this element will default to
true during a POST request, and will inherit its previous value during a
PUT request.
"""
_tag = 'guestsCanSeeGuests'
_namespace = GCAL_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value='true', *args, **kwargs):
atom.AtomBase.__init__(self, *args, **kwargs)
self.value = value
class GuestsCanModify(atom.AtomBase):
"""Indicates whether event attendees may modify the original event.
If yes, changes are visible to organizer and other attendees. Otherwise,
any changes made by attendees will be restricted to that attendee's
calendar.
This element may only be changed by the organizer of the event, and may
be set to 'true' only if both gCal:guestsCanInviteOthers and
gCal:guestsCanSeeGuests are set to true in the same PUT/POST request.
Otherwise, request fails with HTTP error code 400 (Bad Request).
If not included as part of the event entry, this element will default to
false during a POST request, and will inherit its previous value during a
PUT request."""
_tag = 'guestsCanModify'
_namespace = GCAL_NAMESPACE
_attributes = atom.AtomBase._attributes.copy()
_attributes['value'] = 'value'
def __init__(self, value='false', *args, **kwargs):
atom.AtomBase.__init__(self, *args, **kwargs)
self.value = value
class CalendarEventEntry(gdata.BatchEntry):
"""A Google Calendar flavor of an Atom Entry """
_tag = gdata.BatchEntry._tag
_namespace = gdata.BatchEntry._namespace
_children = gdata.BatchEntry._children.copy()
_attributes = gdata.BatchEntry._attributes.copy()
# This class also contains WebContentLinks but converting those members
# is handled in a special version of _ConvertElementTreeToMember.
_children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', [Where])
_children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', [When])
_children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', [Who])
_children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = (
'extended_property', [ExtendedProperty])
_children['{%s}visibility' % gdata.GDATA_NAMESPACE] = ('visibility',
Visibility)
_children['{%s}transparency' % gdata.GDATA_NAMESPACE] = ('transparency',
Transparency)
_children['{%s}eventStatus' % gdata.GDATA_NAMESPACE] = ('event_status',
EventStatus)
_children['{%s}recurrence' % gdata.GDATA_NAMESPACE] = ('recurrence',
Recurrence)
_children['{%s}recurrenceException' % gdata.GDATA_NAMESPACE] = (
'recurrence_exception', [RecurrenceException])
_children['{%s}sendEventNotifications' % GCAL_NAMESPACE] = (
'send_event_notifications', SendEventNotifications)
_children['{%s}quickadd' % GCAL_NAMESPACE] = ('quick_add', QuickAdd)
_children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments)
_children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event',
OriginalEvent)
_children['{%s}sequence' % GCAL_NAMESPACE] = ('sequence', Sequence)
_children['{%s}reminder' % gdata.GDATA_NAMESPACE] = ('reminder', [Reminder])
_children['{%s}syncEvent' % GCAL_NAMESPACE] = ('sync_event', SyncEvent)
_children['{%s}uid' % GCAL_NAMESPACE] = ('uid', UID)
_children['{%s}guestsCanInviteOthers' % GCAL_NAMESPACE] = (
'guests_can_invite_others', GuestsCanInviteOthers)
_children['{%s}guestsCanModify' % GCAL_NAMESPACE] = (
'guests_can_modify', GuestsCanModify)
_children['{%s}guestsCanSeeGuests' % GCAL_NAMESPACE] = (
'guests_can_see_guests', GuestsCanSeeGuests)
def __init__(self, author=None, category=None, content=None,
atom_id=None, link=None, published=None,
title=None, updated=None,
transparency=None, comments=None, event_status=None,
send_event_notifications=None, visibility=None,
recurrence=None, recurrence_exception=None,
where=None, when=None, who=None, quick_add=None,
extended_property=None, original_event=None,
batch_operation=None, batch_id=None, batch_status=None,
sequence=None, reminder=None, sync_event=None, uid=None,
guests_can_invite_others=None, guests_can_modify=None,
guests_can_see_guests=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchEntry.__init__(self, author=author, category=category,
content=content,
atom_id=atom_id, link=link, published=published,
batch_operation=batch_operation, batch_id=batch_id,
batch_status=batch_status,
title=title, updated=updated)
self.transparency = transparency
self.comments = comments
self.event_status = event_status
self.send_event_notifications = send_event_notifications
self.visibility = visibility
self.recurrence = recurrence
self.recurrence_exception = recurrence_exception or []
self.where = where or []
self.when = when or []
self.who = who or []
self.quick_add = quick_add
self.extended_property = extended_property or []
self.original_event = original_event
self.sequence = sequence
self.reminder = reminder or []
self.sync_event = sync_event
self.uid = uid
self.text = text
self.guests_can_invite_others = guests_can_invite_others
self.guests_can_modify = guests_can_modify
self.guests_can_see_guests = guests_can_see_guests
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
# We needed to add special logic to _ConvertElementTreeToMember because we
# want to make links with a rel of WEB_CONTENT_LINK_REL into a
# WebContentLink
def _ConvertElementTreeToMember(self, child_tree):
# Special logic to handle Web Content links
if (child_tree.tag == '{%s}link' % atom.ATOM_NAMESPACE and
child_tree.attrib['rel'] == WEB_CONTENT_LINK_REL):
if self.link is None:
self.link = []
self.link.append(atom._CreateClassFromElementTree(WebContentLink,
child_tree))
return
# Find the element's tag in this class's list of child members
if self.__class__._children.has_key(child_tree.tag):
member_name = self.__class__._children[child_tree.tag][0]
member_class = self.__class__._children[child_tree.tag][1]
# If the class member is supposed to contain a list, make sure the
# matching member is set to a list, then append the new member
# instance to the list.
if isinstance(member_class, list):
if getattr(self, member_name) is None:
setattr(self, member_name, [])
getattr(self, member_name).append(atom._CreateClassFromElementTree(
member_class[0], child_tree))
else:
setattr(self, member_name,
atom._CreateClassFromElementTree(member_class, child_tree))
else:
atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree)
def GetWebContentLink(self):
"""Finds the first link with rel set to WEB_CONTENT_REL
Returns:
A gdata.calendar.WebContentLink or none if none of the links had rel
equal to WEB_CONTENT_REL
"""
for a_link in self.link:
if a_link.rel == WEB_CONTENT_LINK_REL:
return a_link
return None
def CalendarEventEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventEntry, xml_string)
def CalendarEventCommentEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventCommentEntry, xml_string)
CalendarEventEntryLink._children = {'{%s}entry' % atom.ATOM_NAMESPACE:
('entry', CalendarEventEntry)}
def CalendarEventEntryLinkFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventEntryLink, xml_string)
class CalendarEventFeed(gdata.BatchFeed, gdata.LinkFinder):
"""A Google Calendar event feed flavor of an Atom Feed"""
_tag = gdata.BatchFeed._tag
_namespace = gdata.BatchFeed._namespace
_children = gdata.BatchFeed._children.copy()
_attributes = gdata.BatchFeed._attributes.copy()
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
[CalendarEventEntry])
_children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone)
def __init__(self, author=None, category=None, contributor=None,
generator=None, icon=None, atom_id=None, link=None, logo=None,
rights=None, subtitle=None, title=None, updated=None, entry=None,
total_results=None, start_index=None, items_per_page=None,
interrupted=None, timezone=None,
extension_elements=None, extension_attributes=None, text=None):
gdata.BatchFeed.__init__(self, author=author, category=category,
contributor=contributor, generator=generator,
icon=icon, atom_id=atom_id, link=link,
logo=logo, rights=rights, subtitle=subtitle,
title=title, updated=updated, entry=entry,
total_results=total_results,
start_index=start_index,
items_per_page=items_per_page,
interrupted=interrupted,
extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
self.timezone = timezone
def CalendarListEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarListEntry, xml_string)
def CalendarAclEntryFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarAclEntry, xml_string)
def CalendarListFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarListFeed, xml_string)
def CalendarAclFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarAclFeed, xml_string)
def CalendarEventFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventFeed, xml_string)
def CalendarEventCommentFeedFromString(xml_string):
return atom.CreateClassFromXMLString(CalendarEventCommentFeed, xml_string)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2006 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""CalendarService extends the GDataService to streamline Google Calendar operations.
CalendarService: Provides methods to query feeds and manipulate items. Extends
GDataService.
DictionaryToParamList: Function which converts a dictionary into a list of
URL arguments (represented as strings). This is a
utility function used in CRUD operations.
"""
__author__ = 'api.vli (Vivian Li)'
import urllib
import gdata
import atom.service
import gdata.service
import gdata.calendar
import atom
DEFAULT_BATCH_URL = ('http://www.google.com/calendar/feeds/default/private'
'/full/batch')
class Error(Exception):
pass
class RequestError(Error):
pass
class CalendarService(gdata.service.GDataService):
"""Client for the Google Calendar service."""
def __init__(self, email=None, password=None, source=None,
server='www.google.com', additional_headers=None, **kwargs):
"""Creates a client for the Google Calendar service.
Args:
email: string (optional) The user's email address, used for
authentication.
password: string (optional) The user's password.
source: string (optional) The name of the user's application.
server: string (optional) The name of the server to which a connection
will be opened. Default value: 'www.google.com'.
**kwargs: The other parameters to pass to gdata.service.GDataService
constructor.
"""
gdata.service.GDataService.__init__(
self, email=email, password=password, service='cl', source=source,
server=server, additional_headers=additional_headers, **kwargs)
def GetCalendarEventFeed(self, uri='/calendar/feeds/default/private/full'):
return self.Get(uri, converter=gdata.calendar.CalendarEventFeedFromString)
def GetCalendarEventEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventEntryFromString)
def GetCalendarListFeed(self, uri='/calendar/feeds/default/allcalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetAllCalendarsFeed(self, uri='/calendar/feeds/default/allcalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetOwnCalendarsFeed(self, uri='/calendar/feeds/default/owncalendars/full'):
return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString)
def GetCalendarListEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarListEntryFromString)
def GetCalendarAclFeed(self, uri='/calendar/feeds/default/acl/full'):
return self.Get(uri, converter=gdata.calendar.CalendarAclFeedFromString)
def GetCalendarAclEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarAclEntryFromString)
def GetCalendarEventCommentFeed(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventCommentFeedFromString)
def GetCalendarEventCommentEntry(self, uri):
return self.Get(uri, converter=gdata.calendar.CalendarEventCommentEntryFromString)
def Query(self, uri, converter=None):
"""Performs a query and returns a resulting feed or entry.
Args:
feed: string The feed which is to be queried
Returns:
On success, a GDataFeed or Entry depending on which is sent from the
server.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
if converter:
result = self.Get(uri, converter=converter)
else:
result = self.Get(uri)
return result
def CalendarQuery(self, query):
if isinstance(query, CalendarEventQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarEventFeedFromString)
elif isinstance(query, CalendarListQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarListFeedFromString)
elif isinstance(query, CalendarEventCommentQuery):
return self.Query(query.ToUri(),
converter=gdata.calendar.CalendarEventCommentFeedFromString)
else:
return self.Query(query.ToUri())
def InsertEvent(self, new_event, insert_uri, url_params=None,
escape_params=True):
"""Adds an event to Google Calendar.
Args:
new_event: atom.Entry or subclass A new event which is to be added to
Google Calendar.
insert_uri: the URL to post new events to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the event created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_event, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventEntryFromString)
def InsertCalendarSubscription(self, calendar, url_params=None,
escape_params=True):
"""Subscribes the authenticated user to the provided calendar.
Args:
calendar: The calendar to which the user should be subscribed.
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the subscription created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = '/calendar/feeds/default/allcalendars/full'
return self.Post(calendar, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
def InsertCalendar(self, new_calendar, url_params=None,
escape_params=True):
"""Creates a new calendar.
Args:
new_calendar: The calendar to be created
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the calendar created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
insert_uri = '/calendar/feeds/default/owncalendars/full'
response = self.Post(new_calendar, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
return response
def UpdateCalendar(self, calendar, url_params=None,
escape_params=True):
"""Updates a calendar.
Args:
calendar: The calendar which should be updated
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the calendar created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
update_uri = calendar.GetEditLink().href
response = self.Put(data=calendar, uri=update_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarListEntryFromString)
return response
def InsertAclEntry(self, new_entry, insert_uri, url_params=None,
escape_params=True):
"""Adds an ACL entry (rule) to Google Calendar.
Args:
new_entry: atom.Entry or subclass A new ACL entry which is to be added to
Google Calendar.
insert_uri: the URL to post new entries to the ACL feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the ACL entry created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_entry, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarAclEntryFromString)
def InsertEventComment(self, new_entry, insert_uri, url_params=None,
escape_params=True):
"""Adds an entry to Google Calendar.
Args:
new_entry: atom.Entry or subclass A new entry which is to be added to
Google Calendar.
insert_uri: the URL to post new entrys to the feed
url_params: dict (optional) Additional URL parameters to be included
in the insertion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful insert, an entry containing the comment created
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Post(new_entry, insert_uri, url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventCommentEntryFromString)
def _RemoveStandardUrlPrefix(self, url):
url_prefix = 'http://%s/' % self.server
if url.startswith(url_prefix):
return url[len(url_prefix) - 1:]
return url
def DeleteEvent(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an event with the specified ID from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/default/private/full/abx'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
edit_uri = self._RemoveStandardUrlPrefix(edit_uri)
return self.Delete('%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def DeleteAclEntry(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes an ACL entry at the given edit_uri from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, a httplib.HTTPResponse containing the server's
response to the DELETE request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
edit_uri = self._RemoveStandardUrlPrefix(edit_uri)
return self.Delete('%s' % edit_uri,
url_params=url_params, escape_params=escape_params)
def DeleteCalendarEntry(self, edit_uri, extra_headers=None,
url_params=None, escape_params=True):
"""Removes a calendar entry at the given edit_uri from Google Calendar.
Args:
edit_uri: string The edit URL of the entry to be deleted. Example:
'http://www.google.com/calendar/feeds/default/allcalendars/abcdef@group.calendar.google.com'
url_params: dict (optional) Additional URL parameters to be included
in the deletion request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful delete, True is returned
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
return self.Delete(edit_uri, url_params=url_params,
escape_params=escape_params)
def UpdateEvent(self, edit_uri, updated_event, url_params=None,
escape_params=True):
"""Updates an existing event.
Args:
edit_uri: string The edit link URI for the element being updated
updated_event: string, atom.Entry, or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
edit_uri = self._RemoveStandardUrlPrefix(edit_uri)
return self.Put(updated_event, '%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarEventEntryFromString)
def UpdateAclEntry(self, edit_uri, updated_rule, url_params=None,
escape_params=True):
"""Updates an existing ACL rule.
Args:
edit_uri: string The edit link URI for the element being updated
updated_rule: string, atom.Entry, or subclass containing
the Atom Entry which will replace the event which is
stored at the edit_url
url_params: dict (optional) Additional URL parameters to be included
in the update request.
escape_params: boolean (optional) If true, the url_parameters will be
escaped before they are included in the request.
Returns:
On successful update, a httplib.HTTPResponse containing the server's
response to the PUT request.
On failure, a RequestError is raised of the form:
{'status': HTTP status code from server,
'reason': HTTP reason from the server,
'body': HTTP body of the server's response}
"""
edit_uri = self._RemoveStandardUrlPrefix(edit_uri)
return self.Put(updated_rule, '%s' % edit_uri,
url_params=url_params,
escape_params=escape_params,
converter=gdata.calendar.CalendarAclEntryFromString)
def ExecuteBatch(self, batch_feed, url,
converter=gdata.calendar.CalendarEventFeedFromString):
"""Sends a batch request feed to the server.
The batch request needs to be sent to the batch URL for a particular
calendar. You can find the URL by calling GetBatchLink().href on the
CalendarEventFeed.
Args:
batch_feed: gdata.calendar.CalendarEventFeed A feed containing batch
request entries. Each entry contains the operation to be performed
on the data contained in the entry. For example an entry with an
operation type of insert will be used as if the individual entry
had been inserted.
url: str The batch URL for the Calendar to which these operations should
be applied.
converter: Function (optional) The function used to convert the server's
response to an object. The default value is
CalendarEventFeedFromString.
Returns:
The results of the batch request's execution on the server. If the
default converter is used, this is stored in a CalendarEventFeed.
"""
return self.Post(batch_feed, url, converter=converter)
class CalendarEventQuery(gdata.service.Query):
def __init__(self, user='default', visibility='private', projection='full',
text_query=None, params=None, categories=None):
gdata.service.Query.__init__(self,
feed='http://www.google.com/calendar/feeds/%s/%s/%s' % (
urllib.quote(user),
urllib.quote(visibility),
urllib.quote(projection)),
text_query=text_query, params=params, categories=categories)
def _GetStartMin(self):
if 'start-min' in self.keys():
return self['start-min']
else:
return None
def _SetStartMin(self, val):
self['start-min'] = val
start_min = property(_GetStartMin, _SetStartMin,
doc="""The start-min query parameter""")
def _GetStartMax(self):
if 'start-max' in self.keys():
return self['start-max']
else:
return None
def _SetStartMax(self, val):
self['start-max'] = val
start_max = property(_GetStartMax, _SetStartMax,
doc="""The start-max query parameter""")
def _GetOrderBy(self):
if 'orderby' in self.keys():
return self['orderby']
else:
return None
def _SetOrderBy(self, val):
if val is not 'lastmodified' and val is not 'starttime':
raise Error, "Order By must be either 'lastmodified' or 'starttime'"
self['orderby'] = val
orderby = property(_GetOrderBy, _SetOrderBy,
doc="""The orderby query parameter""")
def _GetSortOrder(self):
if 'sortorder' in self.keys():
return self['sortorder']
else:
return None
def _SetSortOrder(self, val):
if (val is not 'ascending' and val is not 'descending'
and val is not 'a' and val is not 'd' and val is not 'ascend'
and val is not 'descend'):
raise Error, "Sort order must be either ascending, ascend, " + (
"a or descending, descend, or d")
self['sortorder'] = val
sortorder = property(_GetSortOrder, _SetSortOrder,
doc="""The sortorder query parameter""")
def _GetSingleEvents(self):
if 'singleevents' in self.keys():
return self['singleevents']
else:
return None
def _SetSingleEvents(self, val):
self['singleevents'] = val
singleevents = property(_GetSingleEvents, _SetSingleEvents,
doc="""The singleevents query parameter""")
def _GetFutureEvents(self):
if 'futureevents' in self.keys():
return self['futureevents']
else:
return None
def _SetFutureEvents(self, val):
self['futureevents'] = val
futureevents = property(_GetFutureEvents, _SetFutureEvents,
doc="""The futureevents query parameter""")
def _GetRecurrenceExpansionStart(self):
if 'recurrence-expansion-start' in self.keys():
return self['recurrence-expansion-start']
else:
return None
def _SetRecurrenceExpansionStart(self, val):
self['recurrence-expansion-start'] = val
recurrence_expansion_start = property(_GetRecurrenceExpansionStart,
_SetRecurrenceExpansionStart,
doc="""The recurrence-expansion-start query parameter""")
def _GetRecurrenceExpansionEnd(self):
if 'recurrence-expansion-end' in self.keys():
return self['recurrence-expansion-end']
else:
return None
def _SetRecurrenceExpansionEnd(self, val):
self['recurrence-expansion-end'] = val
recurrence_expansion_end = property(_GetRecurrenceExpansionEnd,
_SetRecurrenceExpansionEnd,
doc="""The recurrence-expansion-end query parameter""")
def _SetTimezone(self, val):
self['ctz'] = val
def _GetTimezone(self):
if 'ctz' in self.keys():
return self['ctz']
else:
return None
ctz = property(_GetTimezone, _SetTimezone,
doc="""The ctz query parameter which sets report time on the server.""")
class CalendarListQuery(gdata.service.Query):
"""Queries the Google Calendar meta feed"""
def __init__(self, userId=None, text_query=None,
params=None, categories=None):
if userId is None:
userId = 'default'
gdata.service.Query.__init__(self, feed='http://www.google.com/calendar/feeds/'
+userId,
text_query=text_query, params=params,
categories=categories)
class CalendarEventCommentQuery(gdata.service.Query):
"""Queries the Google Calendar event comments feed"""
def __init__(self, feed=None):
gdata.service.Query.__init__(self, feed=feed)
| Python |
#!/usr/bin/python
#
# Copyright (C) 2009 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Contains the data classes of the Geography Extension"""
__author__ = 'j.s@google.com (Jeff Scudder)'
import atom.core
GEORSS_TEMPLATE = '{http://www.georss.org/georss/}%s'
GML_TEMPLATE = '{http://www.opengis.net/gml/}%s'
GEO_TEMPLATE = '{http://www.w3.org/2003/01/geo/wgs84_pos#/}%s'
class GeoLat(atom.core.XmlElement):
"""Describes a W3C latitude."""
_qname = GEO_TEMPLATE % 'lat'
class GeoLong(atom.core.XmlElement):
"""Describes a W3C longitude."""
_qname = GEO_TEMPLATE % 'long'
class GeoRssBox(atom.core.XmlElement):
"""Describes a geographical region."""
_qname = GEORSS_TEMPLATE % 'box'
class GeoRssPoint(atom.core.XmlElement):
"""Describes a geographical location."""
_qname = GEORSS_TEMPLATE % 'point'
class GmlLowerCorner(atom.core.XmlElement):
"""Describes a lower corner of a region."""
_qname = GML_TEMPLATE % 'lowerCorner'
class GmlPos(atom.core.XmlElement):
"""Describes a latitude and longitude."""
_qname = GML_TEMPLATE % 'pos'
class GmlPoint(atom.core.XmlElement):
"""Describes a particular geographical point."""
_qname = GML_TEMPLATE % 'Point'
pos = GmlPos
class GmlUpperCorner(atom.core.XmlElement):
"""Describes an upper corner of a region."""
_qname = GML_TEMPLATE % 'upperCorner'
class GmlEnvelope(atom.core.XmlElement):
"""Describes a Gml geographical region."""
_qname = GML_TEMPLATE % 'Envelope'
lower_corner = GmlLowerCorner
upper_corner = GmlUpperCorner
class GeoRssWhere(atom.core.XmlElement):
"""Describes a geographical location or region."""
_qname = GEORSS_TEMPLATE % 'where'
Point = GmlPoint
Envelope = GmlEnvelope
class W3CPoint(atom.core.XmlElement):
"""Describes a W3C geographical location."""
_qname = GEO_TEMPLATE % 'Point'
long = GeoLong
lat = GeoLat
| Python |
# -*-*- encoding: utf-8 -*-*-
#
# This is gdata.photos.geo, implementing geological positioning in gdata structures
#
# $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $
#
# Copyright 2007 Håvard Gulldahl
# Portions copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Picasa Web Albums uses the georss and gml namespaces for
elements defined in the GeoRSS and Geography Markup Language specifications.
Specifically, Picasa Web Albums uses the following elements:
georss:where
gml:Point
gml:pos
http://code.google.com/apis/picasaweb/reference.html#georss_reference
Picasa Web Albums also accepts geographic-location data in two other formats:
W3C format and plain-GeoRSS (without GML) format.
"""
#
#Over the wire, the Picasa Web Albums only accepts and sends the
#elements mentioned above, but this module will let you seamlessly convert
#between the different formats (TODO 2007-10-18 hg)
__author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: api chokes on non-ascii chars in __author__
__license__ = 'Apache License v2'
import atom
import gdata
GEO_NAMESPACE = 'http://www.w3.org/2003/01/geo/wgs84_pos#'
GML_NAMESPACE = 'http://www.opengis.net/gml'
GEORSS_NAMESPACE = 'http://www.georss.org/georss'
class GeoBaseElement(atom.AtomBase):
"""Base class for elements.
To add new elements, you only need to add the element tag name to self._tag
and the namespace to self._namespace
"""
_tag = ''
_namespace = GML_NAMESPACE
_children = atom.AtomBase._children.copy()
_attributes = atom.AtomBase._attributes.copy()
def __init__(self, name=None, extension_elements=None,
extension_attributes=None, text=None):
self.name = name
self.text = text
self.extension_elements = extension_elements or []
self.extension_attributes = extension_attributes or {}
class Pos(GeoBaseElement):
"""(string) Specifies a latitude and longitude, separated by a space,
e.g. `35.669998 139.770004'"""
_tag = 'pos'
def PosFromString(xml_string):
return atom.CreateClassFromXMLString(Pos, xml_string)
class Point(GeoBaseElement):
"""(container) Specifies a particular geographical point, by means of
a <gml:pos> element."""
_tag = 'Point'
_children = atom.AtomBase._children.copy()
_children['{%s}pos' % GML_NAMESPACE] = ('pos', Pos)
def __init__(self, pos=None, extension_elements=None, extension_attributes=None, text=None):
GeoBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
if pos is None:
pos = Pos()
self.pos=pos
def PointFromString(xml_string):
return atom.CreateClassFromXMLString(Point, xml_string)
class Where(GeoBaseElement):
"""(container) Specifies a geographical location or region.
A container element, containing a single <gml:Point> element.
(Not to be confused with <gd:where>.)
Note that the (only) child attribute, .Point, is title-cased.
This reflects the names of elements in the xml stream
(principle of least surprise).
As a convenience, you can get a tuple of (lat, lon) with Where.location(),
and set the same data with Where.setLocation( (lat, lon) ).
Similarly, there are methods to set and get only latitude and longitude.
"""
_tag = 'where'
_namespace = GEORSS_NAMESPACE
_children = atom.AtomBase._children.copy()
_children['{%s}Point' % GML_NAMESPACE] = ('Point', Point)
def __init__(self, point=None, extension_elements=None, extension_attributes=None, text=None):
GeoBaseElement.__init__(self, extension_elements=extension_elements,
extension_attributes=extension_attributes,
text=text)
if point is None:
point = Point()
self.Point=point
def location(self):
"(float, float) Return Where.Point.pos.text as a (lat,lon) tuple"
try:
return tuple([float(z) for z in self.Point.pos.text.split(' ')])
except AttributeError:
return tuple()
def set_location(self, latlon):
"""(bool) Set Where.Point.pos.text from a (lat,lon) tuple.
Arguments:
lat (float): The latitude in degrees, from -90.0 to 90.0
lon (float): The longitude in degrees, from -180.0 to 180.0
Returns True on success.
"""
assert(isinstance(latlon[0], float))
assert(isinstance(latlon[1], float))
try:
self.Point.pos.text = "%s %s" % (latlon[0], latlon[1])
return True
except AttributeError:
return False
def latitude(self):
"(float) Get the latitude value of the geo-tag. See also .location()"
lat, lon = self.location()
return lat
def longitude(self):
"(float) Get the longtitude value of the geo-tag. See also .location()"
lat, lon = self.location()
return lon
longtitude = longitude
def set_latitude(self, lat):
"""(bool) Set the latitude value of the geo-tag.
Args:
lat (float): The new latitude value
See also .set_location()
"""
_lat, lon = self.location()
return self.set_location(lat, lon)
def set_longitude(self, lon):
"""(bool) Set the longtitude value of the geo-tag.
Args:
lat (float): The new latitude value
See also .set_location()
"""
lat, _lon = self.location()
return self.set_location(lat, lon)
set_longtitude = set_longitude
def WhereFromString(xml_string):
return atom.CreateClassFromXMLString(Where, xml_string)
| Python |
#!/usr/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 |
#
# 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 |
#
# 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 |
#
# 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 |
"""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 |
"""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 |
"""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 |
#
# 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 |
#
# 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 |
#
# 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 |
#
# 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 |
#
# 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 |
"""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 |
#
# 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 |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.