faset over fra Z3950 til google books
This commit is contained in:
526
python/gdata/apps/__init__.py
Normal file
526
python/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)
|
16
python/gdata/apps/adminsettings/__init__.py
Normal file
16
python/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.
|
||||
|
471
python/gdata/apps/adminsettings/service.py
Normal file
471
python/gdata/apps/adminsettings/service.py
Normal file
@@ -0,0 +1,471 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright (C) 2008 Google, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Allow Google Apps domain administrators to set domain admin settings.
|
||||
|
||||
AdminSettingsService: Set admin settings."""
|
||||
|
||||
__author__ = 'jlee@pbu.edu'
|
||||
|
||||
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
|
||||
|
||||
API_VER='2.0'
|
||||
|
||||
class AdminSettingsService(gdata.apps.service.PropertyService):
|
||||
"""Client for the Google Apps Admin Settings service."""
|
||||
|
||||
def _serviceUrl(self, setting_id, domain=None):
|
||||
if domain is None:
|
||||
domain = self.domain
|
||||
return '/a/feeds/domain/%s/%s/%s' % (API_VER, domain, setting_id)
|
||||
|
||||
def genericGet(self, location):
|
||||
"""Generic HTTP Get Wrapper
|
||||
|
||||
Args:
|
||||
location: relative uri to Get
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the get operation."""
|
||||
|
||||
uri = self._serviceUrl(location)
|
||||
try:
|
||||
return self._GetProperties(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def GetDefaultLanguage(self):
|
||||
"""Gets Domain Default Language
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
Default Language as a string. All possible values are listed at:
|
||||
http://code.google.com/apis/apps/email_settings/developers_guide_protocol.html#GA_email_language_tags"""
|
||||
|
||||
result = self.genericGet('general/defaultLanguage')
|
||||
return result['defaultLanguage']
|
||||
|
||||
def UpdateDefaultLanguage(self, defaultLanguage):
|
||||
"""Updates Domain Default Language
|
||||
|
||||
Args:
|
||||
defaultLanguage: Domain Language to set
|
||||
possible values are at:
|
||||
http://code.google.com/apis/apps/email_settings/developers_guide_protocol.html#GA_email_language_tags
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the put operation"""
|
||||
|
||||
uri = self._serviceUrl('general/defaultLanguage')
|
||||
properties = {'defaultLanguage': defaultLanguage}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetOrganizationName(self):
|
||||
"""Gets Domain Default Language
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
Organization Name as a string."""
|
||||
|
||||
result = self.genericGet('general/organizationName')
|
||||
return result['organizationName']
|
||||
|
||||
|
||||
def UpdateOrganizationName(self, organizationName):
|
||||
"""Updates Organization Name
|
||||
|
||||
Args:
|
||||
organizationName: Name of organization
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the put operation"""
|
||||
|
||||
uri = self._serviceUrl('general/organizationName')
|
||||
properties = {'organizationName': organizationName}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetMaximumNumberOfUsers(self):
|
||||
"""Gets Maximum Number of Users Allowed
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: An integer, the maximum number of users"""
|
||||
|
||||
result = self.genericGet('general/maximumNumberOfUsers')
|
||||
return int(result['maximumNumberOfUsers'])
|
||||
|
||||
def GetCurrentNumberOfUsers(self):
|
||||
"""Gets Current Number of Users
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: An integer, the current number of users"""
|
||||
|
||||
result = self.genericGet('general/currentNumberOfUsers')
|
||||
return int(result['currentNumberOfUsers'])
|
||||
|
||||
def IsDomainVerified(self):
|
||||
"""Is the domain verified
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: Boolean, is domain verified"""
|
||||
|
||||
result = self.genericGet('accountInformation/isVerified')
|
||||
if result['isVerified'] == 'true':
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def GetSupportPIN(self):
|
||||
"""Gets Support PIN
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A string, the Support PIN"""
|
||||
|
||||
result = self.genericGet('accountInformation/supportPIN')
|
||||
return result['supportPIN']
|
||||
|
||||
def GetEdition(self):
|
||||
"""Gets Google Apps Domain Edition
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A string, the domain's edition (premier, education, partner)"""
|
||||
|
||||
result = self.genericGet('accountInformation/edition')
|
||||
return result['edition']
|
||||
|
||||
def GetCustomerPIN(self):
|
||||
"""Gets Customer PIN
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A string, the customer PIN"""
|
||||
|
||||
result = self.genericGet('accountInformation/customerPIN')
|
||||
return result['customerPIN']
|
||||
|
||||
def GetCreationTime(self):
|
||||
"""Gets Domain Creation Time
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A string, the domain's creation time"""
|
||||
|
||||
result = self.genericGet('accountInformation/creationTime')
|
||||
return result['creationTime']
|
||||
|
||||
def GetCountryCode(self):
|
||||
"""Gets Domain Country Code
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A string, the domain's country code. Possible values at:
|
||||
http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm"""
|
||||
|
||||
result = self.genericGet('accountInformation/countryCode')
|
||||
return result['countryCode']
|
||||
|
||||
def GetAdminSecondaryEmail(self):
|
||||
"""Gets Domain Admin Secondary Email Address
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A string, the secondary email address for domain admin"""
|
||||
|
||||
result = self.genericGet('accountInformation/adminSecondaryEmail')
|
||||
return result['adminSecondaryEmail']
|
||||
|
||||
def UpdateAdminSecondaryEmail(self, adminSecondaryEmail):
|
||||
"""Gets Domain Creation Time
|
||||
|
||||
Args:
|
||||
adminSecondaryEmail: string, secondary email address of admin
|
||||
|
||||
Returns: A dict containing the result of the put operation"""
|
||||
|
||||
uri = self._serviceUrl('accountInformation/adminSecondaryEmail')
|
||||
properties = {'adminSecondaryEmail': adminSecondaryEmail}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetDomainLogo(self):
|
||||
"""Gets Domain Logo
|
||||
|
||||
This function does not make use of the Google Apps Admin Settings API,
|
||||
it does an HTTP Get of a url specific to the Google Apps domain. It is
|
||||
included for completeness sake.
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: binary image file"""
|
||||
|
||||
import urllib
|
||||
url = 'http://www.google.com/a/cpanel/'+self.domain+'/images/logo.gif'
|
||||
response = urllib.urlopen(url)
|
||||
return response.read()
|
||||
|
||||
def UpdateDomainLogo(self, logoImage):
|
||||
"""Update Domain's Custom Logo
|
||||
|
||||
Args:
|
||||
logoImage: binary image data
|
||||
|
||||
Returns: A dict containing the result of the put operation"""
|
||||
|
||||
from base64 import base64encode
|
||||
uri = self._serviceUrl('appearance/customLogo')
|
||||
properties = {'logoImage': base64encode(logoImage)}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetCNAMEVerificationStatus(self):
|
||||
"""Gets Domain CNAME Verification Status
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A dict {recordName, verified, verifiedMethod}"""
|
||||
|
||||
return self.genericGet('verification/cname')
|
||||
|
||||
def UpdateCNAMEVerificationStatus(self, verified):
|
||||
"""Updates CNAME Verification Status
|
||||
|
||||
Args:
|
||||
verified: boolean, True will retry verification process
|
||||
|
||||
Returns: A dict containing the result of the put operation"""
|
||||
|
||||
uri = self._serviceUrl('verification/cname')
|
||||
properties = self.GetCNAMEVerificationStatus()
|
||||
properties['verified'] = verified
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetMXVerificationStatus(self):
|
||||
"""Gets Domain MX Verification Status
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A dict {verified, verifiedMethod}"""
|
||||
|
||||
return self.genericGet('verification/mx')
|
||||
|
||||
def UpdateMXVerificationStatus(self, verified):
|
||||
"""Updates MX Verification Status
|
||||
|
||||
Args:
|
||||
verified: boolean, True will retry verification process
|
||||
|
||||
Returns: A dict containing the result of the put operation"""
|
||||
|
||||
uri = self._serviceUrl('verification/mx')
|
||||
properties = self.GetMXVerificationStatus()
|
||||
properties['verified'] = verified
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetSSOSettings(self):
|
||||
"""Gets Domain Single Sign-On Settings
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A dict {samlSignonUri, samlLogoutUri, changePasswordUri, enableSSO, ssoWhitelist, useDomainSpecificIssuer}"""
|
||||
|
||||
return self.genericGet('sso/general')
|
||||
|
||||
def UpdateSSOSettings(self, enableSSO=None, samlSignonUri=None,
|
||||
samlLogoutUri=None, changePasswordUri=None,
|
||||
ssoWhitelist=None, useDomainSpecificIssuer=None):
|
||||
"""Update SSO Settings.
|
||||
|
||||
Args:
|
||||
enableSSO: boolean, SSO Master on/off switch
|
||||
samlSignonUri: string, SSO Login Page
|
||||
samlLogoutUri: string, SSO Logout Page
|
||||
samlPasswordUri: string, SSO Password Change Page
|
||||
ssoWhitelist: string, Range of IP Addresses which will see SSO
|
||||
useDomainSpecificIssuer: boolean, Include Google Apps Domain in Issuer
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('sso/general')
|
||||
|
||||
#Get current settings, replace Nones with ''
|
||||
properties = self.GetSSOSettings()
|
||||
if properties['samlSignonUri'] == None:
|
||||
properties['samlSignonUri'] = ''
|
||||
if properties['samlLogoutUri'] == None:
|
||||
properties['samlLogoutUri'] = ''
|
||||
if properties['changePasswordUri'] == None:
|
||||
properties['changePasswordUri'] = ''
|
||||
if properties['ssoWhitelist'] == None:
|
||||
properties['ssoWhitelist'] = ''
|
||||
|
||||
#update only the values we were passed
|
||||
if enableSSO != None:
|
||||
properties['enableSSO'] = gdata.apps.service._bool2str(enableSSO)
|
||||
if samlSignonUri != None:
|
||||
properties['samlSignonUri'] = samlSignonUri
|
||||
if samlLogoutUri != None:
|
||||
properties['samlLogoutUri'] = samlLogoutUri
|
||||
if changePasswordUri != None:
|
||||
properties['changePasswordUri'] = changePasswordUri
|
||||
if ssoWhitelist != None:
|
||||
properties['ssoWhitelist'] = ssoWhitelist
|
||||
if useDomainSpecificIssuer != None:
|
||||
properties['useDomainSpecificIssuer'] = gdata.apps.service._bool2str(useDomainSpecificIssuer)
|
||||
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetSSOKey(self):
|
||||
"""Gets Domain Single Sign-On Signing Key
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns: A dict {modulus, exponent, algorithm, format}"""
|
||||
|
||||
return self.genericGet('sso/signingkey')
|
||||
|
||||
def UpdateSSOKey(self, signingKey):
|
||||
"""Update SSO Settings.
|
||||
|
||||
Args:
|
||||
signingKey: string, public key to be uploaded
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation."""
|
||||
|
||||
uri = self._serviceUrl('sso/signingkey')
|
||||
properties = {'signingKey': signingKey}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def IsUserMigrationEnabled(self):
|
||||
"""Is User Migration Enabled
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
boolean, is user migration enabled"""
|
||||
|
||||
result = self.genericGet('email/migration')
|
||||
if result['enableUserMigration'] == 'true':
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def UpdateUserMigrationStatus(self, enableUserMigration):
|
||||
"""Update User Migration Status
|
||||
|
||||
Args:
|
||||
enableUserMigration: boolean, user migration enable/disable
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation."""
|
||||
|
||||
uri = self._serviceUrl('email/migration')
|
||||
properties = {'enableUserMigration': enableUserMigration}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def GetOutboundGatewaySettings(self):
|
||||
"""Get Outbound Gateway Settings
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
A dict {smartHost, smtpMode}"""
|
||||
|
||||
uri = self._serviceUrl('email/gateway')
|
||||
try:
|
||||
return self._GetProperties(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
except TypeError:
|
||||
#if no outbound gateway is set, we get a TypeError,
|
||||
#catch it and return nothing...
|
||||
return {'smartHost': None, 'smtpMode': None}
|
||||
|
||||
def UpdateOutboundGatewaySettings(self, smartHost=None, smtpMode=None):
|
||||
"""Update Outbound Gateway Settings
|
||||
|
||||
Args:
|
||||
smartHost: string, ip address or hostname of outbound gateway
|
||||
smtpMode: string, SMTP or SMTP_TLS
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation."""
|
||||
|
||||
uri = self._serviceUrl('email/gateway')
|
||||
|
||||
#Get current settings, replace Nones with ''
|
||||
properties = GetOutboundGatewaySettings()
|
||||
if properties['smartHost'] == None:
|
||||
properties['smartHost'] = ''
|
||||
if properties['smtpMode'] == None:
|
||||
properties['smtpMode'] = ''
|
||||
|
||||
#If we were passed new values for smartHost or smtpMode, update them
|
||||
if smartHost != None:
|
||||
properties['smartHost'] = smartHost
|
||||
if smtpMode != None:
|
||||
properties['smtpMode'] = smtpMode
|
||||
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def AddEmailRoute(self, routeDestination, routeRewriteTo, routeEnabled, bounceNotifications, accountHandling):
|
||||
"""Adds Domain Email Route
|
||||
|
||||
Args:
|
||||
routeDestination: string, destination ip address or hostname
|
||||
routeRewriteTo: boolean, rewrite smtp envelop To:
|
||||
routeEnabled: boolean, enable disable email routing
|
||||
bounceNotifications: boolean, send bound notificiations to sender
|
||||
accountHandling: string, which to route, "allAccounts", "provisionedAccounts", "unknownAccounts"
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation."""
|
||||
|
||||
uri = self._serviceUrl('emailrouting')
|
||||
properties = {}
|
||||
properties['routeDestination'] = routeDestination
|
||||
properties['routeRewriteTo'] = gdata.apps.service._bool2str(routeRewriteTo)
|
||||
properties['routeEnabled'] = gdata.apps.service._bool2str(routeEnabled)
|
||||
properties['bounceNotifications'] = gdata.apps.service._bool2str(bounceNotifications)
|
||||
properties['accountHandling'] = accountHandling
|
||||
return self._PostProperties(uri, properties)
|
1
python/gdata/apps/audit/__init__.py
Normal file
1
python/gdata/apps/audit/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
|
277
python/gdata/apps/audit/service.py
Normal file
277
python/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
python/gdata/apps/emailsettings/__init__.py
Normal file
15
python/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.
|
400
python/gdata/apps/emailsettings/client.py
Normal file
400
python/gdata/apps/emailsettings/client.py
Normal file
@@ -0,0 +1,400 @@
|
||||
#!/usr/bin/python2.4
|
||||
#
|
||||
# Copyright 2010 Google Inc. All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""EmailSettingsClient simplifies Email Settings API calls.
|
||||
|
||||
EmailSettingsClient extends gdata.client.GDClient to ease interaction with
|
||||
the Google Apps Email Settings API. These interactions include the ability
|
||||
to create labels, filters, aliases, and update web-clip, forwarding, POP,
|
||||
IMAP, vacation-responder, signature, language, and general settings.
|
||||
"""
|
||||
|
||||
|
||||
__author__ = 'Claudio Cherubino <ccherubino@google.com>'
|
||||
|
||||
|
||||
import gdata.apps.emailsettings.data
|
||||
import gdata.client
|
||||
|
||||
|
||||
# Email Settings URI template
|
||||
# The strings in this template are eventually replaced with the API version,
|
||||
# Google Apps domain name, username, and settingID, respectively.
|
||||
EMAIL_SETTINGS_URI_TEMPLATE = '/a/feeds/emailsettings/%s/%s/%s/%s'
|
||||
|
||||
|
||||
# The settingID value for the label requests
|
||||
SETTING_ID_LABEL = 'label'
|
||||
# The settingID value for the filter requests
|
||||
SETTING_ID_FILTER = 'filter'
|
||||
# The settingID value for the send-as requests
|
||||
SETTING_ID_SENDAS = 'sendas'
|
||||
# The settingID value for the webclip requests
|
||||
SETTING_ID_WEBCLIP = 'webclip'
|
||||
# The settingID value for the forwarding requests
|
||||
SETTING_ID_FORWARDING = 'forwarding'
|
||||
# The settingID value for the POP requests
|
||||
SETTING_ID_POP = 'pop'
|
||||
# The settingID value for the IMAP requests
|
||||
SETTING_ID_IMAP = 'imap'
|
||||
# The settingID value for the vacation responder requests
|
||||
SETTING_ID_VACATION_RESPONDER = 'vacation'
|
||||
# The settingID value for the signature requests
|
||||
SETTING_ID_SIGNATURE = 'signature'
|
||||
# The settingID value for the language requests
|
||||
SETTING_ID_LANGUAGE = 'language'
|
||||
# The settingID value for the general requests
|
||||
SETTING_ID_GENERAL = 'general'
|
||||
|
||||
# The KEEP action for the email settings
|
||||
ACTION_KEEP = 'KEEP'
|
||||
# The ARCHIVE action for the email settings
|
||||
ACTION_ARCHIVE = 'ARCHIVE'
|
||||
# The DELETE action for the email settings
|
||||
ACTION_DELETE = 'DELETE'
|
||||
|
||||
# The ALL_MAIL setting for POP enable_for property
|
||||
POP_ENABLE_FOR_ALL_MAIL = 'ALL_MAIL'
|
||||
# The MAIL_FROM_NOW_ON setting for POP enable_for property
|
||||
POP_ENABLE_FOR_MAIL_FROM_NOW_ON = 'MAIL_FROM_NOW_ON'
|
||||
|
||||
|
||||
class EmailSettingsClient(gdata.client.GDClient):
|
||||
"""Client extension for the Google Email Settings API service.
|
||||
|
||||
Attributes:
|
||||
host: string The hostname for the Email Settings API service.
|
||||
api_version: string The version of the Email Settings API.
|
||||
"""
|
||||
|
||||
host = 'apps-apis.google.com'
|
||||
api_version = '2.0'
|
||||
auth_service = 'apps'
|
||||
auth_scopes = gdata.gauth.AUTH_SCOPES['apps']
|
||||
ssl = True
|
||||
|
||||
def __init__(self, domain, auth_token=None, **kwargs):
|
||||
"""Constructs a new client for the Email Settings API.
|
||||
|
||||
Args:
|
||||
domain: string The Google Apps domain with Email Settings.
|
||||
auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or
|
||||
OAuthToken which authorizes this client to edit the email settings.
|
||||
kwargs: The other parameters to pass to the gdata.client.GDClient
|
||||
constructor.
|
||||
"""
|
||||
gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs)
|
||||
self.domain = domain
|
||||
|
||||
def make_email_settings_uri(self, username, setting_id):
|
||||
"""Creates the URI for the Email Settings API call.
|
||||
|
||||
Using this client's Google Apps domain, create the URI to setup
|
||||
email settings for the given user in that domain. If params are provided,
|
||||
append them as GET params.
|
||||
|
||||
Args:
|
||||
username: string The name of the user affected by this setting.
|
||||
setting_id: string The key of the setting to be configured.
|
||||
|
||||
Returns:
|
||||
A string giving the URI for Email Settings API calls for this client's
|
||||
Google Apps domain.
|
||||
"""
|
||||
uri = EMAIL_SETTINGS_URI_TEMPLATE % (self.api_version, self.domain,
|
||||
username, setting_id)
|
||||
return uri
|
||||
|
||||
MakeEmailSettingsUri = make_email_settings_uri
|
||||
|
||||
def create_label(self, username, name, **kwargs):
|
||||
"""Creates a label with the given properties.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
name: string The name of the label.
|
||||
kwargs: The other parameters to pass to gdata.client.GDClient.post().
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsLabel of the new resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_LABEL)
|
||||
new_label = gdata.apps.emailsettings.data.EmailSettingsLabel(
|
||||
uri=uri, name=name)
|
||||
return self.post(new_label, uri, **kwargs)
|
||||
|
||||
CreateLabel = create_label
|
||||
|
||||
def create_filter(self, username, from_address=None,
|
||||
to_address=None, subject=None, has_the_word=None,
|
||||
does_not_have_the_word=None, has_attachments=None,
|
||||
label=None, mark_as_read=None, archive=None, **kwargs):
|
||||
"""Creates a filter with the given properties.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
from_address: string The source email address for the filter.
|
||||
to_address: string (optional) The destination email address for
|
||||
the filter.
|
||||
subject: string (optional) The value the email must have in its
|
||||
subject to be filtered.
|
||||
has_the_word: string (optional) The value the email must have
|
||||
in its subject or body to be filtered.
|
||||
does_not_have_the_word: string (optional) The value the email
|
||||
cannot have in its subject or body to be filtered.
|
||||
has_attachments: string (optional) A boolean string representing
|
||||
whether the email must have an attachment to be filtered.
|
||||
label: string (optional) The name of the label to apply to
|
||||
messages matching the filter criteria.
|
||||
mark_as_read: Boolean (optional) Whether or not to mark
|
||||
messages matching the filter criteria as read.
|
||||
archive: Boolean (optional) Whether or not to move messages
|
||||
matching to Archived state.
|
||||
kwargs: The other parameters to pass to gdata.client.GDClient.post().
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsFilter of the new resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_FILTER)
|
||||
new_filter = gdata.apps.emailsettings.data.EmailSettingsFilter(
|
||||
uri=uri, from_address=from_address,
|
||||
to_address=to_address, subject=subject,
|
||||
has_the_word=has_the_word,
|
||||
does_not_have_the_word=does_not_have_the_word,
|
||||
has_attachments=has_attachments, label=label,
|
||||
mark_as_read=mark_as_read, archive=archive)
|
||||
return self.post(new_filter, uri, **kwargs)
|
||||
|
||||
CreateFilter = create_filter
|
||||
|
||||
def create_send_as(self, username, name, address, reply_to=None,
|
||||
make_default=None, **kwargs):
|
||||
"""Creates a send-as alias with the given properties.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
name: string The name that will appear in the "From" field.
|
||||
address: string The email address that appears as the
|
||||
origination address for emails sent by this user.
|
||||
reply_to: string (optional) The address to be used as the reply-to
|
||||
address in email sent using the alias.
|
||||
make_default: Boolean (optional) Whether or not this alias should
|
||||
become the default alias for this user.
|
||||
kwargs: The other parameters to pass to gdata.client.GDClient.post().
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsSendAsAlias of the
|
||||
new resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_SENDAS)
|
||||
new_alias = gdata.apps.emailsettings.data.EmailSettingsSendAsAlias(
|
||||
uri=uri, name=name, address=address,
|
||||
reply_to=reply_to, make_default=make_default)
|
||||
return self.post(new_alias, uri, **kwargs)
|
||||
|
||||
CreateSendAs = create_send_as
|
||||
|
||||
def update_webclip(self, username, enable, **kwargs):
|
||||
"""Enable/Disable Google Mail web clip.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
enable: Boolean Whether to enable showing Web clips.
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsWebClip of the
|
||||
updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_WEBCLIP)
|
||||
new_webclip = gdata.apps.emailsettings.data.EmailSettingsWebClip(
|
||||
uri=uri, enable=enable)
|
||||
return self.update(new_webclip, **kwargs)
|
||||
|
||||
UpdateWebclip = update_webclip
|
||||
|
||||
def update_forwarding(self, username, enable, forward_to=None,
|
||||
action=None, **kwargs):
|
||||
"""Update Google Mail Forwarding settings.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
enable: Boolean Whether to enable incoming email forwarding.
|
||||
forward_to: (optional) string The address email will be forwarded to.
|
||||
action: string (optional) The action to perform after forwarding
|
||||
an email (ACTION_KEEP, ACTION_ARCHIVE, ACTION_DELETE).
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsForwarding of the
|
||||
updated resource
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_FORWARDING)
|
||||
new_forwarding = gdata.apps.emailsettings.data.EmailSettingsForwarding(
|
||||
uri=uri, enable=enable, forward_to=forward_to, action=action)
|
||||
return self.update(new_forwarding, **kwargs)
|
||||
|
||||
UpdateForwarding = update_forwarding
|
||||
|
||||
def update_pop(self, username, enable, enable_for=None, action=None,
|
||||
**kwargs):
|
||||
"""Update Google Mail POP settings.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
enable: Boolean Whether to enable incoming POP3 access.
|
||||
enable_for: string (optional) Whether to enable POP3 for all mail
|
||||
(POP_ENABLE_FOR_ALL_MAIL), or mail from now on
|
||||
(POP_ENABLE_FOR_MAIL_FROM_NOW_ON).
|
||||
action: string (optional) What Google Mail should do with its copy
|
||||
of the email after it is retrieved using POP (ACTION_KEEP,
|
||||
ACTION_ARCHIVE, ACTION_DELETE).
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsPop of the updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_POP)
|
||||
new_pop = gdata.apps.emailsettings.data.EmailSettingsPop(
|
||||
uri=uri, enable=enable,
|
||||
enable_for=enable_for, action=action)
|
||||
return self.update(new_pop, **kwargs)
|
||||
|
||||
UpdatePop = update_pop
|
||||
|
||||
def update_imap(self, username, enable, **kwargs):
|
||||
"""Update Google Mail IMAP settings.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
enable: Boolean Whether to enable IMAP access.language
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsImap of the updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_IMAP)
|
||||
new_imap = gdata.apps.emailsettings.data.EmailSettingsImap(
|
||||
uri=uri, enable=enable)
|
||||
return self.update(new_imap, **kwargs)
|
||||
|
||||
UpdateImap = update_imap
|
||||
|
||||
def update_vacation(self, username, enable, subject=None, message=None,
|
||||
contacts_only=None, **kwargs):
|
||||
"""Update Google Mail vacation-responder settings.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
enable: Boolean Whether to enable the vacation responder.
|
||||
subject: string (optional) The subject line of the vacation responder
|
||||
autoresponse.
|
||||
message: string (optional) The message body of the vacation responder
|
||||
autoresponse.
|
||||
contacts_only: Boolean (optional) Whether to only send autoresponses
|
||||
to known contacts.
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsVacationResponder of the
|
||||
updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_VACATION_RESPONDER)
|
||||
new_vacation = gdata.apps.emailsettings.data.EmailSettingsVacationResponder(
|
||||
uri=uri, enable=enable, subject=subject,
|
||||
message=message, contacts_only=contacts_only)
|
||||
return self.update(new_vacation, **kwargs)
|
||||
|
||||
UpdateVacation = update_vacation
|
||||
|
||||
def update_signature(self, username, signature, **kwargs):
|
||||
"""Update Google Mail signature.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
signature: string The signature to be appended to outgoing messages.
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsSignature of the
|
||||
updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_SIGNATURE)
|
||||
new_signature = gdata.apps.emailsettings.data.EmailSettingsSignature(
|
||||
uri=uri, signature=signature)
|
||||
return self.update(new_signature, **kwargs)
|
||||
|
||||
UpdateSignature = update_signature
|
||||
|
||||
def update_language(self, username, language, **kwargs):
|
||||
"""Update Google Mail language settings.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
language: string The language tag for Google Mail's display language.
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsLanguage of the
|
||||
updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_LANGUAGE)
|
||||
new_language = gdata.apps.emailsettings.data.EmailSettingsLanguage(
|
||||
uri=uri, language=language)
|
||||
return self.update(new_language, **kwargs)
|
||||
|
||||
UpdateLanguage = update_language
|
||||
|
||||
def update_general_settings(self, username, page_size=None, shortcuts=None,
|
||||
arrows=None, snippets=None, use_unicode=None,
|
||||
**kwargs):
|
||||
"""Update Google Mail general settings.
|
||||
|
||||
Args:
|
||||
username: string The name of the user.
|
||||
page_size: int (optional) The number of conversations to be shown per
|
||||
page.
|
||||
shortcuts: Boolean (optional) Whether to enable keyboard shortcuts.
|
||||
arrows: Boolean (optional) Whether to display arrow-shaped personal
|
||||
indicators next to email sent specifically to the user.
|
||||
snippets: Boolean (optional) Whether to display snippets of the messages
|
||||
in the inbox and when searching.
|
||||
use_unicode: Boolean (optional) Whether to use UTF-8 (unicode) encoding
|
||||
for all outgoing messages.
|
||||
kwargs: The other parameters to pass to the update method.
|
||||
|
||||
Returns:
|
||||
gdata.apps.emailsettings.data.EmailSettingsGeneral of the
|
||||
updated resource.
|
||||
"""
|
||||
uri = self.MakeEmailSettingsUri(username=username,
|
||||
setting_id=SETTING_ID_GENERAL)
|
||||
new_general = gdata.apps.emailsettings.data.EmailSettingsGeneral(
|
||||
uri=uri, page_size=page_size, shortcuts=shortcuts,
|
||||
arrows=arrows, snippets=snippets, use_unicode=use_unicode)
|
||||
return self.update(new_general, **kwargs)
|
||||
|
||||
UpdateGeneralSettings = update_general_settings
|
1130
python/gdata/apps/emailsettings/data.py
Normal file
1130
python/gdata/apps/emailsettings/data.py
Normal file
File diff suppressed because it is too large
Load Diff
264
python/gdata/apps/emailsettings/service.py
Normal file
264
python/gdata/apps/emailsettings/service.py
Normal file
@@ -0,0 +1,264 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright (C) 2008 Google, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Allow Google Apps domain administrators to set users' email settings.
|
||||
|
||||
EmailSettingsService: Set various email settings.
|
||||
"""
|
||||
|
||||
__author__ = 'google-apps-apis@googlegroups.com'
|
||||
|
||||
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
|
||||
|
||||
API_VER='2.0'
|
||||
# Forwarding and POP3 options
|
||||
KEEP='KEEP'
|
||||
ARCHIVE='ARCHIVE'
|
||||
DELETE='DELETE'
|
||||
ALL_MAIL='ALL_MAIL'
|
||||
MAIL_FROM_NOW_ON='MAIL_FROM_NOW_ON'
|
||||
|
||||
|
||||
class EmailSettingsService(gdata.apps.service.PropertyService):
|
||||
"""Client for the Google Apps Email Settings service."""
|
||||
|
||||
def _serviceUrl(self, setting_id, username, domain=None):
|
||||
if domain is None:
|
||||
domain = self.domain
|
||||
return '/a/feeds/emailsettings/%s/%s/%s/%s' % (API_VER, domain, username,
|
||||
setting_id)
|
||||
|
||||
def CreateLabel(self, username, label):
|
||||
"""Create a label.
|
||||
|
||||
Args:
|
||||
username: User to create label for.
|
||||
label: Label to create.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the create operation.
|
||||
"""
|
||||
uri = self._serviceUrl('label', username)
|
||||
properties = {'label': label}
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def CreateFilter(self, username, from_=None, to=None, subject=None,
|
||||
has_the_word=None, does_not_have_the_word=None,
|
||||
has_attachment=None, label=None, should_mark_as_read=None,
|
||||
should_archive=None):
|
||||
"""Create a filter.
|
||||
|
||||
Args:
|
||||
username: User to create filter for.
|
||||
from_: Filter from string.
|
||||
to: Filter to string.
|
||||
subject: Filter subject.
|
||||
has_the_word: Words to filter in.
|
||||
does_not_have_the_word: Words to filter out.
|
||||
has_attachment: Boolean for message having attachment.
|
||||
label: Label to apply.
|
||||
should_mark_as_read: Boolean for marking message as read.
|
||||
should_archive: Boolean for archiving message.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the create operation.
|
||||
"""
|
||||
uri = self._serviceUrl('filter', username)
|
||||
properties = {}
|
||||
properties['from'] = from_
|
||||
properties['to'] = to
|
||||
properties['subject'] = subject
|
||||
properties['hasTheWord'] = has_the_word
|
||||
properties['doesNotHaveTheWord'] = does_not_have_the_word
|
||||
properties['hasAttachment'] = gdata.apps.service._bool2str(has_attachment)
|
||||
properties['label'] = label
|
||||
properties['shouldMarkAsRead'] = gdata.apps.service._bool2str(should_mark_as_read)
|
||||
properties['shouldArchive'] = gdata.apps.service._bool2str(should_archive)
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def CreateSendAsAlias(self, username, name, address, reply_to=None,
|
||||
make_default=None):
|
||||
"""Create alias to send mail as.
|
||||
|
||||
Args:
|
||||
username: User to create alias for.
|
||||
name: Name of alias.
|
||||
address: Email address to send from.
|
||||
reply_to: Email address to reply to.
|
||||
make_default: Boolean for whether this is the new default sending alias.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the create operation.
|
||||
"""
|
||||
uri = self._serviceUrl('sendas', username)
|
||||
properties = {}
|
||||
properties['name'] = name
|
||||
properties['address'] = address
|
||||
properties['replyTo'] = reply_to
|
||||
properties['makeDefault'] = gdata.apps.service._bool2str(make_default)
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def UpdateWebClipSettings(self, username, enable):
|
||||
"""Update WebClip Settings
|
||||
|
||||
Args:
|
||||
username: User to update forwarding for.
|
||||
enable: Boolean whether to enable Web Clip.
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('webclip', username)
|
||||
properties = {}
|
||||
properties['enable'] = gdata.apps.service._bool2str(enable)
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def UpdateForwarding(self, username, enable, forward_to=None, action=None):
|
||||
"""Update forwarding settings.
|
||||
|
||||
Args:
|
||||
username: User to update forwarding for.
|
||||
enable: Boolean whether to enable this forwarding rule.
|
||||
forward_to: Email address to forward to.
|
||||
action: Action to take after forwarding.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('forwarding', username)
|
||||
properties = {}
|
||||
properties['enable'] = gdata.apps.service._bool2str(enable)
|
||||
if enable is True:
|
||||
properties['forwardTo'] = forward_to
|
||||
properties['action'] = action
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def UpdatePop(self, username, enable, enable_for=None, action=None):
|
||||
"""Update POP3 settings.
|
||||
|
||||
Args:
|
||||
username: User to update POP3 settings for.
|
||||
enable: Boolean whether to enable POP3.
|
||||
enable_for: Which messages to make available via POP3.
|
||||
action: Action to take after user retrieves email via POP3.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('pop', username)
|
||||
properties = {}
|
||||
properties['enable'] = gdata.apps.service._bool2str(enable)
|
||||
if enable is True:
|
||||
properties['enableFor'] = enable_for
|
||||
properties['action'] = action
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def UpdateImap(self, username, enable):
|
||||
"""Update IMAP settings.
|
||||
|
||||
Args:
|
||||
username: User to update IMAP settings for.
|
||||
enable: Boolean whether to enable IMAP.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('imap', username)
|
||||
properties = {'enable': gdata.apps.service._bool2str(enable)}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def UpdateVacation(self, username, enable, subject=None, message=None,
|
||||
contacts_only=None):
|
||||
"""Update vacation settings.
|
||||
|
||||
Args:
|
||||
username: User to update vacation settings for.
|
||||
enable: Boolean whether to enable vacation responses.
|
||||
subject: Vacation message subject.
|
||||
message: Vacation message body.
|
||||
contacts_only: Boolean whether to send message only to contacts.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('vacation', username)
|
||||
properties = {}
|
||||
properties['enable'] = gdata.apps.service._bool2str(enable)
|
||||
if enable is True:
|
||||
properties['subject'] = subject
|
||||
properties['message'] = message
|
||||
properties['contactsOnly'] = gdata.apps.service._bool2str(contacts_only)
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def UpdateSignature(self, username, signature):
|
||||
"""Update signature.
|
||||
|
||||
Args:
|
||||
username: User to update signature for.
|
||||
signature: Signature string.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('signature', username)
|
||||
properties = {'signature': signature}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def UpdateLanguage(self, username, language):
|
||||
"""Update user interface language.
|
||||
|
||||
Args:
|
||||
username: User to update language for.
|
||||
language: Language code.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('language', username)
|
||||
properties = {'language': language}
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None,
|
||||
snippets=None, unicode=None):
|
||||
"""Update general settings.
|
||||
|
||||
Args:
|
||||
username: User to update general settings for.
|
||||
page_size: Number of messages to show.
|
||||
shortcuts: Boolean whether shortcuts are enabled.
|
||||
arrows: Boolean whether arrows are enabled.
|
||||
snippets: Boolean whether snippets are enabled.
|
||||
unicode: Wheter unicode is enabled.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._serviceUrl('general', username)
|
||||
properties = {}
|
||||
if page_size != None:
|
||||
properties['pageSize'] = str(page_size)
|
||||
if shortcuts != None:
|
||||
properties['shortcuts'] = gdata.apps.service._bool2str(shortcuts)
|
||||
if arrows != None:
|
||||
properties['arrows'] = gdata.apps.service._bool2str(arrows)
|
||||
if snippets != None:
|
||||
properties['snippets'] = gdata.apps.service._bool2str(snippets)
|
||||
if unicode != None:
|
||||
properties['unicode'] = gdata.apps.service._bool2str(unicode)
|
||||
return self._PutProperties(uri, properties)
|
0
python/gdata/apps/groups/__init__.py
Normal file
0
python/gdata/apps/groups/__init__.py
Normal file
387
python/gdata/apps/groups/service.py
Normal file
387
python/gdata/apps/groups/service.py
Normal file
@@ -0,0 +1,387 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright (C) 2008 Google, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Allow Google Apps domain administrators to manage groups, group members and group owners.
|
||||
|
||||
GroupsService: Provides methods to manage groups, members and owners.
|
||||
"""
|
||||
|
||||
__author__ = 'google-apps-apis@googlegroups.com'
|
||||
|
||||
|
||||
import urllib
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
|
||||
|
||||
API_VER = '2.0'
|
||||
BASE_URL = '/a/feeds/group/' + API_VER + '/%s'
|
||||
GROUP_MEMBER_URL = BASE_URL + '?member=%s'
|
||||
GROUP_MEMBER_DIRECT_URL = GROUP_MEMBER_URL + '&directOnly=%s'
|
||||
GROUP_ID_URL = BASE_URL + '/%s'
|
||||
MEMBER_URL = BASE_URL + '/%s/member'
|
||||
MEMBER_WITH_SUSPENDED_URL = MEMBER_URL + '?includeSuspendedUsers=%s'
|
||||
MEMBER_ID_URL = MEMBER_URL + '/%s'
|
||||
OWNER_URL = BASE_URL + '/%s/owner'
|
||||
OWNER_WITH_SUSPENDED_URL = OWNER_URL + '?includeSuspendedUsers=%s'
|
||||
OWNER_ID_URL = OWNER_URL + '/%s'
|
||||
|
||||
PERMISSION_OWNER = 'Owner'
|
||||
PERMISSION_MEMBER = 'Member'
|
||||
PERMISSION_DOMAIN = 'Domain'
|
||||
PERMISSION_ANYONE = 'Anyone'
|
||||
|
||||
|
||||
class GroupsService(gdata.apps.service.PropertyService):
|
||||
"""Client for the Google Apps Groups service."""
|
||||
|
||||
def _ServiceUrl(self, service_type, is_existed, group_id, member_id, owner_email,
|
||||
direct_only=False, domain=None, suspended_users=False):
|
||||
if domain is None:
|
||||
domain = self.domain
|
||||
|
||||
if service_type == 'group':
|
||||
if group_id != '' and is_existed:
|
||||
return GROUP_ID_URL % (domain, group_id)
|
||||
elif member_id != '':
|
||||
if direct_only:
|
||||
return GROUP_MEMBER_DIRECT_URL % (domain, urllib.quote_plus(member_id),
|
||||
self._Bool2Str(direct_only))
|
||||
else:
|
||||
return GROUP_MEMBER_URL % (domain, urllib.quote_plus(member_id))
|
||||
else:
|
||||
return BASE_URL % (domain)
|
||||
|
||||
if service_type == 'member':
|
||||
if member_id != '' and is_existed:
|
||||
return MEMBER_ID_URL % (domain, group_id, urllib.quote_plus(member_id))
|
||||
elif suspended_users:
|
||||
return MEMBER_WITH_SUSPENDED_URL % (domain, group_id,
|
||||
self._Bool2Str(suspended_users))
|
||||
else:
|
||||
return MEMBER_URL % (domain, group_id)
|
||||
|
||||
if service_type == 'owner':
|
||||
if owner_email != '' and is_existed:
|
||||
return OWNER_ID_URL % (domain, group_id, urllib.quote_plus(owner_email))
|
||||
elif suspended_users:
|
||||
return OWNER_WITH_SUSPENDED_URL % (domain, group_id,
|
||||
self._Bool2Str(suspended_users))
|
||||
else:
|
||||
return OWNER_URL % (domain, group_id)
|
||||
|
||||
def _Bool2Str(self, b):
|
||||
if b is None:
|
||||
return None
|
||||
return str(b is True).lower()
|
||||
|
||||
def _IsExisted(self, uri):
|
||||
try:
|
||||
self._GetProperties(uri)
|
||||
return True
|
||||
except gdata.apps.service.AppsForYourDomainException, e:
|
||||
if e.error_code == gdata.apps.service.ENTITY_DOES_NOT_EXIST:
|
||||
return False
|
||||
else:
|
||||
raise e
|
||||
|
||||
def CreateGroup(self, group_id, group_name, description, email_permission):
|
||||
"""Create a group.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
group_name: The name of the group.
|
||||
description: A description of the group
|
||||
email_permission: The subscription permission of the group.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the create operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', False, group_id, '', '')
|
||||
properties = {}
|
||||
properties['groupId'] = group_id
|
||||
properties['groupName'] = group_name
|
||||
properties['description'] = description
|
||||
properties['emailPermission'] = email_permission
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def UpdateGroup(self, group_id, group_name, description, email_permission):
|
||||
"""Update a group's name, description and/or permission.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
group_name: The name of the group.
|
||||
description: A description of the group
|
||||
email_permission: The subscription permission of the group.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', True, group_id, '', '')
|
||||
properties = {}
|
||||
properties['groupId'] = group_id
|
||||
properties['groupName'] = group_name
|
||||
properties['description'] = description
|
||||
properties['emailPermission'] = email_permission
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def RetrieveGroup(self, group_id):
|
||||
"""Retrieve a group based on its ID.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', True, group_id, '', '')
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def RetrieveAllGroups(self):
|
||||
"""Retrieve all groups in the domain.
|
||||
|
||||
Args:
|
||||
None
|
||||
|
||||
Returns:
|
||||
A list containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', True, '', '', '')
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def RetrievePageOfGroups(self, start_group=None):
|
||||
"""Retrieve one page of groups in the domain.
|
||||
|
||||
Args:
|
||||
start_group: The key to continue for pagination through all groups.
|
||||
|
||||
Returns:
|
||||
A feed object containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', True, '', '', '')
|
||||
if start_group is not None:
|
||||
uri += "?start="+start_group
|
||||
property_feed = self._GetPropertyFeed(uri)
|
||||
return property_feed
|
||||
|
||||
def RetrieveGroups(self, member_id, direct_only=False):
|
||||
"""Retrieve all groups that belong to the given member_id.
|
||||
|
||||
Args:
|
||||
member_id: The member's email address (e.g. member@example.com).
|
||||
direct_only: Boolean whether only return groups that this member directly belongs to.
|
||||
|
||||
Returns:
|
||||
A list containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', True, '', member_id, '', direct_only=direct_only)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def DeleteGroup(self, group_id):
|
||||
"""Delete a group based on its ID.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the delete operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('group', True, group_id, '', '')
|
||||
return self._DeleteProperties(uri)
|
||||
|
||||
def AddMemberToGroup(self, member_id, group_id):
|
||||
"""Add a member to a group.
|
||||
|
||||
Args:
|
||||
member_id: The member's email address (e.g. member@example.com).
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the add operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('member', False, group_id, member_id, '')
|
||||
properties = {}
|
||||
properties['memberId'] = member_id
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def IsMember(self, member_id, group_id):
|
||||
"""Check whether the given member already exists in the given group.
|
||||
|
||||
Args:
|
||||
member_id: The member's email address (e.g. member@example.com).
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
True if the member exists in the group. False otherwise.
|
||||
"""
|
||||
uri = self._ServiceUrl('member', True, group_id, member_id, '')
|
||||
return self._IsExisted(uri)
|
||||
|
||||
def RetrieveMember(self, member_id, group_id):
|
||||
"""Retrieve the given member in the given group.
|
||||
|
||||
Args:
|
||||
member_id: The member's email address (e.g. member@example.com).
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('member', True, group_id, member_id, '')
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def RetrieveAllMembers(self, group_id, suspended_users=False):
|
||||
"""Retrieve all members in the given group.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
suspended_users: A boolean; should we include any suspended users in
|
||||
the membership list returned?
|
||||
|
||||
Returns:
|
||||
A list containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('member', True, group_id, '', '',
|
||||
suspended_users=suspended_users)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def RetrievePageOfMembers(self, group_id, suspended_users=False, start=None):
|
||||
"""Retrieve one page of members of a given group.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
suspended_users: A boolean; should we include any suspended users in
|
||||
the membership list returned?
|
||||
start: The key to continue for pagination through all members.
|
||||
|
||||
Returns:
|
||||
A feed object containing the result of the retrieve operation.
|
||||
"""
|
||||
|
||||
uri = self._ServiceUrl('member', True, group_id, '', '',
|
||||
suspended_users=suspended_users)
|
||||
if start is not None:
|
||||
if suspended_users:
|
||||
uri += "&start="+start
|
||||
else:
|
||||
uri += "?start="+start
|
||||
property_feed = self._GetPropertyFeed(uri)
|
||||
return property_feed
|
||||
|
||||
def RemoveMemberFromGroup(self, member_id, group_id):
|
||||
"""Remove the given member from the given group.
|
||||
|
||||
Args:
|
||||
member_id: The member's email address (e.g. member@example.com).
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the remove operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('member', True, group_id, member_id, '')
|
||||
return self._DeleteProperties(uri)
|
||||
|
||||
def AddOwnerToGroup(self, owner_email, group_id):
|
||||
"""Add an owner to a group.
|
||||
|
||||
Args:
|
||||
owner_email: The email address of a group owner.
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the add operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('owner', False, group_id, '', owner_email)
|
||||
properties = {}
|
||||
properties['email'] = owner_email
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def IsOwner(self, owner_email, group_id):
|
||||
"""Check whether the given member an owner of the given group.
|
||||
|
||||
Args:
|
||||
owner_email: The email address of a group owner.
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
True if the member is an owner of the given group. False otherwise.
|
||||
"""
|
||||
uri = self._ServiceUrl('owner', True, group_id, '', owner_email)
|
||||
return self._IsExisted(uri)
|
||||
|
||||
def RetrieveOwner(self, owner_email, group_id):
|
||||
"""Retrieve the given owner in the given group.
|
||||
|
||||
Args:
|
||||
owner_email: The email address of a group owner.
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('owner', True, group_id, '', owner_email)
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def RetrieveAllOwners(self, group_id, suspended_users=False):
|
||||
"""Retrieve all owners of the given group.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
suspended_users: A boolean; should we include any suspended users in
|
||||
the ownership list returned?
|
||||
|
||||
Returns:
|
||||
A list containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('owner', True, group_id, '', '',
|
||||
suspended_users=suspended_users)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def RetrievePageOfOwners(self, group_id, suspended_users=False, start=None):
|
||||
"""Retrieve one page of owners of the given group.
|
||||
|
||||
Args:
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
suspended_users: A boolean; should we include any suspended users in
|
||||
the ownership list returned?
|
||||
start: The key to continue for pagination through all owners.
|
||||
|
||||
Returns:
|
||||
A feed object containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('owner', True, group_id, '', '',
|
||||
suspended_users=suspended_users)
|
||||
if start is not None:
|
||||
if suspended_users:
|
||||
uri += "&start="+start
|
||||
else:
|
||||
uri += "?start="+start
|
||||
property_feed = self._GetPropertyFeed(uri)
|
||||
return property_feed
|
||||
|
||||
def RemoveOwnerFromGroup(self, owner_email, group_id):
|
||||
"""Remove the given owner from the given group.
|
||||
|
||||
Args:
|
||||
owner_email: The email address of a group owner.
|
||||
group_id: The ID of the group (e.g. us-sales).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the remove operation.
|
||||
"""
|
||||
uri = self._ServiceUrl('owner', True, group_id, '', owner_email)
|
||||
return self._DeleteProperties(uri)
|
212
python/gdata/apps/migration/__init__.py
Normal file
212
python/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
python/gdata/apps/migration/service.py
Normal file
129
python/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
|
0
python/gdata/apps/organization/__init__.py
Normal file
0
python/gdata/apps/organization/__init__.py
Normal file
297
python/gdata/apps/organization/service.py
Normal file
297
python/gdata/apps/organization/service.py
Normal file
@@ -0,0 +1,297 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright (C) 2008 Google, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
"""Allow Google Apps domain administrators to manage organization unit and organization user.
|
||||
|
||||
OrganizationService: Provides methods to manage organization unit and organization user.
|
||||
"""
|
||||
|
||||
__author__ = 'Alexandre Vivien (alex@simplecode.fr)'
|
||||
|
||||
|
||||
import gdata.apps
|
||||
import gdata.apps.service
|
||||
import gdata.service
|
||||
|
||||
|
||||
API_VER = '2.0'
|
||||
CUSTOMER_BASE_URL = '/a/feeds/customer/2.0/customerId'
|
||||
BASE_UNIT_URL = '/a/feeds/orgunit/' + API_VER + '/%s'
|
||||
UNIT_URL = BASE_UNIT_URL + '/%s'
|
||||
UNIT_ALL_URL = BASE_UNIT_URL + '?get=all'
|
||||
UNIT_CHILD_URL = BASE_UNIT_URL + '?get=children&orgUnitPath=%s'
|
||||
BASE_USER_URL = '/a/feeds/orguser/' + API_VER + '/%s'
|
||||
USER_URL = BASE_USER_URL + '/%s'
|
||||
USER_ALL_URL = BASE_USER_URL + '?get=all'
|
||||
USER_CHILD_URL = BASE_USER_URL + '?get=children&orgUnitPath=%s'
|
||||
|
||||
|
||||
class OrganizationService(gdata.apps.service.PropertyService):
|
||||
"""Client for the Google Apps Organizations service."""
|
||||
|
||||
def _Bool2Str(self, b):
|
||||
if b is None:
|
||||
return None
|
||||
return str(b is True).lower()
|
||||
|
||||
def RetrieveCustomerId(self):
|
||||
"""Retrieve the Customer ID for the account of the authenticated administrator making this request.
|
||||
|
||||
Args:
|
||||
None.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the retrieve operation.
|
||||
"""
|
||||
|
||||
uri = CUSTOMER_BASE_URL
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def CreateOrgUnit(self, customer_id, name, parent_org_unit_path='/', description='', block_inheritance=False):
|
||||
"""Create a Organization Unit.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
name: The simple organization unit text name, not the full path name.
|
||||
parent_org_unit_path: The full path of the parental tree to this organization unit (default: '/').
|
||||
Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)
|
||||
description: The human readable text description of the organization unit (optional).
|
||||
block_inheritance: This parameter blocks policy setting inheritance
|
||||
from organization units higher in the organization tree (default: False).
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the create operation.
|
||||
"""
|
||||
|
||||
uri = BASE_UNIT_URL % (customer_id)
|
||||
properties = {}
|
||||
properties['name'] = name
|
||||
properties['parentOrgUnitPath'] = parent_org_unit_path
|
||||
properties['description'] = description
|
||||
properties['blockInheritance'] = self._Bool2Str(block_inheritance)
|
||||
return self._PostProperties(uri, properties)
|
||||
|
||||
def UpdateOrgUnit(self, customer_id, org_unit_path, name=None, parent_org_unit_path=None,
|
||||
description=None, block_inheritance=None):
|
||||
"""Update a Organization Unit.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
org_unit_path: The organization's full path name.
|
||||
Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)
|
||||
name: The simple organization unit text name, not the full path name.
|
||||
parent_org_unit_path: The full path of the parental tree to this organization unit.
|
||||
Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)
|
||||
description: The human readable text description of the organization unit.
|
||||
block_inheritance: This parameter blocks policy setting inheritance
|
||||
from organization units higher in the organization tree.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
|
||||
uri = UNIT_URL % (customer_id, org_unit_path)
|
||||
properties = {}
|
||||
if name:
|
||||
properties['name'] = name
|
||||
if parent_org_unit_path:
|
||||
properties['parentOrgUnitPath'] = parent_org_unit_path
|
||||
if description:
|
||||
properties['description'] = description
|
||||
if block_inheritance:
|
||||
properties['blockInheritance'] = self._Bool2Str(block_inheritance)
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def MoveUserToOrgUnit(self, customer_id, org_unit_path, users_to_move):
|
||||
"""Move a user to an Organization Unit.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
org_unit_path: The organization's full path name.
|
||||
Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)
|
||||
users_to_move: Email addresses list of users to move. Note: You can move a maximum of 25 users at one time.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
|
||||
uri = UNIT_URL % (customer_id, org_unit_path)
|
||||
properties = {}
|
||||
if users_to_move and isinstance(users_to_move, list):
|
||||
properties['usersToMove'] = ', '.join(users_to_move)
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def RetrieveOrgUnit(self, customer_id, org_unit_path):
|
||||
"""Retrieve a Orgunit based on its path.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
org_unit_path: The organization's full path name.
|
||||
Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = UNIT_URL % (customer_id, org_unit_path)
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def DeleteOrgUnit(self, customer_id, org_unit_path):
|
||||
"""Delete a Orgunit based on its path.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
org_unit_path: The organization's full path name.
|
||||
Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the delete operation.
|
||||
"""
|
||||
uri = UNIT_URL % (customer_id, org_unit_path)
|
||||
return self._DeleteProperties(uri)
|
||||
|
||||
def RetrieveAllOrgUnits(self, customer_id):
|
||||
"""Retrieve all OrgUnits in the customer's domain.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
|
||||
Returns:
|
||||
A list containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = UNIT_ALL_URL % (customer_id)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def RetrievePageOfOrgUnits(self, customer_id, startKey=None):
|
||||
"""Retrieve one page of OrgUnits in the customer's domain.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
startKey: The key to continue for pagination through all OrgUnits.
|
||||
|
||||
Returns:
|
||||
A feed object containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = UNIT_ALL_URL % (customer_id)
|
||||
if startKey is not None:
|
||||
uri += "&startKey=" + startKey
|
||||
property_feed = self._GetPropertyFeed(uri)
|
||||
return property_feed
|
||||
|
||||
def RetrieveSubOrgUnits(self, customer_id, org_unit_path):
|
||||
"""Retrieve all Sub-OrgUnits of the provided OrgUnit.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
org_unit_path: The organization's full path name.
|
||||
Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)
|
||||
|
||||
Returns:
|
||||
A list containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = UNIT_CHILD_URL % (customer_id, org_unit_path)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def RetrieveOrgUser(self, customer_id, user_email):
|
||||
"""Retrieve the OrgUnit of the user.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
user_email: The email address of the user.
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = USER_URL % (customer_id, user_email)
|
||||
return self._GetProperties(uri)
|
||||
|
||||
def UpdateOrgUser(self, customer_id, user_email, org_unit_path):
|
||||
"""Update the OrgUnit of a OrgUser.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
user_email: The email address of the user.
|
||||
org_unit_path: The new organization's full path name.
|
||||
Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)
|
||||
|
||||
Returns:
|
||||
A dict containing the result of the update operation.
|
||||
"""
|
||||
|
||||
uri = USER_URL % (customer_id, user_email)
|
||||
properties = {}
|
||||
if org_unit_path:
|
||||
properties['orgUnitPath'] = org_unit_path
|
||||
return self._PutProperties(uri, properties)
|
||||
|
||||
def RetrieveAllOrgUsers(self, customer_id):
|
||||
"""Retrieve all OrgUsers in the customer's domain.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
|
||||
Returns:
|
||||
A list containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = USER_ALL_URL % (customer_id)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def RetrievePageOfOrgUsers(self, customer_id, startKey=None):
|
||||
"""Retrieve one page of OrgUsers in the customer's domain.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
startKey: The key to continue for pagination through all OrgUnits.
|
||||
|
||||
Returns:
|
||||
A feed object containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = USER_ALL_URL % (customer_id)
|
||||
if startKey is not None:
|
||||
uri += "&startKey=" + startKey
|
||||
property_feed = self._GetPropertyFeed(uri)
|
||||
return property_feed
|
||||
|
||||
def RetrieveOrgUnitUsers(self, customer_id, org_unit_path):
|
||||
"""Retrieve all OrgUsers of the provided OrgUnit.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
org_unit_path: The organization's full path name.
|
||||
Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)
|
||||
|
||||
Returns:
|
||||
A list containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = USER_CHILD_URL % (customer_id, org_unit_path)
|
||||
return self._GetPropertiesList(uri)
|
||||
|
||||
def RetrieveOrgUnitPageOfUsers(self, customer_id, org_unit_path, startKey=None):
|
||||
"""Retrieve one page of OrgUsers of the provided OrgUnit.
|
||||
|
||||
Args:
|
||||
customer_id: The ID of the Google Apps customer.
|
||||
org_unit_path: The organization's full path name.
|
||||
Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)
|
||||
startKey: The key to continue for pagination through all OrgUsers.
|
||||
|
||||
Returns:
|
||||
A feed object containing the result of the retrieve operation.
|
||||
"""
|
||||
uri = USER_CHILD_URL % (customer_id, org_unit_path)
|
||||
if startKey is not None:
|
||||
uri += "&startKey=" + startKey
|
||||
property_feed = self._GetPropertyFeed(uri)
|
||||
return property_feed
|
552
python/gdata/apps/service.py
Normal file
552
python/gdata/apps/service.py
Normal file
@@ -0,0 +1,552 @@
|
||||
#!/usr/bin/python
|
||||
#
|
||||
# Copyright (C) 2007 SIOS Technology, Inc.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
__author__ = 'tmatsuo@sios.com (Takashi MATSUO)'
|
||||
|
||||
try:
|
||||
from xml.etree import cElementTree as ElementTree
|
||||
except ImportError:
|
||||
try:
|
||||
import cElementTree as ElementTree
|
||||
except ImportError:
|
||||
try:
|
||||
from xml.etree import ElementTree
|
||||
except ImportError:
|
||||
from elementtree import ElementTree
|
||||
import urllib
|
||||
import gdata
|
||||
import atom.service
|
||||
import gdata.service
|
||||
import gdata.apps
|
||||
import atom
|
||||
|
||||
API_VER="2.0"
|
||||
HTTP_OK=200
|
||||
|
||||
UNKOWN_ERROR=1000
|
||||
USER_DELETED_RECENTLY=1100
|
||||
USER_SUSPENDED=1101
|
||||
DOMAIN_USER_LIMIT_EXCEEDED=1200
|
||||
DOMAIN_ALIAS_LIMIT_EXCEEDED=1201
|
||||
DOMAIN_SUSPENDED=1202
|
||||
DOMAIN_FEATURE_UNAVAILABLE=1203
|
||||
ENTITY_EXISTS=1300
|
||||
ENTITY_DOES_NOT_EXIST=1301
|
||||
ENTITY_NAME_IS_RESERVED=1302
|
||||
ENTITY_NAME_NOT_VALID=1303
|
||||
INVALID_GIVEN_NAME=1400
|
||||
INVALID_FAMILY_NAME=1401
|
||||
INVALID_PASSWORD=1402
|
||||
INVALID_USERNAME=1403
|
||||
INVALID_HASH_FUNCTION_NAME=1404
|
||||
INVALID_HASH_DIGGEST_LENGTH=1405
|
||||
INVALID_EMAIL_ADDRESS=1406
|
||||
INVALID_QUERY_PARAMETER_VALUE=1407
|
||||
TOO_MANY_RECIPIENTS_ON_EMAIL_LIST=1500
|
||||
|
||||
DEFAULT_QUOTA_LIMIT='2048'
|
||||
|
||||
|
||||
class Error(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class AppsForYourDomainException(Error):
|
||||
|
||||
def __init__(self, response):
|
||||
|
||||
Error.__init__(self, response)
|
||||
try:
|
||||
self.element_tree = ElementTree.fromstring(response['body'])
|
||||
self.error_code = int(self.element_tree[0].attrib['errorCode'])
|
||||
self.reason = self.element_tree[0].attrib['reason']
|
||||
self.invalidInput = self.element_tree[0].attrib['invalidInput']
|
||||
except:
|
||||
self.error_code = UNKOWN_ERROR
|
||||
|
||||
|
||||
class AppsService(gdata.service.GDataService):
|
||||
"""Client for the Google Apps Provisioning service."""
|
||||
|
||||
def __init__(self, email=None, password=None, domain=None, source=None,
|
||||
server='apps-apis.google.com', additional_headers=None,
|
||||
**kwargs):
|
||||
"""Creates a client for the Google Apps Provisioning service.
|
||||
|
||||
Args:
|
||||
email: string (optional) The user's email address, used for
|
||||
authentication.
|
||||
password: string (optional) The user's password.
|
||||
domain: string (optional) The Google Apps domain name.
|
||||
source: string (optional) The name of the user's application.
|
||||
server: string (optional) The name of the server to which a connection
|
||||
will be opened. Default value: 'apps-apis.google.com'.
|
||||
**kwargs: The other parameters to pass to gdata.service.GDataService
|
||||
constructor.
|
||||
"""
|
||||
gdata.service.GDataService.__init__(
|
||||
self, email=email, password=password, service='apps', source=source,
|
||||
server=server, additional_headers=additional_headers, **kwargs)
|
||||
self.ssl = True
|
||||
self.port = 443
|
||||
self.domain = domain
|
||||
|
||||
def _baseURL(self):
|
||||
return "/a/feeds/%s" % self.domain
|
||||
|
||||
def AddAllElementsFromAllPages(self, link_finder, func):
|
||||
"""retrieve all pages and add all elements"""
|
||||
next = link_finder.GetNextLink()
|
||||
while next is not None:
|
||||
next_feed = self.Get(next.href, converter=func)
|
||||
for a_entry in next_feed.entry:
|
||||
link_finder.entry.append(a_entry)
|
||||
next = next_feed.GetNextLink()
|
||||
return link_finder
|
||||
|
||||
def RetrievePageOfEmailLists(self, start_email_list_name=None,
|
||||
num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY,
|
||||
backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve one page of email list"""
|
||||
uri = "%s/emailList/%s" % (self._baseURL(), API_VER)
|
||||
if start_email_list_name is not None:
|
||||
uri += "?startEmailListName=%s" % start_email_list_name
|
||||
try:
|
||||
return gdata.apps.EmailListFeedFromString(str(self.GetWithRetries(
|
||||
uri, num_retries=num_retries, delay=delay, backoff=backoff)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def GetGeneratorForAllEmailLists(
|
||||
self, num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve a generator for all emaillists in this domain."""
|
||||
first_page = self.RetrievePageOfEmailLists(num_retries=num_retries,
|
||||
delay=delay,
|
||||
backoff=backoff)
|
||||
return self.GetGeneratorFromLinkFinder(
|
||||
first_page, gdata.apps.EmailListRecipientFeedFromString,
|
||||
num_retries=num_retries, delay=delay, backoff=backoff)
|
||||
|
||||
def RetrieveAllEmailLists(self):
|
||||
"""Retrieve all email list of a domain."""
|
||||
|
||||
ret = self.RetrievePageOfEmailLists()
|
||||
# pagination
|
||||
return self.AddAllElementsFromAllPages(
|
||||
ret, gdata.apps.EmailListFeedFromString)
|
||||
|
||||
def RetrieveEmailList(self, list_name):
|
||||
"""Retreive a single email list by the list's name."""
|
||||
|
||||
uri = "%s/emailList/%s/%s" % (
|
||||
self._baseURL(), API_VER, list_name)
|
||||
try:
|
||||
return self.Get(uri, converter=gdata.apps.EmailListEntryFromString)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def RetrieveEmailLists(self, recipient):
|
||||
"""Retrieve All Email List Subscriptions for an Email Address."""
|
||||
|
||||
uri = "%s/emailList/%s?recipient=%s" % (
|
||||
self._baseURL(), API_VER, recipient)
|
||||
try:
|
||||
ret = gdata.apps.EmailListFeedFromString(str(self.Get(uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
# pagination
|
||||
return self.AddAllElementsFromAllPages(
|
||||
ret, gdata.apps.EmailListFeedFromString)
|
||||
|
||||
def RemoveRecipientFromEmailList(self, recipient, list_name):
|
||||
"""Remove recipient from email list."""
|
||||
|
||||
uri = "%s/emailList/%s/%s/recipient/%s" % (
|
||||
self._baseURL(), API_VER, list_name, recipient)
|
||||
try:
|
||||
self.Delete(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def RetrievePageOfRecipients(self, list_name, start_recipient=None,
|
||||
num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY,
|
||||
backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve one page of recipient of an email list. """
|
||||
|
||||
uri = "%s/emailList/%s/%s/recipient" % (
|
||||
self._baseURL(), API_VER, list_name)
|
||||
|
||||
if start_recipient is not None:
|
||||
uri += "?startRecipient=%s" % start_recipient
|
||||
try:
|
||||
return gdata.apps.EmailListRecipientFeedFromString(str(
|
||||
self.GetWithRetries(
|
||||
uri, num_retries=num_retries, delay=delay, backoff=backoff)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def GetGeneratorForAllRecipients(
|
||||
self, list_name, num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve a generator for all recipients of a particular emaillist."""
|
||||
first_page = self.RetrievePageOfRecipients(list_name,
|
||||
num_retries=num_retries,
|
||||
delay=delay,
|
||||
backoff=backoff)
|
||||
return self.GetGeneratorFromLinkFinder(
|
||||
first_page, gdata.apps.EmailListRecipientFeedFromString,
|
||||
num_retries=num_retries, delay=delay, backoff=backoff)
|
||||
|
||||
def RetrieveAllRecipients(self, list_name):
|
||||
"""Retrieve all recipient of an email list."""
|
||||
|
||||
ret = self.RetrievePageOfRecipients(list_name)
|
||||
# pagination
|
||||
return self.AddAllElementsFromAllPages(
|
||||
ret, gdata.apps.EmailListRecipientFeedFromString)
|
||||
|
||||
def AddRecipientToEmailList(self, recipient, list_name):
|
||||
"""Add a recipient to a email list."""
|
||||
|
||||
uri = "%s/emailList/%s/%s/recipient" % (
|
||||
self._baseURL(), API_VER, list_name)
|
||||
recipient_entry = gdata.apps.EmailListRecipientEntry()
|
||||
recipient_entry.who = gdata.apps.Who(email=recipient)
|
||||
|
||||
try:
|
||||
return gdata.apps.EmailListRecipientEntryFromString(
|
||||
str(self.Post(recipient_entry, uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def DeleteEmailList(self, list_name):
|
||||
"""Delete a email list"""
|
||||
|
||||
uri = "%s/emailList/%s/%s" % (self._baseURL(), API_VER, list_name)
|
||||
try:
|
||||
self.Delete(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def CreateEmailList(self, list_name):
|
||||
"""Create a email list. """
|
||||
|
||||
uri = "%s/emailList/%s" % (self._baseURL(), API_VER)
|
||||
email_list_entry = gdata.apps.EmailListEntry()
|
||||
email_list_entry.email_list = gdata.apps.EmailList(name=list_name)
|
||||
try:
|
||||
return gdata.apps.EmailListEntryFromString(
|
||||
str(self.Post(email_list_entry, uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def DeleteNickname(self, nickname):
|
||||
"""Delete a nickname"""
|
||||
|
||||
uri = "%s/nickname/%s/%s" % (self._baseURL(), API_VER, nickname)
|
||||
try:
|
||||
self.Delete(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def RetrievePageOfNicknames(self, start_nickname=None,
|
||||
num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY,
|
||||
backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve one page of nicknames in the domain"""
|
||||
|
||||
uri = "%s/nickname/%s" % (self._baseURL(), API_VER)
|
||||
if start_nickname is not None:
|
||||
uri += "?startNickname=%s" % start_nickname
|
||||
try:
|
||||
return gdata.apps.NicknameFeedFromString(str(self.GetWithRetries(
|
||||
uri, num_retries=num_retries, delay=delay, backoff=backoff)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def GetGeneratorForAllNicknames(
|
||||
self, num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve a generator for all nicknames in this domain."""
|
||||
first_page = self.RetrievePageOfNicknames(num_retries=num_retries,
|
||||
delay=delay,
|
||||
backoff=backoff)
|
||||
return self.GetGeneratorFromLinkFinder(
|
||||
first_page, gdata.apps.NicknameFeedFromString, num_retries=num_retries,
|
||||
delay=delay, backoff=backoff)
|
||||
|
||||
def RetrieveAllNicknames(self):
|
||||
"""Retrieve all nicknames in the domain"""
|
||||
|
||||
ret = self.RetrievePageOfNicknames()
|
||||
# pagination
|
||||
return self.AddAllElementsFromAllPages(
|
||||
ret, gdata.apps.NicknameFeedFromString)
|
||||
|
||||
def GetGeneratorForAllNicknamesOfAUser(
|
||||
self, user_name, num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve a generator for all nicknames of a particular user."""
|
||||
uri = "%s/nickname/%s?username=%s" % (self._baseURL(), API_VER, user_name)
|
||||
try:
|
||||
first_page = gdata.apps.NicknameFeedFromString(str(self.GetWithRetries(
|
||||
uri, num_retries=num_retries, delay=delay, backoff=backoff)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
return self.GetGeneratorFromLinkFinder(
|
||||
first_page, gdata.apps.NicknameFeedFromString, num_retries=num_retries,
|
||||
delay=delay, backoff=backoff)
|
||||
|
||||
def RetrieveNicknames(self, user_name):
|
||||
"""Retrieve nicknames of the user"""
|
||||
|
||||
uri = "%s/nickname/%s?username=%s" % (self._baseURL(), API_VER, user_name)
|
||||
try:
|
||||
ret = gdata.apps.NicknameFeedFromString(str(self.Get(uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
# pagination
|
||||
return self.AddAllElementsFromAllPages(
|
||||
ret, gdata.apps.NicknameFeedFromString)
|
||||
|
||||
def RetrieveNickname(self, nickname):
|
||||
"""Retrieve a nickname.
|
||||
|
||||
Args:
|
||||
nickname: string The nickname to retrieve
|
||||
|
||||
Returns:
|
||||
gdata.apps.NicknameEntry
|
||||
"""
|
||||
|
||||
uri = "%s/nickname/%s/%s" % (self._baseURL(), API_VER, nickname)
|
||||
try:
|
||||
return gdata.apps.NicknameEntryFromString(str(self.Get(uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def CreateNickname(self, user_name, nickname):
|
||||
"""Create a nickname"""
|
||||
|
||||
uri = "%s/nickname/%s" % (self._baseURL(), API_VER)
|
||||
nickname_entry = gdata.apps.NicknameEntry()
|
||||
nickname_entry.login = gdata.apps.Login(user_name=user_name)
|
||||
nickname_entry.nickname = gdata.apps.Nickname(name=nickname)
|
||||
|
||||
try:
|
||||
return gdata.apps.NicknameEntryFromString(
|
||||
str(self.Post(nickname_entry, uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def DeleteUser(self, user_name):
|
||||
"""Delete a user account"""
|
||||
|
||||
uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name)
|
||||
try:
|
||||
return self.Delete(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def UpdateUser(self, user_name, user_entry):
|
||||
"""Update a user account."""
|
||||
|
||||
uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name)
|
||||
try:
|
||||
return gdata.apps.UserEntryFromString(str(self.Put(user_entry, uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def CreateUser(self, user_name, family_name, given_name, password,
|
||||
suspended='false', quota_limit=None,
|
||||
password_hash_function=None,
|
||||
change_password=None):
|
||||
"""Create a user account. """
|
||||
|
||||
uri = "%s/user/%s" % (self._baseURL(), API_VER)
|
||||
user_entry = gdata.apps.UserEntry()
|
||||
user_entry.login = gdata.apps.Login(
|
||||
user_name=user_name, password=password, suspended=suspended,
|
||||
hash_function_name=password_hash_function,
|
||||
change_password=change_password)
|
||||
user_entry.name = gdata.apps.Name(family_name=family_name,
|
||||
given_name=given_name)
|
||||
if quota_limit is not None:
|
||||
user_entry.quota = gdata.apps.Quota(limit=str(quota_limit))
|
||||
|
||||
try:
|
||||
return gdata.apps.UserEntryFromString(str(self.Post(user_entry, uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def SuspendUser(self, user_name):
|
||||
user_entry = self.RetrieveUser(user_name)
|
||||
if user_entry.login.suspended != 'true':
|
||||
user_entry.login.suspended = 'true'
|
||||
user_entry = self.UpdateUser(user_name, user_entry)
|
||||
return user_entry
|
||||
|
||||
def RestoreUser(self, user_name):
|
||||
user_entry = self.RetrieveUser(user_name)
|
||||
if user_entry.login.suspended != 'false':
|
||||
user_entry.login.suspended = 'false'
|
||||
user_entry = self.UpdateUser(user_name, user_entry)
|
||||
return user_entry
|
||||
|
||||
def RetrieveUser(self, user_name):
|
||||
"""Retrieve an user account.
|
||||
|
||||
Args:
|
||||
user_name: string The user name to retrieve
|
||||
|
||||
Returns:
|
||||
gdata.apps.UserEntry
|
||||
"""
|
||||
|
||||
uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name)
|
||||
try:
|
||||
return gdata.apps.UserEntryFromString(str(self.Get(uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def RetrievePageOfUsers(self, start_username=None,
|
||||
num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY,
|
||||
backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve one page of users in this domain."""
|
||||
|
||||
uri = "%s/user/%s" % (self._baseURL(), API_VER)
|
||||
if start_username is not None:
|
||||
uri += "?startUsername=%s" % start_username
|
||||
try:
|
||||
return gdata.apps.UserFeedFromString(str(self.GetWithRetries(
|
||||
uri, num_retries=num_retries, delay=delay, backoff=backoff)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise AppsForYourDomainException(e.args[0])
|
||||
|
||||
def GetGeneratorForAllUsers(self,
|
||||
num_retries=gdata.service.DEFAULT_NUM_RETRIES,
|
||||
delay=gdata.service.DEFAULT_DELAY,
|
||||
backoff=gdata.service.DEFAULT_BACKOFF):
|
||||
"""Retrieve a generator for all users in this domain."""
|
||||
first_page = self.RetrievePageOfUsers(num_retries=num_retries, delay=delay,
|
||||
backoff=backoff)
|
||||
return self.GetGeneratorFromLinkFinder(
|
||||
first_page, gdata.apps.UserFeedFromString, num_retries=num_retries,
|
||||
delay=delay, backoff=backoff)
|
||||
|
||||
def RetrieveAllUsers(self):
|
||||
"""Retrieve all users in this domain. OBSOLETE"""
|
||||
|
||||
ret = self.RetrievePageOfUsers()
|
||||
# pagination
|
||||
return self.AddAllElementsFromAllPages(
|
||||
ret, gdata.apps.UserFeedFromString)
|
||||
|
||||
|
||||
class PropertyService(gdata.service.GDataService):
|
||||
"""Client for the Google Apps Property service."""
|
||||
|
||||
def __init__(self, email=None, password=None, domain=None, source=None,
|
||||
server='apps-apis.google.com', additional_headers=None):
|
||||
gdata.service.GDataService.__init__(self, email=email, password=password,
|
||||
service='apps', source=source,
|
||||
server=server,
|
||||
additional_headers=additional_headers)
|
||||
self.ssl = True
|
||||
self.port = 443
|
||||
self.domain = domain
|
||||
|
||||
def AddAllElementsFromAllPages(self, link_finder, func):
|
||||
"""retrieve all pages and add all elements"""
|
||||
next = link_finder.GetNextLink()
|
||||
while next is not None:
|
||||
next_feed = self.Get(next.href, converter=func)
|
||||
for a_entry in next_feed.entry:
|
||||
link_finder.entry.append(a_entry)
|
||||
next = next_feed.GetNextLink()
|
||||
return link_finder
|
||||
|
||||
def _GetPropertyEntry(self, properties):
|
||||
property_entry = gdata.apps.PropertyEntry()
|
||||
property = []
|
||||
for name, value in properties.iteritems():
|
||||
if name is not None and value is not None:
|
||||
property.append(gdata.apps.Property(name=name, value=value))
|
||||
property_entry.property = property
|
||||
return property_entry
|
||||
|
||||
def _PropertyEntry2Dict(self, property_entry):
|
||||
properties = {}
|
||||
for i, property in enumerate(property_entry.property):
|
||||
properties[property.name] = property.value
|
||||
return properties
|
||||
|
||||
def _GetPropertyFeed(self, uri):
|
||||
try:
|
||||
return gdata.apps.PropertyFeedFromString(str(self.Get(uri)))
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
|
||||
def _GetPropertiesList(self, uri):
|
||||
property_feed = self._GetPropertyFeed(uri)
|
||||
# pagination
|
||||
property_feed = self.AddAllElementsFromAllPages(
|
||||
property_feed, gdata.apps.PropertyFeedFromString)
|
||||
properties_list = []
|
||||
for property_entry in property_feed.entry:
|
||||
properties_list.append(self._PropertyEntry2Dict(property_entry))
|
||||
return properties_list
|
||||
|
||||
def _GetProperties(self, uri):
|
||||
try:
|
||||
return self._PropertyEntry2Dict(gdata.apps.PropertyEntryFromString(
|
||||
str(self.Get(uri))))
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
|
||||
def _PostProperties(self, uri, properties):
|
||||
property_entry = self._GetPropertyEntry(properties)
|
||||
try:
|
||||
return self._PropertyEntry2Dict(gdata.apps.PropertyEntryFromString(
|
||||
str(self.Post(property_entry, uri))))
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
|
||||
def _PutProperties(self, uri, properties):
|
||||
property_entry = self._GetPropertyEntry(properties)
|
||||
try:
|
||||
return self._PropertyEntry2Dict(gdata.apps.PropertyEntryFromString(
|
||||
str(self.Put(property_entry, uri))))
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
|
||||
def _DeleteProperties(self, uri):
|
||||
try:
|
||||
self.Delete(uri)
|
||||
except gdata.service.RequestError, e:
|
||||
raise gdata.apps.service.AppsForYourDomainException(e.args[0])
|
||||
|
||||
|
||||
def _bool2str(b):
|
||||
if b is None:
|
||||
return None
|
||||
return str(b is True).lower()
|
Reference in New Issue
Block a user