mirror of
https://github.com/GAM-team/GAM.git
synced 2026-06-29 18:31:38 +00:00
Add existing GAM 3.21 code
This commit is contained in:
526
gdata/apps/__init__.py
Normal file
526
gdata/apps/__init__.py
Normal file
@@ -0,0 +1,526 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright (C) 2007 SIOS Technology, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Contains objects used with Google Apps."""
|
||||
|
||||
__author__ = 'tmatsuo@sios.com (Takashi MATSUO)'
|
||||
|
||||
|
||||
import atom
|
||||
import gdata
|
||||
|
||||
|
||||
# XML namespaces which are often used in Google Apps entity.
|
||||
APPS_NAMESPACE = 'http://schemas.google.com/apps/2006'
|
||||
APPS_TEMPLATE = '{http://schemas.google.com/apps/2006}%s'
|
||||
|
||||
|
||||
class EmailList(atom.AtomBase):
|
||||
"""The Google Apps EmailList element"""
|
||||
|
||||
_tag = 'emailList'
|
||||
_namespace = APPS_NAMESPACE
|
||||
_children = atom.AtomBase._children.copy()
|
||||
_attributes = atom.AtomBase._attributes.copy()
|
||||
_attributes['name'] = 'name'
|
||||
|
||||
def __init__(self, name=None, extension_elements=None,
|
||||
extension_attributes=None, text=None):
|
||||
self.name = name
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
def EmailListFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(EmailList, xml_string)
|
||||
|
||||
|
||||
class Who(atom.AtomBase):
|
||||
"""The Google Apps Who element"""
|
||||
|
||||
_tag = 'who'
|
||||
_namespace = gdata.GDATA_NAMESPACE
|
||||
_children = atom.AtomBase._children.copy()
|
||||
_attributes = atom.AtomBase._attributes.copy()
|
||||
_attributes['rel'] = 'rel'
|
||||
_attributes['email'] = 'email'
|
||||
|
||||
def __init__(self, rel=None, email=None, extension_elements=None,
|
||||
extension_attributes=None, text=None):
|
||||
self.rel = rel
|
||||
self.email = email
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
def WhoFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(Who, xml_string)
|
||||
|
||||
|
||||
class Login(atom.AtomBase):
|
||||
"""The Google Apps Login element"""
|
||||
|
||||
_tag = 'login'
|
||||
_namespace = APPS_NAMESPACE
|
||||
_children = atom.AtomBase._children.copy()
|
||||
_attributes = atom.AtomBase._attributes.copy()
|
||||
_attributes['userName'] = 'user_name'
|
||||
_attributes['password'] = 'password'
|
||||
_attributes['suspended'] = 'suspended'
|
||||
_attributes['admin'] = 'admin'
|
||||
_attributes['changePasswordAtNextLogin'] = 'change_password'
|
||||
_attributes['agreedToTerms'] = 'agreed_to_terms'
|
||||
_attributes['ipWhitelisted'] = 'ip_whitelisted'
|
||||
_attributes['hashFunctionName'] = 'hash_function_name'
|
||||
|
||||
def __init__(self, user_name=None, password=None, suspended=None,
|
||||
ip_whitelisted=None, hash_function_name=None,
|
||||
admin=None, change_password=None, agreed_to_terms=None,
|
||||
extension_elements=None, extension_attributes=None,
|
||||
text=None):
|
||||
self.user_name = user_name
|
||||
self.password = password
|
||||
self.suspended = suspended
|
||||
self.admin = admin
|
||||
self.change_password = change_password
|
||||
self.agreed_to_terms = agreed_to_terms
|
||||
self.ip_whitelisted = ip_whitelisted
|
||||
self.hash_function_name = hash_function_name
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def LoginFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(Login, xml_string)
|
||||
|
||||
|
||||
class Quota(atom.AtomBase):
|
||||
"""The Google Apps Quota element"""
|
||||
|
||||
_tag = 'quota'
|
||||
_namespace = APPS_NAMESPACE
|
||||
_children = atom.AtomBase._children.copy()
|
||||
_attributes = atom.AtomBase._attributes.copy()
|
||||
_attributes['limit'] = 'limit'
|
||||
|
||||
def __init__(self, limit=None, extension_elements=None,
|
||||
extension_attributes=None, text=None):
|
||||
self.limit = limit
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def QuotaFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(Quota, xml_string)
|
||||
|
||||
|
||||
class Name(atom.AtomBase):
|
||||
"""The Google Apps Name element"""
|
||||
|
||||
_tag = 'name'
|
||||
_namespace = APPS_NAMESPACE
|
||||
_children = atom.AtomBase._children.copy()
|
||||
_attributes = atom.AtomBase._attributes.copy()
|
||||
_attributes['familyName'] = 'family_name'
|
||||
_attributes['givenName'] = 'given_name'
|
||||
|
||||
def __init__(self, family_name=None, given_name=None,
|
||||
extension_elements=None, extension_attributes=None, text=None):
|
||||
self.family_name = family_name
|
||||
self.given_name = given_name
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def NameFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(Name, xml_string)
|
||||
|
||||
|
||||
class Nickname(atom.AtomBase):
|
||||
"""The Google Apps Nickname element"""
|
||||
|
||||
_tag = 'nickname'
|
||||
_namespace = APPS_NAMESPACE
|
||||
_children = atom.AtomBase._children.copy()
|
||||
_attributes = atom.AtomBase._attributes.copy()
|
||||
_attributes['name'] = 'name'
|
||||
|
||||
def __init__(self, name=None,
|
||||
extension_elements=None, extension_attributes=None, text=None):
|
||||
self.name = name
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def NicknameFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(Nickname, xml_string)
|
||||
|
||||
|
||||
class NicknameEntry(gdata.GDataEntry):
|
||||
"""A Google Apps flavor of an Atom Entry for Nickname"""
|
||||
|
||||
_tag = 'entry'
|
||||
_namespace = atom.ATOM_NAMESPACE
|
||||
_children = gdata.GDataEntry._children.copy()
|
||||
_attributes = gdata.GDataEntry._attributes.copy()
|
||||
_children['{%s}login' % APPS_NAMESPACE] = ('login', Login)
|
||||
_children['{%s}nickname' % APPS_NAMESPACE] = ('nickname', Nickname)
|
||||
|
||||
def __init__(self, author=None, category=None, content=None,
|
||||
atom_id=None, link=None, published=None,
|
||||
title=None, updated=None,
|
||||
login=None, nickname=None,
|
||||
extended_property=None,
|
||||
extension_elements=None, extension_attributes=None, text=None):
|
||||
|
||||
gdata.GDataEntry.__init__(self, author=author, category=category,
|
||||
content=content,
|
||||
atom_id=atom_id, link=link, published=published,
|
||||
title=title, updated=updated)
|
||||
self.login = login
|
||||
self.nickname = nickname
|
||||
self.extended_property = extended_property or []
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def NicknameEntryFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(NicknameEntry, xml_string)
|
||||
|
||||
|
||||
class NicknameFeed(gdata.GDataFeed, gdata.LinkFinder):
|
||||
"""A Google Apps Nickname feed flavor of an Atom Feed"""
|
||||
|
||||
_tag = 'feed'
|
||||
_namespace = atom.ATOM_NAMESPACE
|
||||
_children = gdata.GDataFeed._children.copy()
|
||||
_attributes = gdata.GDataFeed._attributes.copy()
|
||||
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [NicknameEntry])
|
||||
|
||||
def __init__(self, author=None, category=None, contributor=None,
|
||||
generator=None, icon=None, atom_id=None, link=None, logo=None,
|
||||
rights=None, subtitle=None, title=None, updated=None,
|
||||
entry=None, total_results=None, start_index=None,
|
||||
items_per_page=None, extension_elements=None,
|
||||
extension_attributes=None, text=None):
|
||||
gdata.GDataFeed.__init__(self, author=author, category=category,
|
||||
contributor=contributor, generator=generator,
|
||||
icon=icon, atom_id=atom_id, link=link,
|
||||
logo=logo, rights=rights, subtitle=subtitle,
|
||||
title=title, updated=updated, entry=entry,
|
||||
total_results=total_results,
|
||||
start_index=start_index,
|
||||
items_per_page=items_per_page,
|
||||
extension_elements=extension_elements,
|
||||
extension_attributes=extension_attributes,
|
||||
text=text)
|
||||
|
||||
|
||||
def NicknameFeedFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(NicknameFeed, xml_string)
|
||||
|
||||
|
||||
class UserEntry(gdata.GDataEntry):
|
||||
"""A Google Apps flavor of an Atom Entry"""
|
||||
|
||||
_tag = 'entry'
|
||||
_namespace = atom.ATOM_NAMESPACE
|
||||
_children = gdata.GDataEntry._children.copy()
|
||||
_attributes = gdata.GDataEntry._attributes.copy()
|
||||
_children['{%s}login' % APPS_NAMESPACE] = ('login', Login)
|
||||
_children['{%s}name' % APPS_NAMESPACE] = ('name', Name)
|
||||
_children['{%s}quota' % APPS_NAMESPACE] = ('quota', Quota)
|
||||
# This child may already be defined in GDataEntry, confirm before removing.
|
||||
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
|
||||
[gdata.FeedLink])
|
||||
_children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who)
|
||||
|
||||
def __init__(self, author=None, category=None, content=None,
|
||||
atom_id=None, link=None, published=None,
|
||||
title=None, updated=None,
|
||||
login=None, name=None, quota=None, who=None, feed_link=None,
|
||||
extended_property=None,
|
||||
extension_elements=None, extension_attributes=None, text=None):
|
||||
|
||||
gdata.GDataEntry.__init__(self, author=author, category=category,
|
||||
content=content,
|
||||
atom_id=atom_id, link=link, published=published,
|
||||
title=title, updated=updated)
|
||||
self.login = login
|
||||
self.name = name
|
||||
self.quota = quota
|
||||
self.who = who
|
||||
self.feed_link = feed_link or []
|
||||
self.extended_property = extended_property or []
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def UserEntryFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(UserEntry, xml_string)
|
||||
|
||||
|
||||
class UserFeed(gdata.GDataFeed, gdata.LinkFinder):
|
||||
"""A Google Apps User feed flavor of an Atom Feed"""
|
||||
|
||||
_tag = 'feed'
|
||||
_namespace = atom.ATOM_NAMESPACE
|
||||
_children = gdata.GDataFeed._children.copy()
|
||||
_attributes = gdata.GDataFeed._attributes.copy()
|
||||
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [UserEntry])
|
||||
|
||||
def __init__(self, author=None, category=None, contributor=None,
|
||||
generator=None, icon=None, atom_id=None, link=None, logo=None,
|
||||
rights=None, subtitle=None, title=None, updated=None,
|
||||
entry=None, total_results=None, start_index=None,
|
||||
items_per_page=None, extension_elements=None,
|
||||
extension_attributes=None, text=None):
|
||||
gdata.GDataFeed.__init__(self, author=author, category=category,
|
||||
contributor=contributor, generator=generator,
|
||||
icon=icon, atom_id=atom_id, link=link,
|
||||
logo=logo, rights=rights, subtitle=subtitle,
|
||||
title=title, updated=updated, entry=entry,
|
||||
total_results=total_results,
|
||||
start_index=start_index,
|
||||
items_per_page=items_per_page,
|
||||
extension_elements=extension_elements,
|
||||
extension_attributes=extension_attributes,
|
||||
text=text)
|
||||
|
||||
|
||||
def UserFeedFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(UserFeed, xml_string)
|
||||
|
||||
|
||||
class EmailListEntry(gdata.GDataEntry):
|
||||
"""A Google Apps EmailList flavor of an Atom Entry"""
|
||||
|
||||
_tag = 'entry'
|
||||
_namespace = atom.ATOM_NAMESPACE
|
||||
_children = gdata.GDataEntry._children.copy()
|
||||
_attributes = gdata.GDataEntry._attributes.copy()
|
||||
_children['{%s}emailList' % APPS_NAMESPACE] = ('email_list', EmailList)
|
||||
# Might be able to remove this _children entry.
|
||||
_children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link',
|
||||
[gdata.FeedLink])
|
||||
|
||||
def __init__(self, author=None, category=None, content=None,
|
||||
atom_id=None, link=None, published=None,
|
||||
title=None, updated=None,
|
||||
email_list=None, feed_link=None,
|
||||
extended_property=None,
|
||||
extension_elements=None, extension_attributes=None, text=None):
|
||||
|
||||
gdata.GDataEntry.__init__(self, author=author, category=category,
|
||||
content=content,
|
||||
atom_id=atom_id, link=link, published=published,
|
||||
title=title, updated=updated)
|
||||
self.email_list = email_list
|
||||
self.feed_link = feed_link or []
|
||||
self.extended_property = extended_property or []
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def EmailListEntryFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(EmailListEntry, xml_string)
|
||||
|
||||
|
||||
class EmailListFeed(gdata.GDataFeed, gdata.LinkFinder):
|
||||
"""A Google Apps EmailList feed flavor of an Atom Feed"""
|
||||
|
||||
_tag = 'feed'
|
||||
_namespace = atom.ATOM_NAMESPACE
|
||||
_children = gdata.GDataFeed._children.copy()
|
||||
_attributes = gdata.GDataFeed._attributes.copy()
|
||||
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [EmailListEntry])
|
||||
|
||||
def __init__(self, author=None, category=None, contributor=None,
|
||||
generator=None, icon=None, atom_id=None, link=None, logo=None,
|
||||
rights=None, subtitle=None, title=None, updated=None,
|
||||
entry=None, total_results=None, start_index=None,
|
||||
items_per_page=None, extension_elements=None,
|
||||
extension_attributes=None, text=None):
|
||||
gdata.GDataFeed.__init__(self, author=author, category=category,
|
||||
contributor=contributor, generator=generator,
|
||||
icon=icon, atom_id=atom_id, link=link,
|
||||
logo=logo, rights=rights, subtitle=subtitle,
|
||||
title=title, updated=updated, entry=entry,
|
||||
total_results=total_results,
|
||||
start_index=start_index,
|
||||
items_per_page=items_per_page,
|
||||
extension_elements=extension_elements,
|
||||
extension_attributes=extension_attributes,
|
||||
text=text)
|
||||
|
||||
|
||||
def EmailListFeedFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(EmailListFeed, xml_string)
|
||||
|
||||
|
||||
class EmailListRecipientEntry(gdata.GDataEntry):
|
||||
"""A Google Apps EmailListRecipient flavor of an Atom Entry"""
|
||||
|
||||
_tag = 'entry'
|
||||
_namespace = atom.ATOM_NAMESPACE
|
||||
_children = gdata.GDataEntry._children.copy()
|
||||
_attributes = gdata.GDataEntry._attributes.copy()
|
||||
_children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who)
|
||||
|
||||
def __init__(self, author=None, category=None, content=None,
|
||||
atom_id=None, link=None, published=None,
|
||||
title=None, updated=None,
|
||||
who=None,
|
||||
extended_property=None,
|
||||
extension_elements=None, extension_attributes=None, text=None):
|
||||
|
||||
gdata.GDataEntry.__init__(self, author=author, category=category,
|
||||
content=content,
|
||||
atom_id=atom_id, link=link, published=published,
|
||||
title=title, updated=updated)
|
||||
self.who = who
|
||||
self.extended_property = extended_property or []
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def EmailListRecipientEntryFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(EmailListRecipientEntry, xml_string)
|
||||
|
||||
|
||||
class EmailListRecipientFeed(gdata.GDataFeed, gdata.LinkFinder):
|
||||
"""A Google Apps EmailListRecipient feed flavor of an Atom Feed"""
|
||||
|
||||
_tag = 'feed'
|
||||
_namespace = atom.ATOM_NAMESPACE
|
||||
_children = gdata.GDataFeed._children.copy()
|
||||
_attributes = gdata.GDataFeed._attributes.copy()
|
||||
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry',
|
||||
[EmailListRecipientEntry])
|
||||
|
||||
def __init__(self, author=None, category=None, contributor=None,
|
||||
generator=None, icon=None, atom_id=None, link=None, logo=None,
|
||||
rights=None, subtitle=None, title=None, updated=None,
|
||||
entry=None, total_results=None, start_index=None,
|
||||
items_per_page=None, extension_elements=None,
|
||||
extension_attributes=None, text=None):
|
||||
gdata.GDataFeed.__init__(self, author=author, category=category,
|
||||
contributor=contributor, generator=generator,
|
||||
icon=icon, atom_id=atom_id, link=link,
|
||||
logo=logo, rights=rights, subtitle=subtitle,
|
||||
title=title, updated=updated, entry=entry,
|
||||
total_results=total_results,
|
||||
start_index=start_index,
|
||||
items_per_page=items_per_page,
|
||||
extension_elements=extension_elements,
|
||||
extension_attributes=extension_attributes,
|
||||
text=text)
|
||||
|
||||
|
||||
def EmailListRecipientFeedFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(EmailListRecipientFeed, xml_string)
|
||||
|
||||
|
||||
class Property(atom.AtomBase):
|
||||
"""The Google Apps Property element"""
|
||||
|
||||
_tag = 'property'
|
||||
_namespace = APPS_NAMESPACE
|
||||
_children = atom.AtomBase._children.copy()
|
||||
_attributes = atom.AtomBase._attributes.copy()
|
||||
_attributes['name'] = 'name'
|
||||
_attributes['value'] = 'value'
|
||||
|
||||
def __init__(self, name=None, value=None, extension_elements=None,
|
||||
extension_attributes=None, text=None):
|
||||
self.name = name
|
||||
self.value = value
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def PropertyFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(Property, xml_string)
|
||||
|
||||
|
||||
class PropertyEntry(gdata.GDataEntry):
|
||||
"""A Google Apps Property flavor of an Atom Entry"""
|
||||
|
||||
_tag = 'entry'
|
||||
_namespace = atom.ATOM_NAMESPACE
|
||||
_children = gdata.GDataEntry._children.copy()
|
||||
_attributes = gdata.GDataEntry._attributes.copy()
|
||||
_children['{%s}property' % APPS_NAMESPACE] = ('property', [Property])
|
||||
|
||||
def __init__(self, author=None, category=None, content=None,
|
||||
atom_id=None, link=None, published=None,
|
||||
title=None, updated=None,
|
||||
property=None,
|
||||
extended_property=None,
|
||||
extension_elements=None, extension_attributes=None, text=None):
|
||||
|
||||
gdata.GDataEntry.__init__(self, author=author, category=category,
|
||||
content=content,
|
||||
atom_id=atom_id, link=link, published=published,
|
||||
title=title, updated=updated)
|
||||
self.property = property
|
||||
self.extended_property = extended_property or []
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def PropertyEntryFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(PropertyEntry, xml_string)
|
||||
|
||||
class PropertyFeed(gdata.GDataFeed, gdata.LinkFinder):
|
||||
"""A Google Apps Property feed flavor of an Atom Feed"""
|
||||
|
||||
_tag = 'feed'
|
||||
_namespace = atom.ATOM_NAMESPACE
|
||||
_children = gdata.GDataFeed._children.copy()
|
||||
_attributes = gdata.GDataFeed._attributes.copy()
|
||||
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [PropertyEntry])
|
||||
|
||||
def __init__(self, author=None, category=None, contributor=None,
|
||||
generator=None, icon=None, atom_id=None, link=None, logo=None,
|
||||
rights=None, subtitle=None, title=None, updated=None,
|
||||
entry=None, total_results=None, start_index=None,
|
||||
items_per_page=None, extension_elements=None,
|
||||
extension_attributes=None, text=None):
|
||||
gdata.GDataFeed.__init__(self, author=author, category=category,
|
||||
contributor=contributor, generator=generator,
|
||||
icon=icon, atom_id=atom_id, link=link,
|
||||
logo=logo, rights=rights, subtitle=subtitle,
|
||||
title=title, updated=updated, entry=entry,
|
||||
total_results=total_results,
|
||||
start_index=start_index,
|
||||
items_per_page=items_per_page,
|
||||
extension_elements=extension_elements,
|
||||
extension_attributes=extension_attributes,
|
||||
text=text)
|
||||
|
||||
def PropertyFeedFromString(xml_string):
|
||||
return atom.CreateClassFromXMLString(PropertyFeed, xml_string)
|
||||
0
gdata/apps/adminaudit/__init__.py
Normal file
0
gdata/apps/adminaudit/__init__.py
Normal file
82
gdata/apps/adminaudit/service.py
Normal file
82
gdata/apps/adminaudit/service.py
Normal file
@@ -0,0 +1,82 @@
|
||||
#!/usr/bin/python2.4
|
||||
#
|
||||
# Copyright 2010 Google Inc. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""AdminAuditService simplifies Admin Audit API calls.
|
||||
|
||||
AdminAuditService extends gdata.apps.service.PropertyService to ease interaction with
|
||||
the Google Apps Admin Audit API.
|
||||
"""
|
||||
|
||||
__author__ = 'Jay Lee <jay0lee@gmail.com>'
|
||||
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
import json
|
||||
|
||||
|
||||
class AdminAuditService(gdata.apps.service.PropertyService):
|
||||
"""Service extension for the Google Admin Audit API service."""
|
||||
|
||||
def __init__(self, email=None, password=None, domain=None, source=None,
|
||||
server='www.googleapis.com', additional_headers=None,
|
||||
**kwargs):
|
||||
"""Creates a client for the Admin Audit service.
|
||||
|
||||
Args:
|
||||
email: string (optional) The user's email address, used for
|
||||
authentication.
|
||||
password: string (optional) The user's password.
|
||||
domain: string (optional) The Google Apps domain name.
|
||||
source: string (optional) The name of the user's application.
|
||||
server: string (optional) The name of the server to which a connection
|
||||
will be opened. Default value: 'apps-apis.google.com'.
|
||||
**kwargs: The other parameters to pass to gdata.service.GDataService
|
||||
constructor.
|
||||
"""
|
||||
gdata.service.GDataService.__init__(
|
||||
self, email=email, password=password, service='apps', source=source,
|
||||
server=server, additional_headers=additional_headers, **kwargs)
|
||||
self.ssl = True
|
||||
self.port = 443
|
||||
self.domain = domain
|
||||
|
||||
def retrieve_audit(self, customer_id, admin=None, event=None, start_date=None, end_date=None, max_results=None):
|
||||
"""Retrieves an audit
|
||||
|
||||
"""
|
||||
uri = '/apps/reporting/audit/v1/%s/207535951991' % customer_id
|
||||
use_char = '?'
|
||||
if admin != None:
|
||||
uri += '%sactorEmail=%s' % (use_char, admin)
|
||||
use_char = '&'
|
||||
if event != None:
|
||||
uri += '%seventName=%s' % (use_char, event)
|
||||
use_char = '&'
|
||||
if start_date != None:
|
||||
uri += '%sstartTime=%s' % (use_char, start_date)
|
||||
use_char = '&'
|
||||
if end_date != None:
|
||||
uri += '%sendTime=%s' % (use_char, end_date)
|
||||
use_char = '&'
|
||||
if max_results != None:
|
||||
uri += '%smaxResults=%s' % (use_char, max_results)
|
||||
try:
|
||||
return self.Get(uri, converter=str)
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
|
||||
RetrieveAudit = retrieve_audit
|
||||
16
gdata/apps/adminsettings/__init__.py
Normal file
16
gdata/apps/adminsettings/__init__.py
Normal file
@@ -0,0 +1,16 @@
|
||||
#!/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.
|
||||
|
||||
474
gdata/apps/adminsettings/service.py
Normal file
474
gdata/apps/adminsettings/service.py
Normal file
@@ -0,0 +1,474 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright (C) 2008 Google, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Allow Google Apps domain administrators to set domain admin settings.
|
||||
|
||||
AdminSettingsService: Set admin settings."""
|
||||
|
||||
__author__ = 'jlee@pbu.edu'
|
||||
|
||||
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
|
||||
|
||||
API_VER='2.0'
|
||||
|
||||
class AdminSettingsService(gdata.apps.service.PropertyService):
|
||||
"""Client for the Google Apps Admin Settings service."""
|
||||
|
||||
def _serviceUrl(self, setting_id, domain=None):
|
||||
if domain is None:
|
||||
domain = self.domain
|
||||
return '/a/feeds/domain/%s/%s/%s' % (API_VER, domain, setting_id)
|
||||
|
||||
def genericGet(self, location):
|
||||
"""Generic HTTP Get Wrapper
|
||||
|
||||
Args:
|
||||
location: relative uri to Get
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the get operation."""
|
||||
|
||||
uri = self._serviceUrl(location)
|
||||
try:
|
||||
return self._GetProperties(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def GetDefaultLanguage(self):
|
||||
"""Gets Domain Default Language
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
Default Language as a string. All possible values are listed at:
|
||||
http://code.google.com/apis/apps/email_settings/developers_guide_protocol.html#GA_email_language_tags"""
|
||||
|
||||
result = self.genericGet('general/defaultLanguage')
|
||||
return result['defaultLanguage']
|
||||
|
||||
def UpdateDefaultLanguage(self, defaultLanguage):
|
||||
"""Updates Domain Default Language
|
||||
|
||||
Args:
|
||||
defaultLanguage: Domain Language to set
|
||||
possible values are at:
|
||||
http://code.google.com/apis/apps/email_settings/developers_guide_protocol.html#GA_email_language_tags
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the put operation"""
|
||||
|
||||
uri = self._serviceUrl('general/defaultLanguage')
|
||||
properties = {'defaultLanguage': defaultLanguage}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetOrganizationName(self):
|
||||
"""Gets Domain Default Language
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
Organization Name as a string."""
|
||||
|
||||
result = self.genericGet('general/organizationName')
|
||||
return result['organizationName']
|
||||
|
||||
|
||||
def UpdateOrganizationName(self, organizationName):
|
||||
"""Updates Organization Name
|
||||
|
||||
Args:
|
||||
organizationName: Name of organization
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the put operation"""
|
||||
|
||||
uri = self._serviceUrl('general/organizationName')
|
||||
properties = {'organizationName': organizationName}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetMaximumNumberOfUsers(self):
|
||||
"""Gets Maximum Number of Users Allowed
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: An integer, the maximum number of users"""
|
||||
|
||||
result = self.genericGet('general/maximumNumberOfUsers')
|
||||
return int(result['maximumNumberOfUsers'])
|
||||
|
||||
def GetCurrentNumberOfUsers(self):
|
||||
"""Gets Current Number of Users
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: An integer, the current number of users"""
|
||||
|
||||
result = self.genericGet('general/currentNumberOfUsers')
|
||||
return int(result['currentNumberOfUsers'])
|
||||
|
||||
def IsDomainVerified(self):
|
||||
"""Is the domain verified
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: Boolean, is domain verified"""
|
||||
|
||||
result = self.genericGet('accountInformation/isVerified')
|
||||
if result['isVerified'] == 'true':
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def GetSupportPIN(self):
|
||||
"""Gets Support PIN
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A string, the Support PIN"""
|
||||
|
||||
result = self.genericGet('accountInformation/supportPIN')
|
||||
return result['supportPIN']
|
||||
|
||||
def GetEdition(self):
|
||||
"""Gets Google Apps Domain Edition
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A string, the domain's edition (premier, education, partner)"""
|
||||
|
||||
result = self.genericGet('accountInformation/edition')
|
||||
return result['edition']
|
||||
|
||||
def GetCustomerPIN(self):
|
||||
"""Gets Customer PIN
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A string, the customer PIN"""
|
||||
|
||||
result = self.genericGet('accountInformation/customerPIN')
|
||||
return result['customerPIN']
|
||||
|
||||
def GetCreationTime(self):
|
||||
"""Gets Domain Creation Time
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A string, the domain's creation time"""
|
||||
|
||||
result = self.genericGet('accountInformation/creationTime')
|
||||
return result['creationTime']
|
||||
|
||||
def GetCountryCode(self):
|
||||
"""Gets Domain Country Code
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A string, the domain's country code. Possible values at:
|
||||
http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm"""
|
||||
|
||||
result = self.genericGet('accountInformation/countryCode')
|
||||
return result['countryCode']
|
||||
|
||||
def GetAdminSecondaryEmail(self):
|
||||
"""Gets Domain Admin Secondary Email Address
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A string, the secondary email address for domain admin"""
|
||||
|
||||
result = self.genericGet('accountInformation/adminSecondaryEmail')
|
||||
return result['adminSecondaryEmail']
|
||||
|
||||
def UpdateAdminSecondaryEmail(self, adminSecondaryEmail):
|
||||
"""Gets Domain Creation Time
|
||||
|
||||
Args:
|
||||
adminSecondaryEmail: string, secondary email address of admin
|
||||
|
||||
Returns: A dict containing the result of the put operation"""
|
||||
|
||||
uri = self._serviceUrl('accountInformation/adminSecondaryEmail')
|
||||
properties = {'adminSecondaryEmail': adminSecondaryEmail}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetDomainLogo(self):
|
||||
"""Gets Domain Logo
|
||||
|
||||
This function does not make use of the Google Apps Admin Settings API,
|
||||
it does an HTTP Get of a url specific to the Google Apps domain. It is
|
||||
included for completeness sake.
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: binary image file"""
|
||||
|
||||
import urllib
|
||||
url = 'http://www.google.com/a/cpanel/'+self.domain+'/images/logo.gif'
|
||||
response = urllib.urlopen(url)
|
||||
return response.read()
|
||||
|
||||
def UpdateDomainLogo(self, logoImage):
|
||||
"""Update Domain's Custom Logo
|
||||
|
||||
Args:
|
||||
logoImage: binary image data
|
||||
|
||||
Returns: A dict containing the result of the put operation"""
|
||||
|
||||
from base64 import b64encode
|
||||
uri = self._serviceUrl('appearance/customLogo')
|
||||
properties = {'logoImage': b64encode(logoImage)}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetCNAMEVerificationStatus(self):
|
||||
"""Gets Domain CNAME Verification Status
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A dict {recordName, verified, verifiedMethod}"""
|
||||
|
||||
return self.genericGet('verification/cname')
|
||||
|
||||
def UpdateCNAMEVerificationStatus(self, verified='true'):
|
||||
"""Updates CNAME Verification Status
|
||||
|
||||
Args:
|
||||
verified: boolean, True will retry verification process
|
||||
|
||||
Returns: A dict containing the result of the put operation"""
|
||||
|
||||
uri = self._serviceUrl('verification/cname')
|
||||
properties = self.GetCNAMEVerificationStatus()
|
||||
properties['verified'] = verified
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetMXVerificationStatus(self):
|
||||
"""Gets Domain MX Verification Status
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A dict {verified, verifiedMethod}"""
|
||||
|
||||
return self.genericGet('verification/mx')
|
||||
|
||||
def UpdateMXVerificationStatus(self, verified='true'):
|
||||
"""Updates MX Verification Status
|
||||
|
||||
Args:
|
||||
verified: boolean, True will retry verification process
|
||||
|
||||
Returns: A dict containing the result of the put operation"""
|
||||
|
||||
uri = self._serviceUrl('verification/mx')
|
||||
properties = self.GetMXVerificationStatus()
|
||||
properties['verified'] = verified
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetSSOSettings(self):
|
||||
"""Gets Domain Single Sign-On Settings
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A dict {samlSignonUri, samlLogoutUri, changePasswordUri, enableSSO, ssoWhitelist, useDomainSpecificIssuer}"""
|
||||
|
||||
return self.genericGet('sso/general')
|
||||
|
||||
def UpdateSSOSettings(self, enableSSO=None, samlSignonUri=None,
|
||||
samlLogoutUri=None, changePasswordUri=None,
|
||||
ssoWhitelist=None, useDomainSpecificIssuer=None):
|
||||
"""Update SSO Settings.
|
||||
|
||||
Args:
|
||||
enableSSO: boolean, SSO Master on/off switch
|
||||
samlSignonUri: string, SSO Login Page
|
||||
samlLogoutUri: string, SSO Logout Page
|
||||
samlPasswordUri: string, SSO Password Change Page
|
||||
ssoWhitelist: string, Range of IP Addresses which will see SSO
|
||||
useDomainSpecificIssuer: boolean, Include Google Apps Domain in Issuer
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('sso/general')
|
||||
|
||||
#Get current settings, replace Nones with ''
|
||||
properties = self.GetSSOSettings()
|
||||
if properties['samlSignonUri'] == None:
|
||||
properties['samlSignonUri'] = ''
|
||||
if properties['samlLogoutUri'] == None:
|
||||
properties['samlLogoutUri'] = ''
|
||||
if properties['changePasswordUri'] == None:
|
||||
properties['changePasswordUri'] = ''
|
||||
if properties['ssoWhitelist'] == None:
|
||||
properties['ssoWhitelist'] = ''
|
||||
|
||||
#update only the values we were passed
|
||||
if enableSSO != None:
|
||||
properties['enableSSO'] = gdata.apps.service._bool2str(enableSSO)
|
||||
if samlSignonUri != None:
|
||||
properties['samlSignonUri'] = samlSignonUri
|
||||
if samlLogoutUri != None:
|
||||
properties['samlLogoutUri'] = samlLogoutUri
|
||||
if changePasswordUri != None:
|
||||
properties['changePasswordUri'] = changePasswordUri
|
||||
if ssoWhitelist != None:
|
||||
properties['ssoWhitelist'] = ssoWhitelist
|
||||
if useDomainSpecificIssuer != None:
|
||||
properties['useDomainSpecificIssuer'] = gdata.apps.service._bool2str(useDomainSpecificIssuer)
|
||||
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetSSOKey(self):
|
||||
"""Gets Domain Single Sign-On Signing Key
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A dict {modulus, exponent, algorithm, format}"""
|
||||
|
||||
return self.genericGet('sso/signingkey')
|
||||
|
||||
def UpdateSSOKey(self, signingKey):
|
||||
"""Update SSO Settings.
|
||||
|
||||
Args:
|
||||
signingKey: binary, public key to be uploaded
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation."""
|
||||
|
||||
from base64 import b64encode
|
||||
uri = self._serviceUrl('sso/signingkey')
|
||||
properties = {'signingKey': b64encode(signingKey)}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def IsUserMigrationEnabled(self):
|
||||
"""Is User Migration Enabled
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
boolean, is user migration enabled"""
|
||||
|
||||
result = self.genericGet('email/migration')
|
||||
if result['enableUserMigration'] == 'true':
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def UpdateUserMigrationStatus(self, enableUserMigration):
|
||||
"""Update User Migration Status
|
||||
|
||||
Args:
|
||||
enableUserMigration: boolean, user migration enable/disable
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation."""
|
||||
|
||||
uri = self._serviceUrl('email/migration')
|
||||
properties = {'enableUserMigration': enableUserMigration}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetOutboundGatewaySettings(self):
|
||||
"""Get Outbound Gateway Settings
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
A dict {smartHost, smtpMode}"""
|
||||
|
||||
uri = self._serviceUrl('email/gateway')
|
||||
try:
|
||||
return self._GetProperties(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
except TypeError:
|
||||
#if no outbound gateway is set, we get a TypeError,
|
||||
#catch it and return nothing...
|
||||
return {'smartHost': None, 'smtpMode': None}
|
||||
|
||||
def UpdateOutboundGatewaySettings(self, smartHost=None, smtpMode=None):
|
||||
"""Update Outbound Gateway Settings
|
||||
|
||||
Args:
|
||||
smartHost: string, ip address or hostname of outbound gateway
|
||||
smtpMode: string, SMTP or SMTP_TLS
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation."""
|
||||
|
||||
uri = self._serviceUrl('email/gateway')
|
||||
|
||||
#Get current settings, replace Nones with ''
|
||||
properties = self.GetOutboundGatewaySettings()
|
||||
if properties['smartHost'] == None:
|
||||
properties['smartHost'] = ''
|
||||
try:
|
||||
if properties['smtpMode'] == None:
|
||||
properties['smtpMode'] = ''
|
||||
except KeyError:
|
||||
properties['smtpMode'] = ''
|
||||
|
||||
#If we were passed new values for smartHost or smtpMode, update them
|
||||
if smartHost != None:
|
||||
properties['smartHost'] = smartHost
|
||||
if smtpMode != None:
|
||||
properties['smtpMode'] = smtpMode
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def AddEmailRoute(self, routeDestination, routeRewriteTo, routeEnabled, bounceNotifications, accountHandling):
|
||||
"""Adds Domain Email Route
|
||||
|
||||
Args:
|
||||
routeDestination: string, destination ip address or hostname
|
||||
routeRewriteTo: boolean, rewrite smtp envelop To:
|
||||
routeEnabled: boolean, enable disable email routing
|
||||
bounceNotifications: boolean, send bound notificiations to sender
|
||||
accountHandling: string, which to route, "allAccounts", "provisionedAccounts", "unknownAccounts"
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation."""
|
||||
|
||||
uri = self._serviceUrl('emailrouting')
|
||||
properties = {}
|
||||
properties['routeDestination'] = routeDestination
|
||||
properties['routeRewriteTo'] = gdata.apps.service._bool2str(routeRewriteTo)
|
||||
properties['routeEnabled'] = gdata.apps.service._bool2str(routeEnabled)
|
||||
properties['bounceNotifications'] = gdata.apps.service._bool2str(bounceNotifications)
|
||||
properties['accountHandling'] = accountHandling
|
||||
return self._PostProperties(uri, properties)
|
||||
1
gdata/apps/audit/__init__.py
Normal file
1
gdata/apps/audit/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
277
gdata/apps/audit/service.py
Normal file
277
gdata/apps/audit/service.py
Normal file
@@ -0,0 +1,277 @@
|
||||
# Copyright (C) 2008 Google, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Allow Google Apps domain administrators to audit user data.
|
||||
|
||||
AuditService: Set auditing."""
|
||||
|
||||
__author__ = 'jlee@pbu.edu'
|
||||
|
||||
from base64 import b64encode
|
||||
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
|
||||
class AuditService(gdata.apps.service.PropertyService):
|
||||
"""Client for the Google Apps Audit service."""
|
||||
|
||||
def _serviceUrl(self, setting_id, domain=None, user=None):
|
||||
if domain is None:
|
||||
domain = self.domain
|
||||
if user is None:
|
||||
return '/a/feeds/compliance/audit/%s/%s' % (setting_id, domain)
|
||||
else:
|
||||
return '/a/feeds/compliance/audit/%s/%s/%s' % (setting_id, domain, user)
|
||||
|
||||
def updatePGPKey(self, pgpkey):
|
||||
"""Updates Public PGP Key Google uses to encrypt audit data
|
||||
|
||||
Args:
|
||||
pgpkey: string, ASCII text of PGP Public Key to be used
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the POST operation."""
|
||||
|
||||
uri = self._serviceUrl('publickey')
|
||||
b64pgpkey = b64encode(pgpkey)
|
||||
properties = {}
|
||||
properties['publicKey'] = b64pgpkey
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def createEmailMonitor(self, source_user, destination_user, end_date,
|
||||
begin_date=None, incoming_headers_only=False,
|
||||
outgoing_headers_only=False, drafts=False,
|
||||
drafts_headers_only=False, chats=False,
|
||||
chats_headers_only=False):
|
||||
"""Creates a email monitor, forwarding the source_users emails/chats
|
||||
|
||||
Args:
|
||||
source_user: string, the user whose email will be audited
|
||||
destination_user: string, the user to receive the audited email
|
||||
end_date: string, the date the audit will end in
|
||||
"yyyy-MM-dd HH:mm" format, required
|
||||
begin_date: string, the date the audit will start in
|
||||
"yyyy-MM-dd HH:mm" format, leave blank to use current time
|
||||
incoming_headers_only: boolean, whether to audit only the headers of
|
||||
mail delivered to source user
|
||||
outgoing_headers_only: boolean, whether to audit only the headers of
|
||||
mail sent from the source user
|
||||
drafts: boolean, whether to audit draft messages of the source user
|
||||
drafts_headers_only: boolean, whether to audit only the headers of
|
||||
mail drafts saved by the user
|
||||
chats: boolean, whether to audit archived chats of the source user
|
||||
chats_headers_only: boolean, whether to audit only the headers of
|
||||
archived chats of the source user
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the POST operation."""
|
||||
|
||||
uri = self._serviceUrl('mail/monitor', user=source_user)
|
||||
properties = {}
|
||||
properties['destUserName'] = destination_user
|
||||
if begin_date is not None:
|
||||
properties['beginDate'] = begin_date
|
||||
properties['endDate'] = end_date
|
||||
if incoming_headers_only:
|
||||
properties['incomingEmailMonitorLevel'] = 'HEADER_ONLY'
|
||||
else:
|
||||
properties['incomingEmailMonitorLevel'] = 'FULL_MESSAGE'
|
||||
if outgoing_headers_only:
|
||||
properties['outgoingEmailMonitorLevel'] = 'HEADER_ONLY'
|
||||
else:
|
||||
properties['outgoingEmailMonitorLevel'] = 'FULL_MESSAGE'
|
||||
if drafts:
|
||||
if drafts_headers_only:
|
||||
properties['draftMonitorLevel'] = 'HEADER_ONLY'
|
||||
else:
|
||||
properties['draftMonitorLevel'] = 'FULL_MESSAGE'
|
||||
if chats:
|
||||
if chats_headers_only:
|
||||
properties['chatMonitorLevel'] = 'HEADER_ONLY'
|
||||
else:
|
||||
properties['chatMonitorLevel'] = 'FULL_MESSAGE'
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def getEmailMonitors(self, user):
|
||||
""""Gets the email monitors for the given user
|
||||
|
||||
Args:
|
||||
user: string, the user to retrieve email monitors for
|
||||
|
||||
Returns:
|
||||
list results of the POST operation
|
||||
|
||||
"""
|
||||
uri = self._serviceUrl('mail/monitor', user=user)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def deleteEmailMonitor(self, source_user, destination_user):
|
||||
"""Deletes the email monitor for the given user
|
||||
|
||||
Args:
|
||||
source_user: string, the user who is being monitored
|
||||
destination_user: string, theuser who recieves the monitored emails
|
||||
|
||||
Returns:
|
||||
Nothing
|
||||
"""
|
||||
|
||||
uri = self._serviceUrl('mail/monitor', user=source_user+'/'+destination_user)
|
||||
try:
|
||||
return self._DeleteProperties(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def createAccountInformationRequest(self, user):
|
||||
"""Creates a request for account auditing details
|
||||
|
||||
Args:
|
||||
user: string, the user to request account information for
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the post operation."""
|
||||
|
||||
uri = self._serviceUrl('account', user=user)
|
||||
properties = {}
|
||||
#XML Body is left empty
|
||||
try:
|
||||
return self._PostProperties(uri, properties)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def getAccountInformationRequestStatus(self, user, request_id):
|
||||
"""Gets the status of an account auditing request
|
||||
|
||||
Args:
|
||||
user: string, the user whose account auditing details were requested
|
||||
request_id: string, the request_id
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the get operation."""
|
||||
|
||||
uri = self._serviceUrl('account', user=user+'/'+request_id)
|
||||
try:
|
||||
return self._GetProperties(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def getAllAccountInformationRequestsStatus(self):
|
||||
"""Gets the status of all account auditing requests for the domain
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
list results of the POST operation
|
||||
"""
|
||||
|
||||
uri = self._serviceUrl('account')
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
|
||||
def deleteAccountInformationRequest(self, user, request_id):
|
||||
"""Deletes the request for account auditing information
|
||||
|
||||
Args:
|
||||
user: string, the user whose account auditing details were requested
|
||||
request_id: string, the request_id
|
||||
|
||||
Returns:
|
||||
Nothing
|
||||
"""
|
||||
|
||||
uri = self._serviceUrl('account', user=user+'/'+request_id)
|
||||
try:
|
||||
return self._DeleteProperties(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def createMailboxExportRequest(self, user, begin_date=None, end_date=None, include_deleted=False, search_query=None, headers_only=False):
|
||||
"""Creates a mailbox export request
|
||||
|
||||
Args:
|
||||
user: string, the user whose mailbox export is being requested
|
||||
begin_date: string, date of earliest emails to export, optional, defaults to date of account creation
|
||||
format is 'yyyy-MM-dd HH:mm'
|
||||
end_date: string, date of latest emails to export, optional, defaults to current date
|
||||
format is 'yyyy-MM-dd HH:mm'
|
||||
include_deleted: boolean, whether to include deleted emails in export, mutually exclusive with search_query
|
||||
search_query: string, gmail style search query, matched emails will be exported, mutually exclusive with include_deleted
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the post operation."""
|
||||
|
||||
uri = self._serviceUrl('mail/export', user=user)
|
||||
properties = {}
|
||||
if begin_date is not None:
|
||||
properties['beginDate'] = begin_date
|
||||
if end_date is not None:
|
||||
properties['endDate'] = end_date
|
||||
if include_deleted is not None:
|
||||
properties['includeDeleted'] = gdata.apps.service._bool2str(include_deleted)
|
||||
if search_query is not None:
|
||||
properties['searchQuery'] = search_query
|
||||
if headers_only is True:
|
||||
properties['packageContent'] = 'HEADER_ONLY'
|
||||
else:
|
||||
properties['packageContent'] = 'FULL_MESSAGE'
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def getMailboxExportRequestStatus(self, user, request_id):
|
||||
"""Gets the status of an mailbox export request
|
||||
|
||||
Args:
|
||||
user: string, the user whose mailbox were requested
|
||||
request_id: string, the request_id
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the get operation."""
|
||||
|
||||
uri = self._serviceUrl('mail/export', user=user+'/'+request_id)
|
||||
try:
|
||||
return self._GetProperties(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def getAllMailboxExportRequestsStatus(self):
|
||||
"""Gets the status of all mailbox export requests for the domain
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
list results of the POST operation
|
||||
"""
|
||||
|
||||
uri = self._serviceUrl('mail/export')
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
|
||||
def deleteMailboxExportRequest(self, user, request_id):
|
||||
"""Deletes the request for mailbox export
|
||||
|
||||
Args:
|
||||
user: string, the user whose mailbox were requested
|
||||
request_id: string, the request_id
|
||||
|
||||
Returns:
|
||||
Nothing
|
||||
"""
|
||||
|
||||
uri = self._serviceUrl('mail/export', user=user+'/'+request_id)
|
||||
try:
|
||||
return self._DeleteProperties(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
15
gdata/apps/emailsettings/__init__.py
Normal file
15
gdata/apps/emailsettings/__init__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
#!/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.
|
||||
386
gdata/apps/emailsettings/client.py
Normal file
386
gdata/apps/emailsettings/client.py
Normal file
@@ -0,0 +1,386 @@
|
||||
#!/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.
|
||||
|
||||
"""EmailSettingsClient simplifies Email Settings API calls.
|
||||
|
||||
EmailSettingsClient extends gdata.client.GDClient to ease interaction with
|
||||
the Google Apps Email Settings API. These interactions include the ability
|
||||
to create labels, filters, aliases, and update web-clip, forwarding, POP,
|
||||
IMAP, vacation-responder, signature, language, and general settings.
|
||||
"""
|
||||
|
||||
|
||||
__author__ = 'Claudio Cherubino <ccherubino@google.com>'
|
||||
|
||||
|
||||
import gdata.apps.emailsettings.data
|
||||
import gdata.client
|
||||
import urllib
|
||||
|
||||
|
||||
# Email Settings URI template
|
||||
# The strings in this template are eventually replaced with the API version,
|
||||
# Google Apps domain name, username, and settingID, respectively.
|
||||
EMAIL_SETTINGS_URI_TEMPLATE = '/a/feeds/emailsettings/%s/%s/%s/%s'
|
||||
|
||||
|
||||
# The settingID value for the label requests
|
||||
SETTING_ID_LABEL = 'label'
|
||||
# The settingID value for the filter requests
|
||||
SETTING_ID_FILTER = 'filter'
|
||||
# The settingID value for the send-as requests
|
||||
SETTING_ID_SENDAS = 'sendas'
|
||||
# The settingID value for the webclip requests
|
||||
SETTING_ID_WEBCLIP = 'webclip'
|
||||
# The settingID value for the forwarding requests
|
||||
SETTING_ID_FORWARDING = 'forwarding'
|
||||
# The settingID value for the POP requests
|
||||
SETTING_ID_POP = 'pop'
|
||||
# The settingID value for the IMAP requests
|
||||
SETTING_ID_IMAP = 'imap'
|
||||
# The settingID value for the vacation responder requests
|
||||
SETTING_ID_VACATION_RESPONDER = 'vacation'
|
||||
# The settingID value for the signature requests
|
||||
SETTING_ID_SIGNATURE = 'signature'
|
||||
# The settingID value for the language requests
|
||||
SETTING_ID_LANGUAGE = 'language'
|
||||
# The settingID value for the general requests
|
||||
SETTING_ID_GENERAL = 'general'
|
||||
|
||||
|
||||
class EmailSettingsClient(gdata.client.GDClient):
|
||||
"""Client extension for the Google Email Settings API service.
|
||||
|
||||
Attributes:
|
||||
host: string The hostname for the Email Settings API service.
|
||||
api_version: string The version of the Email Settings API.
|
||||
"""
|
||||
|
||||
host = 'apps-apis.google.com'
|
||||
api_version = '2.0'
|
||||
auth_service = 'apps'
|
||||
auth_scopes = gdata.gauth.AUTH_SCOPES['apps']
|
||||
ssl = True
|
||||
|
||||
def __init__(self, domain, auth_token=None, **kwargs):
|
||||
"""Constructs a new client for the Email Settings API.
|
||||
|
||||
Args:
|
||||
domain: string The Google Apps domain with Email Settings.
|
||||
auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or
|
||||
OAuthToken which authorizes this client to edit the email settings.
|
||||
kwargs: The other parameters to pass to the gdata.client.GDClient
|
||||
constructor.
|
||||
"""
|
||||
gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs)
|
||||
self.domain = domain
|
||||
|
||||
def make_email_settings_uri(self, username, setting_id):
|
||||
"""Creates the URI for the Email Settings API call.
|
||||
|
||||
Using this client's Google Apps domain, create the URI to setup
|
||||
email settings for the given user in that domain. If params are provided,
|
||||
append them as GET params.
|
||||
|
||||
Args:
|
||||
username: string The name of the user affected by this setting.
|
||||
setting_id: string The key of the setting to be configured.
|
||||
|
||||
Returns:
|
||||
A string giving the URI for Email Settings API calls for this client's
|
||||
Google Apps domain.
|
||||
"""
|
||||
uri = EMAIL_SETTINGS_URI_TEMPLATE % (self.api_version, self.domain,
|
||||
username, setting_id)
|
||||
return uri
|
||||
|
||||
MakeEmailSettingsUri = make_email_settings_uri
|
||||
|
||||
def create_label(self, username, name, **kwargs):
|
||||
"""Creates a label with the given properties.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
name: string The name of the label.
|
||||
kwargs: The other parameters to pass to gdata.client.GDClient.post().
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsLabel of the new resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_LABEL)
|
||||
new_label = gdata.apps.emailsettings.data.EmailSettingsLabel(
|
||||
uri=uri, name=name)
|
||||
return self.post(new_label, uri, **kwargs)
|
||||
|
||||
CreateLabel = create_label
|
||||
|
||||
def create_filter(self, username, from_address=None,
|
||||
to_address=None, subject=None, has_the_word=None,
|
||||
does_not_have_the_word=None, has_attachments=None,
|
||||
label=None, mark_as_read=None, archive=None, **kwargs):
|
||||
"""Creates a filter with the given properties.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
from_address: string The source email address for the filter.
|
||||
to_address: string (optional) The destination email address for
|
||||
the filter.
|
||||
subject: string (optional) The value the email must have in its
|
||||
subject to be filtered.
|
||||
has_the_word: string (optional) The value the email must have
|
||||
in its subject or body to be filtered.
|
||||
does_not_have_the_word: string (optional) The value the email
|
||||
cannot have in its subject or body to be filtered.
|
||||
has_attachments: string (optional) A boolean string representing
|
||||
whether the email must have an attachment to be filtered.
|
||||
label: string (optional) The name of the label to apply to
|
||||
messages matching the filter criteria.
|
||||
mark_as_read: Boolean (optional) Whether or not to mark
|
||||
messages matching the filter criteria as read.
|
||||
archive: Boolean (optional) Whether or not to move messages
|
||||
matching to Archived state.
|
||||
kwargs: The other parameters to pass to gdata.client.GDClient.post().
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsFilter of the new resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_FILTER)
|
||||
new_filter = gdata.apps.emailsettings.data.EmailSettingsFilter(
|
||||
uri=uri, from_address=from_address,
|
||||
to_address=to_address, subject=subject,
|
||||
has_the_word=has_the_word,
|
||||
does_not_have_the_word=does_not_have_the_word,
|
||||
has_attachments=has_attachments, label=label,
|
||||
mark_as_read=mark_as_read, archive=archive)
|
||||
return self.post(new_filter, uri, **kwargs)
|
||||
|
||||
CreateFilter = create_filter
|
||||
|
||||
def create_sendas(self, username, name, address, reply_to=None,
|
||||
make_default=None, **kwargs):
|
||||
"""Creates a send-as alias with the given properties.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
name: string The name that will appear in the "From" field.
|
||||
address: string The email address that appears as the
|
||||
origination address for emails sent by this user.
|
||||
reply_to: string (optional) The address to be used as the reply-to
|
||||
address in email sent using the alias.
|
||||
make_default: Boolean (optional) Whether or not this alias should
|
||||
become the default alias for this user.
|
||||
kwargs: The other parameters to pass to gdata.client.GDClient.post().
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsSendAsAlias of the
|
||||
new resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_SENDAS)
|
||||
new_alias = gdata.apps.emailsettings.data.EmailSettingsSendAsAlias(
|
||||
uri=uri, name=name, address=address,
|
||||
reply_to=reply_to, make_default=make_default)
|
||||
return self.post(new_alias, uri, **kwargs)
|
||||
|
||||
CreateSendAs = create_sendas
|
||||
|
||||
def update_webclip(self, username, enable, **kwargs):
|
||||
"""Enable/Disable Google Mail web clip.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
enable: Boolean Whether to enable showing Web clips.
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsWebClip of the
|
||||
updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_WEBCLIP)
|
||||
new_webclip = gdata.apps.emailsettings.data.EmailSettingsWebClip(
|
||||
uri=uri, enable=enable)
|
||||
return self.update(new_webclip, **kwargs)
|
||||
|
||||
UpdateWebclip = update_webclip
|
||||
|
||||
def update_forwarding(self, username, enable, forward_to=None,
|
||||
action=None, **kwargs):
|
||||
"""Update Google Mail Forwarding settings.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
enable: Boolean Whether to enable incoming email forwarding.
|
||||
forward_to: (optional) string The address email will be forwarded to.
|
||||
action: string (optional) The action to perform after forwarding
|
||||
an email ("KEEP", "ARCHIVE", "DELETE").
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsForwarding of the
|
||||
updated resource
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_FORWARDING)
|
||||
new_forwarding = gdata.apps.emailsettings.data.EmailSettingsForwarding(
|
||||
uri=uri, enable=enable, forward_to=forward_to, action=action)
|
||||
return self.update(new_forwarding, **kwargs)
|
||||
|
||||
UpdateForwarding = update_forwarding
|
||||
|
||||
def update_pop(self, username, enable, enable_for=None, action=None,
|
||||
**kwargs):
|
||||
"""Update Google Mail POP settings.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
enable: Boolean Whether to enable incoming POP3 access.
|
||||
enable_for: string (optional) Whether to enable POP3 for all mail
|
||||
("ALL_MAIL"), or mail from now on ("MAIL_FROM_NOW_ON").
|
||||
action: string (optional) What Google Mail should do with its copy
|
||||
of the email after it is retrieved using POP ("KEEP",
|
||||
"ARCHIVE", or "DELETE").
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsPop of the updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_POP)
|
||||
new_pop = gdata.apps.emailsettings.data.EmailSettingsPop(
|
||||
uri=uri, enable=enable,
|
||||
enable_for=enable_for, action=action)
|
||||
return self.update(new_pop, **kwargs)
|
||||
|
||||
UpdatePop = update_pop
|
||||
|
||||
def update_imap(self, username, enable, **kwargs):
|
||||
"""Update Google Mail IMAP settings.
|
||||
|
||||
Args:import gdata.apps_property
|
||||
username: string The name of the user.
|
||||
enable: Boolean Whether to enable IMAP access.language
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsImap of the updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_IMAP)
|
||||
new_imap = gdata.apps.emailsettings.data.EmailSettingsImap(
|
||||
uri=uri, enable=enable)
|
||||
return self.update(new_imap, **kwargs)
|
||||
|
||||
UpdateImap = update_imap
|
||||
|
||||
def update_vacation(self, username, enable, subject=None, message=None,
|
||||
contacts_only=None, **kwargs):
|
||||
"""Update Google Mail vacation-responder settings.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
enable: Boolean Whether to enable the vacation responder.
|
||||
subject: string (optional) The subject line of the vacation responder
|
||||
autoresponse.
|
||||
message: string (optional) The message body of the vacation responder
|
||||
autoresponse.
|
||||
contacts_only: Boolean (optional) Whether to only send autoresponses
|
||||
to known contacts.
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsVacationResponder of the
|
||||
updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_VACATION_RESPONDER)
|
||||
new_vacation = gdata.apps.emailsettings.data.EmailSettingsVacationResponder(
|
||||
uri=uri, enable=enable, subject=subject,
|
||||
message=message, contacts_only=contacts_only)
|
||||
return self.update(new_vacation, **kwargs)
|
||||
|
||||
UpdateVacation = update_vacation
|
||||
|
||||
def update_signature(self, username, signature, **kwargs):
|
||||
"""Update Google Mail signature.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
signature: string The signature to be appended to outgoing messages.
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsSignature of the
|
||||
updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_SIGNATURE)
|
||||
new_signature = gdata.apps.emailsettings.data.EmailSettingsSignature(
|
||||
uri=uri, signature=signature)
|
||||
return self.update(new_signature, **kwargs)
|
||||
|
||||
UpdateSignature = update_signature
|
||||
|
||||
def update_language(self, username, language, **kwargs):
|
||||
"""Update Google Mail language settings.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
signature: string The language tag for Google Mail's display language.
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsLanguage of the
|
||||
updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_LANGUAGE)
|
||||
new_language = gdata.apps.emailsettings.data.EmailSettingsLanguage(
|
||||
uri=uri, language=language)
|
||||
return self.update(new_language, **kwargs)
|
||||
|
||||
UpdateLanguage = update_language
|
||||
|
||||
def update_general(self, username, page_size=None, shortcuts=None, arrows=None,
|
||||
snippets=None, use_unicode=None, **kwargs):
|
||||
"""Update Google Mail general settings.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
page_size: int (optional) The number of conversations to be shown per page.
|
||||
shortcuts: Boolean (optional) Whether to enable keyboard shortcuts.
|
||||
arrows: Boolean (optional) Whether to display arrow-shaped personal
|
||||
indicators next to email sent specifically to the user.
|
||||
snippets: Boolean (optional) Whether to display snippets of the messages
|
||||
in the inbox and when searching.
|
||||
use_unicode: Boolean (optional) Whether to use UTF-8 (unicode) encoding
|
||||
for all outgoing messages.
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsGeneral of the
|
||||
updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_GENERAL)
|
||||
new_general = gdata.apps.emailsettings.data.EmailSettingsGeneral(
|
||||
uri=uri, page_size=page_size, shortcuts=shortcuts,
|
||||
arrows=arrows, snippets=snippets, use_unicode=use_unicode)
|
||||
return self.update(new_general, **kwargs)
|
||||
|
||||
UpdateGeneral = update_general
|
||||
1130
gdata/apps/emailsettings/data.py
Normal file
1130
gdata/apps/emailsettings/data.py
Normal file
File diff suppressed because it is too large
Load Diff
394
gdata/apps/emailsettings/service.py
Normal file
394
gdata/apps/emailsettings/service.py
Normal file
@@ -0,0 +1,394 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright (C) 2008 Google, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Allow Google Apps domain administrators to set users' email settings.
|
||||
|
||||
EmailSettingsService: Set various email settings.
|
||||
"""
|
||||
|
||||
__author__ = 'google-apps-apis@googlegroups.com'
|
||||
|
||||
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
|
||||
import urllib
|
||||
|
||||
API_VER='2.0'
|
||||
# Forwarding and POP3 options
|
||||
KEEP='KEEP'
|
||||
ARCHIVE='ARCHIVE'
|
||||
DELETE='DELETE'
|
||||
ALL_MAIL='ALL_MAIL'
|
||||
MAIL_FROM_NOW_ON='MAIL_FROM_NOW_ON'
|
||||
|
||||
|
||||
class EmailSettingsService(gdata.apps.service.PropertyService):
|
||||
"""Client for the Google Apps Email Settings service."""
|
||||
|
||||
def _serviceUrl(self, setting_id, username, domain=None):
|
||||
if domain is None:
|
||||
domain = self.domain
|
||||
return '/a/feeds/emailsettings/%s/%s/%s/%s' % (API_VER, domain, username,
|
||||
setting_id)
|
||||
|
||||
def CreateLabel(self, username, label):
|
||||
"""Create a label.
|
||||
|
||||
Args:
|
||||
username: User to create label for.
|
||||
label: Label to create.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the create operation.
|
||||
"""
|
||||
uri = self._serviceUrl('label', username)
|
||||
properties = {'label': label}
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def DeleteLabel(self, username, label):
|
||||
"""Delete a label.
|
||||
|
||||
Args:
|
||||
username: User to delete label for.
|
||||
label: Label to delete.
|
||||
|
||||
Returns:
|
||||
Nothing
|
||||
"""
|
||||
label = urllib.quote_plus(label, '')
|
||||
uri = self._serviceUrl('label/%s' % label, username)
|
||||
return self._DeleteProperties(uri)
|
||||
|
||||
def GetLabels(self, username):
|
||||
"""Get labels for a user.
|
||||
|
||||
Args:
|
||||
username: User to retrieve labels for.
|
||||
|
||||
Returns:
|
||||
A list of labels
|
||||
"""
|
||||
uri = self._serviceUrl('label', username)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def CreateFilter(self, username, from_=None, to=None, subject=None,
|
||||
has_the_word=None, does_not_have_the_word=None,
|
||||
has_attachment=None, label=None, should_mark_as_read=None,
|
||||
should_archive=None, should_star=None, forward_to=None,
|
||||
should_trash=None, should_not_spam=None):
|
||||
"""Create a filter.
|
||||
|
||||
Args:
|
||||
username: User to create filter for.
|
||||
from_: Filter from string.
|
||||
to: Filter to string.
|
||||
subject: Filter subject.
|
||||
has_the_word: Words to filter in.
|
||||
does_not_have_the_word: Words to filter out.
|
||||
has_attachment: Boolean for message having attachment.
|
||||
label: Label to apply.
|
||||
should_mark_as_read: Boolean for marking message as read.
|
||||
should_archive: Boolean for archiving message.
|
||||
should_star: Boolean for starring message
|
||||
forward_to: string email address to forward message to
|
||||
should_trash: Boolean for trashing message
|
||||
should_not_spam: Boolean for never sending message to spam
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the create operation.
|
||||
"""
|
||||
uri = self._serviceUrl('filter', username)
|
||||
properties = {}
|
||||
if from_ != None:
|
||||
properties['from'] = from_
|
||||
if to != None:
|
||||
properties['to'] = to
|
||||
if subject != None:
|
||||
properties['subject'] = subject
|
||||
if has_the_word != None:
|
||||
properties['hasTheWord'] = has_the_word
|
||||
if does_not_have_the_word != None:
|
||||
properties['doesNotHaveTheWord'] = does_not_have_the_word
|
||||
if has_attachment != None:
|
||||
properties['hasAttachment'] = gdata.apps.service._bool2str(has_attachment)
|
||||
if label != None:
|
||||
properties['label'] = label
|
||||
if should_mark_as_read != None:
|
||||
properties['shouldMarkAsRead'] = gdata.apps.service._bool2str(should_mark_as_read)
|
||||
if should_archive != None:
|
||||
properties['shouldArchive'] = gdata.apps.service._bool2str(should_archive)
|
||||
if should_star != None:
|
||||
properties['shouldStar'] = gdata.apps.service._bool2str(should_star)
|
||||
if forward_to != None:
|
||||
properties['forwardTo'] = forward_to
|
||||
if should_trash != None:
|
||||
properties['shouldTrash'] = gdata.apps.service._bool2str(should_trash)
|
||||
if should_not_spam != None:
|
||||
properties['neverSpam'] = gdata.apps.service._bool2str(should_not_spam)
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def CreateSendAsAlias(self, username, name, address, reply_to=None,
|
||||
make_default=None):
|
||||
"""Create alias to send mail as.
|
||||
|
||||
Args:
|
||||
username: User to create alias for.
|
||||
name: Name of alias.
|
||||
address: Email address to send from.
|
||||
reply_to: Email address to reply to.
|
||||
make_default: Boolean for whether this is the new default sending alias.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the create operation.
|
||||
"""
|
||||
uri = self._serviceUrl('sendas', username)
|
||||
properties = {}
|
||||
properties['name'] = name
|
||||
properties['address'] = address
|
||||
properties['replyTo'] = reply_to
|
||||
properties['makeDefault'] = gdata.apps.service._bool2str(make_default)
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def GetSendAsAlias(self, username):
|
||||
"""Retrieve send as aliases for a user.
|
||||
|
||||
Args:
|
||||
username: User to retrieve send as aliases for
|
||||
|
||||
Return:
|
||||
Alist containg the user's send as aliases.
|
||||
"""
|
||||
uri = self._serviceUrl('sendas', username)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def UpdateWebClipSettings(self, username, enable):
|
||||
"""Update WebClip Settings
|
||||
|
||||
Args:
|
||||
username: User to update forwarding for.
|
||||
enable: Boolean whether to enable Web Clip.
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('webclip', username)
|
||||
properties = {}
|
||||
properties['enable'] = gdata.apps.service._bool2str(enable)
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def UpdateForwarding(self, username, enable, forward_to=None, action=None):
|
||||
"""Update forwarding settings.
|
||||
|
||||
Args:
|
||||
username: User to update forwarding for.
|
||||
enable: Boolean whether to enable this forwarding rule.
|
||||
forward_to: Email address to forward to.
|
||||
action: Action to take after forwarding.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('forwarding', username)
|
||||
properties = {}
|
||||
properties['enable'] = gdata.apps.service._bool2str(enable)
|
||||
if enable is True:
|
||||
properties['forwardTo'] = forward_to
|
||||
properties['action'] = action
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def UpdatePop(self, username, enable, enable_for=None, action=None):
|
||||
"""Update POP3 settings.
|
||||
|
||||
Args:
|
||||
username: User to update POP3 settings for.
|
||||
enable: Boolean whether to enable POP3.
|
||||
enable_for: Which messages to make available via POP3.
|
||||
action: Action to take after user retrieves email via POP3.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('pop', username)
|
||||
properties = {}
|
||||
properties['enable'] = gdata.apps.service._bool2str(enable)
|
||||
if enable is True:
|
||||
properties['enableFor'] = enable_for
|
||||
properties['action'] = action
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetPop(self, username):
|
||||
uri = self._serviceUrl('pop', username)
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def GetImap(self, username):
|
||||
uri = self._serviceUrl('imap', username)
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def UpdateImap(self, username, enable):
|
||||
"""Update IMAP settings.
|
||||
|
||||
Args:
|
||||
username: User to update IMAP settings for.
|
||||
enable: Boolean whether to enable IMAP.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('imap', username)
|
||||
properties = {'enable': gdata.apps.service._bool2str(enable)}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetVacation(self, username):
|
||||
uri = self._serviceUrl('vacation', username)
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def GetForward(self, username):
|
||||
uri = self._serviceUrl('forwarding', username)
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def UpdateVacation(self, username, enable, subject=None, message=None,
|
||||
contacts_only=None, domain_only=None, start_date=None, end_date=None):
|
||||
"""Update vacation settings.
|
||||
|
||||
Args:
|
||||
username: User to update vacation settings for.
|
||||
enable: Boolean whether to enable vacation responses.
|
||||
subject: Vacation message subject.
|
||||
message: Vacation message body.
|
||||
contacts_only: Boolean whether to send message only to contacts.
|
||||
domain_only: Boolean Whether to only send the autoresponse to users in the same primary domain as the user taking the vacation.
|
||||
start_date: String "YYYY-MM-DD" The first day when the vacation responder was enabled for the user. In this version of the API, the startDate is in the UTC timezone, not the user's timezone.
|
||||
end_date: String "YYYY-MM-DD" The last day until which vacation responder is enabled for the user. In this version of the API, the endDate is the UTC timezone, not the user's timezone.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('vacation', username)
|
||||
properties = {}
|
||||
properties['enable'] = gdata.apps.service._bool2str(enable)
|
||||
if enable is True:
|
||||
properties['subject'] = subject
|
||||
properties['message'] = message
|
||||
if contacts_only != None:
|
||||
properties['contactsOnly'] = gdata.apps.service._bool2str(contacts_only)
|
||||
if domain_only != None:
|
||||
properties['domainOnly'] = gdata.apps.service._bool2str(domain_only)
|
||||
if start_date != None:
|
||||
properties['startDate'] = start_date
|
||||
if end_date != None:
|
||||
properties['endDate'] = end_date
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def UpdateSignature(self, username, signature):
|
||||
"""Update signature.
|
||||
|
||||
Args:
|
||||
username: User to update signature for.
|
||||
signature: Signature string.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('signature', username)
|
||||
properties = {'signature': signature}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetSignature(self, username):
|
||||
uri = self._serviceUrl('signature', username)
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def CreateDelegate(self, delegate, delegator):
|
||||
"""Create delegate
|
||||
|
||||
Args:
|
||||
delegate: User who will have access to delegator's account
|
||||
delegator: User whose account will be accessible by delegate
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the operation.
|
||||
"""
|
||||
uri = self._serviceUrl('delegation', delegator)
|
||||
properties = {'address': delegate}
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def GetDelegates(self, delegator):
|
||||
"""Retrieve delegates
|
||||
|
||||
Args:
|
||||
delegator: User whose account is accessible by retrieved delegates
|
||||
|
||||
Returns:
|
||||
A dict contaning the delegates
|
||||
"""
|
||||
uri = self._serviceUrl('delegation', delegator)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def DeleteDelegate(self, delegate, delegator):
|
||||
"""Delete delegate
|
||||
|
||||
Args:
|
||||
delegate: User account who has access to delegator's account
|
||||
delegator: Email address whose account will no longer be accessible by delegate
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the operation.
|
||||
"""
|
||||
uri = self._serviceUrl('delegation', delegator)+"/%s" % delegate
|
||||
return self._DeleteProperties(uri)
|
||||
|
||||
def UpdateLanguage(self, username, language):
|
||||
"""Update user interface language.
|
||||
|
||||
Args:
|
||||
username: User to update language for.
|
||||
language: Language code.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('language', username)
|
||||
properties = {'language': language}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None,
|
||||
snippets=None, unicode=None):
|
||||
"""Update general settings.
|
||||
|
||||
Args:
|
||||
username: User to update general settings for.
|
||||
page_size: Number of messages to show.
|
||||
shortcuts: Boolean whether shortcuts are enabled.
|
||||
arrows: Boolean whether arrows are enabled.
|
||||
snippets: Boolean whether snippets are enabled.
|
||||
unicode: Wheter unicode is enabled.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('general', username)
|
||||
properties = {}
|
||||
if page_size != None:
|
||||
properties['pageSize'] = str(page_size)
|
||||
if shortcuts != None:
|
||||
properties['shortcuts'] = gdata.apps.service._bool2str(shortcuts)
|
||||
if arrows != None:
|
||||
properties['arrows'] = gdata.apps.service._bool2str(arrows)
|
||||
if snippets != None:
|
||||
properties['snippets'] = gdata.apps.service._bool2str(snippets)
|
||||
if unicode != None:
|
||||
properties['unicode'] = gdata.apps.service._bool2str(unicode)
|
||||
return self._PutProperties(uri, properties)
|
||||
0
gdata/apps/groups/__init__.py
Normal file
0
gdata/apps/groups/__init__.py
Normal file
392
gdata/apps/groups/service.py
Normal file
392
gdata/apps/groups/service.py
Normal file
@@ -0,0 +1,392 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright (C) 2008 Google, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Allow Google Apps domain administrators to manage groups, group members and group owners.
|
||||
|
||||
GroupsService: Provides methods to manage groups, members and owners.
|
||||
"""
|
||||
|
||||
__author__ = 'google-apps-apis@googlegroups.com'
|
||||
|
||||
|
||||
import urllib
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
|
||||
|
||||
API_VER = '2.0'
|
||||
BASE_URL = '/a/feeds/group/' + API_VER + '/%s'
|
||||
GROUP_MEMBER_URL = BASE_URL + '?member=%s'
|
||||
GROUP_MEMBER_DIRECT_URL = GROUP_MEMBER_URL + '&directOnly=%s'
|
||||
GROUP_ID_URL = BASE_URL + '/%s'
|
||||
MEMBER_URL = BASE_URL + '/%s/member'
|
||||
MEMBER_WITH_SUSPENDED_URL = MEMBER_URL + '?includeSuspendedUsers=%s'
|
||||
MEMBER_ID_URL = MEMBER_URL + '/%s'
|
||||
OWNER_URL = BASE_URL + '/%s/owner'
|
||||
OWNER_WITH_SUSPENDED_URL = OWNER_URL + '?includeSuspendedUsers=%s'
|
||||
OWNER_ID_URL = OWNER_URL + '/%s'
|
||||
|
||||
PERMISSION_OWNER = 'Owner'
|
||||
PERMISSION_MEMBER = 'Member'
|
||||
PERMISSION_DOMAIN = 'Domain'
|
||||
PERMISSION_ANYONE = 'Anyone'
|
||||
|
||||
|
||||
class GroupsService(gdata.apps.service.PropertyService):
|
||||
"""Client for the Google Apps Groups service."""
|
||||
|
||||
def _ServiceUrl(self, service_type, is_existed, group_id, member_id, owner_email,
|
||||
direct_only=False, domain=None, suspended_users=False):
|
||||
if domain is None:
|
||||
domain = self.domain
|
||||
|
||||
if service_type == 'group':
|
||||
if group_id != '' and is_existed:
|
||||
return GROUP_ID_URL % (domain, group_id)
|
||||
elif member_id != '':
|
||||
#if direct_only:
|
||||
return GROUP_MEMBER_DIRECT_URL % (domain, urllib.quote_plus(member_id),
|
||||
self._Bool2Str(direct_only))
|
||||
#else:
|
||||
# return GROUP_MEMBER_URL % (domain, urllib.quote_plus(member_id))
|
||||
else:
|
||||
return BASE_URL % (domain)
|
||||
|
||||
if service_type == 'member':
|
||||
if member_id != '' and is_existed:
|
||||
return MEMBER_ID_URL % (domain, group_id, urllib.quote_plus(member_id))
|
||||
elif suspended_users:
|
||||
return MEMBER_WITH_SUSPENDED_URL % (domain, group_id,
|
||||
self._Bool2Str(suspended_users))
|
||||
else:
|
||||
return MEMBER_URL % (domain, group_id)
|
||||
|
||||
if service_type == 'owner':
|
||||
if owner_email != '' and is_existed:
|
||||
return OWNER_ID_URL % (domain, group_id, urllib.quote_plus(owner_email))
|
||||
elif suspended_users:
|
||||
return OWNER_WITH_SUSPENDED_URL % (domain, group_id,
|
||||
self._Bool2Str(suspended_users))
|
||||
else:
|
||||
return OWNER_URL % (domain, group_id)
|
||||
|
||||
def _Bool2Str(self, b):
|
||||
if b is None:
|
||||
return None
|
||||
return str(b is True).lower()
|
||||
|
||||
def _IsExisted(self, uri):
|
||||
try:
|
||||
self._GetProperties(uri)
|
||||
return True
|
||||
except gdata.apps.service.AppsForYourDomainException, e:
|
||||
if e.error_code == gdata.apps.service.ENTITY_DOES_NOT_EXIST:
|
||||
return False
|
||||
else:
|
||||
raise e
|
||||
|
||||
def CreateGroup(self, group_id, group_name, description, email_permission):
|
||||
"""Create a group.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
group_name: The name of the group.
|
||||
description: A description of the group
|
||||
email_permission: The subscription permission of the group.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the create operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', False, group_id, '', '')
|
||||
properties = {}
|
||||
properties['groupId'] = group_id
|
||||
properties['groupName'] = group_name
|
||||
properties['description'] = description
|
||||
properties['emailPermission'] = email_permission
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def UpdateGroup(self, group_id, group_name, description, email_permission):
|
||||
"""Update a group's name, description and/or permission.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
group_name: The name of the group.
|
||||
description: A description of the group
|
||||
email_permission: The subscription permission of the group.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', True, group_id, '', '')
|
||||
properties = {}
|
||||
properties['groupId'] = group_id
|
||||
properties['groupName'] = group_name
|
||||
properties['description'] = description
|
||||
properties['emailPermission'] = email_permission
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def RetrieveGroup(self, group_id):
|
||||
"""Retrieve a group based on its ID.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', True, group_id, '', '')
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def RetrieveAllGroups(self, noUserManagedGroups=False):
|
||||
"""Retrieve all groups in the domain.
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
A list containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', True, '', '', '')
|
||||
if noUserManagedGroups:
|
||||
uri = uri + '?skipUserCreatedGroups=True'
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def RetrievePageOfGroups(self, start_group=None):
|
||||
"""Retrieve one page of groups in the domain.
|
||||
|
||||
Args:
|
||||
start_group: The key to continue for pagination through all groups.
|
||||
|
||||
Returns:
|
||||
A feed object containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', True, '', '', '')
|
||||
if start_group is not None:
|
||||
uri += "?start="+start_group
|
||||
property_feed = self._GetPropertyFeed(uri)
|
||||
return property_feed
|
||||
|
||||
def RetrieveGroups(self, member_id, direct_only=False):
|
||||
"""Retrieve all groups that belong to the given member_id.
|
||||
|
||||
Args:
|
||||
member_id: The member's email address (e.g. member@example.com).
|
||||
direct_only: Boolean whether only return groups that this member directly belongs to.
|
||||
|
||||
Returns:
|
||||
A list containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', True, '', member_id, '', direct_only=direct_only)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def DeleteGroup(self, group_id):
|
||||
"""Delete a group based on its ID.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the delete operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', True, group_id, '', '')
|
||||
return self._DeleteProperties(uri)
|
||||
|
||||
def AddMemberToGroup(self, member_id, group_id):
|
||||
"""Add a member to a group.
|
||||
|
||||
Args:
|
||||
member_id: The member's email address (e.g. member@example.com).
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the add operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('member', False, group_id, member_id, '')
|
||||
properties = {}
|
||||
properties['memberId'] = member_id
|
||||
properties['membershipType'] = 'manager'
|
||||
properties['membership_type'] = 'manager'
|
||||
properties['delivery'] = '0'
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def IsMember(self, member_id, group_id):
|
||||
"""Check whether the given member already exists in the given group.
|
||||
|
||||
Args:
|
||||
member_id: The member's email address (e.g. member@example.com).
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
True if the member exists in the group. False otherwise.
|
||||
"""
|
||||
uri = self._ServiceUrl('member', True, group_id, member_id, '')
|
||||
return self._IsExisted(uri)
|
||||
|
||||
def RetrieveMember(self, member_id, group_id):
|
||||
"""Retrieve the given member in the given group.
|
||||
|
||||
Args:
|
||||
member_id: The member's email address (e.g. member@example.com).
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('member', True, group_id, member_id, '')
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def RetrieveAllMembers(self, group_id, suspended_users=False):
|
||||
"""Retrieve all members in the given group.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
suspended_users: A boolean; should we include any suspended users in
|
||||
the membership list returned?
|
||||
|
||||
Returns:
|
||||
A list containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('member', True, group_id, '', '',
|
||||
suspended_users=suspended_users)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def RetrievePageOfMembers(self, group_id, suspended_users=False, start=None):
|
||||
"""Retrieve one page of members of a given group.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
suspended_users: A boolean; should we include any suspended users in
|
||||
the membership list returned?
|
||||
start: The key to continue for pagination through all members.
|
||||
|
||||
Returns:
|
||||
A feed object containing the result of the retrieve operation.
|
||||
"""
|
||||
|
||||
uri = self._ServiceUrl('member', True, group_id, '', '',
|
||||
suspended_users=suspended_users)
|
||||
if start is not None:
|
||||
if suspended_users:
|
||||
uri += "&start="+start
|
||||
else:
|
||||
uri += "?start="+start
|
||||
property_feed = self._GetPropertyFeed(uri)
|
||||
return property_feed
|
||||
|
||||
def RemoveMemberFromGroup(self, member_id, group_id):
|
||||
"""Remove the given member from the given group.
|
||||
|
||||
Args:
|
||||
member_id: The member's email address (e.g. member@example.com).
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the remove operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('member', True, group_id, member_id, '')
|
||||
return self._DeleteProperties(uri)
|
||||
|
||||
def AddOwnerToGroup(self, owner_email, group_id):
|
||||
"""Add an owner to a group.
|
||||
|
||||
Args:
|
||||
owner_email: The email address of a group owner.
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the add operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('owner', False, group_id, '', owner_email)
|
||||
properties = {}
|
||||
properties['email'] = owner_email
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def IsOwner(self, owner_email, group_id):
|
||||
"""Check whether the given member an owner of the given group.
|
||||
|
||||
Args:
|
||||
owner_email: The email address of a group owner.
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
True if the member is an owner of the given group. False otherwise.
|
||||
"""
|
||||
uri = self._ServiceUrl('owner', True, group_id, '', owner_email)
|
||||
return self._IsExisted(uri)
|
||||
|
||||
def RetrieveOwner(self, owner_email, group_id):
|
||||
"""Retrieve the given owner in the given group.
|
||||
|
||||
Args:
|
||||
owner_email: The email address of a group owner.
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('owner', True, group_id, '', owner_email)
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def RetrieveAllOwners(self, group_id, suspended_users=False):
|
||||
"""Retrieve all owners of the given group.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
suspended_users: A boolean; should we include any suspended users in
|
||||
the ownership list returned?
|
||||
|
||||
Returns:
|
||||
A list containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('owner', True, group_id, '', '',
|
||||
suspended_users=suspended_users)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def RetrievePageOfOwners(self, group_id, suspended_users=False, start=None):
|
||||
"""Retrieve one page of owners of the given group.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
suspended_users: A boolean; should we include any suspended users in
|
||||
the ownership list returned?
|
||||
start: The key to continue for pagination through all owners.
|
||||
|
||||
Returns:
|
||||
A feed object containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('owner', True, group_id, '', '',
|
||||
suspended_users=suspended_users)
|
||||
if start is not None:
|
||||
if suspended_users:
|
||||
uri += "&start="+start
|
||||
else:
|
||||
uri += "?start="+start
|
||||
property_feed = self._GetPropertyFeed(uri)
|
||||
return property_feed
|
||||
|
||||
def RemoveOwnerFromGroup(self, owner_email, group_id):
|
||||
"""Remove the given owner from the given group.
|
||||
|
||||
Args:
|
||||
owner_email: The email address of a group owner.
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the remove operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('owner', True, group_id, '', owner_email)
|
||||
return self._DeleteProperties(uri)
|
||||
0
gdata/apps/groupsettings/__init__.py
Normal file
0
gdata/apps/groupsettings/__init__.py
Normal file
172
gdata/apps/groupsettings/service.py
Normal file
172
gdata/apps/groupsettings/service.py
Normal file
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/python2.4
|
||||
#
|
||||
# Copyright 2010 Google Inc. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""GroupSettingsService simplifies Group Settings API calls.
|
||||
|
||||
GroupSettingsService extends gdata.apps.service.PropertyService to ease interaction with
|
||||
the Google Apps Group Settings API.
|
||||
"""
|
||||
|
||||
__author__ = 'Jay Lee <jay0lee@gmail.com>'
|
||||
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
|
||||
# Group Settings URI template
|
||||
GROUP_SETTINGS_URI_TEMPLATE = '/groups/v1/groups/%s?alt=atom'
|
||||
|
||||
class GroupSettingsService(gdata.apps.service.PropertyService):
|
||||
"""Service extension for the Google Group Settings API service."""
|
||||
|
||||
def __init__(self, email=None, password=None, domain=None, source=None,
|
||||
server='www.googleapis.com', additional_headers=None,
|
||||
**kwargs):
|
||||
"""Creates a client for the Group Settings service.
|
||||
|
||||
Args:
|
||||
email: string (optional) The user's email address, used for
|
||||
authentication.
|
||||
password: string (optional) The user's password.
|
||||
domain: string (optional) The Google Apps domain name.
|
||||
source: string (optional) The name of the user's application.
|
||||
server: string (optional) The name of the server to which a connection
|
||||
will be opened. Default value: 'apps-apis.google.com'.
|
||||
**kwargs: The other parameters to pass to gdata.service.GDataService
|
||||
constructor.
|
||||
"""
|
||||
gdata.service.GDataService.__init__(
|
||||
self, email=email, password=password, service='apps', source=source,
|
||||
server=server, additional_headers=additional_headers, **kwargs)
|
||||
self.ssl = True
|
||||
self.port = 443
|
||||
self.domain = domain
|
||||
|
||||
def make_group_settings_uri(self, group_email):
|
||||
"""Creates the URI for the Group Settings API call.
|
||||
|
||||
Create the URI to access the group settings API. If params are provided,
|
||||
append them as GET params.
|
||||
|
||||
Args:
|
||||
group: email address of the group
|
||||
|
||||
Returns:
|
||||
A string giving the URI for Group Settings API calls
|
||||
|
||||
"""
|
||||
uri = GROUP_SETTINGS_URI_TEMPLATE % (group_email)
|
||||
return uri
|
||||
|
||||
MakeGroupSettingsUri = make_group_settings_uri
|
||||
|
||||
def retrieve_group_settings(self, group_email):
|
||||
"""Retrieves group settings
|
||||
|
||||
Args:
|
||||
group_email: string, the group email address
|
||||
|
||||
Returns:
|
||||
A dict. The group settings
|
||||
"""
|
||||
uri = self.MakeGroupSettingsUri(group_email)
|
||||
group_settings_entry = self.Get(uri)
|
||||
group_settings_values = []
|
||||
for group_settings_value in group_settings_entry.extension_elements:
|
||||
group_settings_values.append({group_settings_value.tag: group_settings_value.text})
|
||||
return group_settings_values
|
||||
|
||||
RetrieveGroupSettings = retrieve_group_settings
|
||||
|
||||
def update_group_settings(self, group_email, allow_external_members=None,
|
||||
allow_google_communication=None, allow_web_posting=None, archive_only=None, custom_reply_to=None,
|
||||
default_message_deny_notification_text=None, description=None, is_archived=None, max_message_bytes=None,
|
||||
members_can_post_as_the_group=None, message_display_font=None, message_moderation_level=None, name=None,
|
||||
primary_language=None, reply_to=None, send_message_deny_notification=None, show_in_group_directory=None,
|
||||
who_can_invite=None, who_can_join=None, who_can_post_message=None, who_can_view_group=None,
|
||||
who_can_view_membership=None, include_in_global_address_list=None, spam_moderation_level=None):
|
||||
|
||||
uri = self.MakeGroupSettingsUri(group_email)
|
||||
|
||||
xml = '''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<entry xmlns="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006" xmlns:gd="http://schemas.google.com/g/2005">
|
||||
<id>tag:googleapis.com,2010:apps:groupssettings:GROUP:NNN</id>
|
||||
<title>Groups Resource Entry</title>
|
||||
<author>
|
||||
<name>Google</name>
|
||||
</author>
|
||||
<apps:id>%s</apps:id>
|
||||
<apps:email>%s</apps:email>
|
||||
|
||||
''' % (group_email, group_email)
|
||||
|
||||
template = "<apps:%s>%s</apps:%s>\n"
|
||||
if name != None:
|
||||
xml += template % ('name', name, 'name')
|
||||
if allow_external_members != None:
|
||||
xml += template % ('allowExternalMembers', allow_external_members, 'allowExternalMembers')
|
||||
if allow_google_communication != None:
|
||||
xml += template % ('allowGoogleCommunication', allow_google_communication, 'allowGoogleCommunication')
|
||||
if allow_web_posting != None:
|
||||
xml += template % ('allowWebPosting', allow_web_posting, 'allowWebPosting')
|
||||
if archive_only != None:
|
||||
xml += template % ('archiveOnly', archive_only, 'archiveOnly')
|
||||
if custom_reply_to != None:
|
||||
xml += template % ('customReplyTo', custom_reply_to, 'customReplyTo')
|
||||
if default_message_deny_notification_text != None:
|
||||
xml += template % ('defaultMessageDenyNotificationText', default_message_deny_notification_text, 'defaultMessageDenyNotificationText')
|
||||
if description != None:
|
||||
xml += template % ('description', description, 'description')
|
||||
if is_archived != None:
|
||||
xml += template % ('isArchived', is_archived, 'isArchived')
|
||||
if max_message_bytes != None:
|
||||
xml += template % ('maxMessageBytes', max_message_bytes, 'maxMessageBytes')
|
||||
if members_can_post_as_the_group != None:
|
||||
xml += template % ('membersCanPostAsTheGroup', members_can_post_as_the_group, 'membersCanPostAsTheGroup')
|
||||
if message_display_font != None:
|
||||
xml += template % ('messageDisplayFont', message_display_font, 'messageDisplayFont')
|
||||
if message_moderation_level != None:
|
||||
xml += template % ('messageModerationLevel', message_moderation_level, 'messageModerationLevel')
|
||||
if primary_language != None:
|
||||
xml += template % ('primaryLanguage', primary_language, 'primaryLanguage')
|
||||
if reply_to != None:
|
||||
xml += template % ('replyTo', reply_to, 'replyTo')
|
||||
if send_message_deny_notification != None:
|
||||
xml += template % ('sendMessageDenyNotification', send_message_deny_notification, 'sendMessageDenyNotification')
|
||||
if show_in_group_directory != None:
|
||||
xml += template % ('showInGroupDirectory', show_in_group_directory, 'showInGroupDirectory')
|
||||
if who_can_invite != None:
|
||||
xml += template % ('whoCanInvite', who_can_invite, 'whoCanInvite')
|
||||
if who_can_join != None:
|
||||
xml += template % ('whoCanJoin', who_can_join, 'whoCanJoin')
|
||||
if who_can_post_message != None:
|
||||
xml += template % ('whoCanPostMessage', who_can_post_message, 'whoCanPostMessage')
|
||||
if who_can_view_group != None:
|
||||
xml += template % ('whoCanViewGroup', who_can_view_group, 'whoCanViewGroup')
|
||||
if who_can_view_membership != None:
|
||||
xml += template % ('whoCanViewMembership', who_can_view_membership, 'whoCanViewMembership')
|
||||
if include_in_global_address_list != None:
|
||||
xml += template % ('includeInGlobalAddressList', include_in_global_address_list, 'includeInGlobalAddressList')
|
||||
if spam_moderation_level != None:
|
||||
xml += template % ('spamModerationLevel', spam_moderation_level, 'spamModerationLevel')
|
||||
xml += '</entry>'
|
||||
group_settings_entry = self.Put(uri=uri, data=xml)
|
||||
group_settings_values = []
|
||||
for group_settings_value in group_settings_entry.extension_elements:
|
||||
group_settings_values.append({group_settings_value.tag: group_settings_value.text})
|
||||
return group_settings_values
|
||||
|
||||
UpdateGroupSettings = update_group_settings
|
||||
212
gdata/apps/migration/__init__.py
Normal file
212
gdata/apps/migration/__init__.py
Normal file
@@ -0,0 +1,212 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright (C) 2008 Google
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Contains objects used with Google Apps."""
|
||||
|
||||
__author__ = 'google-apps-apis@googlegroups.com'
|
||||
|
||||
|
||||
import atom
|
||||
import gdata
|
||||
|
||||
|
||||
# XML namespaces which are often used in Google Apps entity.
|
||||
APPS_NAMESPACE = 'http://schemas.google.com/apps/2006'
|
||||
APPS_TEMPLATE = '{http://schemas.google.com/apps/2006}%s'
|
||||
|
||||
|
||||
class Rfc822Msg(atom.AtomBase):
|
||||
"""The Migration rfc822Msg element."""
|
||||
|
||||
_tag = 'rfc822Msg'
|
||||
_namespace = APPS_NAMESPACE
|
||||
_children = atom.AtomBase._children.copy()
|
||||
_attributes = atom.AtomBase._attributes.copy()
|
||||
_attributes['encoding'] = 'encoding'
|
||||
|
||||
def __init__(self, extension_elements=None,
|
||||
extension_attributes=None, text=None):
|
||||
self.text = text
|
||||
self.encoding = 'base64'
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def Rfc822MsgFromString(xml_string):
|
||||
"""Parse in the Rrc822 message from the XML definition."""
|
||||
|
||||
return atom.CreateClassFromXMLString(Rfc822Msg, xml_string)
|
||||
|
||||
|
||||
class MailItemProperty(atom.AtomBase):
|
||||
"""The Migration mailItemProperty element."""
|
||||
|
||||
_tag = 'mailItemProperty'
|
||||
_namespace = APPS_NAMESPACE
|
||||
_children = atom.AtomBase._children.copy()
|
||||
_attributes = atom.AtomBase._attributes.copy()
|
||||
_attributes['value'] = 'value'
|
||||
|
||||
def __init__(self, value=None, extension_elements=None,
|
||||
extension_attributes=None, text=None):
|
||||
self.value = value
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def MailItemPropertyFromString(xml_string):
|
||||
"""Parse in the MailItemProperiy from the XML definition."""
|
||||
|
||||
return atom.CreateClassFromXMLString(MailItemProperty, xml_string)
|
||||
|
||||
|
||||
class Label(atom.AtomBase):
|
||||
"""The Migration label element."""
|
||||
|
||||
_tag = 'label'
|
||||
_namespace = APPS_NAMESPACE
|
||||
_children = atom.AtomBase._children.copy()
|
||||
_attributes = atom.AtomBase._attributes.copy()
|
||||
_attributes['labelName'] = 'label_name'
|
||||
|
||||
def __init__(self, label_name=None,
|
||||
extension_elements=None, extension_attributes=None,
|
||||
text=None):
|
||||
self.label_name = label_name
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def LabelFromString(xml_string):
|
||||
"""Parse in the mailItemProperty from the XML definition."""
|
||||
|
||||
return atom.CreateClassFromXMLString(Label, xml_string)
|
||||
|
||||
|
||||
class MailEntry(gdata.GDataEntry):
|
||||
"""A Google Migration flavor of an Atom Entry."""
|
||||
|
||||
_tag = 'entry'
|
||||
_namespace = atom.ATOM_NAMESPACE
|
||||
_children = gdata.GDataEntry._children.copy()
|
||||
_attributes = gdata.GDataEntry._attributes.copy()
|
||||
_children['{%s}rfc822Msg' % APPS_NAMESPACE] = ('rfc822_msg', Rfc822Msg)
|
||||
_children['{%s}mailItemProperty' % APPS_NAMESPACE] = ('mail_item_property',
|
||||
[MailItemProperty])
|
||||
_children['{%s}label' % APPS_NAMESPACE] = ('label', [Label])
|
||||
|
||||
def __init__(self, author=None, category=None, content=None,
|
||||
atom_id=None, link=None, published=None,
|
||||
title=None, updated=None,
|
||||
rfc822_msg=None, mail_item_property=None, label=None,
|
||||
extended_property=None,
|
||||
extension_elements=None, extension_attributes=None, text=None):
|
||||
|
||||
gdata.GDataEntry.__init__(self, author=author, category=category,
|
||||
content=content,
|
||||
atom_id=atom_id, link=link, published=published,
|
||||
title=title, updated=updated)
|
||||
self.rfc822_msg = rfc822_msg
|
||||
self.mail_item_property = mail_item_property
|
||||
self.label = label
|
||||
self.extended_property = extended_property or []
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def MailEntryFromString(xml_string):
|
||||
"""Parse in the MailEntry from the XML definition."""
|
||||
|
||||
return atom.CreateClassFromXMLString(MailEntry, xml_string)
|
||||
|
||||
|
||||
class BatchMailEntry(gdata.BatchEntry):
|
||||
"""A Google Migration flavor of an Atom Entry."""
|
||||
|
||||
_tag = gdata.BatchEntry._tag
|
||||
_namespace = gdata.BatchEntry._namespace
|
||||
_children = gdata.BatchEntry._children.copy()
|
||||
_attributes = gdata.BatchEntry._attributes.copy()
|
||||
_children['{%s}rfc822Msg' % APPS_NAMESPACE] = ('rfc822_msg', Rfc822Msg)
|
||||
_children['{%s}mailItemProperty' % APPS_NAMESPACE] = ('mail_item_property',
|
||||
[MailItemProperty])
|
||||
_children['{%s}label' % APPS_NAMESPACE] = ('label', [Label])
|
||||
|
||||
def __init__(self, author=None, category=None, content=None,
|
||||
atom_id=None, link=None, published=None,
|
||||
title=None, updated=None,
|
||||
rfc822_msg=None, mail_item_property=None, label=None,
|
||||
batch_operation=None, batch_id=None, batch_status=None,
|
||||
extended_property=None,
|
||||
extension_elements=None, extension_attributes=None, text=None):
|
||||
|
||||
gdata.BatchEntry.__init__(self, author=author, category=category,
|
||||
content=content,
|
||||
atom_id=atom_id, link=link, published=published,
|
||||
batch_operation=batch_operation,
|
||||
batch_id=batch_id, batch_status=batch_status,
|
||||
title=title, updated=updated)
|
||||
self.rfc822_msg = rfc822_msg or None
|
||||
self.mail_item_property = mail_item_property or []
|
||||
self.label = label or []
|
||||
self.extended_property = extended_property or []
|
||||
self.text = text
|
||||
self.extension_elements = extension_elements or []
|
||||
self.extension_attributes = extension_attributes or {}
|
||||
|
||||
|
||||
def BatchMailEntryFromString(xml_string):
|
||||
"""Parse in the BatchMailEntry from the XML definition."""
|
||||
|
||||
return atom.CreateClassFromXMLString(BatchMailEntry, xml_string)
|
||||
|
||||
|
||||
class BatchMailEventFeed(gdata.BatchFeed):
|
||||
"""A Migration event feed flavor of an Atom Feed."""
|
||||
|
||||
_tag = gdata.BatchFeed._tag
|
||||
_namespace = gdata.BatchFeed._namespace
|
||||
_children = gdata.BatchFeed._children.copy()
|
||||
_attributes = gdata.BatchFeed._attributes.copy()
|
||||
_children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BatchMailEntry])
|
||||
|
||||
def __init__(self, author=None, category=None, contributor=None,
|
||||
generator=None, icon=None, atom_id=None, link=None, logo=None,
|
||||
rights=None, subtitle=None, title=None, updated=None,
|
||||
entry=None, total_results=None, start_index=None,
|
||||
items_per_page=None, interrupted=None, extension_elements=None,
|
||||
extension_attributes=None, text=None):
|
||||
gdata.BatchFeed.__init__(self, author=author, category=category,
|
||||
contributor=contributor, generator=generator,
|
||||
icon=icon, atom_id=atom_id, link=link,
|
||||
logo=logo, rights=rights, subtitle=subtitle,
|
||||
title=title, updated=updated, entry=entry,
|
||||
total_results=total_results,
|
||||
start_index=start_index,
|
||||
items_per_page=items_per_page,
|
||||
interrupted=interrupted,
|
||||
extension_elements=extension_elements,
|
||||
extension_attributes=extension_attributes,
|
||||
text=text)
|
||||
|
||||
|
||||
def BatchMailEventFeedFromString(xml_string):
|
||||
"""Parse in the BatchMailEventFeed from the XML definition."""
|
||||
|
||||
return atom.CreateClassFromXMLString(BatchMailEventFeed, xml_string)
|
||||
129
gdata/apps/migration/service.py
Normal file
129
gdata/apps/migration/service.py
Normal file
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright (C) 2008 Google.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Contains the methods to import mail via Google Apps Email Migration API.
|
||||
|
||||
MigrationService: Provides methids to import mail.
|
||||
"""
|
||||
|
||||
__author__ = 'google-apps-apis@googlegroups.com'
|
||||
|
||||
|
||||
import base64
|
||||
import gdata
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
from gdata.apps import migration
|
||||
|
||||
|
||||
API_VER = '2.0'
|
||||
|
||||
|
||||
class MigrationService(gdata.apps.service.AppsService):
|
||||
"""Client for the EMAPI migration service. Use either ImportMail to import
|
||||
one message at a time, or AddBatchEntry and SubmitBatch to import a batch of
|
||||
messages at a time.
|
||||
"""
|
||||
def __init__(self, email=None, password=None, domain=None, source=None,
|
||||
server='apps-apis.google.com', additional_headers=None):
|
||||
gdata.apps.service.AppsService.__init__(
|
||||
self, email=email, password=password, domain=domain, source=source,
|
||||
server=server, additional_headers=additional_headers)
|
||||
self.mail_batch = migration.BatchMailEventFeed()
|
||||
|
||||
def _BaseURL(self):
|
||||
return '/a/feeds/migration/%s/%s' % (API_VER, self.domain)
|
||||
|
||||
def ImportMail(self, user_name, mail_message, mail_item_properties,
|
||||
mail_labels):
|
||||
"""Import a single mail message.
|
||||
|
||||
Args:
|
||||
user_name: The username to import messages to.
|
||||
mail_message: An RFC822 format email message.
|
||||
mail_item_properties: A list of Gmail properties to apply to the message.
|
||||
mail_labels: A list of labels to apply to the message.
|
||||
|
||||
Returns:
|
||||
A MailEntry representing the successfully imported message.
|
||||
|
||||
Raises:
|
||||
AppsForYourDomainException: An error occurred importing the message.
|
||||
"""
|
||||
uri = '%s/%s/mail' % (self._BaseURL(), user_name)
|
||||
|
||||
mail_entry = migration.MailEntry()
|
||||
mail_entry.rfc822_msg = migration.Rfc822Msg(text=(base64.b64encode(
|
||||
mail_message)))
|
||||
mail_entry.rfc822_msg.encoding = 'base64'
|
||||
mail_entry.mail_item_property = map(
|
||||
lambda x: migration.MailItemProperty(value=x), mail_item_properties)
|
||||
mail_entry.label = map(lambda x: migration.Label(label_name=x),
|
||||
mail_labels)
|
||||
|
||||
try:
|
||||
return migration.MailEntryFromString(str(self.Post(mail_entry, uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
|
||||
def AddBatchEntry(self, mail_message, mail_item_properties,
|
||||
mail_labels):
|
||||
"""Add a message to the current batch that you later will submit.
|
||||
|
||||
Args:
|
||||
mail_message: An RFC822 format email message.
|
||||
mail_item_properties: A list of Gmail properties to apply to the message.
|
||||
mail_labels: A list of labels to apply to the message.
|
||||
|
||||
Returns:
|
||||
The length of the MailEntry representing the message.
|
||||
"""
|
||||
mail_entry = migration.BatchMailEntry()
|
||||
mail_entry.rfc822_msg = migration.Rfc822Msg(text=(base64.b64encode(
|
||||
mail_message)))
|
||||
mail_entry.rfc822_msg.encoding = 'base64'
|
||||
mail_entry.mail_item_property = map(
|
||||
lambda x: migration.MailItemProperty(value=x), mail_item_properties)
|
||||
mail_entry.label = map(lambda x: migration.Label(label_name=x),
|
||||
mail_labels)
|
||||
|
||||
self.mail_batch.AddBatchEntry(mail_entry)
|
||||
|
||||
return len(str(mail_entry))
|
||||
|
||||
def SubmitBatch(self, user_name):
|
||||
"""Send a all the mail items you have added to the batch to the server.
|
||||
|
||||
Args:
|
||||
user_name: The username to import messages to.
|
||||
|
||||
Returns:
|
||||
A HTTPResponse from the web service call.
|
||||
|
||||
Raises:
|
||||
AppsForYourDomainException: An error occurred importing the batch.
|
||||
"""
|
||||
uri = '%s/%s/mail/batch' % (self._BaseURL(), user_name)
|
||||
|
||||
try:
|
||||
self.result = self.Post(self.mail_batch, uri,
|
||||
converter=migration.BatchMailEventFeedFromString)
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
|
||||
self.mail_batch = migration.BatchMailEventFeed()
|
||||
|
||||
return self.result
|
||||
16
gdata/apps/multidomain/__init__.py
Normal file
16
gdata/apps/multidomain/__init__.py
Normal file
@@ -0,0 +1,16 @@
|
||||
#!/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.
|
||||
|
||||
155
gdata/apps/multidomain/service.py
Normal file
155
gdata/apps/multidomain/service.py
Normal file
@@ -0,0 +1,155 @@
|
||||
#!/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.
|
||||
|
||||
"""Extended Multi Domain Support.
|
||||
|
||||
MultiDomainService: Multi Domain Support."""
|
||||
|
||||
__author__ = 'jay@ditoweb.com'
|
||||
|
||||
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
|
||||
import urllib
|
||||
|
||||
API_VER='2.0'
|
||||
|
||||
class MultiDomainService(gdata.apps.service.PropertyService):
|
||||
"""Extended functions for Google Apps Multi-Domain Support."""
|
||||
|
||||
def _serviceUrl(self, setting_id, email=None, params=None):
|
||||
uri = '/a/feeds/%s/%s/%s' % (setting_id, API_VER, self.domain)
|
||||
if email:
|
||||
uri += '/' + email
|
||||
if params:
|
||||
uri += '?' + urllib.urlencode(params)
|
||||
return uri
|
||||
|
||||
|
||||
def CreateUser(self, user_email, password, first_name, last_name, is_admin=None, hash_function=None, change_password=None, agreed_to_terms=None,
|
||||
suspended=None, ip_whitelisted=None, quota_in_gb=None):
|
||||
if user_email.find('@') == -1:
|
||||
user_email = '%s@%s' % (user_email, self.domain)
|
||||
uri = self._serviceUrl(setting_id='user')
|
||||
properties = {}
|
||||
properties['userEmail'] = user_email
|
||||
properties['password'] = password
|
||||
properties['firstName'] = first_name
|
||||
properties['lastName'] = last_name
|
||||
if is_admin != None:
|
||||
properties['isAdmin'] = gdata.apps.service._bool2str(is_admin)
|
||||
if hash_function != None:
|
||||
properties['hashFunction'] = hash_function
|
||||
if change_password != None:
|
||||
properties['isChangePasswordAtNextLogin'] = gdata.apps.service._bool2str(change_password)
|
||||
if agreed_to_terms != None:
|
||||
properties['agreedToTerms'] = gdata.apps.service._bool2str(agreed_to_terms)
|
||||
if suspended != None:
|
||||
properties['isSuspended'] = gdata.apps.service._bool2str(suspended)
|
||||
if ip_whitelisted != None:
|
||||
properties['ipWhitelisted'] = gdata.apps.service._bool2str(ip_whitelisted)
|
||||
if quota_in_gb != None:
|
||||
properties['quotaInGb'] = quota_in_gb
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def UpdateUser(self, user_email, password=None, first_name=None, last_name=None, is_admin=None, hash_function=None, change_password=None, agreed_to_terms=None,
|
||||
suspended=None, ip_whitelisted=None, quota_in_gb=None):
|
||||
if user_email.find('@') == -1:
|
||||
user_email = '%s@%s' % (user_email, self.domain)
|
||||
uri = self._serviceUrl(setting_id='user', email=user_email)
|
||||
properties = {}
|
||||
if password != None:
|
||||
properties['password'] = password
|
||||
if first_name != None:
|
||||
properties['firstName'] = first_name
|
||||
if last_name != None:
|
||||
properties['lastName'] = last_name
|
||||
if is_admin != None:
|
||||
properties['isAdmin'] = gdata.apps.service._bool2str(is_admin)
|
||||
if hash_function != None:
|
||||
properties['hashFunction'] = hash_function
|
||||
if change_password != None:
|
||||
properties['isChangePasswordAtNextLogin'] = gdata.apps.service._bool2str(change_password)
|
||||
if agreed_to_terms != None:
|
||||
properties['agreedToTerms'] = gdata.apps.service._bool2str(agreed_to_terms)
|
||||
if suspended != None:
|
||||
properties['isSuspended'] = gdata.apps.service._bool2str(suspended)
|
||||
if ip_whitelisted != None:
|
||||
properties['ipWhitelisted'] = gdata.apps.service._bool2str(ip_whitelisted)
|
||||
if quota_in_gb != None:
|
||||
properties['quotaInGb'] = str(quota_in_gb)
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def RetrieveUser(self, user_email):
|
||||
if user_email.find('@') == -1:
|
||||
user_email = '%s@%s' % (user_email, self.domain)
|
||||
uri = self._serviceUrl(setting_id='user', email=user_email)
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def RetrieveAllUsers(self):
|
||||
uri = self._serviceUrl(setting_id='user')
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def DeleteUser(self, user_email):
|
||||
if user_email.find('@') == -1:
|
||||
user_email = '%s@%s' % (user_email, self.domain)
|
||||
uri = self._serviceUrl(setting_id='user', email=user_email)
|
||||
return self._DeleteProperties(uri)
|
||||
|
||||
def RenameUser(self, old_email, new_email):
|
||||
if old_email.find('@') == -1:
|
||||
old_email = '%s@%s' % (old_email, self.domain)
|
||||
if new_email.find('@') == -1:
|
||||
new_email = '%s@%s' % (new_email, self.domain)
|
||||
uri = self._serviceUrl(setting_id='user/userEmail', email=old_email)
|
||||
properties = {}
|
||||
properties['newEmail'] = new_email
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def CreateAlias(self, user_email, alias_email):
|
||||
if alias_email.find('@') == -1:
|
||||
alias_email = '%s@%s' % (alias_email, self.domain)
|
||||
if user_email.find('@') == -1:
|
||||
user_email = '%s@%s' % (user_email, self.domain)
|
||||
uri = self._serviceUrl(setting_id='alias')
|
||||
properties = {}
|
||||
properties['userEmail'] = user_email
|
||||
properties['aliasEmail'] = alias_email
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def RetrieveAlias(self, alias_email):
|
||||
if alias_email.find('@') == -1:
|
||||
alias_email = '%s@%s' % (alias_email, self.domain)
|
||||
uri = self._serviceUrl(setting_id='alias', email=alias_email)
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def RetrieveAllAliases(self):
|
||||
uri = self._serviceUrl(setting_id='alias')
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def DeleteAlias(self, alias_email):
|
||||
if alias_email.find('@') == -1:
|
||||
alias_email = '%s@%s' % (alias_email, self.domain)
|
||||
uri = self._serviceUrl(setting_id='alias', email=alias_email)
|
||||
return self._DeleteProperties(uri)
|
||||
|
||||
def GetUserAliases(self, user_email):
|
||||
if user_email.find('@') == -1:
|
||||
user_email = '%s@%s' % (user_email, self.domain)
|
||||
uri = self._serviceUrl(setting_id='alias', params={'userEmail' : user_email})
|
||||
return self._GetPropertiesList(uri)
|
||||
16
gdata/apps/orgs/__init__.py
Normal file
16
gdata/apps/orgs/__init__.py
Normal file
@@ -0,0 +1,16 @@
|
||||
#!/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.
|
||||
|
||||
170
gdata/apps/orgs/service.py
Normal file
170
gdata/apps/orgs/service.py
Normal file
@@ -0,0 +1,170 @@
|
||||
#!/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.
|
||||
|
||||
"""Organization Support.
|
||||
|
||||
OrganizationService: Organization Support."""
|
||||
|
||||
__author__ = 'jlee@pbu.edu'
|
||||
|
||||
|
||||
import urllib
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
|
||||
|
||||
API_VER='2.0'
|
||||
|
||||
class OrganizationService(gdata.apps.service.PropertyService):
|
||||
"""Extended functions for Google Apps Organization Support."""
|
||||
|
||||
def _serviceUrl(self, setting_id, domain=None):
|
||||
if domain is None:
|
||||
domain = self.domain
|
||||
return '/a/feeds/%s/%s/%s' % (setting_id, API_VER, domain)
|
||||
|
||||
def RetrieveCustomerId(self):
|
||||
|
||||
uri = '/a/feeds/customer/2.0/customerId'
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def CreateOrganizationUnit(self, name, description, parent_org_unit_path='/', block_inheritance=False):
|
||||
|
||||
customer_id = self.RetrieveCustomerId()['customerId']
|
||||
uri = '/a/feeds/orgunit/2.0/%s' % customer_id
|
||||
properties = {}
|
||||
properties['name'] = name
|
||||
properties['description'] = description
|
||||
properties['parentOrgUnitPath'] = urllib.quote_plus(parent_org_unit_path, safe='/')
|
||||
properties['blockInheritance'] = gdata.apps.service._bool2str(block_inheritance)
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def UpdateOrganizationUnit(self, old_name, new_name=None, description=None, parent_org_unit_path=None, block_inheritance=None, users_to_move=None):
|
||||
|
||||
customer_id = self.RetrieveCustomerId()['customerId']
|
||||
old_name = urllib.quote_plus(old_name, safe='/')
|
||||
uri = '/a/feeds/orgunit/2.0/%s/%s' % (customer_id, old_name)
|
||||
properties = {}
|
||||
if new_name != None:
|
||||
properties['name'] = new_name
|
||||
if description != None:
|
||||
properties['description'] = description
|
||||
if parent_org_unit_path != None:
|
||||
properties['parentOrgUnitPath'] = urllib.quote_plus(parent_org_unit_path, safe='/')
|
||||
if block_inheritance != None:
|
||||
properties['blockInheritance'] = gdata.apps.service._bool2str(block_inheritance)
|
||||
if users_to_move != None:
|
||||
properties['usersToMove'] = ''
|
||||
for user in users_to_move:
|
||||
if user.find('@') < 0:
|
||||
user = user+'@'+self.domain
|
||||
properties['usersToMove'] += user+', '
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def UpdateUserOrganization(self, user, new_name, old_name=None, customer_id=None):
|
||||
|
||||
if customer_id == None:
|
||||
customer_id = self.RetrieveCustomerId()['customerId']
|
||||
uri = '/a/feeds/orguser/2.0/%s/%s' % (customer_id, urllib.quote_plus(user))
|
||||
properties = {}
|
||||
properties['orgUnitPath'] = new_name
|
||||
if old_name != None:
|
||||
properties['oldOrgUnitPath'] = old_name
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def RetrieveOrganizationUnit(self, name):
|
||||
|
||||
customer_id = self.RetrieveCustomerId()['customerId']
|
||||
name = urllib.quote_plus(name, safe='/')
|
||||
uri = '/a/feeds/orgunit/2.0/%s/%s' % (customer_id, name)
|
||||
org = self._GetProperties(uri)
|
||||
try:
|
||||
org['orgUnitPath'] = urllib.unquote_plus(org['orgUnitPath'])
|
||||
org['parentOrgUnitPath'] = urllib.unquote_plus(org['parentOrgUnitPath'])
|
||||
except AttributeError:
|
||||
pass
|
||||
return org
|
||||
|
||||
def RetrieveAllOrganizationUnits(self):
|
||||
|
||||
customer_id = self.RetrieveCustomerId()['customerId']
|
||||
uri = '/a/feeds/orgunit/2.0/%s?get=all' % customer_id
|
||||
all_orgs = self._GetPropertiesList(uri)
|
||||
for org in all_orgs:
|
||||
try:
|
||||
org['orgUnitPath'] = urllib.unquote_plus(org['orgUnitPath'])
|
||||
org['parentOrgUnitPath'] = urllib.unquote_plus(org['parentOrgUnitPath'])
|
||||
except AttributeError:
|
||||
pass
|
||||
return all_orgs
|
||||
|
||||
def RetrieveSubOrganizationUnits(self, name):
|
||||
|
||||
customer_id = self.RetrieveCustomerId()['customerId']
|
||||
uri = '/a/feeds/orgunit/2.0/%s?get=children&orgUnitPath=%s' % (customer_id, urllib.quote_plus(name, safe='/'))
|
||||
sub_orgs = self._GetPropertiesList(uri)
|
||||
for org in sub_orgs:
|
||||
try:
|
||||
org['orgUnitPath'] = urllib.unquote_plus(org['orgUnitPath'])
|
||||
org['parentOrgUnitPath'] = urllib.unquote_plus(org['parentOrgUnitPath'])
|
||||
except AttributeError:
|
||||
pass
|
||||
return sub_orgs
|
||||
|
||||
def DeleteOrganizationUnit(self, name):
|
||||
|
||||
customer_id = self.RetrieveCustomerId()['customerId']
|
||||
name = urllib.quote_plus(name, safe='/')
|
||||
uri = '/a/feeds/orgunit/2.0/%s/%s' % (customer_id, name)
|
||||
return self._DeleteProperties(uri)
|
||||
|
||||
def RetrieveUserOrganization(self, user):
|
||||
|
||||
customer_id = self.RetrieveCustomerId()['customerId']
|
||||
if user.find('@') < 0:
|
||||
user = user+'@'+self.domain
|
||||
uri = '/a/feeds/orguser/2.0/%s/%s' % (customer_id, urllib.quote_plus(user))
|
||||
org = self._GetProperties(uri)
|
||||
try:
|
||||
org['orgUnitPath'] = urllib.unquote_plus(org['orgUnitPath'])
|
||||
except AttributeError:
|
||||
pass
|
||||
return org
|
||||
|
||||
def RetrieveAllOrganizationUsers(self):
|
||||
|
||||
customer_id = self.RetrieveCustomerId()['customerId']
|
||||
uri = '/a/feeds/orguser/2.0/%s?get=all' % customer_id
|
||||
all_users = self._GetPropertiesList(uri)
|
||||
for user in all_users:
|
||||
try:
|
||||
user['orgUnitPath'] = urllib.unquote_plus(user['orgUnitPath'])
|
||||
except AttributeError:
|
||||
pass
|
||||
return all_users
|
||||
|
||||
def RetrieveAllOrganizationUnitUsers(self, name):
|
||||
|
||||
customer_id = self.RetrieveCustomerId()['customerId']
|
||||
uri = '/a/feeds/orguser/2.0/%s?get=children&orgUnitPath=%s' % (customer_id, urllib.quote_plus(name))
|
||||
all_users = self._GetPropertiesList(uri)
|
||||
for user in all_users:
|
||||
try:
|
||||
user['orgUnitPath'] = urllib.unquote_plus(user['orgUnitPath'])
|
||||
except AttributeError:
|
||||
pass
|
||||
return all_users
|
||||
0
gdata/apps/reporting/__init__.py
Normal file
0
gdata/apps/reporting/__init__.py
Normal file
99
gdata/apps/reporting/service.py
Normal file
99
gdata/apps/reporting/service.py
Normal file
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/python2.4
|
||||
#
|
||||
# Copyright 2010 Google Inc. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""ReportService simplifies Reporting API calls.
|
||||
|
||||
ReportService extends gdata.apps.service.PropertyService to ease interaction with
|
||||
the Google Apps Reporting API.
|
||||
"""
|
||||
|
||||
__author__ = 'Jay Lee <jay0lee@gmail.com>'
|
||||
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
import time
|
||||
|
||||
class ReportService(gdata.apps.service.PropertyService):
|
||||
"""Service extension for the Google Reporting API service."""
|
||||
|
||||
def __init__(self, email=None, password=None, domain=None, source=None,
|
||||
server='www.google.com', additional_headers=None,
|
||||
**kwargs):
|
||||
"""Creates a client for the Reporting service.
|
||||
|
||||
Args:
|
||||
email: string (optional) The user's email address, used for
|
||||
authentication.
|
||||
password: string (optional) The user's password.
|
||||
domain: string (optional) The Google Apps domain name.
|
||||
source: string (optional) The name of the user's application.
|
||||
server: string (optional) The name of the server to which a connection
|
||||
will be opened. Default value: 'apps-apis.google.com'.
|
||||
**kwargs: The other parameters to pass to gdata.service.GDataService
|
||||
constructor.
|
||||
"""
|
||||
gdata.service.GDataService.__init__(
|
||||
self, email=email, password=password, service='apps', source=source,
|
||||
server=server, additional_headers=additional_headers, **kwargs)
|
||||
self.ssl = True
|
||||
self.port = 443
|
||||
self.domain = domain
|
||||
|
||||
def retrieve_report(self, report, date=None):
|
||||
"""Retrieves a report
|
||||
|
||||
Args:
|
||||
report: string, accounts, activity, disk_space, email_clients or summary
|
||||
date: string: YYYY-MM-DD. If not specified, most recent day that has past 12pm PST will be used (in other words, today if it's after 12pm PST or yesterday if not)
|
||||
|
||||
Returns:
|
||||
String, the report data
|
||||
"""
|
||||
uri = '/hosted/services/v1.0/reports/ReportingData'
|
||||
if date == None:
|
||||
now = time.time()
|
||||
report_time = time.gmtime(now)
|
||||
if report_time.tm_hour < 20:
|
||||
report_time = time.gmtime(now - 60*60*24)
|
||||
date = '%s-%s-0%s' % (report_time.tm_year, report_time.tm_mon, report_time.tm_mday)
|
||||
page = 1
|
||||
report_data = ''
|
||||
while True:
|
||||
xml = '''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<rest xmlns="google:accounts:rest:protocol"
|
||||
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance ">
|
||||
<type>Report</type>
|
||||
<domain>%s</domain>
|
||||
<date>%s</date>
|
||||
<page>%s</page>
|
||||
<reportType>daily</reportType>
|
||||
<reportName>%s</reportName>
|
||||
</rest>''' % (self.domain, date, page, report)
|
||||
try:
|
||||
report_page = self.Post(xml, uri, converter=str)
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
if report_page == 'End-Of-Report':
|
||||
return report_data
|
||||
else:
|
||||
if page == 1:
|
||||
report_data += report_page # 1st page has headers
|
||||
else:
|
||||
report_data += report_page[report_page.find('\n')+1:] # remove header on additional pages
|
||||
page = page + 1
|
||||
|
||||
RetrieveReport = retrieve_report
|
||||
1
gdata/apps/res_cal/__init__.py
Normal file
1
gdata/apps/res_cal/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
71
gdata/apps/res_cal/service.py
Normal file
71
gdata/apps/res_cal/service.py
Normal file
@@ -0,0 +1,71 @@
|
||||
# Copyright (C) 2008 Google, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Allow Google Apps domain administrators to create/modify/delete resource calendars.
|
||||
|
||||
ResCalService: Interact with Resource Calendars."""
|
||||
|
||||
__author__ = 'jlee@pbu.edu'
|
||||
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
|
||||
class ResCalService(gdata.apps.service.PropertyService):
|
||||
"""Client for the Google Apps Resource Calendar service."""
|
||||
|
||||
def _serviceUrl(self, domain=None):
|
||||
if domain is None:
|
||||
domain = self.domain
|
||||
return '/a/feeds/calendar/resource/2.0/%s' % domain
|
||||
|
||||
def CreateResourceCalendar(self, id, common_name, description=None, type=None):
|
||||
|
||||
uri = self._serviceUrl()
|
||||
properties = {}
|
||||
properties['resourceId'] = id
|
||||
properties['resourceCommonName'] = common_name
|
||||
if description != None:
|
||||
properties['resourceDescription'] = description
|
||||
if type != None:
|
||||
properties['resourceType'] = type
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def RetrieveResourceCalendar(self, id):
|
||||
|
||||
uri = self._serviceUrl()+'/'+id
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def RetrieveAllResourceCalendars(self):
|
||||
|
||||
uri = self._serviceUrl()+'/'
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def UpdateResourceCalendar(self, id, common_name=None, description=None, type=None):
|
||||
|
||||
uri = self._serviceUrl()+'/'+id
|
||||
properties = {}
|
||||
properties['resourceId'] = id
|
||||
if common_name != None:
|
||||
properties['resourceCommonName'] = common_name
|
||||
if description != None:
|
||||
properties['resourceDescription'] = description
|
||||
if type != None:
|
||||
properties['resourceType'] = type
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def DeleteResourceCalendar(self, id):
|
||||
|
||||
uri = self._serviceUrl()+'/'+id
|
||||
return self._DeleteProperties(uri)
|
||||
553
gdata/apps/service.py
Normal file
553
gdata/apps/service.py
Normal file
@@ -0,0 +1,553 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright (C) 2007 SIOS Technology, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
__author__ = 'tmatsuo@sios.com (Takashi MATSUO)'
|
||||
|
||||
try:
|
||||
from xml.etree import cElementTree as ElementTree
|
||||
except ImportError:
|
||||
try:
|
||||
import cElementTree as ElementTree
|
||||
except ImportError:
|
||||
try:
|
||||
from xml.etree import ElementTree
|
||||
except ImportError:
|
||||
from elementtree import ElementTree
|
||||
import urllib
|
||||
import gdata
|
||||
import atom.service
|
||||
import gdata.service
|
||||
import gdata.apps
|
||||
import atom
|
||||
|
||||
API_VER="2.0"
|
||||
HTTP_OK=200
|
||||
|
||||
UNKOWN_ERROR=1000
|
||||
USER_DELETED_RECENTLY=1100
|
||||
USER_SUSPENDED=1101
|
||||
DOMAIN_USER_LIMIT_EXCEEDED=1200
|
||||
DOMAIN_ALIAS_LIMIT_EXCEEDED=1201
|
||||
DOMAIN_SUSPENDED=1202
|
||||
DOMAIN_FEATURE_UNAVAILABLE=1203
|
||||
ENTITY_EXISTS=1300
|
||||
ENTITY_DOES_NOT_EXIST=1301
|
||||
ENTITY_NAME_IS_RESERVED=1302
|
||||
ENTITY_NAME_NOT_VALID=1303
|
||||
INVALID_GIVEN_NAME=1400
|
||||
INVALID_FAMILY_NAME=1401
|
||||
INVALID_PASSWORD=1402
|
||||
INVALID_USERNAME=1403
|
||||
INVALID_HASH_FUNCTION_NAME=1404
|
||||
INVALID_HASH_DIGGEST_LENGTH=1405
|
||||
INVALID_EMAIL_ADDRESS=1406
|
||||
INVALID_QUERY_PARAMETER_VALUE=1407
|
||||
TOO_MANY_RECIPIENTS_ON_EMAIL_LIST=1500
|
||||
|
||||
DEFAULT_QUOTA_LIMIT='2048'
|
||||
|
||||
|
||||
class Error(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class AppsForYourDomainException(Error):
|
||||
|
||||
def __init__(self, response):
|
||||
|
||||
Error.__init__(self, response)
|
||||
try:
|
||||
self.element_tree = ElementTree.fromstring(response['body'])
|
||||
self.error_code = int(self.element_tree[0].attrib['errorCode'])
|
||||
self.reason = self.element_tree[0].attrib['reason']
|
||||
self.invalidInput = self.element_tree[0].attrib['invalidInput']
|
||||
except:
|
||||
self.error_code = 600
|
||||
|
||||
class AppsService(gdata.service.GDataService):
|
||||
"""Client for the Google Apps Provisioning service."""
|
||||
|
||||
def __init__(self, email=None, password=None, domain=None, source=None,
|
||||
server='apps-apis.google.com', additional_headers=None,
|
||||
**kwargs):
|
||||
"""Creates a client for the Google Apps Provisioning service.
|
||||
|
||||
Args:
|
||||
email: string (optional) The user's email address, used for
|
||||
authentication.
|
||||
password: string (optional) The user's password.
|
||||
domain: string (optional) The Google Apps domain name.
|
||||
source: string (optional) The name of the user's application.
|
||||
server: string (optional) The name of the server to which a connection
|
||||
will be opened. Default value: 'apps-apis.google.com'.
|
||||
**kwargs: The other parameters to pass to gdata.service.GDataService
|
||||
constructor.
|
||||
"""
|
||||
gdata.service.GDataService.__init__(
|
||||
self, email=email, password=password, service='apps', source=source,
|
||||
server=server, additional_headers=additional_headers, **kwargs)
|
||||
self.ssl = True
|
||||
self.port = 443
|
||||
self.domain = domain
|
||||
|
||||
def _baseURL(self):
|
||||
return "/a/feeds/%s" % self.domain
|
||||
|
||||
def AddAllElementsFromAllPages(self, link_finder, func):
|
||||
"""retrieve all pages and add all elements"""
|
||||
next = link_finder.GetNextLink()
|
||||
while next is not None:
|
||||
next_feed = self.Get(next.href, converter=func)
|
||||
for a_entry in next_feed.entry:
|
||||
link_finder.entry.append(a_entry)
|
||||
next = next_feed.GetNextLink()
|
||||
return link_finder
|
||||
|
||||
def RetrievePageOfEmailLists(self, start_email_list_name=None,
|
||||
num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY,
|
||||
backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve one page of email list"""
|
||||
uri = "%s/emailList/%s" % (self._baseURL(), API_VER)
|
||||
if start_email_list_name is not None:
|
||||
uri += "?startEmailListName=%s" % start_email_list_name
|
||||
try:
|
||||
return gdata.apps.EmailListFeedFromString(str(self.GetWithRetries(
|
||||
uri, num_retries=num_retries, delay=delay, backoff=backoff)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def GetGeneratorForAllEmailLists(
|
||||
self, num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve a generator for all emaillists in this domain."""
|
||||
first_page = self.RetrievePageOfEmailLists(num_retries=num_retries,
|
||||
delay=delay,
|
||||
backoff=backoff)
|
||||
return self.GetGeneratorFromLinkFinder(
|
||||
first_page, gdata.apps.EmailListRecipientFeedFromString,
|
||||
num_retries=num_retries, delay=delay, backoff=backoff)
|
||||
|
||||
def RetrieveAllEmailLists(self):
|
||||
"""Retrieve all email list of a domain."""
|
||||
|
||||
ret = self.RetrievePageOfEmailLists()
|
||||
# pagination
|
||||
return self.AddAllElementsFromAllPages(
|
||||
ret, gdata.apps.EmailListFeedFromString)
|
||||
|
||||
def RetrieveEmailList(self, list_name):
|
||||
"""Retreive a single email list by the list's name."""
|
||||
|
||||
uri = "%s/emailList/%s/%s" % (
|
||||
self._baseURL(), API_VER, list_name)
|
||||
try:
|
||||
return self.Get(uri, converter=gdata.apps.EmailListEntryFromString)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def RetrieveEmailLists(self, recipient):
|
||||
"""Retrieve All Email List Subscriptions for an Email Address."""
|
||||
|
||||
uri = "%s/emailList/%s?recipient=%s" % (
|
||||
self._baseURL(), API_VER, recipient)
|
||||
try:
|
||||
ret = gdata.apps.EmailListFeedFromString(str(self.Get(uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
# pagination
|
||||
return self.AddAllElementsFromAllPages(
|
||||
ret, gdata.apps.EmailListFeedFromString)
|
||||
|
||||
def RemoveRecipientFromEmailList(self, recipient, list_name):
|
||||
"""Remove recipient from email list."""
|
||||
|
||||
uri = "%s/emailList/%s/%s/recipient/%s" % (
|
||||
self._baseURL(), API_VER, list_name, recipient)
|
||||
try:
|
||||
self.Delete(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def RetrievePageOfRecipients(self, list_name, start_recipient=None,
|
||||
num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY,
|
||||
backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve one page of recipient of an email list. """
|
||||
|
||||
uri = "%s/emailList/%s/%s/recipient" % (
|
||||
self._baseURL(), API_VER, list_name)
|
||||
|
||||
if start_recipient is not None:
|
||||
uri += "?startRecipient=%s" % start_recipient
|
||||
try:
|
||||
return gdata.apps.EmailListRecipientFeedFromString(str(
|
||||
self.GetWithRetries(
|
||||
uri, num_retries=num_retries, delay=delay, backoff=backoff)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def GetGeneratorForAllRecipients(
|
||||
self, list_name, num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve a generator for all recipients of a particular emaillist."""
|
||||
first_page = self.RetrievePageOfRecipients(list_name,
|
||||
num_retries=num_retries,
|
||||
delay=delay,
|
||||
backoff=backoff)
|
||||
return self.GetGeneratorFromLinkFinder(
|
||||
first_page, gdata.apps.EmailListRecipientFeedFromString,
|
||||
num_retries=num_retries, delay=delay, backoff=backoff)
|
||||
|
||||
def RetrieveAllRecipients(self, list_name):
|
||||
"""Retrieve all recipient of an email list."""
|
||||
|
||||
ret = self.RetrievePageOfRecipients(list_name)
|
||||
# pagination
|
||||
return self.AddAllElementsFromAllPages(
|
||||
ret, gdata.apps.EmailListRecipientFeedFromString)
|
||||
|
||||
def AddRecipientToEmailList(self, recipient, list_name):
|
||||
"""Add a recipient to a email list."""
|
||||
|
||||
uri = "%s/emailList/%s/%s/recipient" % (
|
||||
self._baseURL(), API_VER, list_name)
|
||||
recipient_entry = gdata.apps.EmailListRecipientEntry()
|
||||
recipient_entry.who = gdata.apps.Who(email=recipient)
|
||||
|
||||
try:
|
||||
return gdata.apps.EmailListRecipientEntryFromString(
|
||||
str(self.Post(recipient_entry, uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def DeleteEmailList(self, list_name):
|
||||
"""Delete a email list"""
|
||||
|
||||
uri = "%s/emailList/%s/%s" % (self._baseURL(), API_VER, list_name)
|
||||
try:
|
||||
self.Delete(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def CreateEmailList(self, list_name):
|
||||
"""Create a email list. """
|
||||
|
||||
uri = "%s/emailList/%s" % (self._baseURL(), API_VER)
|
||||
email_list_entry = gdata.apps.EmailListEntry()
|
||||
email_list_entry.email_list = gdata.apps.EmailList(name=list_name)
|
||||
try:
|
||||
return gdata.apps.EmailListEntryFromString(
|
||||
str(self.Post(email_list_entry, uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def DeleteNickname(self, nickname):
|
||||
"""Delete a nickname"""
|
||||
|
||||
uri = "%s/nickname/%s/%s" % (self._baseURL(), API_VER, nickname)
|
||||
try:
|
||||
self.Delete(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def RetrievePageOfNicknames(self, start_nickname=None,
|
||||
num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY,
|
||||
backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve one page of nicknames in the domain"""
|
||||
|
||||
uri = "%s/nickname/%s" % (self._baseURL(), API_VER)
|
||||
if start_nickname is not None:
|
||||
uri += "?startNickname=%s" % start_nickname
|
||||
try:
|
||||
return gdata.apps.NicknameFeedFromString(str(self.GetWithRetries(
|
||||
uri, num_retries=num_retries, delay=delay, backoff=backoff)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def GetGeneratorForAllNicknames(
|
||||
self, num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve a generator for all nicknames in this domain."""
|
||||
first_page = self.RetrievePageOfNicknames(num_retries=num_retries,
|
||||
delay=delay,
|
||||
backoff=backoff)
|
||||
return self.GetGeneratorFromLinkFinder(
|
||||
first_page, gdata.apps.NicknameFeedFromString, num_retries=num_retries,
|
||||
delay=delay, backoff=backoff)
|
||||
|
||||
def RetrieveAllNicknames(self):
|
||||
"""Retrieve all nicknames in the domain"""
|
||||
|
||||
ret = self.RetrievePageOfNicknames()
|
||||
# pagination
|
||||
return self.AddAllElementsFromAllPages(
|
||||
ret, gdata.apps.NicknameFeedFromString)
|
||||
|
||||
def GetGeneratorForAllNicknamesOfAUser(
|
||||
self, user_name, num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve a generator for all nicknames of a particular user."""
|
||||
uri = "%s/nickname/%s?username=%s" % (self._baseURL(), API_VER, user_name)
|
||||
try:
|
||||
first_page = gdata.apps.NicknameFeedFromString(str(self.GetWithRetries(
|
||||
uri, num_retries=num_retries, delay=delay, backoff=backoff)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
return self.GetGeneratorFromLinkFinder(
|
||||
first_page, gdata.apps.NicknameFeedFromString, num_retries=num_retries,
|
||||
delay=delay, backoff=backoff)
|
||||
|
||||
def RetrieveNicknames(self, user_name):
|
||||
"""Retrieve nicknames of the user"""
|
||||
|
||||
uri = "%s/nickname/%s?username=%s" % (self._baseURL(), API_VER, user_name)
|
||||
try:
|
||||
ret = gdata.apps.NicknameFeedFromString(str(self.Get(uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
# pagination
|
||||
return self.AddAllElementsFromAllPages(
|
||||
ret, gdata.apps.NicknameFeedFromString)
|
||||
|
||||
def RetrieveNickname(self, nickname):
|
||||
"""Retrieve a nickname.
|
||||
|
||||
Args:
|
||||
nickname: string The nickname to retrieve
|
||||
|
||||
Returns:
|
||||
gdata.apps.NicknameEntry
|
||||
"""
|
||||
|
||||
uri = "%s/nickname/%s/%s" % (self._baseURL(), API_VER, nickname)
|
||||
try:
|
||||
return gdata.apps.NicknameEntryFromString(str(self.Get(uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def CreateNickname(self, user_name, nickname):
|
||||
"""Create a nickname"""
|
||||
|
||||
uri = "%s/nickname/%s" % (self._baseURL(), API_VER)
|
||||
nickname_entry = gdata.apps.NicknameEntry()
|
||||
nickname_entry.login = gdata.apps.Login(user_name=user_name)
|
||||
nickname_entry.nickname = gdata.apps.Nickname(name=nickname)
|
||||
|
||||
try:
|
||||
return gdata.apps.NicknameEntryFromString(
|
||||
str(self.Post(nickname_entry, uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def DeleteUser(self, user_name):
|
||||
"""Delete a user account"""
|
||||
|
||||
uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name)
|
||||
try:
|
||||
return self.Delete(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def UpdateUser(self, user_name, user_entry):
|
||||
"""Update a user account."""
|
||||
|
||||
uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name)
|
||||
try:
|
||||
return gdata.apps.UserEntryFromString(str(self.Put(user_entry, uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def CreateUser(self, user_name, family_name, given_name, password,
|
||||
suspended='false', quota_limit=None,
|
||||
password_hash_function=None,
|
||||
change_password=None):
|
||||
"""Create a user account. """
|
||||
|
||||
uri = "%s/user/%s" % (self._baseURL(), API_VER)
|
||||
user_entry = gdata.apps.UserEntry()
|
||||
user_entry.login = gdata.apps.Login(
|
||||
user_name=user_name, password=password, suspended=suspended,
|
||||
hash_function_name=password_hash_function,
|
||||
change_password=change_password)
|
||||
user_entry.name = gdata.apps.Name(family_name=family_name,
|
||||
given_name=given_name)
|
||||
if quota_limit is not None:
|
||||
user_entry.quota = gdata.apps.Quota(limit=str(quota_limit))
|
||||
|
||||
try:
|
||||
return gdata.apps.UserEntryFromString(str(self.Post(user_entry, uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def SuspendUser(self, user_name):
|
||||
user_entry = self.RetrieveUser(user_name)
|
||||
if user_entry.login.suspended != 'true':
|
||||
user_entry.login.suspended = 'true'
|
||||
user_entry = self.UpdateUser(user_name, user_entry)
|
||||
return user_entry
|
||||
|
||||
def RestoreUser(self, user_name):
|
||||
user_entry = self.RetrieveUser(user_name)
|
||||
if user_entry.login.suspended != 'false':
|
||||
user_entry.login.suspended = 'false'
|
||||
user_entry = self.UpdateUser(user_name, user_entry)
|
||||
return user_entry
|
||||
|
||||
def RetrieveUser(self, user_name):
|
||||
"""Retrieve an user account.
|
||||
|
||||
Args:
|
||||
user_name: string The user name to retrieve
|
||||
|
||||
Returns:
|
||||
gdata.apps.UserEntry
|
||||
"""
|
||||
|
||||
uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name)
|
||||
try:
|
||||
return gdata.apps.UserEntryFromString(str(self.Get(uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def RetrievePageOfUsers(self, start_username=None,
|
||||
num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY,
|
||||
backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve one page of users in this domain."""
|
||||
|
||||
uri = "%s/user/%s" % (self._baseURL(), API_VER)
|
||||
if start_username is not None:
|
||||
uri += "?startUsername=%s" % start_username
|
||||
try:
|
||||
return gdata.apps.UserFeedFromString(str(self.GetWithRetries(
|
||||
uri, num_retries=num_retries, delay=delay, backoff=backoff)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def GetGeneratorForAllUsers(self,
|
||||
num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY,
|
||||
backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve a generator for all users in this domain."""
|
||||
first_page = self.RetrievePageOfUsers(num_retries=num_retries, delay=delay,
|
||||
backoff=backoff)
|
||||
return self.GetGeneratorFromLinkFinder(
|
||||
first_page, gdata.apps.UserFeedFromString, num_retries=num_retries,
|
||||
delay=delay, backoff=backoff)
|
||||
|
||||
def RetrieveAllUsers(self):
|
||||
"""Retrieve all users in this domain. OBSOLETE"""
|
||||
|
||||
ret = self.RetrievePageOfUsers()
|
||||
# pagination
|
||||
return self.AddAllElementsFromAllPages(
|
||||
ret, gdata.apps.UserFeedFromString)
|
||||
|
||||
|
||||
class PropertyService(gdata.service.GDataService):
|
||||
"""Client for the Google Apps Property service."""
|
||||
|
||||
def __init__(self, email=None, password=None, domain=None, source=None,
|
||||
server='apps-apis.google.com', additional_headers=None):
|
||||
gdata.service.GDataService.__init__(self, email=email, password=password,
|
||||
service='apps', source=source,
|
||||
server=server,
|
||||
additional_headers=additional_headers)
|
||||
self.ssl = True
|
||||
self.port = 443
|
||||
self.domain = domain
|
||||
|
||||
def AddAllElementsFromAllPages(self, link_finder, func):
|
||||
"""retrieve all pages and add all elements"""
|
||||
next = link_finder.GetNextLink()
|
||||
count = 0
|
||||
while next is not None:
|
||||
next_feed = self.Get(next.href, converter=func)
|
||||
count = count + len(next_feed.entry)
|
||||
for a_entry in next_feed.entry:
|
||||
link_finder.entry.append(a_entry)
|
||||
next = next_feed.GetNextLink()
|
||||
return link_finder
|
||||
|
||||
def _GetPropertyEntry(self, properties):
|
||||
property_entry = gdata.apps.PropertyEntry()
|
||||
property = []
|
||||
for name, value in properties.iteritems():
|
||||
if name is not None and value is not None:
|
||||
property.append(gdata.apps.Property(name=name, value=value))
|
||||
property_entry.property = property
|
||||
return property_entry
|
||||
|
||||
def _PropertyEntry2Dict(self, property_entry):
|
||||
properties = {}
|
||||
for i, property in enumerate(property_entry.property):
|
||||
properties[property.name] = property.value
|
||||
return properties
|
||||
|
||||
def _GetPropertyFeed(self, uri):
|
||||
try:
|
||||
return gdata.apps.PropertyFeedFromString(str(self.Get(uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
|
||||
def _GetPropertiesList(self, uri):
|
||||
property_feed = self._GetPropertyFeed(uri)
|
||||
# pagination
|
||||
property_feed = self.AddAllElementsFromAllPages(
|
||||
property_feed, gdata.apps.PropertyFeedFromString)
|
||||
properties_list = []
|
||||
for property_entry in property_feed.entry:
|
||||
properties_list.append(self._PropertyEntry2Dict(property_entry))
|
||||
return properties_list
|
||||
|
||||
def _GetProperties(self, uri):
|
||||
try:
|
||||
return self._PropertyEntry2Dict(gdata.apps.PropertyEntryFromString(
|
||||
str(self.Get(uri))))
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
|
||||
def _PostProperties(self, uri, properties):
|
||||
property_entry = self._GetPropertyEntry(properties)
|
||||
try:
|
||||
return self._PropertyEntry2Dict(gdata.apps.PropertyEntryFromString(
|
||||
str(self.Post(property_entry, uri))))
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
|
||||
def _PutProperties(self, uri, properties):
|
||||
property_entry = self._GetPropertyEntry(properties)
|
||||
try:
|
||||
return self._PropertyEntry2Dict(gdata.apps.PropertyEntryFromString(
|
||||
str(self.Put(property_entry, uri))))
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
|
||||
def _DeleteProperties(self, uri):
|
||||
try:
|
||||
self.Delete(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
|
||||
|
||||
def _bool2str(b):
|
||||
if b is None:
|
||||
return None
|
||||
return str(b is True).lower()
|
||||
Reference in New Issue
Block a user