Add existing GAM 3.21 code

This commit is contained in:
Jay Lee
2014-06-28 10:14:05 -04:00
parent 8a904a81f5
commit d0356796e9
486 changed files with 158994 additions and 0 deletions

View File

@@ -0,0 +1,269 @@
#!/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)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,654 @@
#!/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'
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'
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, 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(self):
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_edit_media_link(self):
"""Extracts the Resource's resumable update link.
Returns:
A gdata.data.FeedLink object.
"""
for feed_link in self.feed_link:
if feed_link.rel == RESUMABLE_EDIT_MEDIA_LINK_REL:
return feed_link
return None
GetRevisionsFeedLink = get_revisions_feed_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 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]

View File

@@ -0,0 +1,618 @@
#!/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)