code
stringlengths
1
1.72M
language
stringclasses
1 value
# Just use the MD5 module from the Python standard library __revision__ = "$Id: MD5.py,v 1.4 2002/07/11 14:31:19 akuchling Exp $" from md5 import * import md5 if hasattr(md5, 'digestsize'): digest_size = digestsize del digestsize del md5
Python
"""HMAC (Keyed-Hashing for Message Authentication) Python module. Implements the HMAC algorithm as described by RFC 2104. This is just a copy of the Python 2.2 HMAC module, modified to work when used on versions of Python before 2.2. """ __revision__ = "$Id: HMAC.py,v 1.5 2002/07/25 17:19:02 z3p Exp $" import string def _strxor(s1, s2): """Utility method. XOR the two strings s1 and s2 (must have same length). """ return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2)) # The size of the digests returned by HMAC depends on the underlying # hashing module used. digest_size = None class HMAC: """RFC2104 HMAC class. This supports the API for Cryptographic Hash Functions (PEP 247). """ def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. Defaults to the md5 module. """ if digestmod == None: import md5 digestmod = md5 self.digestmod = digestmod self.outer = digestmod.new() self.inner = digestmod.new() try: self.digest_size = digestmod.digest_size except AttributeError: self.digest_size = len(self.outer.digest()) blocksize = 64 ipad = "\x36" * blocksize opad = "\x5C" * blocksize if len(key) > blocksize: key = digestmod.new(key).digest() key = key + chr(0) * (blocksize - len(key)) self.outer.update(_strxor(key, opad)) self.inner.update(_strxor(key, ipad)) if (msg): self.update(msg) ## def clear(self): ## raise NotImplementedError, "clear() method not available in HMAC." def update(self, msg): """Update this hashing object with the string msg. """ self.inner.update(msg) def copy(self): """Return a separate copy of this hashing object. An update to this copy won't affect the original object. """ other = HMAC("") other.digestmod = self.digestmod other.inner = self.inner.copy() other.outer = self.outer.copy() return other def digest(self): """Return the hash value of this hashing object. This returns a string containing 8-bit data. The object is not altered in any way by this function; you can continue updating the object after calling this function. """ h = self.outer.copy() h.update(self.inner.digest()) return h.digest() def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead. """ return "".join([string.zfill(hex(ord(x))[2:], 2) for x in tuple(self.digest())]) def new(key, msg = None, digestmod = None): """Create a new hashing object and return it. key: The starting key for the hash. msg: if available, will immediately be hashed into the object's starting state. You can now feed arbitrary strings into the object using its update() method, and can ask for the hash value at any time by calling its digest() method. """ return HMAC(key, msg, digestmod)
Python
# Just use the SHA module from the Python standard library __revision__ = "$Id: SHA.py,v 1.4 2002/07/11 14:31:19 akuchling Exp $" from sha import * import sha if hasattr(sha, 'digestsize'): digest_size = digestsize del digestsize del sha
Python
"""Hashing algorithms Hash functions take arbitrary strings as input, and produce an output of fixed size that is dependent on the input; it should never be possible to derive the input data given only the hash function's output. Hash functions can be used simply as a checksum, or, in association with a public-key algorithm, can be used to implement digital signatures. The hashing modules here all support the interface described in PEP 247, "API for Cryptographic Hash Functions". Submodules: Crypto.Hash.HMAC RFC 2104: Keyed-Hashing for Message Authentication Crypto.Hash.MD2 Crypto.Hash.MD4 Crypto.Hash.MD5 Crypto.Hash.RIPEMD Crypto.Hash.SHA """ __all__ = ['HMAC', 'MD2', 'MD4', 'MD5', 'RIPEMD', 'SHA', 'SHA256'] __revision__ = "$Id: __init__.py,v 1.6 2003/12/19 14:24:25 akuchling Exp $"
Python
"""Python Cryptography Toolkit A collection of cryptographic modules implementing various algorithms and protocols. Subpackages: Crypto.Cipher Secret-key encryption algorithms (AES, DES, ARC4) Crypto.Hash Hashing algorithms (MD5, SHA, HMAC) Crypto.Protocol Cryptographic protocols (Chaffing, all-or-nothing transform). This package does not contain any network protocols. Crypto.PublicKey Public-key encryption and signature algorithms (RSA, DSA) Crypto.Util Various useful modules and functions (long-to-string conversion, random number generation, number theoretic functions) """ __all__ = ['Cipher', 'Hash', 'Protocol', 'PublicKey', 'Util'] __version__ = '2.0.1' __revision__ = "$Id: __init__.py,v 1.12 2005/06/14 01:20:22 akuchling Exp $"
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the data classes of the Google Finance Portfolio Data API""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import atom.data import gdata.data import gdata.opensearch.data GF_TEMPLATE = '{http://schemas.google.com/finance/2007/}%s' class Commission(atom.core.XmlElement): """Commission for the transaction""" _qname = GF_TEMPLATE % 'commission' money = [gdata.data.Money] class CostBasis(atom.core.XmlElement): """Cost basis for the portfolio or position""" _qname = GF_TEMPLATE % 'costBasis' money = [gdata.data.Money] class DaysGain(atom.core.XmlElement): """Today's gain for the portfolio or position""" _qname = GF_TEMPLATE % 'daysGain' money = [gdata.data.Money] class Gain(atom.core.XmlElement): """Total gain for the portfolio or position""" _qname = GF_TEMPLATE % 'gain' money = [gdata.data.Money] class MarketValue(atom.core.XmlElement): """Market value for the portfolio or position""" _qname = GF_TEMPLATE % 'marketValue' money = [gdata.data.Money] class PortfolioData(atom.core.XmlElement): """Data for the portfolio""" _qname = GF_TEMPLATE % 'portfolioData' return_overall = 'returnOverall' currency_code = 'currencyCode' return3y = 'return3y' return4w = 'return4w' market_value = MarketValue return_y_t_d = 'returnYTD' cost_basis = CostBasis gain_percentage = 'gainPercentage' days_gain = DaysGain return3m = 'return3m' return5y = 'return5y' return1w = 'return1w' gain = Gain return1y = 'return1y' class PortfolioEntry(gdata.data.GDEntry): """Describes an entry in a feed of Finance portfolios""" portfolio_data = PortfolioData class PortfolioFeed(gdata.data.GDFeed): """Describes a Finance portfolio feed""" entry = [PortfolioEntry] class PositionData(atom.core.XmlElement): """Data for the position""" _qname = GF_TEMPLATE % 'positionData' return_y_t_d = 'returnYTD' return5y = 'return5y' return_overall = 'returnOverall' cost_basis = CostBasis return3y = 'return3y' return1y = 'return1y' return4w = 'return4w' shares = 'shares' days_gain = DaysGain gain_percentage = 'gainPercentage' market_value = MarketValue gain = Gain return3m = 'return3m' return1w = 'return1w' class Price(atom.core.XmlElement): """Price of the transaction""" _qname = GF_TEMPLATE % 'price' money = [gdata.data.Money] class Symbol(atom.core.XmlElement): """Stock symbol for the company""" _qname = GF_TEMPLATE % 'symbol' symbol = 'symbol' exchange = 'exchange' full_name = 'fullName' class PositionEntry(gdata.data.GDEntry): """Describes an entry in a feed of Finance positions""" symbol = Symbol position_data = PositionData class PositionFeed(gdata.data.GDFeed): """Describes a Finance position feed""" entry = [PositionEntry] class TransactionData(atom.core.XmlElement): """Data for the transction""" _qname = GF_TEMPLATE % 'transactionData' shares = 'shares' notes = 'notes' date = 'date' type = 'type' commission = Commission price = Price class TransactionEntry(gdata.data.GDEntry): """Describes an entry in a feed of Finance transactions""" transaction_data = TransactionData class TransactionFeed(gdata.data.GDFeed): """Describes a Finance transaction feed""" entry = [TransactionEntry]
Python
#!/usr/bin/python # # Copyright (C) 2009 Tan Swee Heng # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains extensions to Atom objects used with Google Finance.""" __author__ = 'thesweeheng@gmail.com' import atom import gdata GD_NAMESPACE = 'http://schemas.google.com/g/2005' GF_NAMESPACE = 'http://schemas.google.com/finance/2007' class Money(atom.AtomBase): """The <gd:money> element.""" _tag = 'money' _namespace = GD_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['amount'] = 'amount' _attributes['currencyCode'] = 'currency_code' def __init__(self, amount=None, currency_code=None, **kwargs): self.amount = amount self.currency_code = currency_code atom.AtomBase.__init__(self, **kwargs) def __str__(self): return "%s %s" % (self.amount, self.currency_code) def MoneyFromString(xml_string): return atom.CreateClassFromXMLString(Money, xml_string) class _Monies(atom.AtomBase): """An element containing multiple <gd:money> in multiple currencies.""" _namespace = GF_NAMESPACE _children = atom.AtomBase._children.copy() _children['{%s}money' % GD_NAMESPACE] = ('money', [Money]) def __init__(self, money=None, **kwargs): self.money = money or [] atom.AtomBase.__init__(self, **kwargs) def __str__(self): return " / ".join(["%s" % i for i in self.money]) class CostBasis(_Monies): """The <gf:costBasis> element.""" _tag = 'costBasis' def CostBasisFromString(xml_string): return atom.CreateClassFromXMLString(CostBasis, xml_string) class DaysGain(_Monies): """The <gf:daysGain> element.""" _tag = 'daysGain' def DaysGainFromString(xml_string): return atom.CreateClassFromXMLString(DaysGain, xml_string) class Gain(_Monies): """The <gf:gain> element.""" _tag = 'gain' def GainFromString(xml_string): return atom.CreateClassFromXMLString(Gain, xml_string) class MarketValue(_Monies): """The <gf:marketValue> element.""" _tag = 'gain' _tag = 'marketValue' def MarketValueFromString(xml_string): return atom.CreateClassFromXMLString(MarketValue, xml_string) class Commission(_Monies): """The <gf:commission> element.""" _tag = 'commission' def CommissionFromString(xml_string): return atom.CreateClassFromXMLString(Commission, xml_string) class Price(_Monies): """The <gf:price> element.""" _tag = 'price' def PriceFromString(xml_string): return atom.CreateClassFromXMLString(Price, xml_string) class Symbol(atom.AtomBase): """The <gf:symbol> element.""" _tag = 'symbol' _namespace = GF_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['fullName'] = 'full_name' _attributes['exchange'] = 'exchange' _attributes['symbol'] = 'symbol' def __init__(self, full_name=None, exchange=None, symbol=None, **kwargs): self.full_name = full_name self.exchange = exchange self.symbol = symbol atom.AtomBase.__init__(self, **kwargs) def __str__(self): return "%s:%s (%s)" % (self.exchange, self.symbol, self.full_name) def SymbolFromString(xml_string): return atom.CreateClassFromXMLString(Symbol, xml_string) class TransactionData(atom.AtomBase): """The <gf:transactionData> element.""" _tag = 'transactionData' _namespace = GF_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' _attributes['date'] = 'date' _attributes['shares'] = 'shares' _attributes['notes'] = 'notes' _children = atom.AtomBase._children.copy() _children['{%s}commission' % GF_NAMESPACE] = ('commission', Commission) _children['{%s}price' % GF_NAMESPACE] = ('price', Price) def __init__(self, type=None, date=None, shares=None, notes=None, commission=None, price=None, **kwargs): self.type = type self.date = date self.shares = shares self.notes = notes self.commission = commission self.price = price atom.AtomBase.__init__(self, **kwargs) def TransactionDataFromString(xml_string): return atom.CreateClassFromXMLString(TransactionData, xml_string) class TransactionEntry(gdata.GDataEntry): """An entry of the transaction feed. A TransactionEntry contains TransactionData such as the transaction type (Buy, Sell, Sell Short, or Buy to Cover), the number of units, the date, the price, any commission, and any notes. """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _children['{%s}transactionData' % GF_NAMESPACE] = ( 'transaction_data', TransactionData) def __init__(self, transaction_data=None, **kwargs): self.transaction_data = transaction_data gdata.GDataEntry.__init__(self, **kwargs) def transaction_id(self): return self.id.text.split("/")[-1] transaction_id = property(transaction_id, doc='The transaction ID.') def TransactionEntryFromString(xml_string): return atom.CreateClassFromXMLString(TransactionEntry, xml_string) class TransactionFeed(gdata.GDataFeed): """A feed that lists all of the transactions that have been recorded for a particular position. A transaction is a collection of information about an instance of buying or selling a particular security. The TransactionFeed lists all of the transactions that have been recorded for a particular position as a list of TransactionEntries. """ _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [TransactionEntry]) def TransactionFeedFromString(xml_string): return atom.CreateClassFromXMLString(TransactionFeed, xml_string) class TransactionFeedLink(atom.AtomBase): """Link to TransactionFeed embedded in PositionEntry. If a PositionFeed is queried with transactions='true', TransactionFeeds are inlined in the returned PositionEntries. These TransactionFeeds are accessible via TransactionFeedLink's feed attribute. """ _tag = 'feedLink' _namespace = GD_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['href'] = 'href' _children = atom.AtomBase._children.copy() _children['{%s}feed' % atom.ATOM_NAMESPACE] = ( 'feed', TransactionFeed) def __init__(self, href=None, feed=None, **kwargs): self.href = href self.feed = feed atom.AtomBase.__init__(self, **kwargs) class PositionData(atom.AtomBase): """The <gf:positionData> element.""" _tag = 'positionData' _namespace = GF_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['gainPercentage'] = 'gain_percentage' _attributes['return1w'] = 'return1w' _attributes['return4w'] = 'return4w' _attributes['return3m'] = 'return3m' _attributes['returnYTD'] = 'returnYTD' _attributes['return1y'] = 'return1y' _attributes['return3y'] = 'return3y' _attributes['return5y'] = 'return5y' _attributes['returnOverall'] = 'return_overall' _attributes['shares'] = 'shares' _children = atom.AtomBase._children.copy() _children['{%s}costBasis' % GF_NAMESPACE] = ('cost_basis', CostBasis) _children['{%s}daysGain' % GF_NAMESPACE] = ('days_gain', DaysGain) _children['{%s}gain' % GF_NAMESPACE] = ('gain', Gain) _children['{%s}marketValue' % GF_NAMESPACE] = ('market_value', MarketValue) def __init__(self, gain_percentage=None, return1w=None, return4w=None, return3m=None, returnYTD=None, return1y=None, return3y=None, return5y=None, return_overall=None, shares=None, cost_basis=None, days_gain=None, gain=None, market_value=None, **kwargs): self.gain_percentage = gain_percentage self.return1w = return1w self.return4w = return4w self.return3m = return3m self.returnYTD = returnYTD self.return1y = return1y self.return3y = return3y self.return5y = return5y self.return_overall = return_overall self.shares = shares self.cost_basis = cost_basis self.days_gain = days_gain self.gain = gain self.market_value = market_value atom.AtomBase.__init__(self, **kwargs) def PositionDataFromString(xml_string): return atom.CreateClassFromXMLString(PositionData, xml_string) class PositionEntry(gdata.GDataEntry): """An entry of the position feed. A PositionEntry contains the ticker exchange and Symbol for a stock, mutual fund, or other security, along with PositionData such as the number of units of that security that the user holds, and performance statistics. """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _children['{%s}positionData' % GF_NAMESPACE] = ( 'position_data', PositionData) _children['{%s}symbol' % GF_NAMESPACE] = ('symbol', Symbol) _children['{%s}feedLink' % GD_NAMESPACE] = ( 'feed_link', TransactionFeedLink) def __init__(self, position_data=None, symbol=None, feed_link=None, **kwargs): self.position_data = position_data self.symbol = symbol self.feed_link = feed_link gdata.GDataEntry.__init__(self, **kwargs) def position_title(self): return self.title.text position_title = property(position_title, doc='The position title as a string (i.e. position.title.text).') def ticker_id(self): return self.id.text.split("/")[-1] ticker_id = property(ticker_id, doc='The position TICKER ID.') def transactions(self): if self.feed_link.feed: return self.feed_link.feed.entry else: return None transactions = property(transactions, doc=""" Inlined TransactionEntries are returned if PositionFeed is queried with transactions='true'.""") def PositionEntryFromString(xml_string): return atom.CreateClassFromXMLString(PositionEntry, xml_string) class PositionFeed(gdata.GDataFeed): """A feed that lists all of the positions in a particular portfolio. A position is a collection of information about a security that the user holds. The PositionFeed lists all of the positions in a particular portfolio as a list of PositionEntries. """ _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [PositionEntry]) def PositionFeedFromString(xml_string): return atom.CreateClassFromXMLString(PositionFeed, xml_string) class PositionFeedLink(atom.AtomBase): """Link to PositionFeed embedded in PortfolioEntry. If a PortfolioFeed is queried with positions='true', the PositionFeeds are inlined in the returned PortfolioEntries. These PositionFeeds are accessible via PositionFeedLink's feed attribute. """ _tag = 'feedLink' _namespace = GD_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['href'] = 'href' _children = atom.AtomBase._children.copy() _children['{%s}feed' % atom.ATOM_NAMESPACE] = ( 'feed', PositionFeed) def __init__(self, href=None, feed=None, **kwargs): self.href = href self.feed = feed atom.AtomBase.__init__(self, **kwargs) class PortfolioData(atom.AtomBase): """The <gf:portfolioData> element.""" _tag = 'portfolioData' _namespace = GF_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['currencyCode'] = 'currency_code' _attributes['gainPercentage'] = 'gain_percentage' _attributes['return1w'] = 'return1w' _attributes['return4w'] = 'return4w' _attributes['return3m'] = 'return3m' _attributes['returnYTD'] = 'returnYTD' _attributes['return1y'] = 'return1y' _attributes['return3y'] = 'return3y' _attributes['return5y'] = 'return5y' _attributes['returnOverall'] = 'return_overall' _children = atom.AtomBase._children.copy() _children['{%s}costBasis' % GF_NAMESPACE] = ('cost_basis', CostBasis) _children['{%s}daysGain' % GF_NAMESPACE] = ('days_gain', DaysGain) _children['{%s}gain' % GF_NAMESPACE] = ('gain', Gain) _children['{%s}marketValue' % GF_NAMESPACE] = ('market_value', MarketValue) def __init__(self, currency_code=None, gain_percentage=None, return1w=None, return4w=None, return3m=None, returnYTD=None, return1y=None, return3y=None, return5y=None, return_overall=None, cost_basis=None, days_gain=None, gain=None, market_value=None, **kwargs): self.currency_code = currency_code self.gain_percentage = gain_percentage self.return1w = return1w self.return4w = return4w self.return3m = return3m self.returnYTD = returnYTD self.return1y = return1y self.return3y = return3y self.return5y = return5y self.return_overall = return_overall self.cost_basis = cost_basis self.days_gain = days_gain self.gain = gain self.market_value = market_value atom.AtomBase.__init__(self, **kwargs) def PortfolioDataFromString(xml_string): return atom.CreateClassFromXMLString(PortfolioData, xml_string) class PortfolioEntry(gdata.GDataEntry): """An entry of the PortfolioFeed. A PortfolioEntry contains the portfolio's title along with PortfolioData such as currency, total market value, and overall performance statistics. """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _children['{%s}portfolioData' % GF_NAMESPACE] = ( 'portfolio_data', PortfolioData) _children['{%s}feedLink' % GD_NAMESPACE] = ( 'feed_link', PositionFeedLink) def __init__(self, portfolio_data=None, feed_link=None, **kwargs): self.portfolio_data = portfolio_data self.feed_link = feed_link gdata.GDataEntry.__init__(self, **kwargs) def portfolio_title(self): return self.title.text def set_portfolio_title(self, portfolio_title): self.title = atom.Title(text=portfolio_title, title_type='text') portfolio_title = property(portfolio_title, set_portfolio_title, doc='The portfolio title as a string (i.e. portfolio.title.text).') def portfolio_id(self): return self.id.text.split("/")[-1] portfolio_id = property(portfolio_id, doc='The portfolio ID. Do not confuse with portfolio.id.') def positions(self): if self.feed_link.feed: return self.feed_link.feed.entry else: return None positions = property(positions, doc=""" Inlined PositionEntries are returned if PortfolioFeed was queried with positions='true'.""") def PortfolioEntryFromString(xml_string): return atom.CreateClassFromXMLString(PortfolioEntry, xml_string) class PortfolioFeed(gdata.GDataFeed): """A feed that lists all of the user's portfolios. A portfolio is a collection of positions that the user holds in various securities, plus metadata. The PortfolioFeed lists all of the user's portfolios as a list of PortfolioEntries. """ _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [PortfolioEntry]) def PortfolioFeedFromString(xml_string): return atom.CreateClassFromXMLString(PortfolioFeed, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2009 Tan Swee Heng # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Classes to interact with the Google Finance server.""" __author__ = 'thesweeheng@gmail.com' import gdata.service import gdata.finance import atom class PortfolioQuery(gdata.service.Query): """A query object for the list of a user's portfolios.""" def returns(self): return self.get('returns', False) def set_returns(self, value): if value is 'true' or value is True: self['returns'] = 'true' returns = property(returns, set_returns, doc="The returns query parameter") def positions(self): return self.get('positions', False) def set_positions(self, value): if value is 'true' or value is True: self['positions'] = 'true' positions = property(positions, set_positions, doc="The positions query parameter") class PositionQuery(gdata.service.Query): """A query object for the list of a user's positions in a portfolio.""" def returns(self): return self.get('returns', False) def set_returns(self, value): if value is 'true' or value is True: self['returns'] = 'true' returns = property(returns, set_returns, doc="The returns query parameter") def transactions(self): return self.get('transactions', False) def set_transactions(self, value): if value is 'true' or value is True: self['transactions'] = 'true' transactions = property(transactions, set_transactions, doc="The transactions query parameter") class FinanceService(gdata.service.GDataService): def __init__(self, email=None, password=None, source=None, server='finance.google.com', **kwargs): """Creates a client for the Finance service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'finance.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__(self, email=email, password=password, service='finance', server=server, **kwargs) def GetPortfolioFeed(self, query=None): uri = '/finance/feeds/default/portfolios' if query: uri = PortfolioQuery(feed=uri, params=query).ToUri() return self.Get(uri, converter=gdata.finance.PortfolioFeedFromString) def GetPositionFeed(self, portfolio_entry=None, portfolio_id=None, query=None): """ Args: portfolio_entry: PortfolioEntry (optional; see Notes) portfolio_id: string (optional; see Notes) This may be obtained from a PortfolioEntry's portfolio_id attribute. query: PortfolioQuery (optional) Notes: Either a PortfolioEntry OR a portfolio ID must be provided. """ if portfolio_entry: uri = portfolio_entry.GetSelfLink().href + '/positions' elif portfolio_id: uri = '/finance/feeds/default/portfolios/%s/positions' % portfolio_id if query: uri = PositionQuery(feed=uri, params=query).ToUri() return self.Get(uri, converter=gdata.finance.PositionFeedFromString) def GetTransactionFeed(self, position_entry=None, portfolio_id=None, ticker_id=None): """ Args: position_entry: PositionEntry (optional; see Notes) portfolio_id: string (optional; see Notes) This may be obtained from a PortfolioEntry's portfolio_id attribute. ticker_id: string (optional; see Notes) This may be obtained from a PositionEntry's ticker_id attribute. Alternatively it can be constructed using the security's exchange and symbol, e.g. 'NASDAQ:GOOG' Notes: Either a PositionEntry OR (a portfolio ID AND ticker ID) must be provided. """ if position_entry: uri = position_entry.GetSelfLink().href + '/transactions' elif portfolio_id and ticker_id: uri = '/finance/feeds/default/portfolios/%s/positions/%s/transactions' \ % (portfolio_id, ticker_id) return self.Get(uri, converter=gdata.finance.TransactionFeedFromString) def GetPortfolio(self, portfolio_id=None, query=None): uri = '/finance/feeds/default/portfolios/%s' % portfolio_id if query: uri = PortfolioQuery(feed=uri, params=query).ToUri() return self.Get(uri, converter=gdata.finance.PortfolioEntryFromString) def AddPortfolio(self, portfolio_entry=None): uri = '/finance/feeds/default/portfolios' return self.Post(portfolio_entry, uri, converter=gdata.finance.PortfolioEntryFromString) def UpdatePortfolio(self, portfolio_entry=None): uri = portfolio_entry.GetEditLink().href return self.Put(portfolio_entry, uri, converter=gdata.finance.PortfolioEntryFromString) def DeletePortfolio(self, portfolio_entry=None): uri = portfolio_entry.GetEditLink().href return self.Delete(uri) def GetPosition(self, portfolio_id=None, ticker_id=None, query=None): uri = '/finance/feeds/default/portfolios/%s/positions/%s' \ % (portfolio_id, ticker_id) if query: uri = PositionQuery(feed=uri, params=query).ToUri() return self.Get(uri, converter=gdata.finance.PositionEntryFromString) def DeletePosition(self, position_entry=None, portfolio_id=None, ticker_id=None, transaction_feed=None): """A position is deleted by deleting all its transactions. Args: position_entry: PositionEntry (optional; see Notes) portfolio_id: string (optional; see Notes) This may be obtained from a PortfolioEntry's portfolio_id attribute. ticker_id: string (optional; see Notes) This may be obtained from a PositionEntry's ticker_id attribute. Alternatively it can be constructed using the security's exchange and symbol, e.g. 'NASDAQ:GOOG' transaction_feed: TransactionFeed (optional; see Notes) Notes: Either a PositionEntry OR (a portfolio ID AND ticker ID) OR a TransactionFeed must be provided. """ if transaction_feed: feed = transaction_feed else: if position_entry: feed = self.GetTransactionFeed(position_entry=position_entry) elif portfolio_id and ticker_id: feed = self.GetTransactionFeed( portfolio_id=portfolio_id, ticker_id=ticker_id) for txn in feed.entry: self.DeleteTransaction(txn) return True def GetTransaction(self, portfolio_id=None, ticker_id=None, transaction_id=None): uri = '/finance/feeds/default/portfolios/%s/positions/%s/transactions/%s' \ % (portfolio_id, ticker_id, transaction_id) return self.Get(uri, converter=gdata.finance.TransactionEntryFromString) def AddTransaction(self, transaction_entry=None, transaction_feed = None, position_entry=None, portfolio_id=None, ticker_id=None): """ Args: transaction_entry: TransactionEntry (required) transaction_feed: TransactionFeed (optional; see Notes) position_entry: PositionEntry (optional; see Notes) portfolio_id: string (optional; see Notes) This may be obtained from a PortfolioEntry's portfolio_id attribute. ticker_id: string (optional; see Notes) This may be obtained from a PositionEntry's ticker_id attribute. Alternatively it can be constructed using the security's exchange and symbol, e.g. 'NASDAQ:GOOG' Notes: Either a TransactionFeed OR a PositionEntry OR (a portfolio ID AND ticker ID) must be provided. """ if transaction_feed: uri = transaction_feed.GetPostLink().href elif position_entry: uri = position_entry.GetSelfLink().href + '/transactions' elif portfolio_id and ticker_id: uri = '/finance/feeds/default/portfolios/%s/positions/%s/transactions' \ % (portfolio_id, ticker_id) return self.Post(transaction_entry, uri, converter=gdata.finance.TransactionEntryFromString) def UpdateTransaction(self, transaction_entry=None): uri = transaction_entry.GetEditLink().href return self.Put(transaction_entry, uri, converter=gdata.finance.TransactionEntryFromString) def DeleteTransaction(self, transaction_entry=None): uri = transaction_entry.GetEditLink().href return self.Delete(uri)
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the data classes of the Yahoo! Media RSS Extension""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core MEDIA_TEMPLATE = '{http://search.yahoo.com/mrss//}%s' class MediaCategory(atom.core.XmlElement): """Describes a media category.""" _qname = MEDIA_TEMPLATE % 'category' scheme = 'scheme' label = 'label' class MediaCopyright(atom.core.XmlElement): """Describes a media copyright.""" _qname = MEDIA_TEMPLATE % 'copyright' url = 'url' class MediaCredit(atom.core.XmlElement): """Describes a media credit.""" _qname = MEDIA_TEMPLATE % 'credit' role = 'role' scheme = 'scheme' class MediaDescription(atom.core.XmlElement): """Describes a media description.""" _qname = MEDIA_TEMPLATE % 'description' type = 'type' class MediaHash(atom.core.XmlElement): """Describes a media hash.""" _qname = MEDIA_TEMPLATE % 'hash' algo = 'algo' class MediaKeywords(atom.core.XmlElement): """Describes a media keywords.""" _qname = MEDIA_TEMPLATE % 'keywords' class MediaPlayer(atom.core.XmlElement): """Describes a media player.""" _qname = MEDIA_TEMPLATE % 'player' height = 'height' width = 'width' url = 'url' class MediaRating(atom.core.XmlElement): """Describes a media rating.""" _qname = MEDIA_TEMPLATE % 'rating' scheme = 'scheme' class MediaRestriction(atom.core.XmlElement): """Describes a media restriction.""" _qname = MEDIA_TEMPLATE % 'restriction' relationship = 'relationship' type = 'type' class MediaText(atom.core.XmlElement): """Describes a media text.""" _qname = MEDIA_TEMPLATE % 'text' end = 'end' lang = 'lang' type = 'type' start = 'start' class MediaThumbnail(atom.core.XmlElement): """Describes a media thumbnail.""" _qname = MEDIA_TEMPLATE % 'thumbnail' time = 'time' url = 'url' width = 'width' height = 'height' class MediaTitle(atom.core.XmlElement): """Describes a media title.""" _qname = MEDIA_TEMPLATE % 'title' type = 'type' class MediaContent(atom.core.XmlElement): """Describes a media content.""" _qname = MEDIA_TEMPLATE % 'content' bitrate = 'bitrate' is_default = 'isDefault' medium = 'medium' height = 'height' credit = [MediaCredit] language = 'language' hash = MediaHash width = 'width' player = MediaPlayer url = 'url' file_size = 'fileSize' channels = 'channels' expression = 'expression' text = [MediaText] samplingrate = 'samplingrate' title = MediaTitle category = [MediaCategory] rating = [MediaRating] type = 'type' description = MediaDescription framerate = 'framerate' thumbnail = [MediaThumbnail] duration = 'duration' copyright = MediaCopyright keywords = MediaKeywords restriction = [MediaRestriction] class MediaGroup(atom.core.XmlElement): """Describes a media group.""" _qname = MEDIA_TEMPLATE % 'group' credit = [MediaCredit] content = [MediaContent] copyright = MediaCopyright description = MediaDescription category = [MediaCategory] player = MediaPlayer rating = [MediaRating] hash = MediaHash title = MediaTitle keywords = MediaKeywords restriction = [MediaRestriction] thumbnail = [MediaThumbnail] text = [MediaText]
Python
# -*-*- encoding: utf-8 -*-*- # # This is gdata.photos.media, implementing parts of the MediaRSS spec in gdata structures # # $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # Portions copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Essential attributes of photos in Google Photos/Picasa Web Albums are expressed using elements from the `media' namespace, defined in the MediaRSS specification[1]. Due to copyright issues, the elements herein are documented sparingly, please consult with the Google Photos API Reference Guide[2], alternatively the official MediaRSS specification[1] for details. (If there is a version conflict between the two sources, stick to the Google Photos API). [1]: http://search.yahoo.com/mrss (version 1.1.1) [2]: http://code.google.com/apis/picasaweb/reference.html#media_reference Keep in mind that Google Photos only uses a subset of the MediaRSS elements (and some of the attributes are trimmed down, too): media:content media:credit media:description media:group media:keywords media:thumbnail media:title """ __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: api chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' import atom import gdata MEDIA_NAMESPACE = 'http://search.yahoo.com/mrss/' YOUTUBE_NAMESPACE = 'http://gdata.youtube.com/schemas/2007' class MediaBaseElement(atom.AtomBase): """Base class for elements in the MEDIA_NAMESPACE. To add new elements, you only need to add the element tag name to self._tag """ _tag = '' _namespace = MEDIA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Content(MediaBaseElement): """(attribute container) This element describes the original content, e.g. an image or a video. There may be multiple Content elements in a media:Group. For example, a video may have a <media:content medium="image"> element that specifies a JPEG representation of the video, and a <media:content medium="video"> element that specifies the URL of the video itself. Attributes: url: non-ambigous reference to online object width: width of the object frame, in pixels height: width of the object frame, in pixels medium: one of `image' or `video', allowing the api user to quickly determine the object's type type: Internet media Type[1] (a.k.a. mime type) of the object -- a more verbose way of determining the media type. To set the type member in the contructor, use the content_type parameter. (optional) fileSize: the size of the object, in bytes [1]: http://en.wikipedia.org/wiki/Internet_media_type """ _tag = 'content' _attributes = atom.AtomBase._attributes.copy() _attributes['url'] = 'url' _attributes['width'] = 'width' _attributes['height'] = 'height' _attributes['medium'] = 'medium' _attributes['type'] = 'type' _attributes['fileSize'] = 'fileSize' def __init__(self, url=None, width=None, height=None, medium=None, content_type=None, fileSize=None, format=None, extension_elements=None, extension_attributes=None, text=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.url = url self.width = width self.height = height self.medium = medium self.type = content_type self.fileSize = fileSize def ContentFromString(xml_string): return atom.CreateClassFromXMLString(Content, xml_string) class Credit(MediaBaseElement): """(string) Contains the nickname of the user who created the content, e.g. `Liz Bennet'. This is a user-specified value that should be used when referring to the user by name. Note that none of the attributes from the MediaRSS spec are supported. """ _tag = 'credit' def CreditFromString(xml_string): return atom.CreateClassFromXMLString(Credit, xml_string) class Description(MediaBaseElement): """(string) A description of the media object. Either plain unicode text, or entity-encoded html (look at the `type' attribute). E.g `A set of photographs I took while vacationing in Italy.' For `api' projections, the description is in plain text; for `base' projections, the description is in HTML. Attributes: type: either `text' or `html'. To set the type member in the contructor, use the description_type parameter. """ _tag = 'description' _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' def __init__(self, description_type=None, extension_elements=None, extension_attributes=None, text=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.type = description_type def DescriptionFromString(xml_string): return atom.CreateClassFromXMLString(Description, xml_string) class Keywords(MediaBaseElement): """(string) Lists the tags associated with the entry, e.g `italy, vacation, sunset'. Contains a comma-separated list of tags that have been added to the photo, or all tags that have been added to photos in the album. """ _tag = 'keywords' def KeywordsFromString(xml_string): return atom.CreateClassFromXMLString(Keywords, xml_string) class Thumbnail(MediaBaseElement): """(attributes) Contains the URL of a thumbnail of a photo or album cover. There can be multiple <media:thumbnail> elements for a given <media:group>; for example, a given item may have multiple thumbnails at different sizes. Photos generally have two thumbnails at different sizes; albums generally have one cropped thumbnail. If the thumbsize parameter is set to the initial query, this element points to thumbnails of the requested sizes; otherwise the thumbnails are the default thumbnail size. This element must not be confused with the <gphoto:thumbnail> element. Attributes: url: The URL of the thumbnail image. height: The height of the thumbnail image, in pixels. width: The width of the thumbnail image, in pixels. """ _tag = 'thumbnail' _attributes = atom.AtomBase._attributes.copy() _attributes['url'] = 'url' _attributes['width'] = 'width' _attributes['height'] = 'height' def __init__(self, url=None, width=None, height=None, extension_attributes=None, text=None, extension_elements=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.url = url self.width = width self.height = height def ThumbnailFromString(xml_string): return atom.CreateClassFromXMLString(Thumbnail, xml_string) class Title(MediaBaseElement): """(string) Contains the title of the entry's media content, in plain text. Attributes: type: Always set to plain. To set the type member in the constructor, use the title_type parameter. """ _tag = 'title' _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' def __init__(self, title_type=None, extension_attributes=None, text=None, extension_elements=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.type = title_type def TitleFromString(xml_string): return atom.CreateClassFromXMLString(Title, xml_string) class Player(MediaBaseElement): """(string) Contains the embeddable player URL for the entry's media content if the media is a video. Attributes: url: Always set to plain """ _tag = 'player' _attributes = atom.AtomBase._attributes.copy() _attributes['url'] = 'url' def __init__(self, player_url=None, extension_attributes=None, extension_elements=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes) self.url= player_url class Private(atom.AtomBase): """The YouTube Private element""" _tag = 'private' _namespace = YOUTUBE_NAMESPACE class Duration(atom.AtomBase): """The YouTube Duration element""" _tag = 'duration' _namespace = YOUTUBE_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['seconds'] = 'seconds' class Category(MediaBaseElement): """The mediagroup:category element""" _tag = 'category' _attributes = atom.AtomBase._attributes.copy() _attributes['term'] = 'term' _attributes['scheme'] = 'scheme' _attributes['label'] = 'label' def __init__(self, term=None, scheme=None, label=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Category Args: term: str scheme: str label: str text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.term = term self.scheme = scheme self.label = label self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Group(MediaBaseElement): """Container element for all media elements. The <media:group> element can appear as a child of an album, photo or video entry.""" _tag = 'group' _children = atom.AtomBase._children.copy() _children['{%s}content' % MEDIA_NAMESPACE] = ('content', [Content,]) _children['{%s}credit' % MEDIA_NAMESPACE] = ('credit', Credit) _children['{%s}description' % MEDIA_NAMESPACE] = ('description', Description) _children['{%s}keywords' % MEDIA_NAMESPACE] = ('keywords', Keywords) _children['{%s}thumbnail' % MEDIA_NAMESPACE] = ('thumbnail', [Thumbnail,]) _children['{%s}title' % MEDIA_NAMESPACE] = ('title', Title) _children['{%s}category' % MEDIA_NAMESPACE] = ('category', [Category,]) _children['{%s}duration' % YOUTUBE_NAMESPACE] = ('duration', Duration) _children['{%s}private' % YOUTUBE_NAMESPACE] = ('private', Private) _children['{%s}player' % MEDIA_NAMESPACE] = ('player', Player) def __init__(self, content=None, credit=None, description=None, keywords=None, thumbnail=None, title=None, duration=None, private=None, category=None, player=None, extension_elements=None, extension_attributes=None, text=None): MediaBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.content=content self.credit=credit self.description=description self.keywords=keywords self.thumbnail=thumbnail or [] self.title=title self.duration=duration self.private=private self.category=category or [] self.player=player def GroupFromString(xml_string): return atom.CreateClassFromXMLString(Group, xml_string)
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. """Provides auth related token classes and functions for Google Data APIs. Token classes represent a user's authorization of this app to access their data. Usually these are not created directly but by a GDClient object. ClientLoginToken AuthSubToken SecureAuthSubToken OAuthHmacToken OAuthRsaToken TwoLeggedOAuthHmacToken TwoLeggedOAuthRsaToken Functions which are often used in application code (as opposed to just within the gdata-python-client library) are the following: generate_auth_sub_url authorize_request_token The following are helper functions which are used to save and load auth token objects in the App Engine datastore. These should only be used if you are using this library within App Engine: ae_load ae_save """ import datetime import time import random import urllib import urlparse import atom.http_core try: import simplejson except ImportError: try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson try: from urlparse import parse_qsl except ImportError: from cgi import parse_qsl __author__ = 'j.s@google.com (Jeff Scudder)' PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth=' AUTHSUB_AUTH_LABEL = 'AuthSub token=' OAUTH2_AUTH_LABEL = 'OAuth ' # This dict provides the AuthSub and OAuth scopes for all services by service # name. The service name (key) is used in ClientLogin requests. AUTH_SCOPES = { 'cl': ( # Google Calendar API 'https://www.google.com/calendar/feeds/', 'http://www.google.com/calendar/feeds/'), 'gbase': ( # Google Base API 'http://base.google.com/base/feeds/', 'http://www.google.com/base/feeds/'), 'blogger': ( # Blogger API 'http://www.blogger.com/feeds/',), 'codesearch': ( # Google Code Search API 'http://www.google.com/codesearch/feeds/',), 'cp': ( # Contacts API 'https://www.google.com/m8/feeds/', 'http://www.google.com/m8/feeds/'), 'finance': ( # Google Finance API 'http://finance.google.com/finance/feeds/',), 'health': ( # Google Health API 'https://www.google.com/health/feeds/',), 'writely': ( # Documents List API 'https://docs.google.com/feeds/', 'https://spreadsheets.google.com/feeds/', 'https://docs.googleusercontent.com/'), 'lh2': ( # Picasa Web Albums API 'http://picasaweb.google.com/data/',), 'apps': ( # Google Apps Domain Info & Management APIs 'https://apps-apis.google.com/a/feeds/user/', 'https://apps-apis.google.com/a/feeds/policies/', 'https://apps-apis.google.com/a/feeds/alias/', 'https://apps-apis.google.com/a/feeds/groups/', 'https://apps-apis.google.com/a/feeds/compliance/audit/', 'https://apps-apis.google.com/a/feeds/migration/', 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/'), 'weaver': ( # Health H9 Sandbox 'https://www.google.com/h9/feeds/',), 'wise': ( # Spreadsheets Data API 'https://spreadsheets.google.com/feeds/',), 'sitemaps': ( # Google Webmaster Tools API 'https://www.google.com/webmasters/tools/feeds/',), 'youtube': ( # YouTube API 'http://gdata.youtube.com/feeds/api/', 'http://uploads.gdata.youtube.com/feeds/api', 'http://gdata.youtube.com/action/GetUploadToken'), 'books': ( # Google Books API 'http://www.google.com/books/feeds/',), 'analytics': ( # Google Analytics API 'https://www.google.com/analytics/feeds/',), 'jotspot': ( # Google Sites API 'http://sites.google.com/feeds/', 'https://sites.google.com/feeds/'), 'local': ( # Google Maps Data API 'http://maps.google.com/maps/feeds/',), 'code': ( # Project Hosting Data API 'http://code.google.com/feeds/issues',)} class Error(Exception): pass class UnsupportedTokenType(Error): """Raised when token to or from blob is unable to convert the token.""" pass class OAuth2AccessTokenError(Error): """Raised when an OAuth2 error occurs.""" def __init__(self, error_message): self.error_message = error_message # ClientLogin functions and classes. def generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): """Creates the body of the autentication request See http://code.google.com/apis/accounts/AuthForInstalledApps.html#Request for more details. Args: email: str password: str service: str source: str account_type: str (optional) Defaul is 'HOSTED_OR_GOOGLE', other valid values are 'GOOGLE' and 'HOSTED' captcha_token: str (optional) captcha_response: str (optional) Returns: The HTTP body to send in a request for a client login token. """ # Create a POST body containing the user's credentials. request_fields = {'Email': email, 'Passwd': password, 'accountType': account_type, 'service': service, 'source': source} if captcha_token and captcha_response: # Send the captcha token and response as part of the POST body if the # user is responding to a captch challenge. request_fields['logintoken'] = captcha_token request_fields['logincaptcha'] = captcha_response return urllib.urlencode(request_fields) GenerateClientLoginRequestBody = generate_client_login_request_body def get_client_login_token_string(http_body): """Returns the token value for a ClientLoginToken. Reads the token from the server's response to a Client Login request and creates the token value string to use in requests. Args: http_body: str The body of the server's HTTP response to a Client Login request Returns: The token value string for a ClientLoginToken. """ for response_line in http_body.splitlines(): if response_line.startswith('Auth='): # Strip off the leading Auth= and return the Authorization value. return response_line[5:] return None GetClientLoginTokenString = get_client_login_token_string def get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): """Returns the URL and token for a CAPTCHA challenge issued by the server. Args: http_body: str The body of the HTTP response from the server which contains the CAPTCHA challenge. captcha_base_url: str This function returns a full URL for viewing the challenge image which is built from the server's response. This base_url is used as the beginning of the URL because the server only provides the end of the URL. For example the server provides 'Captcha?ctoken=Hi...N' and the URL for the image is 'http://www.google.com/accounts/Captcha?ctoken=Hi...N' Returns: A dictionary containing the information needed to repond to the CAPTCHA challenge, the image URL and the ID token of the challenge. The dictionary is in the form: {'token': string identifying the CAPTCHA image, 'url': string containing the URL of the image} Returns None if there was no CAPTCHA challenge in the response. """ contains_captcha_challenge = False captcha_parameters = {} for response_line in http_body.splitlines(): if response_line.startswith('Error=CaptchaRequired'): contains_captcha_challenge = True elif response_line.startswith('CaptchaToken='): # Strip off the leading CaptchaToken= captcha_parameters['token'] = response_line[13:] elif response_line.startswith('CaptchaUrl='): captcha_parameters['url'] = '%s%s' % (captcha_base_url, response_line[11:]) if contains_captcha_challenge: return captcha_parameters else: return None GetCaptchaChallenge = get_captcha_challenge class ClientLoginToken(object): def __init__(self, token_string): self.token_string = token_string def modify_request(self, http_request): http_request.headers['Authorization'] = '%s%s' % (PROGRAMMATIC_AUTH_LABEL, self.token_string) ModifyRequest = modify_request # AuthSub functions and classes. def _to_uri(str_or_uri): if isinstance(str_or_uri, (str, unicode)): return atom.http_core.Uri.parse_uri(str_or_uri) return str_or_uri def generate_auth_sub_url(next, scopes, secure=False, session=True, request_url=atom.http_core.parse_uri( 'https://www.google.com/accounts/AuthSubRequest'), domain='default', scopes_param_prefix='auth_sub_scopes'): """Constructs a URI for requesting a multiscope AuthSub token. The generated token will contain a URL parameter to pass along the requested scopes to the next URL. When the Google Accounts page redirects the broswser to the 'next' URL, it appends the single use AuthSub token value to the URL as a URL parameter with the key 'token'. However, the information about which scopes were requested is not included by Google Accounts. This method adds the scopes to the next URL before making the request so that the redirect will be sent to a page, and both the token value and the list of scopes for which the token was requested. Args: next: atom.http_core.Uri or string The URL user will be sent to after authorizing this web application to access their data. scopes: list containint strings or atom.http_core.Uri objects. The URLs of the services to be accessed. Could also be a single string or single atom.http_core.Uri for requesting just one scope. secure: boolean (optional) Determines whether or not the issued token is a secure token. session: boolean (optional) Determines whether or not the issued token can be upgraded to a session token. request_url: atom.http_core.Uri or str The beginning of the request URL. This is normally 'http://www.google.com/accounts/AuthSubRequest' or '/accounts/AuthSubRequest' domain: The domain which the account is part of. This is used for Google Apps accounts, the default value is 'default' which means that the requested account is a Google Account (@gmail.com for example) scopes_param_prefix: str (optional) The requested scopes are added as a URL parameter to the next URL so that the page at the 'next' URL can extract the token value and the valid scopes from the URL. The key for the URL parameter defaults to 'auth_sub_scopes' Returns: An atom.http_core.Uri which the user's browser should be directed to in order to authorize this application to access their information. """ if isinstance(next, (str, unicode)): next = atom.http_core.Uri.parse_uri(next) # If the user passed in a string instead of a list for scopes, convert to # a single item tuple. if isinstance(scopes, (str, unicode, atom.http_core.Uri)): scopes = (scopes,) scopes_string = ' '.join([str(scope) for scope in scopes]) next.query[scopes_param_prefix] = scopes_string if isinstance(request_url, (str, unicode)): request_url = atom.http_core.Uri.parse_uri(request_url) request_url.query['next'] = str(next) request_url.query['scope'] = scopes_string if session: request_url.query['session'] = '1' else: request_url.query['session'] = '0' if secure: request_url.query['secure'] = '1' else: request_url.query['secure'] = '0' request_url.query['hd'] = domain return request_url def auth_sub_string_from_url(url, scopes_param_prefix='auth_sub_scopes'): """Finds the token string (and scopes) after the browser is redirected. After the Google Accounts AuthSub pages redirect the user's broswer back to the web application (using the 'next' URL from the request) the web app must extract the token from the current page's URL. The token is provided as a URL parameter named 'token' and if generate_auth_sub_url was used to create the request, the token's valid scopes are included in a URL parameter whose name is specified in scopes_param_prefix. Args: url: atom.url.Url or str representing the current URL. The token value and valid scopes should be included as URL parameters. scopes_param_prefix: str (optional) The URL parameter key which maps to the list of valid scopes for the token. Returns: A tuple containing the token value as a string, and a tuple of scopes (as atom.http_core.Uri objects) which are URL prefixes under which this token grants permission to read and write user data. (token_string, (scope_uri, scope_uri, scope_uri, ...)) If no scopes were included in the URL, the second value in the tuple is None. If there was no token param in the url, the tuple returned is (None, None) """ if isinstance(url, (str, unicode)): url = atom.http_core.Uri.parse_uri(url) if 'token' not in url.query: return (None, None) token = url.query['token'] # TODO: decide whether no scopes should be None or (). scopes = None # Default to None for no scopes. if scopes_param_prefix in url.query: scopes = tuple(url.query[scopes_param_prefix].split(' ')) return (token, scopes) AuthSubStringFromUrl = auth_sub_string_from_url def auth_sub_string_from_body(http_body): """Extracts the AuthSub token from an HTTP body string. Used to find the new session token after making a request to upgrade a single use AuthSub token. Args: http_body: str The repsonse from the server which contains the AuthSub key. For example, this function would find the new session token from the server's response to an upgrade token request. Returns: The raw token value string to use in an AuthSubToken object. """ for response_line in http_body.splitlines(): if response_line.startswith('Token='): # Strip off Token= and return the token value string. return response_line[6:] return None class AuthSubToken(object): def __init__(self, token_string, scopes=None): self.token_string = token_string self.scopes = scopes or [] def modify_request(self, http_request): """Sets Authorization header, allows app to act on the user's behalf.""" http_request.headers['Authorization'] = '%s%s' % (AUTHSUB_AUTH_LABEL, self.token_string) ModifyRequest = modify_request def from_url(str_or_uri): """Creates a new AuthSubToken using information in the URL. Uses auth_sub_string_from_url. Args: str_or_uri: The current page's URL (as a str or atom.http_core.Uri) which should contain a token query parameter since the Google auth server redirected the user's browser to this URL. """ token_and_scopes = auth_sub_string_from_url(str_or_uri) return AuthSubToken(token_and_scopes[0], token_and_scopes[1]) from_url = staticmethod(from_url) FromUrl = from_url def _upgrade_token(self, http_body): """Replaces the token value with a session token from the auth server. Uses the response of a token upgrade request to modify this token. Uses auth_sub_string_from_body. """ self.token_string = auth_sub_string_from_body(http_body) # Functions and classes for Secure-mode AuthSub def build_auth_sub_data(http_request, timestamp, nonce): """Creates the data string which must be RSA-signed in secure requests. For more details see the documenation on secure AuthSub requests: http://code.google.com/apis/accounts/docs/AuthSub.html#signingrequests Args: http_request: The request being made to the server. The Request's URL must be complete before this signature is calculated as any changes to the URL will invalidate the signature. nonce: str Random 64-bit, unsigned number encoded as an ASCII string in decimal format. The nonce/timestamp pair should always be unique to prevent replay attacks. timestamp: Integer representing the time the request is sent. The timestamp should be expressed in number of seconds after January 1, 1970 00:00:00 GMT. """ return '%s %s %s %s' % (http_request.method, str(http_request.uri), str(timestamp), nonce) def generate_signature(data, rsa_key): """Signs the data string for a secure AuthSub request.""" import base64 try: from tlslite.utils import keyfactory except ImportError: try: from gdata.tlslite.utils import keyfactory except ImportError: from tlslite.tlslite.utils import keyfactory private_key = keyfactory.parsePrivateKey(rsa_key) signed = private_key.hashAndSign(data) # Python2.3 and lower does not have the base64.b64encode function. if hasattr(base64, 'b64encode'): return base64.b64encode(signed) else: return base64.encodestring(signed).replace('\n', '') class SecureAuthSubToken(AuthSubToken): def __init__(self, token_string, rsa_private_key, scopes=None): self.token_string = token_string self.scopes = scopes or [] self.rsa_private_key = rsa_private_key def from_url(str_or_uri, rsa_private_key): """Creates a new SecureAuthSubToken using information in the URL. Uses auth_sub_string_from_url. Args: str_or_uri: The current page's URL (as a str or atom.http_core.Uri) which should contain a token query parameter since the Google auth server redirected the user's browser to this URL. rsa_private_key: str the private RSA key cert used to sign all requests made with this token. """ token_and_scopes = auth_sub_string_from_url(str_or_uri) return SecureAuthSubToken(token_and_scopes[0], rsa_private_key, token_and_scopes[1]) from_url = staticmethod(from_url) FromUrl = from_url def modify_request(self, http_request): """Sets the Authorization header and includes a digital signature. Calculates a digital signature using the private RSA key, a timestamp (uses now at the time this method is called) and a random nonce. Args: http_request: The atom.http_core.HttpRequest which contains all of the information needed to send a request to the remote server. The URL and the method of the request must be already set and cannot be changed after this token signs the request, or the signature will not be valid. """ timestamp = str(int(time.time())) nonce = ''.join([str(random.randint(0, 9)) for i in xrange(15)]) data = build_auth_sub_data(http_request, timestamp, nonce) signature = generate_signature(data, self.rsa_private_key) http_request.headers['Authorization'] = ( '%s%s sigalg="rsa-sha1" data="%s" sig="%s"' % (AUTHSUB_AUTH_LABEL, self.token_string, data, signature)) ModifyRequest = modify_request # OAuth functions and classes. RSA_SHA1 = 'RSA-SHA1' HMAC_SHA1 = 'HMAC-SHA1' def build_oauth_base_string(http_request, consumer_key, nonce, signaure_type, timestamp, version, next='oob', token=None, verifier=None): """Generates the base string to be signed in the OAuth request. Args: http_request: The request being made to the server. The Request's URL must be complete before this signature is calculated as any changes to the URL will invalidate the signature. consumer_key: Domain identifying the third-party web application. This is the domain used when registering the application with Google. It identifies who is making the request on behalf of the user. nonce: Random 64-bit, unsigned number encoded as an ASCII string in decimal format. The nonce/timestamp pair should always be unique to prevent replay attacks. signaure_type: either RSA_SHA1 or HMAC_SHA1 timestamp: Integer representing the time the request is sent. The timestamp should be expressed in number of seconds after January 1, 1970 00:00:00 GMT. version: The OAuth version used by the requesting web application. This value must be '1.0' or '1.0a'. If not provided, Google assumes version 1.0 is in use. next: The URL the user should be redirected to after granting access to a Google service(s). It can include url-encoded query parameters. The default value is 'oob'. (This is the oauth_callback.) token: The string for the OAuth request token or OAuth access token. verifier: str Sent as the oauth_verifier and required when upgrading a request token to an access token. """ # First we must build the canonical base string for the request. params = http_request.uri.query.copy() params['oauth_consumer_key'] = consumer_key params['oauth_nonce'] = nonce params['oauth_signature_method'] = signaure_type params['oauth_timestamp'] = str(timestamp) if next is not None: params['oauth_callback'] = str(next) if token is not None: params['oauth_token'] = token if version is not None: params['oauth_version'] = version if verifier is not None: params['oauth_verifier'] = verifier # We need to get the key value pairs in lexigraphically sorted order. sorted_keys = None try: sorted_keys = sorted(params.keys()) # The sorted function is not available in Python2.3 and lower except NameError: sorted_keys = params.keys() sorted_keys.sort() pairs = [] for key in sorted_keys: pairs.append('%s=%s' % (urllib.quote(key, safe='~'), urllib.quote(params[key], safe='~'))) # We want to escape /'s too, so use safe='~' all_parameters = urllib.quote('&'.join(pairs), safe='~') normailzed_host = http_request.uri.host.lower() normalized_scheme = (http_request.uri.scheme or 'http').lower() non_default_port = None if (http_request.uri.port is not None and ((normalized_scheme == 'https' and http_request.uri.port != 443) or (normalized_scheme == 'http' and http_request.uri.port != 80))): non_default_port = http_request.uri.port path = http_request.uri.path or '/' request_path = None if not path.startswith('/'): path = '/%s' % path if non_default_port is not None: # Set the only safe char in url encoding to ~ since we want to escape / # as well. request_path = urllib.quote('%s://%s:%s%s' % ( normalized_scheme, normailzed_host, non_default_port, path), safe='~') else: # Set the only safe char in url encoding to ~ since we want to escape / # as well. request_path = urllib.quote('%s://%s%s' % ( normalized_scheme, normailzed_host, path), safe='~') # TODO: ensure that token escaping logic is correct, not sure if the token # value should be double escaped instead of single. base_string = '&'.join((http_request.method.upper(), request_path, all_parameters)) # Now we have the base string, we can calculate the oauth_signature. return base_string def generate_hmac_signature(http_request, consumer_key, consumer_secret, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): import hmac import base64 base_string = build_oauth_base_string( http_request, consumer_key, nonce, HMAC_SHA1, timestamp, version, next, token, verifier=verifier) hash_key = None hashed = None if token_secret is not None: hash_key = '%s&%s' % (urllib.quote(consumer_secret, safe='~'), urllib.quote(token_secret, safe='~')) else: hash_key = '%s&' % urllib.quote(consumer_secret, safe='~') try: import hashlib hashed = hmac.new(hash_key, base_string, hashlib.sha1) except ImportError: import sha hashed = hmac.new(hash_key, base_string, sha) # Python2.3 does not have base64.b64encode. if hasattr(base64, 'b64encode'): return base64.b64encode(hashed.digest()) else: return base64.encodestring(hashed.digest()).replace('\n', '') def generate_rsa_signature(http_request, consumer_key, rsa_key, timestamp, nonce, version, next='oob', token=None, token_secret=None, verifier=None): import base64 try: from tlslite.utils import keyfactory except ImportError: try: from gdata.tlslite.utils import keyfactory except ImportError: from tlslite.tlslite.utils import keyfactory base_string = build_oauth_base_string( http_request, consumer_key, nonce, RSA_SHA1, timestamp, version, next, token, verifier=verifier) private_key = keyfactory.parsePrivateKey(rsa_key) # Sign using the key signed = private_key.hashAndSign(base_string) # Python2.3 does not have base64.b64encode. if hasattr(base64, 'b64encode'): return base64.b64encode(signed) else: return base64.encodestring(signed).replace('\n', '') def generate_auth_header(consumer_key, timestamp, nonce, signature_type, signature, version='1.0', next=None, token=None, verifier=None): """Builds the Authorization header to be sent in the request. Args: consumer_key: Identifies the application making the request (str). timestamp: nonce: signature_type: One of either HMAC_SHA1 or RSA_SHA1 signature: The HMAC or RSA signature for the request as a base64 encoded string. version: The version of the OAuth protocol that this request is using. Default is '1.0' next: The URL of the page that the user's browser should be sent to after they authorize the token. (Optional) token: str The OAuth token value to be used in the oauth_token parameter of the header. verifier: str The OAuth verifier which must be included when you are upgrading a request token to an access token. """ params = { 'oauth_consumer_key': consumer_key, 'oauth_version': version, 'oauth_nonce': nonce, 'oauth_timestamp': str(timestamp), 'oauth_signature_method': signature_type, 'oauth_signature': signature} if next is not None: params['oauth_callback'] = str(next) if token is not None: params['oauth_token'] = token if verifier is not None: params['oauth_verifier'] = verifier pairs = [ '%s="%s"' % ( k, urllib.quote(v, safe='~')) for k, v in params.iteritems()] return 'OAuth %s' % (', '.join(pairs)) REQUEST_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetRequestToken' ACCESS_TOKEN_URL = 'https://www.google.com/accounts/OAuthGetAccessToken' def generate_request_for_request_token( consumer_key, signature_type, scopes, rsa_key=None, consumer_secret=None, auth_server_url=REQUEST_TOKEN_URL, next='oob', version='1.0'): """Creates request to be sent to auth server to get an OAuth request token. Args: consumer_key: signature_type: either RSA_SHA1 or HMAC_SHA1. The rsa_key must be provided if the signature type is RSA but if the signature method is HMAC, the consumer_secret must be used. scopes: List of URL prefixes for the data which we want to access. For example, to request access to the user's Blogger and Google Calendar data, we would request ['http://www.blogger.com/feeds/', 'https://www.google.com/calendar/feeds/', 'http://www.google.com/calendar/feeds/'] rsa_key: Only used if the signature method is RSA_SHA1. consumer_secret: Only used if the signature method is HMAC_SHA1. auth_server_url: The URL to which the token request should be directed. Defaults to 'https://www.google.com/accounts/OAuthGetRequestToken'. next: The URL of the page that the user's browser should be sent to after they authorize the token. (Optional) version: The OAuth version used by the requesting web application. Defaults to '1.0a' Returns: An atom.http_core.HttpRequest object with the URL, Authorization header and body filled in. """ request = atom.http_core.HttpRequest(auth_server_url, 'POST') # Add the requested auth scopes to the Auth request URL. if scopes: request.uri.query['scope'] = ' '.join(scopes) timestamp = str(int(time.time())) nonce = ''.join([str(random.randint(0, 9)) for i in xrange(15)]) signature = None if signature_type == HMAC_SHA1: signature = generate_hmac_signature( request, consumer_key, consumer_secret, timestamp, nonce, version, next=next) elif signature_type == RSA_SHA1: signature = generate_rsa_signature( request, consumer_key, rsa_key, timestamp, nonce, version, next=next) else: return None request.headers['Authorization'] = generate_auth_header( consumer_key, timestamp, nonce, signature_type, signature, version, next) request.headers['Content-Length'] = '0' return request def generate_request_for_access_token( request_token, auth_server_url=ACCESS_TOKEN_URL): """Creates a request to ask the OAuth server for an access token. Requires a request token which the user has authorized. See the documentation on OAuth with Google Data for more details: http://code.google.com/apis/accounts/docs/OAuth.html#AccessToken Args: request_token: An OAuthHmacToken or OAuthRsaToken which the user has approved using their browser. auth_server_url: (optional) The URL at which the OAuth access token is requested. Defaults to https://www.google.com/accounts/OAuthGetAccessToken Returns: A new HttpRequest object which can be sent to the OAuth server to request an OAuth Access Token. """ http_request = atom.http_core.HttpRequest(auth_server_url, 'POST') http_request.headers['Content-Length'] = '0' return request_token.modify_request(http_request) def oauth_token_info_from_body(http_body): """Exracts an OAuth request token from the server's response. Returns: A tuple of strings containing the OAuth token and token secret. If neither of these are present in the body, returns (None, None) """ token = None token_secret = None for pair in http_body.split('&'): if pair.startswith('oauth_token='): token = urllib.unquote(pair[len('oauth_token='):]) if pair.startswith('oauth_token_secret='): token_secret = urllib.unquote(pair[len('oauth_token_secret='):]) return (token, token_secret) def hmac_token_from_body(http_body, consumer_key, consumer_secret, auth_state): token_value, token_secret = oauth_token_info_from_body(http_body) token = OAuthHmacToken(consumer_key, consumer_secret, token_value, token_secret, auth_state) return token def rsa_token_from_body(http_body, consumer_key, rsa_private_key, auth_state): token_value, token_secret = oauth_token_info_from_body(http_body) token = OAuthRsaToken(consumer_key, rsa_private_key, token_value, token_secret, auth_state) return token DEFAULT_DOMAIN = 'default' OAUTH_AUTHORIZE_URL = 'https://www.google.com/accounts/OAuthAuthorizeToken' def generate_oauth_authorization_url( token, next=None, hd=DEFAULT_DOMAIN, hl=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): """Creates a URL for the page where the request token can be authorized. Args: token: str The request token from the OAuth server. next: str (optional) URL the user should be redirected to after granting access to a Google service(s). It can include url-encoded query parameters. hd: str (optional) Identifies a particular hosted domain account to be accessed (for example, 'mycollege.edu'). Uses 'default' to specify a regular Google account ('username@gmail.com'). hl: str (optional) An ISO 639 country code identifying what language the approval page should be translated in (for example, 'hl=en' for English). The default is the user's selected language. btmpl: str (optional) Forces a mobile version of the approval page. The only accepted value is 'mobile'. auth_server: str (optional) The start of the token authorization web page. Defaults to 'https://www.google.com/accounts/OAuthAuthorizeToken' Returns: An atom.http_core.Uri pointing to the token authorization page where the user may allow or deny this app to access their Google data. """ uri = atom.http_core.Uri.parse_uri(auth_server) uri.query['oauth_token'] = token uri.query['hd'] = hd if next is not None: uri.query['oauth_callback'] = str(next) if hl is not None: uri.query['hl'] = hl if btmpl is not None: uri.query['btmpl'] = btmpl return uri def oauth_token_info_from_url(url): """Exracts an OAuth access token from the redirected page's URL. Returns: A tuple of strings containing the OAuth token and the OAuth verifier which need to sent when upgrading a request token to an access token. """ if isinstance(url, (str, unicode)): url = atom.http_core.Uri.parse_uri(url) token = None verifier = None if 'oauth_token' in url.query: token = urllib.unquote(url.query['oauth_token']) if 'oauth_verifier' in url.query: verifier = urllib.unquote(url.query['oauth_verifier']) return (token, verifier) def authorize_request_token(request_token, url): """Adds information to request token to allow it to become an access token. Modifies the request_token object passed in by setting and unsetting the necessary fields to allow this token to form a valid upgrade request. Args: request_token: The OAuth request token which has been authorized by the user. In order for this token to be upgraded to an access token, certain fields must be extracted from the URL and added to the token so that they can be passed in an upgrade-token request. url: The URL of the current page which the user's browser was redirected to after they authorized access for the app. This function extracts information from the URL which is needed to upgraded the token from a request token to an access token. Returns: The same token object which was passed in. """ token, verifier = oauth_token_info_from_url(url) request_token.token = token request_token.verifier = verifier request_token.auth_state = AUTHORIZED_REQUEST_TOKEN return request_token AuthorizeRequestToken = authorize_request_token def upgrade_to_access_token(request_token, server_response_body): """Extracts access token information from response to an upgrade request. Once the server has responded with the new token info for the OAuth access token, this method modifies the request_token to set and unset necessary fields to create valid OAuth authorization headers for requests. Args: request_token: An OAuth token which this function modifies to allow it to be used as an access token. server_response_body: str The server's response to an OAuthAuthorizeToken request. This should contain the new token and token_secret which are used to generate the signature and parameters of the Authorization header in subsequent requests to Google Data APIs. Returns: The same token object which was passed in. """ token, token_secret = oauth_token_info_from_body(server_response_body) request_token.token = token request_token.token_secret = token_secret request_token.auth_state = ACCESS_TOKEN request_token.next = None request_token.verifier = None return request_token UpgradeToAccessToken = upgrade_to_access_token REQUEST_TOKEN = 1 AUTHORIZED_REQUEST_TOKEN = 2 ACCESS_TOKEN = 3 class OAuthHmacToken(object): SIGNATURE_METHOD = HMAC_SHA1 def __init__(self, consumer_key, consumer_secret, token, token_secret, auth_state, next=None, verifier=None): self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.token = token self.token_secret = token_secret self.auth_state = auth_state self.next = next self.verifier = verifier # Used to convert request token to access token. def generate_authorization_url( self, google_apps_domain=DEFAULT_DOMAIN, language=None, btmpl=None, auth_server=OAUTH_AUTHORIZE_URL): """Creates the URL at which the user can authorize this app to access. Args: google_apps_domain: str (optional) If the user should be signing in using an account under a known Google Apps domain, provide the domain name ('example.com') here. If not provided, 'default' will be used, and the user will be prompted to select an account if they are signed in with a Google Account and Google Apps accounts. language: str (optional) An ISO 639 country code identifying what language the approval page should be translated in (for example, 'en' for English). The default is the user's selected language. btmpl: str (optional) Forces a mobile version of the approval page. The only accepted value is 'mobile'. auth_server: str (optional) The start of the token authorization web page. Defaults to 'https://www.google.com/accounts/OAuthAuthorizeToken' """ return generate_oauth_authorization_url( self.token, hd=google_apps_domain, hl=language, btmpl=btmpl, auth_server=auth_server) GenerateAuthorizationUrl = generate_authorization_url def modify_request(self, http_request): """Sets the Authorization header in the HTTP request using the token. Calculates an HMAC signature using the information in the token to indicate that the request came from this application and that this application has permission to access a particular user's data. Returns: The same HTTP request object which was passed in. """ timestamp = str(int(time.time())) nonce = ''.join([str(random.randint(0, 9)) for i in xrange(15)]) signature = generate_hmac_signature( http_request, self.consumer_key, self.consumer_secret, timestamp, nonce, version='1.0', next=self.next, token=self.token, token_secret=self.token_secret, verifier=self.verifier) http_request.headers['Authorization'] = generate_auth_header( self.consumer_key, timestamp, nonce, HMAC_SHA1, signature, version='1.0', next=self.next, token=self.token, verifier=self.verifier) return http_request ModifyRequest = modify_request class OAuthRsaToken(OAuthHmacToken): SIGNATURE_METHOD = RSA_SHA1 def __init__(self, consumer_key, rsa_private_key, token, token_secret, auth_state, next=None, verifier=None): self.consumer_key = consumer_key self.rsa_private_key = rsa_private_key self.token = token self.token_secret = token_secret self.auth_state = auth_state self.next = next self.verifier = verifier # Used to convert request token to access token. def modify_request(self, http_request): """Sets the Authorization header in the HTTP request using the token. Calculates an RSA signature using the information in the token to indicate that the request came from this application and that this application has permission to access a particular user's data. Returns: The same HTTP request object which was passed in. """ timestamp = str(int(time.time())) nonce = ''.join([str(random.randint(0, 9)) for i in xrange(15)]) signature = generate_rsa_signature( http_request, self.consumer_key, self.rsa_private_key, timestamp, nonce, version='1.0', next=self.next, token=self.token, token_secret=self.token_secret, verifier=self.verifier) http_request.headers['Authorization'] = generate_auth_header( self.consumer_key, timestamp, nonce, RSA_SHA1, signature, version='1.0', next=self.next, token=self.token, verifier=self.verifier) return http_request ModifyRequest = modify_request class TwoLeggedOAuthHmacToken(OAuthHmacToken): def __init__(self, consumer_key, consumer_secret, requestor_id): self.requestor_id = requestor_id OAuthHmacToken.__init__( self, consumer_key, consumer_secret, None, None, ACCESS_TOKEN, next=None, verifier=None) def modify_request(self, http_request): """Sets the Authorization header in the HTTP request using the token. Calculates an HMAC signature using the information in the token to indicate that the request came from this application and that this application has permission to access a particular user's data using 2LO. Returns: The same HTTP request object which was passed in. """ http_request.uri.query['xoauth_requestor_id'] = self.requestor_id return OAuthHmacToken.modify_request(self, http_request) ModifyRequest = modify_request class TwoLeggedOAuthRsaToken(OAuthRsaToken): def __init__(self, consumer_key, rsa_private_key, requestor_id): self.requestor_id = requestor_id OAuthRsaToken.__init__( self, consumer_key, rsa_private_key, None, None, ACCESS_TOKEN, next=None, verifier=None) def modify_request(self, http_request): """Sets the Authorization header in the HTTP request using the token. Calculates an RSA signature using the information in the token to indicate that the request came from this application and that this application has permission to access a particular user's data using 2LO. Returns: The same HTTP request object which was passed in. """ http_request.uri.query['xoauth_requestor_id'] = self.requestor_id return OAuthRsaToken.modify_request(self, http_request) ModifyRequest = modify_request class OAuth2Token(object): """Token object for OAuth 2.0 as described on <http://code.google.com/apis/accounts/docs/OAuth2.html>. Token can be applied to a gdata.client.GDClient object using the authorize() method, which then signs each request from that object with the OAuth 2.0 access token. This class supports 3 flows of OAuth 2.0: Client-side web flow: call generate_authorize_url with `response_type='token'' and the registered `redirect_uri'. Server-side web flow: call generate_authorize_url with the registered `redirect_url'. Native applications flow: call generate_authorize_url as it is. You will have to ask the user to go to the generated url and pass in the authorization code to your application. """ def __init__(self, client_id, client_secret, scope, user_agent, auth_uri='https://accounts.google.com/o/oauth2/auth', token_uri='https://accounts.google.com/o/oauth2/token', access_token=None, refresh_token=None): """Create an instance of OAuth2Token This constructor is not usually called by the user, instead OAuth2Credentials objects are instantiated by the OAuth2WebServerFlow. Args: client_id: string, client identifier. client_secret: string client secret. scope: string, scope of the credentials being requested. user_agent: string, HTTP User-Agent to provide for this application. auth_uri: string, URI for authorization endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. token_uri: string, URI for token endpoint. For convenience defaults to Google's endpoints but any OAuth 2.0 provider can be used. access_token: string, access token. refresh_token: string, refresh token. """ self.client_id = client_id self.client_secret = client_secret self.scope = scope self.user_agent = user_agent self.auth_uri = auth_uri self.token_uri = token_uri self.access_token = access_token self.refresh_token = refresh_token # True if the credentials have been revoked or expired and can't be # refreshed. self._invalid = False @property def invalid(self): """True if the credentials are invalid, such as being revoked.""" return getattr(self, '_invalid', False) def _refresh(self, request): """Refresh the access_token using the refresh_token. Args: http: An instance of httplib2.Http.request or something that acts like it. """ body = urllib.urlencode({ 'grant_type': 'refresh_token', 'client_id': self.client_id, 'client_secret': self.client_secret, 'refresh_token' : self.refresh_token }) headers = { 'user-agent': self.user_agent, } http_request = atom.http_core.HttpRequest( uri=self.token_uri, method='POST', headers=headers) http_request.add_body_part( body, mime_type='application/x-www-form-urlencoded') response = request(http_request) body = response.read() if response.status == 200: self._extract_tokens(body) else: self._invalid = True return response def _extract_tokens(self, body): d = simplejson.loads(body) self.access_token = d['access_token'] self.refresh_token = d.get('refresh_token', self.refresh_token) if 'expires_in' in d: self.token_expiry = datetime.timedelta( seconds = int(d['expires_in'])) + datetime.datetime.now() else: self.token_expiry = None def generate_authorize_url(self, redirect_uri='oob', response_type='code', access_type='offline', **kwargs): """Returns a URI to redirect to the provider. Args: redirect_uri: Either the string 'oob' for a non-web-based application, or a URI that handles the callback from the authorization server. response_type: Either the string 'code' for server-side or native application, or the string 'token' for client-side application. access_type: Either the string 'offline' to request a refresh token or 'online'. If redirect_uri is 'oob' then pass in the generated verification code to get_access_token, otherwise pass in the query parameters received at the callback uri to get_access_token. If the response_type is 'token', no need to call get_access_token as the API will return it within the query parameters received at the callback: oauth2_token.access_token = YOUR_ACCESS_TOKEN """ self.redirect_uri = redirect_uri query = { 'response_type': response_type, 'client_id': self.client_id, 'redirect_uri': redirect_uri, 'scope': self.scope, 'access_type': access_type } query.update(kwargs) parts = list(urlparse.urlparse(self.auth_uri)) query.update(dict(parse_qsl(parts[4]))) # 4 is the index of the query part parts[4] = urllib.urlencode(query) return urlparse.urlunparse(parts) def get_access_token(self, code): """Exhanges a code for an access token. Args: code: string or dict, either the code as a string, or a dictionary of the query parameters to the redirect_uri, which contains the code. """ if not (isinstance(code, str) or isinstance(code, unicode)): code = code['code'] body = urllib.urlencode({ 'grant_type': 'authorization_code', 'client_id': self.client_id, 'client_secret': self.client_secret, 'code': code, 'redirect_uri': self.redirect_uri, 'scope': self.scope }) headers = { 'user-agent': self.user_agent, } http_client = atom.http_core.HttpClient() http_request = atom.http_core.HttpRequest(uri=self.token_uri, method='POST', headers=headers) http_request.add_body_part(data=body, mime_type='application/x-www-form-urlencoded') response = http_client.request(http_request) body = response.read() if response.status == 200: self._extract_tokens(body) return self else: error_msg = 'Invalid response %s.' % response.status try: d = simplejson.loads(body) if 'error' in d: error_msg = d['error'] except: pass raise OAuth2AccessTokenError(error_msg) def authorize(self, client): """Authorize a gdata.client.GDClient instance with these credentials. Args: client: An instance of gdata.client.GDClient or something that acts like it. Returns: A modified instance of client that was passed in. Example: c = gdata.client.GDClient(source='user-agent') c = token.authorize(c) """ client.auth_token = self request_orig = client.http_client.request def new_request(http_request): response = request_orig(http_request) if response.status == 401: refresh_response = self._refresh(request_orig) if self._invalid: return refresh_response else: self.modify_request(http_request) return request_orig(http_request) else: return response client.http_client.request = new_request return client def modify_request(self, http_request): """Sets the Authorization header in the HTTP request using the token. Returns: The same HTTP request object which was passed in. """ http_request.headers['Authorization'] = '%s%s' % (OAUTH2_AUTH_LABEL, self.access_token) return http_request ModifyRequest = modify_request def _join_token_parts(*args): """"Escapes and combines all strings passed in. Used to convert a token object's members into a string instead of using pickle. Note: A None value will be converted to an empty string. Returns: A string in the form 1x|member1|member2|member3... """ return '|'.join([urllib.quote_plus(a or '') for a in args]) def _split_token_parts(blob): """Extracts and unescapes fields from the provided binary string. Reverses the packing performed by _join_token_parts. Used to extract the members of a token object. Note: An empty string from the blob will be interpreted as None. Args: blob: str A string of the form 1x|member1|member2|member3 as created by _join_token_parts Returns: A list of unescaped strings. """ return [urllib.unquote_plus(part) or None for part in blob.split('|')] def token_to_blob(token): """Serializes the token data as a string for storage in a datastore. Supported token classes: ClientLoginToken, AuthSubToken, SecureAuthSubToken, OAuthRsaToken, and OAuthHmacToken, TwoLeggedOAuthRsaToken, TwoLeggedOAuthHmacToken and OAuth2Token. Args: token: A token object which must be of one of the supported token classes. Raises: UnsupportedTokenType if the token is not one of the supported token classes listed above. Returns: A string represenging this token. The string can be converted back into an equivalent token object using token_from_blob. Note that any members which are set to '' will be set to None when the token is deserialized by token_from_blob. """ if isinstance(token, ClientLoginToken): return _join_token_parts('1c', token.token_string) # Check for secure auth sub type first since it is a subclass of # AuthSubToken. elif isinstance(token, SecureAuthSubToken): return _join_token_parts('1s', token.token_string, token.rsa_private_key, *token.scopes) elif isinstance(token, AuthSubToken): return _join_token_parts('1a', token.token_string, *token.scopes) elif isinstance(token, TwoLeggedOAuthRsaToken): return _join_token_parts( '1rtl', token.consumer_key, token.rsa_private_key, token.requestor_id) elif isinstance(token, TwoLeggedOAuthHmacToken): return _join_token_parts( '1htl', token.consumer_key, token.consumer_secret, token.requestor_id) # Check RSA OAuth token first since the OAuthRsaToken is a subclass of # OAuthHmacToken. elif isinstance(token, OAuthRsaToken): return _join_token_parts( '1r', token.consumer_key, token.rsa_private_key, token.token, token.token_secret, str(token.auth_state), token.next, token.verifier) elif isinstance(token, OAuthHmacToken): return _join_token_parts( '1h', token.consumer_key, token.consumer_secret, token.token, token.token_secret, str(token.auth_state), token.next, token.verifier) elif isinstance(token, OAuth2Token): return _join_token_parts( '2o', token.client_id, token.client_secret, token.scope, token.user_agent, token.auth_uri, token.token_uri, token.access_token, token.refresh_token) else: raise UnsupportedTokenType( 'Unable to serialize token of type %s' % type(token)) TokenToBlob = token_to_blob def token_from_blob(blob): """Deserializes a token string from the datastore back into a token object. Supported token classes: ClientLoginToken, AuthSubToken, SecureAuthSubToken, OAuthRsaToken, and OAuthHmacToken, TwoLeggedOAuthRsaToken, TwoLeggedOAuthHmacToken and OAuth2Token. Args: blob: string created by token_to_blob. Raises: UnsupportedTokenType if the token is not one of the supported token classes listed above. Returns: A new token object with members set to the values serialized in the blob string. Note that any members which were set to '' in the original token will now be None. """ parts = _split_token_parts(blob) if parts[0] == '1c': return ClientLoginToken(parts[1]) elif parts[0] == '1a': return AuthSubToken(parts[1], parts[2:]) elif parts[0] == '1s': return SecureAuthSubToken(parts[1], parts[2], parts[3:]) elif parts[0] == '1rtl': return TwoLeggedOAuthRsaToken(parts[1], parts[2], parts[3]) elif parts[0] == '1htl': return TwoLeggedOAuthHmacToken(parts[1], parts[2], parts[3]) elif parts[0] == '1r': auth_state = int(parts[5]) return OAuthRsaToken(parts[1], parts[2], parts[3], parts[4], auth_state, parts[6], parts[7]) elif parts[0] == '1h': auth_state = int(parts[5]) return OAuthHmacToken(parts[1], parts[2], parts[3], parts[4], auth_state, parts[6], parts[7]) elif parts[0] == '2o': return OAuth2Token(parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8]) else: raise UnsupportedTokenType( 'Unable to deserialize token with type marker of %s' % parts[0]) TokenFromBlob = token_from_blob def dump_tokens(tokens): return ','.join([token_to_blob(t) for t in tokens]) def load_tokens(blob): return [token_from_blob(s) for s in blob.split(',')] def find_scopes_for_services(service_names=None): """Creates a combined list of scope URLs for the desired services. This method searches the AUTH_SCOPES dictionary. Args: service_names: list of strings (optional) Each name must be a key in the AUTH_SCOPES dictionary. If no list is provided (None) then the resulting list will contain all scope URLs in the AUTH_SCOPES dict. Returns: A list of URL strings which are the scopes needed to access these services when requesting a token using AuthSub or OAuth. """ result_scopes = [] if service_names is None: for service_name, scopes in AUTH_SCOPES.iteritems(): result_scopes.extend(scopes) else: for service_name in service_names: result_scopes.extend(AUTH_SCOPES[service_name]) return result_scopes FindScopesForServices = find_scopes_for_services def ae_save(token, token_key): """Stores an auth token in the App Engine datastore. This is a convenience method for using the library with App Engine. Recommended usage is to associate the auth token with the current_user. If a user is signed in to the app using the App Engine users API, you can use gdata.gauth.ae_save(some_token, users.get_current_user().user_id()) If you are not using the Users API you are free to choose whatever string you would like for a token_string. Args: token: an auth token object. Must be one of ClientLoginToken, AuthSubToken, SecureAuthSubToken, OAuthRsaToken, or OAuthHmacToken (see token_to_blob). token_key: str A unique identified to be used when you want to retrieve the token. If the user is signed in to App Engine using the users API, I recommend using the user ID for the token_key: users.get_current_user().user_id() """ import gdata.alt.app_engine key_name = ''.join(('gd_auth_token', token_key)) return gdata.alt.app_engine.set_token(key_name, token_to_blob(token)) AeSave = ae_save def ae_load(token_key): """Retrieves a token object from the App Engine datastore. This is a convenience method for using the library with App Engine. See also ae_save. Args: token_key: str The unique key associated with the desired token when it was saved using ae_save. Returns: A token object if there was a token associated with the token_key or None if the key could not be found. """ import gdata.alt.app_engine key_name = ''.join(('gd_auth_token', token_key)) token_string = gdata.alt.app_engine.get_token(key_name) if token_string is not None: return token_from_blob(token_string) else: return None AeLoad = ae_load def ae_delete(token_key): """Removes the token object from the App Engine datastore.""" import gdata.alt.app_engine key_name = ''.join(('gd_auth_token', token_key)) gdata.alt.app_engine.delete_token(key_name) AeDelete = ae_delete
Python
#!/usr/bin/python # # Copyright Google 2007-2008, all rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import StringIO import gdata import gdata.service import gdata.spreadsheet import gdata.spreadsheet.service import gdata.docs import gdata.docs.service """Make the Google Documents API feel more like using a database. This module contains a client and other classes which make working with the Google Documents List Data API and the Google Spreadsheets Data API look a bit more like working with a heirarchical database. Using the DatabaseClient, you can create or find spreadsheets and use them like a database, with worksheets representing tables and rows representing records. Example Usage: # Create a new database, a new table, and add records. client = gdata.spreadsheet.text_db.DatabaseClient(username='jo@example.com', password='12345') database = client.CreateDatabase('My Text Database') table = database.CreateTable('addresses', ['name','email', 'phonenumber', 'mailingaddress']) record = table.AddRecord({'name':'Bob', 'email':'bob@example.com', 'phonenumber':'555-555-1234', 'mailingaddress':'900 Imaginary St.'}) # Edit a record record.content['email'] = 'bob2@example.com' record.Push() # Delete a table table.Delete Warnings: Care should be exercised when using this module on spreadsheets which contain formulas. This module treats all rows as containing text and updating a row will overwrite any formula with the output of the formula. The intended use case is to allow easy storage of text data in a spreadsheet. Error: Domain specific extension of Exception. BadCredentials: Error raised is username or password was incorrect. CaptchaRequired: Raised if a login attempt failed and a CAPTCHA challenge was issued. DatabaseClient: Communicates with Google Docs APIs servers. Database: Represents a spreadsheet and interacts with tables. Table: Represents a worksheet and interacts with records. RecordResultSet: A list of records in a table. Record: Represents a row in a worksheet allows manipulation of text data. """ __author__ = 'api.jscudder (Jeffrey Scudder)' class Error(Exception): pass class BadCredentials(Error): pass class CaptchaRequired(Error): pass class DatabaseClient(object): """Allows creation and finding of Google Spreadsheets databases. The DatabaseClient simplifies the process of creating and finding Google Spreadsheets and will talk to both the Google Spreadsheets API and the Google Documents List API. """ def __init__(self, username=None, password=None): """Constructor for a Database Client. If the username and password are present, the constructor will contact the Google servers to authenticate. Args: username: str (optional) Example: jo@example.com password: str (optional) """ self.__docs_client = gdata.docs.service.DocsService() self.__spreadsheets_client = ( gdata.spreadsheet.service.SpreadsheetsService()) self.SetCredentials(username, password) def SetCredentials(self, username, password): """Attempts to log in to Google APIs using the provided credentials. If the username or password are None, the client will not request auth tokens. Args: username: str (optional) Example: jo@example.com password: str (optional) """ self.__docs_client.email = username self.__docs_client.password = password self.__spreadsheets_client.email = username self.__spreadsheets_client.password = password if username and password: try: self.__docs_client.ProgrammaticLogin() self.__spreadsheets_client.ProgrammaticLogin() except gdata.service.CaptchaRequired: raise CaptchaRequired('Please visit https://www.google.com/accounts/' 'DisplayUnlockCaptcha to unlock your account.') except gdata.service.BadAuthentication: raise BadCredentials('Username or password incorrect.') def CreateDatabase(self, name): """Creates a new Google Spreadsheet with the desired name. Args: name: str The title for the spreadsheet. Returns: A Database instance representing the new spreadsheet. """ # Create a Google Spreadsheet to form the foundation of this database. # Spreadsheet is created by uploading a file to the Google Documents # List API. virtual_csv_file = StringIO.StringIO(',,,') virtual_media_source = gdata.MediaSource(file_handle=virtual_csv_file, content_type='text/csv', content_length=3) db_entry = self.__docs_client.UploadSpreadsheet(virtual_media_source, name) return Database(spreadsheet_entry=db_entry, database_client=self) def GetDatabases(self, spreadsheet_key=None, name=None): """Finds spreadsheets which have the unique key or title. If querying on the spreadsheet_key there will be at most one result, but searching by name could yield multiple results. Args: spreadsheet_key: str The unique key for the spreadsheet, this usually in the the form 'pk23...We' or 'o23...423.12,,,3'. name: str The title of the spreadsheets. Returns: A list of Database objects representing the desired spreadsheets. """ if spreadsheet_key: db_entry = self.__docs_client.GetDocumentListEntry( r'/feeds/documents/private/full/spreadsheet%3A' + spreadsheet_key) return [Database(spreadsheet_entry=db_entry, database_client=self)] else: title_query = gdata.docs.service.DocumentQuery() title_query['title'] = name db_feed = self.__docs_client.QueryDocumentListFeed(title_query.ToUri()) matching_databases = [] for entry in db_feed.entry: matching_databases.append(Database(spreadsheet_entry=entry, database_client=self)) return matching_databases def _GetDocsClient(self): return self.__docs_client def _GetSpreadsheetsClient(self): return self.__spreadsheets_client class Database(object): """Provides interface to find and create tables. The database represents a Google Spreadsheet. """ def __init__(self, spreadsheet_entry=None, database_client=None): """Constructor for a database object. Args: spreadsheet_entry: gdata.docs.DocumentListEntry The Atom entry which represents the Google Spreadsheet. The spreadsheet's key is extracted from the entry and stored as a member. database_client: DatabaseClient A client which can talk to the Google Spreadsheets servers to perform operations on worksheets within this spreadsheet. """ self.entry = spreadsheet_entry if self.entry: id_parts = spreadsheet_entry.id.text.split('/') self.spreadsheet_key = id_parts[-1].replace('spreadsheet%3A', '') self.client = database_client def CreateTable(self, name, fields=None): """Add a new worksheet to this spreadsheet and fill in column names. Args: name: str The title of the new worksheet. fields: list of strings The column names which are placed in the first row of this worksheet. These names are converted into XML tags by the server. To avoid changes during the translation process I recommend using all lowercase alphabetic names. For example ['somelongname', 'theothername'] Returns: Table representing the newly created worksheet. """ worksheet = self.client._GetSpreadsheetsClient().AddWorksheet(title=name, row_count=1, col_count=len(fields), key=self.spreadsheet_key) return Table(name=name, worksheet_entry=worksheet, database_client=self.client, spreadsheet_key=self.spreadsheet_key, fields=fields) def GetTables(self, worksheet_id=None, name=None): """Searches for a worksheet with the specified ID or name. The list of results should have one table at most, or no results if the id or name were not found. Args: worksheet_id: str The ID of the worksheet, example: 'od6' name: str The title of the worksheet. Returns: A list of length 0 or 1 containing the desired Table. A list is returned to make this method feel like GetDatabases and GetRecords. """ if worksheet_id: worksheet_entry = self.client._GetSpreadsheetsClient().GetWorksheetsFeed( self.spreadsheet_key, wksht_id=worksheet_id) return [Table(name=worksheet_entry.title.text, worksheet_entry=worksheet_entry, database_client=self.client, spreadsheet_key=self.spreadsheet_key)] else: matching_tables = [] query = None if name: query = gdata.spreadsheet.service.DocumentQuery() query.title = name worksheet_feed = self.client._GetSpreadsheetsClient().GetWorksheetsFeed( self.spreadsheet_key, query=query) for entry in worksheet_feed.entry: matching_tables.append(Table(name=entry.title.text, worksheet_entry=entry, database_client=self.client, spreadsheet_key=self.spreadsheet_key)) return matching_tables def Delete(self): """Deletes the entire database spreadsheet from Google Spreadsheets.""" entry = self.client._GetDocsClient().Get( r'http://docs.google.com/feeds/documents/private/full/spreadsheet%3A' + self.spreadsheet_key) self.client._GetDocsClient().Delete(entry.GetEditLink().href) class Table(object): def __init__(self, name=None, worksheet_entry=None, database_client=None, spreadsheet_key=None, fields=None): self.name = name self.entry = worksheet_entry id_parts = worksheet_entry.id.text.split('/') self.worksheet_id = id_parts[-1] self.spreadsheet_key = spreadsheet_key self.client = database_client self.fields = fields or [] if fields: self.SetFields(fields) def LookupFields(self): """Queries to find the column names in the first row of the worksheet. Useful when you have retrieved the table from the server and you don't know the column names. """ if self.entry: first_row_contents = [] query = gdata.spreadsheet.service.CellQuery() query.max_row = '1' query.min_row = '1' feed = self.client._GetSpreadsheetsClient().GetCellsFeed( self.spreadsheet_key, wksht_id=self.worksheet_id, query=query) for entry in feed.entry: first_row_contents.append(entry.content.text) # Get the next set of cells if needed. next_link = feed.GetNextLink() while next_link: feed = self.client._GetSpreadsheetsClient().Get(next_link.href, converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString) for entry in feed.entry: first_row_contents.append(entry.content.text) next_link = feed.GetNextLink() # Convert the contents of the cells to valid headers. self.fields = ConvertStringsToColumnHeaders(first_row_contents) def SetFields(self, fields): """Changes the contents of the cells in the first row of this worksheet. Args: fields: list of strings The names in the list comprise the first row of the worksheet. These names are converted into XML tags by the server. To avoid changes during the translation process I recommend using all lowercase alphabetic names. For example ['somelongname', 'theothername'] """ # TODO: If the table already had fields, we might want to clear out the, # current column headers. self.fields = fields i = 0 for column_name in fields: i = i + 1 # TODO: speed this up by using a batch request to update cells. self.client._GetSpreadsheetsClient().UpdateCell(1, i, column_name, self.spreadsheet_key, self.worksheet_id) def Delete(self): """Deletes this worksheet from the spreadsheet.""" worksheet = self.client._GetSpreadsheetsClient().GetWorksheetsFeed( self.spreadsheet_key, wksht_id=self.worksheet_id) self.client._GetSpreadsheetsClient().DeleteWorksheet( worksheet_entry=worksheet) def AddRecord(self, data): """Adds a new row to this worksheet. Args: data: dict of strings Mapping of string values to column names. Returns: Record which represents this row of the spreadsheet. """ new_row = self.client._GetSpreadsheetsClient().InsertRow(data, self.spreadsheet_key, wksht_id=self.worksheet_id) return Record(content=data, row_entry=new_row, spreadsheet_key=self.spreadsheet_key, worksheet_id=self.worksheet_id, database_client=self.client) def GetRecord(self, row_id=None, row_number=None): """Gets a single record from the worksheet based on row ID or number. Args: row_id: The ID for the individual row. row_number: str or int The position of the desired row. Numbering begins at 1, which refers to the second row in the worksheet since the first row is used for column names. Returns: Record for the desired row. """ if row_id: row_entry = self.client._GetSpreadsheetsClient().GetListFeed( self.spreadsheet_key, wksht_id=self.worksheet_id, row_id=row_id) return Record(content=None, row_entry=row_entry, spreadsheet_key=self.spreadsheet_key, worksheet_id=self.worksheet_id, database_client=self.client) else: row_query = gdata.spreadsheet.service.ListQuery() row_query.start_index = str(row_number) row_query.max_results = '1' row_feed = self.client._GetSpreadsheetsClient().GetListFeed( self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query) if len(row_feed.entry) >= 1: return Record(content=None, row_entry=row_feed.entry[0], spreadsheet_key=self.spreadsheet_key, worksheet_id=self.worksheet_id, database_client=self.client) else: return None def GetRecords(self, start_row, end_row): """Gets all rows between the start and end row numbers inclusive. Args: start_row: str or int end_row: str or int Returns: RecordResultSet for the desired rows. """ start_row = int(start_row) end_row = int(end_row) max_rows = end_row - start_row + 1 row_query = gdata.spreadsheet.service.ListQuery() row_query.start_index = str(start_row) row_query.max_results = str(max_rows) rows_feed = self.client._GetSpreadsheetsClient().GetListFeed( self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query) return RecordResultSet(rows_feed, self.client, self.spreadsheet_key, self.worksheet_id) def FindRecords(self, query_string): """Performs a query against the worksheet to find rows which match. For details on query string syntax see the section on sq under http://code.google.com/apis/spreadsheets/reference.html#list_Parameters Args: query_string: str Examples: 'name == john' to find all rows with john in the name column, '(cost < 19.50 and name != toy) or cost > 500' Returns: RecordResultSet with the first group of matches. """ row_query = gdata.spreadsheet.service.ListQuery() row_query.sq = query_string matching_feed = self.client._GetSpreadsheetsClient().GetListFeed( self.spreadsheet_key, wksht_id=self.worksheet_id, query=row_query) return RecordResultSet(matching_feed, self.client, self.spreadsheet_key, self.worksheet_id) class RecordResultSet(list): """A collection of rows which allows fetching of the next set of results. The server may not send all rows in the requested range because there are too many. Using this result set you can access the first set of results as if it is a list, then get the next batch (if there are more results) by calling GetNext(). """ def __init__(self, feed, client, spreadsheet_key, worksheet_id): self.client = client self.spreadsheet_key = spreadsheet_key self.worksheet_id = worksheet_id self.feed = feed list(self) for entry in self.feed.entry: self.append(Record(content=None, row_entry=entry, spreadsheet_key=spreadsheet_key, worksheet_id=worksheet_id, database_client=client)) def GetNext(self): """Fetches the next batch of rows in the result set. Returns: A new RecordResultSet. """ next_link = self.feed.GetNextLink() if next_link and next_link.href: new_feed = self.client._GetSpreadsheetsClient().Get(next_link.href, converter=gdata.spreadsheet.SpreadsheetsListFeedFromString) return RecordResultSet(new_feed, self.client, self.spreadsheet_key, self.worksheet_id) class Record(object): """Represents one row in a worksheet and provides a dictionary of values. Attributes: custom: dict Represents the contents of the row with cell values mapped to column headers. """ def __init__(self, content=None, row_entry=None, spreadsheet_key=None, worksheet_id=None, database_client=None): """Constructor for a record. Args: content: dict of strings Mapping of string values to column names. row_entry: gdata.spreadsheet.SpreadsheetsList The Atom entry representing this row in the worksheet. spreadsheet_key: str The ID of the spreadsheet in which this row belongs. worksheet_id: str The ID of the worksheet in which this row belongs. database_client: DatabaseClient The client which can be used to talk the Google Spreadsheets server to edit this row. """ self.entry = row_entry self.spreadsheet_key = spreadsheet_key self.worksheet_id = worksheet_id if row_entry: self.row_id = row_entry.id.text.split('/')[-1] else: self.row_id = None self.client = database_client self.content = content or {} if not content: self.ExtractContentFromEntry(row_entry) def ExtractContentFromEntry(self, entry): """Populates the content and row_id based on content of the entry. This method is used in the Record's contructor. Args: entry: gdata.spreadsheet.SpreadsheetsList The Atom entry representing this row in the worksheet. """ self.content = {} if entry: self.row_id = entry.id.text.split('/')[-1] for label, custom in entry.custom.iteritems(): self.content[label] = custom.text def Push(self): """Send the content of the record to spreadsheets to edit the row. All items in the content dictionary will be sent. Items which have been removed from the content may remain in the row. The content member of the record will not be modified so additional fields in the row might be absent from this local copy. """ self.entry = self.client._GetSpreadsheetsClient().UpdateRow(self.entry, self.content) def Pull(self): """Query Google Spreadsheets to get the latest data from the server. Fetches the entry for this row and repopulates the content dictionary with the data found in the row. """ if self.row_id: self.entry = self.client._GetSpreadsheetsClient().GetListFeed( self.spreadsheet_key, wksht_id=self.worksheet_id, row_id=self.row_id) self.ExtractContentFromEntry(self.entry) def Delete(self): self.client._GetSpreadsheetsClient().DeleteRow(self.entry) def ConvertStringsToColumnHeaders(proposed_headers): """Converts a list of strings to column names which spreadsheets accepts. When setting values in a record, the keys which represent column names must fit certain rules. They are all lower case, contain no spaces or special characters. If two columns have the same name after being sanitized, the columns further to the right have _2, _3 _4, etc. appended to them. If there are column names which consist of all special characters, or if the column header is blank, an obfuscated value will be used for a column name. This method does not handle blank column names or column names with only special characters. """ headers = [] for input_string in proposed_headers: # TODO: probably a more efficient way to do this. Perhaps regex. sanitized = input_string.lower().replace('_', '').replace( ':', '').replace(' ', '') # When the same sanitized header appears multiple times in the first row # of a spreadsheet, _n is appended to the name to make it unique. header_count = headers.count(sanitized) if header_count > 0: headers.append('%s_%i' % (sanitized, header_count+1)) else: headers.append(sanitized) return headers
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains extensions to Atom objects used with Google Spreadsheets. """ __author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)' try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata import re import string # XML namespaces which are often used in Google Spreadsheets entities. GSPREADSHEETS_NAMESPACE = 'http://schemas.google.com/spreadsheets/2006' GSPREADSHEETS_TEMPLATE = '{http://schemas.google.com/spreadsheets/2006}%s' GSPREADSHEETS_EXTENDED_NAMESPACE = ('http://schemas.google.com/spreadsheets' '/2006/extended') GSPREADSHEETS_EXTENDED_TEMPLATE = ('{http://schemas.google.com/spreadsheets' '/2006/extended}%s') class ColCount(atom.AtomBase): """The Google Spreadsheets colCount element """ _tag = 'colCount' _namespace = GSPREADSHEETS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def ColCountFromString(xml_string): return atom.CreateClassFromXMLString(ColCount, xml_string) class RowCount(atom.AtomBase): """The Google Spreadsheets rowCount element """ _tag = 'rowCount' _namespace = GSPREADSHEETS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def RowCountFromString(xml_string): return atom.CreateClassFromXMLString(RowCount, xml_string) class Cell(atom.AtomBase): """The Google Spreadsheets cell element """ _tag = 'cell' _namespace = GSPREADSHEETS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['row'] = 'row' _attributes['col'] = 'col' _attributes['inputValue'] = 'inputValue' _attributes['numericValue'] = 'numericValue' def __init__(self, text=None, row=None, col=None, inputValue=None, numericValue=None, extension_elements=None, extension_attributes=None): self.text = text self.row = row self.col = col self.inputValue = inputValue self.numericValue = numericValue self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def CellFromString(xml_string): return atom.CreateClassFromXMLString(Cell, xml_string) class Custom(atom.AtomBase): """The Google Spreadsheets custom element""" _namespace = GSPREADSHEETS_EXTENDED_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, column=None, text=None, extension_elements=None, extension_attributes=None): self.column = column # The name of the column self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def _BecomeChildElement(self, tree): new_child = ElementTree.Element('') tree.append(new_child) new_child.tag = '{%s}%s' % (self.__class__._namespace, self.column) self._AddMembersToElementTree(new_child) def _ToElementTree(self): new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace, self.column)) self._AddMembersToElementTree(new_tree) return new_tree def _HarvestElementTree(self, tree): namespace_uri, local_tag = string.split(tree.tag[1:], "}", 1) self.column = local_tag # Fill in the instance members from the contents of the XML tree. for child in tree: self._ConvertElementTreeToMember(child) for attribute, value in tree.attrib.iteritems(): self._ConvertElementAttributeToMember(attribute, value) self.text = tree.text def CustomFromString(xml_string): element_tree = ElementTree.fromstring(xml_string) return _CustomFromElementTree(element_tree) def _CustomFromElementTree(element_tree): namespace_uri, local_tag = string.split(element_tree.tag[1:], "}", 1) if namespace_uri == GSPREADSHEETS_EXTENDED_NAMESPACE: new_custom = Custom() new_custom._HarvestElementTree(element_tree) new_custom.column = local_tag return new_custom return None class SpreadsheetsSpreadsheet(gdata.GDataEntry): """A Google Spreadsheets flavor of a Spreadsheet Atom Entry """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, title=None, control=None, updated=None, text=None, extension_elements=None, extension_attributes=None): self.author = author or [] self.category = category or [] self.content = content self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.published = published self.rights = rights self.source = source self.summary = summary self.control = control self.title = title self.updated = updated self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SpreadsheetsSpreadsheetFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsSpreadsheet, xml_string) class SpreadsheetsWorksheet(gdata.GDataEntry): """A Google Spreadsheets flavor of a Worksheet Atom Entry """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}rowCount' % GSPREADSHEETS_NAMESPACE] = ('row_count', RowCount) _children['{%s}colCount' % GSPREADSHEETS_NAMESPACE] = ('col_count', ColCount) def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, title=None, control=None, updated=None, row_count=None, col_count=None, text=None, extension_elements=None, extension_attributes=None): self.author = author or [] self.category = category or [] self.content = content self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.published = published self.rights = rights self.source = source self.summary = summary self.control = control self.title = title self.updated = updated self.row_count = row_count self.col_count = col_count self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SpreadsheetsWorksheetFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsWorksheet, xml_string) class SpreadsheetsCell(gdata.BatchEntry): """A Google Spreadsheets flavor of a Cell Atom Entry """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.BatchEntry._children.copy() _attributes = gdata.BatchEntry._attributes.copy() _children['{%s}cell' % GSPREADSHEETS_NAMESPACE] = ('cell', Cell) def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, title=None, control=None, updated=None, cell=None, batch_operation=None, batch_id=None, batch_status=None, text=None, extension_elements=None, extension_attributes=None): self.author = author or [] self.category = category or [] self.content = content self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.published = published self.rights = rights self.source = source self.summary = summary self.control = control self.title = title self.batch_operation = batch_operation self.batch_id = batch_id self.batch_status = batch_status self.updated = updated self.cell = cell self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SpreadsheetsCellFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsCell, xml_string) class SpreadsheetsList(gdata.GDataEntry): """A Google Spreadsheets flavor of a List Atom Entry """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, title=None, control=None, updated=None, custom=None, text=None, extension_elements=None, extension_attributes=None): self.author = author or [] self.category = category or [] self.content = content self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.published = published self.rights = rights self.source = source self.summary = summary self.control = control self.title = title self.updated = updated self.custom = custom or {} self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} # We need to overwrite _ConvertElementTreeToMember to add special logic to # convert custom attributes to members def _ConvertElementTreeToMember(self, child_tree): # Find the element's tag in this class's list of child members if self.__class__._children.has_key(child_tree.tag): member_name = self.__class__._children[child_tree.tag][0] member_class = self.__class__._children[child_tree.tag][1] # If the class member is supposed to contain a list, make sure the # matching member is set to a list, then append the new member # instance to the list. if isinstance(member_class, list): if getattr(self, member_name) is None: setattr(self, member_name, []) getattr(self, member_name).append(atom._CreateClassFromElementTree( member_class[0], child_tree)) else: setattr(self, member_name, atom._CreateClassFromElementTree(member_class, child_tree)) elif child_tree.tag.find('{%s}' % GSPREADSHEETS_EXTENDED_NAMESPACE) == 0: # If this is in the custom namespace, make add it to the custom dict. name = child_tree.tag[child_tree.tag.index('}')+1:] custom = _CustomFromElementTree(child_tree) if custom: self.custom[name] = custom else: atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree) # We need to overwtite _AddMembersToElementTree to add special logic to # convert custom members to XML nodes. def _AddMembersToElementTree(self, tree): # Convert the members of this class which are XML child nodes. # This uses the class's _children dictionary to find the members which # should become XML child nodes. member_node_names = [values[0] for tag, values in self.__class__._children.iteritems()] for member_name in member_node_names: member = getattr(self, member_name) if member is None: pass elif isinstance(member, list): for instance in member: instance._BecomeChildElement(tree) else: member._BecomeChildElement(tree) # Convert the members of this class which are XML attributes. for xml_attribute, member_name in self.__class__._attributes.iteritems(): member = getattr(self, member_name) if member is not None: tree.attrib[xml_attribute] = member # Convert all special custom item attributes to nodes for name, custom in self.custom.iteritems(): custom._BecomeChildElement(tree) # Lastly, call the ExtensionContainers's _AddMembersToElementTree to # convert any extension attributes. atom.ExtensionContainer._AddMembersToElementTree(self, tree) def SpreadsheetsListFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsList, xml_string) element_tree = ElementTree.fromstring(xml_string) return _SpreadsheetsListFromElementTree(element_tree) class SpreadsheetsSpreadsheetsFeed(gdata.GDataFeed): """A feed containing Google Spreadsheets Spreadsheets""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [SpreadsheetsSpreadsheet]) def SpreadsheetsSpreadsheetsFeedFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsSpreadsheetsFeed, xml_string) class SpreadsheetsWorksheetsFeed(gdata.GDataFeed): """A feed containing Google Spreadsheets Spreadsheets""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [SpreadsheetsWorksheet]) def SpreadsheetsWorksheetsFeedFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsWorksheetsFeed, xml_string) class SpreadsheetsCellsFeed(gdata.BatchFeed): """A feed containing Google Spreadsheets Cells""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.BatchFeed._children.copy() _attributes = gdata.BatchFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [SpreadsheetsCell]) _children['{%s}rowCount' % GSPREADSHEETS_NAMESPACE] = ('row_count', RowCount) _children['{%s}colCount' % GSPREADSHEETS_NAMESPACE] = ('col_count', ColCount) 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, row_count=None, col_count=None, interrupted=None): gdata.BatchFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text, interrupted=interrupted) self.row_count = row_count self.col_count = col_count def GetBatchLink(self): for link in self.link: if link.rel == 'http://schemas.google.com/g/2005#batch': return link return None def SpreadsheetsCellsFeedFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsCellsFeed, xml_string) class SpreadsheetsListFeed(gdata.GDataFeed): """A feed containing Google Spreadsheets Spreadsheets""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [SpreadsheetsList]) def SpreadsheetsListFeedFromString(xml_string): return atom.CreateClassFromXMLString(SpreadsheetsListFeed, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """SpreadsheetsService extends the GDataService to streamline Google Spreadsheets operations. SpreadsheetService: Provides methods to query feeds and manipulate items. Extends GDataService. DictionaryToParamList: Function which converts a dictionary into a list of URL arguments (represented as strings). This is a utility function used in CRUD operations. """ __author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)' import gdata import atom.service import gdata.service import gdata.spreadsheet import atom class Error(Exception): """Base class for exceptions in this module.""" pass class RequestError(Error): pass class SpreadsheetsService(gdata.service.GDataService): """Client for the Google Spreadsheets service.""" def __init__(self, email=None, password=None, source=None, server='spreadsheets.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Spreadsheets service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'spreadsheets.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='wise', source=source, server=server, additional_headers=additional_headers, **kwargs) def GetSpreadsheetsFeed(self, key=None, query=None, visibility='private', projection='full'): """Gets a spreadsheets feed or a specific entry if a key is defined Args: key: string (optional) The spreadsheet key defined in /ccc?key= query: DocumentQuery (optional) Query parameters Returns: If there is no key, then a SpreadsheetsSpreadsheetsFeed. If there is a key, then a SpreadsheetsSpreadsheet. """ base_uri = 'https://%s/feeds/spreadsheets' % self.server uri = ('%s/%s/%s' % (base_uri, visibility, projection)) if key is not None: uri = '%s/%s' % (uri, key) if query != None: query.feed = base_uri query.visibility = visibility query.projection = projection uri = query.ToUri() if key: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsSpreadsheetFromString) else: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsSpreadsheetsFeedFromString) def GetWorksheetsFeed(self, key, wksht_id=None, query=None, visibility='private', projection='full'): """Gets a worksheets feed or a specific entry if a wksht is defined Args: key: string The spreadsheet key defined in /ccc?key= wksht_id: string (optional) The id for a specific worksheet entry query: DocumentQuery (optional) Query parameters Returns: If there is no wksht_id, then a SpreadsheetsWorksheetsFeed. If there is a wksht_id, then a SpreadsheetsWorksheet. """ uri = ('https://%s/feeds/worksheets/%s/%s/%s' % (self.server, key, visibility, projection)) if wksht_id != None: uri = '%s/%s' % (uri, wksht_id) if query != None: query.feed = uri uri = query.ToUri() if wksht_id: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString) else: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsWorksheetsFeedFromString) def AddWorksheet(self, title, row_count, col_count, key): """Creates a new worksheet in the desired spreadsheet. The new worksheet is appended to the end of the list of worksheets. The new worksheet will only have the available number of columns and cells specified. Args: title: str The title which will be displayed in the list of worksheets. row_count: int or str The number of rows in the new worksheet. col_count: int or str The number of columns in the new worksheet. key: str The spreadsheet key to the spreadsheet to which the new worksheet should be added. Returns: A SpreadsheetsWorksheet if the new worksheet was created succesfully. """ new_worksheet = gdata.spreadsheet.SpreadsheetsWorksheet( title=atom.Title(text=title), row_count=gdata.spreadsheet.RowCount(text=str(row_count)), col_count=gdata.spreadsheet.ColCount(text=str(col_count))) return self.Post(new_worksheet, 'https://%s/feeds/worksheets/%s/private/full' % (self.server, key), converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString) def UpdateWorksheet(self, worksheet_entry, url=None): """Changes the size and/or title of the desired worksheet. Args: worksheet_entry: SpreadsheetWorksheet The new contents of the worksheet. url: str (optional) The URL to which the edited worksheet entry should be sent. If the url is None, the edit URL from the worksheet will be used. Returns: A SpreadsheetsWorksheet with the new information about the worksheet. """ target_url = url or worksheet_entry.GetEditLink().href return self.Put(worksheet_entry, target_url, converter=gdata.spreadsheet.SpreadsheetsWorksheetFromString) def DeleteWorksheet(self, worksheet_entry=None, url=None): """Removes the desired worksheet from the spreadsheet Args: worksheet_entry: SpreadsheetWorksheet (optional) The worksheet to be deleted. If this is none, then the DELETE reqest is sent to the url specified in the url parameter. url: str (optaional) The URL to which the DELETE request should be sent. If left as None, the worksheet's edit URL is used. Returns: True if the worksheet was deleted successfully. """ if url: target_url = url else: target_url = worksheet_entry.GetEditLink().href return self.Delete(target_url) def GetCellsFeed(self, key, wksht_id='default', cell=None, query=None, visibility='private', projection='full'): """Gets a cells feed or a specific entry if a cell is defined Args: key: string The spreadsheet key defined in /ccc?key= wksht_id: string The id for a specific worksheet entry cell: string (optional) The R1C1 address of the cell query: DocumentQuery (optional) Query parameters Returns: If there is no cell, then a SpreadsheetsCellsFeed. If there is a cell, then a SpreadsheetsCell. """ uri = ('https://%s/feeds/cells/%s/%s/%s/%s' % (self.server, key, wksht_id, visibility, projection)) if cell != None: uri = '%s/%s' % (uri, cell) if query != None: query.feed = uri uri = query.ToUri() if cell: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsCellFromString) else: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString) def GetListFeed(self, key, wksht_id='default', row_id=None, query=None, visibility='private', projection='full'): """Gets a list feed or a specific entry if a row_id is defined Args: key: string The spreadsheet key defined in /ccc?key= wksht_id: string The id for a specific worksheet entry row_id: string (optional) The row_id of a row in the list query: DocumentQuery (optional) Query parameters Returns: If there is no row_id, then a SpreadsheetsListFeed. If there is a row_id, then a SpreadsheetsList. """ uri = ('https://%s/feeds/list/%s/%s/%s/%s' % (self.server, key, wksht_id, visibility, projection)) if row_id is not None: uri = '%s/%s' % (uri, row_id) if query is not None: query.feed = uri uri = query.ToUri() if row_id: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsListFromString) else: return self.Get(uri, converter=gdata.spreadsheet.SpreadsheetsListFeedFromString) def UpdateCell(self, row, col, inputValue, key, wksht_id='default'): """Updates an existing cell. Args: row: int The row the cell to be editted is in col: int The column the cell to be editted is in inputValue: str the new value of the cell key: str The key of the spreadsheet in which this cell resides. wksht_id: str The ID of the worksheet which holds this cell. Returns: The updated cell entry """ row = str(row) col = str(col) # make the new cell new_cell = gdata.spreadsheet.Cell(row=row, col=col, inputValue=inputValue) # get the edit uri and PUT cell = 'R%sC%s' % (row, col) entry = self.GetCellsFeed(key, wksht_id, cell) for a_link in entry.link: if a_link.rel == 'edit': entry.cell = new_cell return self.Put(entry, a_link.href, converter=gdata.spreadsheet.SpreadsheetsCellFromString) def _GenerateCellsBatchUrl(self, spreadsheet_key, worksheet_id): return ('https://spreadsheets.google.com/feeds/cells/%s/%s/' 'private/full/batch' % (spreadsheet_key, worksheet_id)) def ExecuteBatch(self, batch_feed, url=None, spreadsheet_key=None, worksheet_id=None, converter=gdata.spreadsheet.SpreadsheetsCellsFeedFromString): """Sends a batch request feed to the server. The batch request needs to be sent to the batch URL for a particular worksheet. You can specify the worksheet by providing the spreadsheet_key and worksheet_id, or by sending the URL from the cells feed's batch link. Args: batch_feed: gdata.spreadsheet.SpreadsheetsCellFeed A feed containing BatchEntry elements which contain the desired CRUD operation and any necessary data to modify a cell. url: str (optional) The batch URL for the cells feed to which these changes should be applied. This can be found by calling cells_feed.GetBatchLink().href. spreadsheet_key: str (optional) Used to generate the batch request URL if the url argument is None. If using the spreadsheet key to generate the URL, the worksheet id is also required. worksheet_id: str (optional) Used if the url is not provided, it is oart of the batch feed target URL. This is used with the spreadsheet key. converter: Function (optional) Function to be executed on the server's response. This function should take one string as a parameter. The default value is SpreadsheetsCellsFeedFromString which will turn the result into a gdata.spreadsheet.SpreadsheetsCellsFeed object. Returns: A gdata.BatchFeed containing the results. """ if url is None: url = self._GenerateCellsBatchUrl(spreadsheet_key, worksheet_id) return self.Post(batch_feed, url, converter=converter) def InsertRow(self, row_data, key, wksht_id='default'): """Inserts a new row with the provided data Args: uri: string The post uri of the list feed row_data: dict A dictionary of column header to row data Returns: The inserted row """ new_entry = gdata.spreadsheet.SpreadsheetsList() for k, v in row_data.iteritems(): new_custom = gdata.spreadsheet.Custom() new_custom.column = k new_custom.text = v new_entry.custom[new_custom.column] = new_custom # Generate the post URL for the worksheet which will receive the new entry. post_url = 'https://spreadsheets.google.com/feeds/list/%s/%s/private/full'%( key, wksht_id) return self.Post(new_entry, post_url, converter=gdata.spreadsheet.SpreadsheetsListFromString) def UpdateRow(self, entry, new_row_data): """Updates a row with the provided data If you want to add additional information to a row, it is often easier to change the values in entry.custom, then use the Put method instead of UpdateRow. This UpdateRow method will replace the contents of the row with new_row_data - it will change all columns not just the columns specified in the new_row_data dict. Args: entry: gdata.spreadsheet.SpreadsheetsList The entry to be updated new_row_data: dict A dictionary of column header to row data Returns: The updated row """ entry.custom = {} for k, v in new_row_data.iteritems(): new_custom = gdata.spreadsheet.Custom() new_custom.column = k new_custom.text = v entry.custom[k] = new_custom for a_link in entry.link: if a_link.rel == 'edit': return self.Put(entry, a_link.href, converter=gdata.spreadsheet.SpreadsheetsListFromString) def DeleteRow(self, entry): """Deletes a row, the provided entry Args: entry: gdata.spreadsheet.SpreadsheetsList The row to be deleted Returns: The delete response """ for a_link in entry.link: if a_link.rel == 'edit': return self.Delete(a_link.href) class DocumentQuery(gdata.service.Query): def _GetTitleQuery(self): return self['title'] def _SetTitleQuery(self, document_query): self['title'] = document_query title = property(_GetTitleQuery, _SetTitleQuery, doc="""The title query parameter""") def _GetTitleExactQuery(self): return self['title-exact'] def _SetTitleExactQuery(self, document_query): self['title-exact'] = document_query title_exact = property(_GetTitleExactQuery, _SetTitleExactQuery, doc="""The title-exact query parameter""") class CellQuery(gdata.service.Query): def _GetMinRowQuery(self): return self['min-row'] def _SetMinRowQuery(self, cell_query): self['min-row'] = cell_query min_row = property(_GetMinRowQuery, _SetMinRowQuery, doc="""The min-row query parameter""") def _GetMaxRowQuery(self): return self['max-row'] def _SetMaxRowQuery(self, cell_query): self['max-row'] = cell_query max_row = property(_GetMaxRowQuery, _SetMaxRowQuery, doc="""The max-row query parameter""") def _GetMinColQuery(self): return self['min-col'] def _SetMinColQuery(self, cell_query): self['min-col'] = cell_query min_col = property(_GetMinColQuery, _SetMinColQuery, doc="""The min-col query parameter""") def _GetMaxColQuery(self): return self['max-col'] def _SetMaxColQuery(self, cell_query): self['max-col'] = cell_query max_col = property(_GetMaxColQuery, _SetMaxColQuery, doc="""The max-col query parameter""") def _GetRangeQuery(self): return self['range'] def _SetRangeQuery(self, cell_query): self['range'] = cell_query range = property(_GetRangeQuery, _SetRangeQuery, doc="""The range query parameter""") def _GetReturnEmptyQuery(self): return self['return-empty'] def _SetReturnEmptyQuery(self, cell_query): self['return-empty'] = cell_query return_empty = property(_GetReturnEmptyQuery, _SetReturnEmptyQuery, doc="""The return-empty query parameter""") class ListQuery(gdata.service.Query): def _GetSpreadsheetQuery(self): return self['sq'] def _SetSpreadsheetQuery(self, list_query): self['sq'] = list_query sq = property(_GetSpreadsheetQuery, _SetSpreadsheetQuery, doc="""The sq query parameter""") def _GetOrderByQuery(self): return self['orderby'] def _SetOrderByQuery(self, list_query): self['orderby'] = list_query orderby = property(_GetOrderByQuery, _SetOrderByQuery, doc="""The orderby query parameter""") def _GetReverseQuery(self): return self['reverse'] def _SetReverseQuery(self, list_query): self['reverse'] = list_query reverse = property(_GetReverseQuery, _SetReverseQuery, doc="""The reverse query parameter""")
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the data classes of the Google Access Control List (ACL) Extension""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import atom.data import gdata.data import gdata.opensearch.data GACL_TEMPLATE = '{http://schemas.google.com/acl/2007}%s' class AclRole(atom.core.XmlElement): """Describes the role of an entry in an access control list.""" _qname = GACL_TEMPLATE % 'role' value = 'value' class AclAdditionalRole(atom.core.XmlElement): """Describes an additionalRole element.""" _qname = GACL_TEMPLATE % 'additionalRole' value = 'value' class AclScope(atom.core.XmlElement): """Describes the scope of an entry in an access control list.""" _qname = GACL_TEMPLATE % 'scope' type = 'type' value = 'value' class AclWithKey(atom.core.XmlElement): """Describes a key that can be used to access a document.""" _qname = GACL_TEMPLATE % 'withKey' key = 'key' role = AclRole additional_role = AclAdditionalRole class AclEntry(gdata.data.GDEntry): """Describes an entry in a feed of an access control list (ACL).""" scope = AclScope role = AclRole with_key = AclWithKey additional_role = AclAdditionalRole class AclFeed(gdata.data.GDFeed): """Describes a feed of an access control list (ACL).""" entry = [AclEntry]
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model classes for parsing and generating XML for the Blogger API.""" __author__ = 'j.s@google.com (Jeff Scudder)' import re import urlparse import atom.core import gdata.data LABEL_SCHEME = 'http://www.blogger.com/atom/ns#' THR_TEMPLATE = '{http://purl.org/syndication/thread/1.0}%s' BLOG_NAME_PATTERN = re.compile('(http://)(\w*)') BLOG_ID_PATTERN = re.compile('(tag:blogger.com,1999:blog-)(\w*)') BLOG_ID2_PATTERN = re.compile('tag:blogger.com,1999:user-(\d+)\.blog-(\d+)') POST_ID_PATTERN = re.compile( '(tag:blogger.com,1999:blog-)(\w*)(.post-)(\w*)') PAGE_ID_PATTERN = re.compile( '(tag:blogger.com,1999:blog-)(\w*)(.page-)(\w*)') COMMENT_ID_PATTERN = re.compile('.*-(\w*)$') class BloggerEntry(gdata.data.GDEntry): """Adds convenience methods inherited by all Blogger entries.""" def get_blog_id(self): """Extracts the Blogger id of this blog. This method is useful when contructing URLs by hand. The blog id is often used in blogger operation URLs. This should not be confused with the id member of a BloggerBlog. The id element is the Atom id XML element. The blog id which this method returns is a part of the Atom id. Returns: The blog's unique id as a string. """ if self.id.text: match = BLOG_ID_PATTERN.match(self.id.text) if match: return match.group(2) else: return BLOG_ID2_PATTERN.match(self.id.text).group(2) return None GetBlogId = get_blog_id def get_blog_name(self): """Finds the name of this blog as used in the 'alternate' URL. An alternate URL is in the form 'http://blogName.blogspot.com/'. For an entry representing the above example, this method would return 'blogName'. Returns: The blog's URL name component as a string. """ for link in self.link: if link.rel == 'alternate': return urlparse.urlparse(link.href)[1].split(".", 1)[0] return None GetBlogName = get_blog_name class Blog(BloggerEntry): """Represents a blog which belongs to the user.""" class BlogFeed(gdata.data.GDFeed): entry = [Blog] class BlogPost(BloggerEntry): """Represents a single post on a blog.""" def add_label(self, label): """Adds a label to the blog post. The label is represented by an Atom category element, so this method is shorthand for appending a new atom.Category object. Args: label: str """ self.category.append(atom.data.Category(scheme=LABEL_SCHEME, term=label)) AddLabel = add_label def get_post_id(self): """Extracts the postID string from the entry's Atom id. Returns: A string of digits which identify this post within the blog. """ if self.id.text: return POST_ID_PATTERN.match(self.id.text).group(4) return None GetPostId = get_post_id class BlogPostFeed(gdata.data.GDFeed): entry = [BlogPost] class BlogPage(BloggerEntry): """Represents a single page on a blog.""" def get_page_id(self): """Extracts the pageID string from entry's Atom id. Returns: A string of digits which identify this post within the blog. """ if self.id.text: return PAGE_ID_PATTERN.match(self.id.text).group(4) return None GetPageId = get_page_id class BlogPageFeed(gdata.data.GDFeed): entry = [BlogPage] class InReplyTo(atom.core.XmlElement): _qname = THR_TEMPLATE % 'in-reply-to' href = 'href' ref = 'ref' source = 'source' type = 'type' class Comment(BloggerEntry): """Blog post comment entry in a feed listing comments on a post or blog.""" in_reply_to = InReplyTo def get_comment_id(self): """Extracts the commentID string from the entry's Atom id. Returns: A string of digits which identify this post within the blog. """ if self.id.text: return COMMENT_ID_PATTERN.match(self.id.text).group(1) return None GetCommentId = get_comment_id class CommentFeed(gdata.data.GDFeed): entry = [Comment]
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains a client to communicate with the Blogger servers. For documentation on the Blogger API, see: http://code.google.com/apis/blogger/ """ __author__ = 'j.s@google.com (Jeff Scudder)' import gdata.client import gdata.gauth import gdata.blogger.data import atom.data import atom.http_core # List user's blogs, takes a user ID, or 'default'. BLOGS_URL = 'http://www.blogger.com/feeds/%s/blogs' # Takes a blog ID. BLOG_POST_URL = 'http://www.blogger.com/feeds/%s/posts/default' # Takes a blog ID. BLOG_PAGE_URL = 'http://www.blogger.com/feeds/%s/pages/default' # Takes a blog ID and post ID. BLOG_POST_COMMENTS_URL = 'http://www.blogger.com/feeds/%s/%s/comments/default' # Takes a blog ID. BLOG_COMMENTS_URL = 'http://www.blogger.com/feeds/%s/comments/default' # Takes a blog ID. BLOG_ARCHIVE_URL = 'http://www.blogger.com/feeds/%s/archive/full' class BloggerClient(gdata.client.GDClient): api_version = '2' auth_service = 'blogger' auth_scopes = gdata.gauth.AUTH_SCOPES['blogger'] def get_blogs(self, user_id='default', auth_token=None, desired_class=gdata.blogger.data.BlogFeed, **kwargs): return self.get_feed(BLOGS_URL % user_id, auth_token=auth_token, desired_class=desired_class, **kwargs) GetBlogs = get_blogs def get_posts(self, blog_id, auth_token=None, desired_class=gdata.blogger.data.BlogPostFeed, query=None, **kwargs): return self.get_feed(BLOG_POST_URL % blog_id, auth_token=auth_token, desired_class=desired_class, query=query, **kwargs) GetPosts = get_posts def get_pages(self, blog_id, auth_token=None, desired_class=gdata.blogger.data.BlogPageFeed, query=None, **kwargs): return self.get_feed(BLOG_PAGE_URL % blog_id, auth_token=auth_token, desired_class=desired_class, query=query, **kwargs) GetPages = get_pages def get_post_comments(self, blog_id, post_id, auth_token=None, desired_class=gdata.blogger.data.CommentFeed, query=None, **kwargs): return self.get_feed(BLOG_POST_COMMENTS_URL % (blog_id, post_id), auth_token=auth_token, desired_class=desired_class, query=query, **kwargs) GetPostComments = get_post_comments def get_blog_comments(self, blog_id, auth_token=None, desired_class=gdata.blogger.data.CommentFeed, query=None, **kwargs): return self.get_feed(BLOG_COMMENTS_URL % blog_id, auth_token=auth_token, desired_class=desired_class, query=query, **kwargs) GetBlogComments = get_blog_comments def get_blog_archive(self, blog_id, auth_token=None, **kwargs): return self.get_feed(BLOG_ARCHIVE_URL % blog_id, auth_token=auth_token, **kwargs) GetBlogArchive = get_blog_archive def add_post(self, blog_id, title, body, labels=None, draft=False, auth_token=None, title_type='text', body_type='html', **kwargs): # Construct an atom Entry for the blog post to be sent to the server. new_entry = gdata.blogger.data.BlogPost( title=atom.data.Title(text=title, type=title_type), content=atom.data.Content(text=body, type=body_type)) if labels: for label in labels: new_entry.add_label(label) if draft: new_entry.control = atom.data.Control(draft=atom.data.Draft(text='yes')) return self.post(new_entry, BLOG_POST_URL % blog_id, auth_token=auth_token, **kwargs) AddPost = add_post def add_page(self, blog_id, title, body, draft=False, auth_token=None, title_type='text', body_type='html', **kwargs): new_entry = gdata.blogger.data.BlogPage( title=atom.data.Title(text=title, type=title_type), content=atom.data.Content(text=body, type=body_type)) if draft: new_entry.control = atom.data.Control(draft=atom.data.Draft(text='yes')) return self.post(new_entry, BLOG_PAGE_URL % blog_id, auth_token=auth_token, **kwargs) AddPage = add_page def add_comment(self, blog_id, post_id, body, auth_token=None, title_type='text', body_type='html', **kwargs): new_entry = gdata.blogger.data.Comment( content=atom.data.Content(text=body, type=body_type)) return self.post(new_entry, BLOG_POST_COMMENTS_URL % (blog_id, post_id), auth_token=auth_token, **kwargs) AddComment = add_comment def update(self, entry, auth_token=None, **kwargs): # The Blogger API does not currently support ETags, so for now remove # the ETag before performing an update. old_etag = entry.etag entry.etag = None response = gdata.client.GDClient.update(self, entry, auth_token=auth_token, **kwargs) entry.etag = old_etag return response Update = update def delete(self, entry_or_uri, auth_token=None, **kwargs): if isinstance(entry_or_uri, (str, unicode, atom.http_core.Uri)): return gdata.client.GDClient.delete(self, entry_or_uri, auth_token=auth_token, **kwargs) # The Blogger API does not currently support ETags, so for now remove # the ETag before performing a delete. old_etag = entry_or_uri.etag entry_or_uri.etag = None response = gdata.client.GDClient.delete(self, entry_or_uri, auth_token=auth_token, **kwargs) # TODO: if GDClient.delete raises and exception, the entry's etag may be # left as None. Should revisit this logic. entry_or_uri.etag = old_etag return response Delete = delete class Query(gdata.client.Query): def __init__(self, order_by=None, **kwargs): gdata.client.Query.__init__(self, **kwargs) self.order_by = order_by def modify_request(self, http_request): gdata.client._add_query_param('orderby', self.order_by, http_request) gdata.client.Query.modify_request(self, http_request) ModifyRequest = modify_request
Python
#!/usr/bin/python # # Copyright (C) 2007, 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains extensions to Atom objects used with Blogger.""" __author__ = 'api.jscudder (Jeffrey Scudder)' import atom import gdata import re LABEL_SCHEME = 'http://www.blogger.com/atom/ns#' THR_NAMESPACE = 'http://purl.org/syndication/thread/1.0' class BloggerEntry(gdata.GDataEntry): """Adds convenience methods inherited by all Blogger entries.""" blog_name_pattern = re.compile('(http://)(\w*)') blog_id_pattern = re.compile('(tag:blogger.com,1999:blog-)(\w*)') blog_id2_pattern = re.compile('tag:blogger.com,1999:user-(\d+)\.blog-(\d+)') def GetBlogId(self): """Extracts the Blogger id of this blog. This method is useful when contructing URLs by hand. The blog id is often used in blogger operation URLs. This should not be confused with the id member of a BloggerBlog. The id element is the Atom id XML element. The blog id which this method returns is a part of the Atom id. Returns: The blog's unique id as a string. """ if self.id.text: match = self.blog_id_pattern.match(self.id.text) if match: return match.group(2) else: return self.blog_id2_pattern.match(self.id.text).group(2) return None def GetBlogName(self): """Finds the name of this blog as used in the 'alternate' URL. An alternate URL is in the form 'http://blogName.blogspot.com/'. For an entry representing the above example, this method would return 'blogName'. Returns: The blog's URL name component as a string. """ for link in self.link: if link.rel == 'alternate': return self.blog_name_pattern.match(link.href).group(2) return None class BlogEntry(BloggerEntry): """Describes a blog entry in the feed listing a user's blogs.""" def BlogEntryFromString(xml_string): return atom.CreateClassFromXMLString(BlogEntry, xml_string) class BlogFeed(gdata.GDataFeed): """Describes a feed of a user's blogs.""" _children = gdata.GDataFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BlogEntry]) def BlogFeedFromString(xml_string): return atom.CreateClassFromXMLString(BlogFeed, xml_string) class BlogPostEntry(BloggerEntry): """Describes a blog post entry in the feed of a blog's posts.""" post_id_pattern = re.compile('(tag:blogger.com,1999:blog-)(\w*)(.post-)(\w*)') def AddLabel(self, label): """Adds a label to the blog post. The label is represented by an Atom category element, so this method is shorthand for appending a new atom.Category object. Args: label: str """ self.category.append(atom.Category(scheme=LABEL_SCHEME, term=label)) def GetPostId(self): """Extracts the postID string from the entry's Atom id. Returns: A string of digits which identify this post within the blog. """ if self.id.text: return self.post_id_pattern.match(self.id.text).group(4) return None def BlogPostEntryFromString(xml_string): return atom.CreateClassFromXMLString(BlogPostEntry, xml_string) class BlogPostFeed(gdata.GDataFeed): """Describes a feed of a blog's posts.""" _children = gdata.GDataFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BlogPostEntry]) def BlogPostFeedFromString(xml_string): return atom.CreateClassFromXMLString(BlogPostFeed, xml_string) class InReplyTo(atom.AtomBase): _tag = 'in-reply-to' _namespace = THR_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['href'] = 'href' _attributes['ref'] = 'ref' _attributes['source'] = 'source' _attributes['type'] = 'type' def __init__(self, href=None, ref=None, source=None, type=None, extension_elements=None, extension_attributes=None, text=None): self.href = href self.ref = ref self.source = source self.type = type self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text def InReplyToFromString(xml_string): return atom.CreateClassFromXMLString(InReplyTo, xml_string) class CommentEntry(BloggerEntry): """Describes a blog post comment entry in the feed of a blog post's comments.""" _children = BloggerEntry._children.copy() _children['{%s}in-reply-to' % THR_NAMESPACE] = ('in_reply_to', InReplyTo) comment_id_pattern = re.compile('.*-(\w*)$') def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, control=None, title=None, updated=None, in_reply_to=None, extension_elements=None, extension_attributes=None, text=None): BloggerEntry.__init__(self, author=author, category=category, content=content, contributor=contributor, atom_id=atom_id, link=link, published=published, rights=rights, source=source, summary=summary, control=control, title=title, updated=updated, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.in_reply_to = in_reply_to def GetCommentId(self): """Extracts the commentID string from the entry's Atom id. Returns: A string of digits which identify this post within the blog. """ if self.id.text: return self.comment_id_pattern.match(self.id.text).group(1) return None def CommentEntryFromString(xml_string): return atom.CreateClassFromXMLString(CommentEntry, xml_string) class CommentFeed(gdata.GDataFeed): """Describes a feed of a blog post's comments.""" _children = gdata.GDataFeed._children.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CommentEntry]) def CommentFeedFromString(xml_string): return atom.CreateClassFromXMLString(CommentFeed, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Classes to interact with the Blogger server.""" __author__ = 'api.jscudder (Jeffrey Scudder)' import gdata.service import gdata.blogger class BloggerService(gdata.service.GDataService): def __init__(self, email=None, password=None, source=None, server='www.blogger.com', **kwargs): """Creates a client for the Blogger service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'www.blogger.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='blogger', source=source, server=server, **kwargs) def GetBlogFeed(self, uri=None): """Retrieve a list of the blogs to which the current user may manage.""" if not uri: uri = '/feeds/default/blogs' return self.Get(uri, converter=gdata.blogger.BlogFeedFromString) def GetBlogCommentFeed(self, blog_id=None, uri=None): """Retrieve a list of the comments for this blog.""" if blog_id: uri = '/feeds/%s/comments/default' % blog_id return self.Get(uri, converter=gdata.blogger.CommentFeedFromString) def GetBlogPostFeed(self, blog_id=None, uri=None): if blog_id: uri = '/feeds/%s/posts/default' % blog_id return self.Get(uri, converter=gdata.blogger.BlogPostFeedFromString) def GetPostCommentFeed(self, blog_id=None, post_id=None, uri=None): """Retrieve a list of the comments for this particular blog post.""" if blog_id and post_id: uri = '/feeds/%s/%s/comments/default' % (blog_id, post_id) return self.Get(uri, converter=gdata.blogger.CommentFeedFromString) def AddPost(self, entry, blog_id=None, uri=None): if blog_id: uri = '/feeds/%s/posts/default' % blog_id return self.Post(entry, uri, converter=gdata.blogger.BlogPostEntryFromString) def UpdatePost(self, entry, uri=None): if not uri: uri = entry.GetEditLink().href return self.Put(entry, uri, converter=gdata.blogger.BlogPostEntryFromString) def DeletePost(self, entry=None, uri=None): if not uri: uri = entry.GetEditLink().href return self.Delete(uri) def AddComment(self, comment_entry, blog_id=None, post_id=None, uri=None): """Adds a new comment to the specified blog post.""" if blog_id and post_id: uri = '/feeds/%s/%s/comments/default' % (blog_id, post_id) return self.Post(comment_entry, uri, converter=gdata.blogger.CommentEntryFromString) def DeleteComment(self, entry=None, uri=None): if not uri: uri = entry.GetEditLink().href return self.Delete(uri) class BlogQuery(gdata.service.Query): def __init__(self, feed=None, params=None, categories=None, blog_id=None): """Constructs a query object for the list of a user's Blogger blogs. Args: feed: str (optional) The beginning of the URL to be queried. If the feed is not set, and there is no blog_id passed in, the default value is used ('/feeds/default/blogs'). params: dict (optional) categories: list (optional) blog_id: str (optional) """ if not feed and blog_id: feed = '/feeds/default/blogs/%s' % blog_id elif not feed: feed = '/feeds/default/blogs' gdata.service.Query.__init__(self, feed=feed, params=params, categories=categories) class BlogPostQuery(gdata.service.Query): def __init__(self, feed=None, params=None, categories=None, blog_id=None, post_id=None): if not feed and blog_id and post_id: feed = '/feeds/%s/posts/default/%s' % (blog_id, post_id) elif not feed and blog_id: feed = '/feeds/%s/posts/default' % blog_id gdata.service.Query.__init__(self, feed=feed, params=params, categories=categories) class BlogCommentQuery(gdata.service.Query): def __init__(self, feed=None, params=None, categories=None, blog_id=None, post_id=None, comment_id=None): if not feed and blog_id and comment_id: feed = '/feeds/%s/comments/default/%s' % (blog_id, comment_id) elif not feed and blog_id and post_id: feed = '/feeds/%s/%s/comments/default' % (blog_id, post_id) elif not feed and blog_id: feed = '/feeds/%s/comments/default' % blog_id gdata.service.Query.__init__(self, feed=feed, params=params, categories=categories)
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the data classes of the OpenSearch Extension""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core OPENSEARCH_TEMPLATE_V1 = '{http://a9.com/-/spec/opensearchrss/1.0//}%s' OPENSEARCH_TEMPLATE_V2 = '{http://a9.com/-/spec/opensearch/1.1//}%s' class ItemsPerPage(atom.core.XmlElement): """Describes the number of items that will be returned per page for paged feeds""" _qname = (OPENSEARCH_TEMPLATE_V1 % 'itemsPerPage', OPENSEARCH_TEMPLATE_V2 % 'itemsPerPage') class StartIndex(atom.core.XmlElement): """Describes the starting index of the contained entries for paged feeds""" _qname = (OPENSEARCH_TEMPLATE_V1 % 'startIndex', OPENSEARCH_TEMPLATE_V2 % 'startIndex') class TotalResults(atom.core.XmlElement): """Describes the total number of results associated with this feed""" _qname = (OPENSEARCH_TEMPLATE_V1 % 'totalResults', OPENSEARCH_TEMPLATE_V2 % 'totalResults')
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model for parsing and generating XML for the Google Apps Marketplace Licensing API.""" __author__ = 'Alexandre Vivien <alex@simplecode.fr>' import atom.core import gdata import gdata.data LICENSES_NAMESPACE = 'http://www.w3.org/2005/Atom' LICENSES_TEMPLATE = '{%s}%%s' % LICENSES_NAMESPACE class Enabled(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'enabled' class Id(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'id' class CustomerId(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'customerid' class DomainName(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'domainname' class InstallerEmail(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'installeremail' class TosAcceptanceTime(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'tosacceptancetime' class LastChangeTime(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'lastchangetime' class ProductConfigId(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'productconfigid' class State(atom.core.XmlElement): """ """ _qname = LICENSES_TEMPLATE % 'state' class Entity(atom.core.XmlElement): """ The entity representing the License. """ _qname = LICENSES_TEMPLATE % 'entity' enabled = Enabled id = Id customer_id = CustomerId domain_name = DomainName installer_email = InstallerEmail tos_acceptance_time = TosAcceptanceTime last_change_time = LastChangeTime product_config_id = ProductConfigId state = State class Content(atom.data.Content): entity = Entity class LicenseEntry(gdata.data.GDEntry): """ Represents a LicenseEntry object. """ content = Content class LicenseFeed(gdata.data.GDFeed): """ Represents a feed of LicenseEntry objects. """ # Override entry so that this feed knows how to type its list of entries. entry = [LicenseEntry]
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """LicensingClient simplifies Google Apps Marketplace Licensing API calls. LicensingClient extends gdata.client.GDClient to ease interaction with the Google Apps Marketplace Licensing API. These interactions include the ability to retrieve License informations for an application in the Google Apps Marketplace. """ __author__ = 'Alexandre Vivien <alex@simplecode.fr>' import gdata.marketplace.data import gdata.client import urllib # Feed URI template. This must end with a / # The strings in this template are eventually replaced with the API version # and Google Apps domain name, respectively. LICENSE_ROOT_URL = 'http://feedserver-enterprise.googleusercontent.com' LICENSE_FEED_TEMPLATE = '%s/license?bq=' % LICENSE_ROOT_URL LICENSE_NOTIFICATIONS_FEED_TEMPLATE = '%s/licensenotification?bq=' % LICENSE_ROOT_URL class LicensingClient(gdata.client.GDClient): """Client extension for the Google Apps Marketplace Licensing API service. Attributes: host: string The hostname for the Google Apps Marketplace Licensing API service. api_version: string The version of the Google Apps Marketplace Licensing API. """ api_version = '1.0' auth_service = 'apps' auth_scopes = gdata.gauth.AUTH_SCOPES['apps'] ssl = False def __init__(self, domain, auth_token=None, **kwargs): """Constructs a new client for the Google Apps Marketplace Licensing API. Args: domain: string The Google Apps domain with the application installed. auth_token: (optional) gdata.gauth.OAuthToken which authorizes this client to retrieve the License information. 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_license_feed_uri(self, app_id=None, params=None): """Creates a license feed URI for the Google Apps Marketplace Licensing API. Using this client's Google Apps domain, create a license feed URI for a particular application in this domain. If params are provided, append them as GET params. Args: app_id: string The ID of the application for which to make a license feed URI. params: dict (optional) key -> value params to append as GET vars to the URI. Example: params={'start': 'my-resource-id'} Returns: A string giving the URI for the application's license for this client's Google Apps domain. """ parameters = '[appid=%s][domain=%s]' % (app_id, self.domain) uri = LICENSE_FEED_TEMPLATE + urllib.quote_plus(parameters) if params: uri += '&' + urllib.urlencode(params) return uri MakeLicenseFeedUri = make_license_feed_uri def make_license_notifications_feed_uri(self, app_id=None, startdatetime=None, max_results=None, params=None): """Creates a license notifications feed URI for the Google Apps Marketplace Licensing API. Using this client's Google Apps domain, create a license notifications feed URI for a particular application. If params are provided, append them as GET params. Args: app_id: string The ID of the application for which to make a license feed URI. startdatetime: Start date to retrieve the License notifications. max_results: Number of results per page. Maximum is 100. params: dict (optional) key -> value params to append as GET vars to the URI. Example: params={'start': 'my-resource-id'} Returns: A string giving the URI for the application's license notifications for this client's Google Apps domain. """ parameters = '[appid=%s]' % (app_id) if startdatetime: parameters += '[startdatetime=%s]' % startdatetime else: parameters += '[startdatetime=1970-01-01T00:00:00Z]' if max_results: parameters += '[max-results=%s]' % max_results else: parameters += '[max-results=100]' uri = LICENSE_NOTIFICATIONS_FEED_TEMPLATE + urllib.quote_plus(parameters) if params: uri += '&' + urllib.urlencode(params) return uri MakeLicenseNotificationsFeedUri = make_license_notifications_feed_uri def get_license(self, uri=None, app_id=None, **kwargs): """Fetches the application's license by application ID. Args: uri: string The base URI of the feed from which to fetch the license. app_id: string The string ID of the application for which to fetch the license. kwargs: The other parameters to pass to gdata.client.GDClient.get_entry(). Returns: A License feed object representing the license with the given base URI and application ID. """ if uri is None: uri = self.MakeLicenseFeedUri(app_id) return self.get_feed(uri, desired_class=gdata.marketplace.data.LicenseFeed, **kwargs) GetLicense = get_license def get_license_notifications(self, uri=None, app_id=None, startdatetime=None, max_results=None, **kwargs): """Fetches the application's license notifications by application ID. Args: uri: string The base URI of the feed from which to fetch the license. app_id: string The string ID of the application for which to fetch the license. startdatetime: Start date to retrieve the License notifications. max_results: Number of results per page. Maximum is 100. kwargs: The other parameters to pass to gdata.client.GDClient.get_entry(). Returns: A License feed object representing the license notifications with the given base URI and application ID. """ if uri is None: uri = self.MakeLicenseNotificationsFeedUri(app_id, startdatetime, max_results) return self.get_feed(uri, desired_class=gdata.marketplace.data.LicenseFeed, **kwargs) GetLicenseNotifications = get_license_notifications
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model classes for parsing and generating XML for the Sites Data API.""" __author__ = 'e.bidelman (Eric Bidelman)' import atom.core import atom.data import gdata.acl.data import gdata.data # XML Namespaces used in Google Sites entities. SITES_NAMESPACE = 'http://schemas.google.com/sites/2008' SITES_TEMPLATE = '{http://schemas.google.com/sites/2008}%s' SPREADSHEETS_NAMESPACE = 'http://schemas.google.com/spreadsheets/2006' SPREADSHEETS_TEMPLATE = '{http://schemas.google.com/spreadsheets/2006}%s' DC_TERMS_TEMPLATE = '{http://purl.org/dc/terms}%s' THR_TERMS_TEMPLATE = '{http://purl.org/syndication/thread/1.0}%s' XHTML_NAMESPACE = 'http://www.w3.org/1999/xhtml' XHTML_TEMPLATE = '{http://www.w3.org/1999/xhtml}%s' SITES_PARENT_LINK_REL = SITES_NAMESPACE + '#parent' SITES_REVISION_LINK_REL = SITES_NAMESPACE + '#revision' SITES_SOURCE_LINK_REL = SITES_NAMESPACE + '#source' SITES_KIND_SCHEME = 'http://schemas.google.com/g/2005#kind' ANNOUNCEMENT_KIND_TERM = SITES_NAMESPACE + '#announcement' ANNOUNCEMENT_PAGE_KIND_TERM = SITES_NAMESPACE + '#announcementspage' ATTACHMENT_KIND_TERM = SITES_NAMESPACE + '#attachment' COMMENT_KIND_TERM = SITES_NAMESPACE + '#comment' FILECABINET_KIND_TERM = SITES_NAMESPACE + '#filecabinet' LISTITEM_KIND_TERM = SITES_NAMESPACE + '#listitem' LISTPAGE_KIND_TERM = SITES_NAMESPACE + '#listpage' WEBPAGE_KIND_TERM = SITES_NAMESPACE + '#webpage' WEBATTACHMENT_KIND_TERM = SITES_NAMESPACE + '#webattachment' FOLDER_KIND_TERM = SITES_NAMESPACE + '#folder' TAG_KIND_TERM = SITES_NAMESPACE + '#tag' SUPPORT_KINDS = [ 'announcement', 'announcementspage', 'attachment', 'comment', 'filecabinet', 'listitem', 'listpage', 'webpage', 'webattachment', 'tag' ] class Revision(atom.core.XmlElement): """Google Sites <sites:revision>.""" _qname = SITES_TEMPLATE % 'revision' class PageName(atom.core.XmlElement): """Google Sites <sites:pageName>.""" _qname = SITES_TEMPLATE % 'pageName' class SiteName(atom.core.XmlElement): """Google Sites <sites:siteName>.""" _qname = SITES_TEMPLATE % 'siteName' class Theme(atom.core.XmlElement): """Google Sites <sites:theme>.""" _qname = SITES_TEMPLATE % 'theme' class Deleted(atom.core.XmlElement): """Google Sites <gd:deleted>.""" _qname = gdata.data.GDATA_TEMPLATE % 'deleted' class Publisher(atom.core.XmlElement): """Google Sites <dc:pulisher>.""" _qname = DC_TERMS_TEMPLATE % 'publisher' class Worksheet(atom.core.XmlElement): """Google Sites List Page <gs:worksheet>.""" _qname = SPREADSHEETS_TEMPLATE % 'worksheet' name = 'name' class Header(atom.core.XmlElement): """Google Sites List Page <gs:header>.""" _qname = SPREADSHEETS_TEMPLATE % 'header' row = 'row' class Column(atom.core.XmlElement): """Google Sites List Page <gs:column>.""" _qname = SPREADSHEETS_TEMPLATE % 'column' index = 'index' name = 'name' class Data(atom.core.XmlElement): """Google Sites List Page <gs:data>.""" _qname = SPREADSHEETS_TEMPLATE % 'data' startRow = 'startRow' column = [Column] class Field(atom.core.XmlElement): """Google Sites List Item <gs:field>.""" _qname = SPREADSHEETS_TEMPLATE % 'field' index = 'index' name = 'name' class InReplyTo(atom.core.XmlElement): """Google Sites List Item <thr:in-reply-to>.""" _qname = THR_TERMS_TEMPLATE % 'in-reply-to' href = 'href' ref = 'ref' source = 'source' type = 'type' class Content(atom.data.Content): """Google Sites version of <atom:content> that encapsulates XHTML.""" def __init__(self, html=None, type=None, **kwargs): if type is None and html: type = 'xhtml' super(Content, self).__init__(type=type, **kwargs) if html is not None: self.html = html def _get_html(self): if self.children: return self.children[0] else: return '' def _set_html(self, html): if not html: self.children = [] return if type(html) == str: html = atom.core.parse(html) if not html.namespace: html.namespace = XHTML_NAMESPACE self.children = [html] html = property(_get_html, _set_html) class Summary(atom.data.Summary): """Google Sites version of <atom:summary>.""" def __init__(self, html=None, type=None, text=None, **kwargs): if type is None and html: type = 'xhtml' super(Summary, self).__init__(type=type, text=text, **kwargs) if html is not None: self.html = html def _get_html(self): if self.children: return self.children[0] else: return '' def _set_html(self, html): if not html: self.children = [] return if type(html) == str: html = atom.core.parse(html) if not html.namespace: html.namespace = XHTML_NAMESPACE self.children = [html] html = property(_get_html, _set_html) class BaseSiteEntry(gdata.data.GDEntry): """Google Sites Entry.""" def __init__(self, kind=None, **kwargs): super(BaseSiteEntry, self).__init__(**kwargs) if kind is not None: self.category.append( atom.data.Category(scheme=SITES_KIND_SCHEME, term='%s#%s' % (SITES_NAMESPACE, kind), label=kind)) def __find_category_scheme(self, scheme): for category in self.category: if category.scheme == scheme: return category return None def kind(self): kind = self.__find_category_scheme(SITES_KIND_SCHEME) if kind is not None: return kind.term[len(SITES_NAMESPACE) + 1:] else: return None Kind = kind def get_node_id(self): return self.id.text[self.id.text.rfind('/') + 1:] GetNodeId = get_node_id def find_parent_link(self): return self.find_url(SITES_PARENT_LINK_REL) FindParentLink = find_parent_link def is_deleted(self): return self.deleted is not None IsDeleted = is_deleted class ContentEntry(BaseSiteEntry): """Google Sites Content Entry.""" content = Content deleted = Deleted publisher = Publisher in_reply_to = InReplyTo worksheet = Worksheet header = Header data = Data field = [Field] revision = Revision page_name = PageName feed_link = gdata.data.FeedLink def find_revison_link(self): return self.find_url(SITES_REVISION_LINK_REL) FindRevisionLink = find_revison_link class ContentFeed(gdata.data.GDFeed): """Google Sites Content Feed. The Content feed is a feed containing the current, editable site content. """ entry = [ContentEntry] def __get_entry_type(self, kind): matches = [] for entry in self.entry: if entry.Kind() == kind: matches.append(entry) return matches def get_announcements(self): return self.__get_entry_type('announcement') GetAnnouncements = get_announcements def get_announcement_pages(self): return self.__get_entry_type('announcementspage') GetAnnouncementPages = get_announcement_pages def get_attachments(self): return self.__get_entry_type('attachment') GetAttachments = get_attachments def get_comments(self): return self.__get_entry_type('comment') GetComments = get_comments def get_file_cabinets(self): return self.__get_entry_type('filecabinet') GetFileCabinets = get_file_cabinets def get_list_items(self): return self.__get_entry_type('listitem') GetListItems = get_list_items def get_list_pages(self): return self.__get_entry_type('listpage') GetListPages = get_list_pages def get_webpages(self): return self.__get_entry_type('webpage') GetWebpages = get_webpages def get_webattachments(self): return self.__get_entry_type('webattachment') GetWebattachments = get_webattachments class ActivityEntry(BaseSiteEntry): """Google Sites Activity Entry.""" summary = Summary class ActivityFeed(gdata.data.GDFeed): """Google Sites Activity Feed. The Activity feed is a feed containing recent Site activity. """ entry = [ActivityEntry] class RevisionEntry(BaseSiteEntry): """Google Sites Revision Entry.""" content = Content class RevisionFeed(gdata.data.GDFeed): """Google Sites Revision Feed. The Activity feed is a feed containing recent Site activity. """ entry = [RevisionEntry] class SiteEntry(gdata.data.GDEntry): """Google Sites Site Feed Entry.""" site_name = SiteName theme = Theme def find_source_link(self): return self.find_url(SITES_SOURCE_LINK_REL) FindSourceLink = find_source_link class SiteFeed(gdata.data.GDFeed): """Google Sites Site Feed. The Site feed can be used to list a user's sites and create new sites. """ entry = [SiteEntry] class AclEntry(gdata.acl.data.AclEntry): """Google Sites ACL Entry.""" class AclFeed(gdata.acl.data.AclFeed): """Google Sites ACL Feed. The ACL feed can be used to modify the sharing permissions of a Site. """ entry = [AclEntry]
Python
#!/usr/bin/python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """SitesClient extends gdata.client.GDClient to streamline Sites API calls.""" __author__ = 'e.bidelman (Eric Bidelman)' import atom.data import gdata.client import gdata.sites.data import gdata.gauth # Feed URI templates CONTENT_FEED_TEMPLATE = '/feeds/content/%s/%s/' REVISION_FEED_TEMPLATE = '/feeds/revision/%s/%s/' ACTIVITY_FEED_TEMPLATE = '/feeds/activity/%s/%s/' SITE_FEED_TEMPLATE = '/feeds/site/%s/' ACL_FEED_TEMPLATE = '/feeds/acl/site/%s/%s/' class SitesClient(gdata.client.GDClient): """Client extension for the Google Sites API service.""" host = 'sites.google.com' # default server for the API domain = 'site' # default site domain name api_version = '1.1' # default major version for the service. auth_service = 'jotspot' auth_scopes = gdata.gauth.AUTH_SCOPES['jotspot'] ssl = True def __init__(self, site=None, domain=None, auth_token=None, **kwargs): """Constructs a new client for the Sites API. Args: site: string (optional) Name (webspace) of the Google Site domain: string (optional) Domain of the (Google Apps hosted) Site. If no domain is given, the Site is assumed to be a consumer Google Site, in which case the value 'site' is used. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: The other parameters to pass to gdata.client.GDClient constructor. """ gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs) self.site = site if domain is not None: self.domain = domain def __make_kind_category(self, label): if label is None: return None return atom.data.Category( scheme=gdata.sites.data.SITES_KIND_SCHEME, term='%s#%s' % (gdata.sites.data.SITES_NAMESPACE, label), label=label) __MakeKindCategory = __make_kind_category def __upload(self, entry, media_source, auth_token=None, **kwargs): """Uploads an attachment file to the Sites API. Args: entry: gdata.sites.data.ContentEntry The Atom XML to include. media_source: gdata.data.MediaSource The file payload to be uploaded. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to gdata.client.post(). Returns: The created entry. """ uri = self.make_content_feed_uri() return self.post(entry, uri, media_source=media_source, auth_token=auth_token, **kwargs) def _get_file_content(self, uri): """Fetches the file content from the specified URI. Args: uri: string The full URL to fetch the file contents from. Returns: The binary file content. Raises: gdata.client.RequestError: on error response from server. """ server_response = self.request('GET', uri) if server_response.status != 200: raise gdata.client.RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': server_response.read()} return server_response.read() _GetFileContent = _get_file_content def make_content_feed_uri(self): return CONTENT_FEED_TEMPLATE % (self.domain, self.site) MakeContentFeedUri = make_content_feed_uri def make_revision_feed_uri(self): return REVISION_FEED_TEMPLATE % (self.domain, self.site) MakeRevisionFeedUri = make_revision_feed_uri def make_activity_feed_uri(self): return ACTIVITY_FEED_TEMPLATE % (self.domain, self.site) MakeActivityFeedUri = make_activity_feed_uri def make_site_feed_uri(self, site_name=None): if site_name is not None: return (SITE_FEED_TEMPLATE % self.domain) + site_name else: return SITE_FEED_TEMPLATE % self.domain MakeSiteFeedUri = make_site_feed_uri def make_acl_feed_uri(self): return ACL_FEED_TEMPLATE % (self.domain, self.site) MakeAclFeedUri = make_acl_feed_uri def get_content_feed(self, uri=None, auth_token=None, **kwargs): """Retrieves the content feed containing the current state of site. Args: uri: string (optional) A full URI to query the Content feed with. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_feed(). Returns: gdata.sites.data.ContentFeed """ if uri is None: uri = self.make_content_feed_uri() return self.get_feed(uri, desired_class=gdata.sites.data.ContentFeed, auth_token=auth_token, **kwargs) GetContentFeed = get_content_feed def get_revision_feed(self, entry_or_uri_or_id, auth_token=None, **kwargs): """Retrieves the revision feed containing the revision history for a node. Args: entry_or_uri_or_id: string or gdata.sites.data.ContentEntry A full URI, content entry node ID, or a content entry object of the entry to retrieve revision information for. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_feed(). Returns: gdata.sites.data.RevisionFeed """ uri = self.make_revision_feed_uri() if isinstance(entry_or_uri_or_id, gdata.sites.data.ContentEntry): uri = entry_or_uri_or_id.FindRevisionLink() elif entry_or_uri_or_id.find('/') == -1: uri += entry_or_uri_or_id else: uri = entry_or_uri_or_id return self.get_feed(uri, desired_class=gdata.sites.data.RevisionFeed, auth_token=auth_token, **kwargs) GetRevisionFeed = get_revision_feed def get_activity_feed(self, uri=None, auth_token=None, **kwargs): """Retrieves the activity feed containing recent Site activity. Args: uri: string (optional) A full URI to query the Activity feed. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_feed(). Returns: gdata.sites.data.ActivityFeed """ if uri is None: uri = self.make_activity_feed_uri() return self.get_feed(uri, desired_class=gdata.sites.data.ActivityFeed, auth_token=auth_token, **kwargs) GetActivityFeed = get_activity_feed def get_site_feed(self, uri=None, auth_token=None, **kwargs): """Retrieves the site feed containing a list of sites a user has access to. Args: uri: string (optional) A full URI to query the site feed. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_feed(). Returns: gdata.sites.data.SiteFeed """ if uri is None: uri = self.make_site_feed_uri() return self.get_feed(uri, desired_class=gdata.sites.data.SiteFeed, auth_token=auth_token, **kwargs) GetSiteFeed = get_site_feed def get_acl_feed(self, uri=None, auth_token=None, **kwargs): """Retrieves the acl feed containing a site's sharing permissions. Args: uri: string (optional) A full URI to query the acl feed. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.get_feed(). Returns: gdata.sites.data.AclFeed """ if uri is None: uri = self.make_acl_feed_uri() return self.get_feed(uri, desired_class=gdata.sites.data.AclFeed, auth_token=auth_token, **kwargs) GetAclFeed = get_acl_feed def create_site(self, title, description=None, source_site=None, theme=None, uri=None, auth_token=None, **kwargs): """Creates a new Google Site. Note: This feature is only available to Google Apps domains. Args: title: string Title for the site. description: string (optional) A description/summary for the site. source_site: string (optional) The site feed URI of the site to copy. This parameter should only be specified when copying a site. theme: string (optional) The name of the theme to create the site with. uri: string (optional) A full site feed URI to override where the site is created/copied. By default, the site will be created under the currently set domain (e.g. self.domain). auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to gdata.client.post(). Returns: gdata.sites.data.SiteEntry of the created site. """ new_entry = gdata.sites.data.SiteEntry(title=atom.data.Title(text=title)) if description is not None: new_entry.summary = gdata.sites.data.Summary(text=description) # Add the source link if we're making a copy of a site. if source_site is not None: source_link = atom.data.Link(rel=gdata.sites.data.SITES_SOURCE_LINK_REL, type='application/atom+xml', href=source_site) new_entry.link.append(source_link) if theme is not None: new_entry.theme = gdata.sites.data.Theme(text=theme) if uri is None: uri = self.make_site_feed_uri() return self.post(new_entry, uri, auth_token=auth_token, **kwargs) CreateSite = create_site def create_page(self, kind, title, html='', page_name=None, parent=None, auth_token=None, **kwargs): """Creates a new page (specified by kind) on a Google Site. Args: kind: string The type of page/item to create. For example, webpage, listpage, comment, announcementspage, filecabinet, etc. The full list of supported kinds can be found in gdata.sites.gdata.SUPPORT_KINDS. title: string Title for the page. html: string (optional) XHTML for the page's content body. page_name: string (optional) The URL page name to set. If not set, the title will be normalized and used as the page's URL path. parent: string or gdata.sites.data.ContentEntry (optional) The parent entry or parent link url to create the page under. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to gdata.client.post(). Returns: gdata.sites.data.ContentEntry of the created page. """ new_entry = gdata.sites.data.ContentEntry( title=atom.data.Title(text=title), kind=kind, content=gdata.sites.data.Content(text=html)) if page_name is not None: new_entry.page_name = gdata.sites.data.PageName(text=page_name) # Add parent link to entry if it should be uploaded as a subpage. if isinstance(parent, gdata.sites.data.ContentEntry): parent_link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent.GetSelfLink().href) new_entry.link.append(parent_link) elif parent is not None: parent_link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent) new_entry.link.append(parent_link) return self.post(new_entry, self.make_content_feed_uri(), auth_token=auth_token, **kwargs) CreatePage = create_page def create_webattachment(self, src, content_type, title, parent, description=None, auth_token=None, **kwargs): """Creates a new webattachment within a filecabinet. Args: src: string The url of the web attachment. content_type: string The MIME type of the web attachment. title: string The title to name the web attachment. parent: string or gdata.sites.data.ContentEntry (optional) The parent entry or url of the filecabinet to create the attachment under. description: string (optional) A summary/description for the attachment. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to gdata.client.post(). Returns: gdata.sites.data.ContentEntry of the created page. """ new_entry = gdata.sites.data.ContentEntry( title=atom.data.Title(text=title), kind='webattachment', content=gdata.sites.data.Content(src=src, type=content_type)) if isinstance(parent, gdata.sites.data.ContentEntry): link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent.GetSelfLink().href) elif parent is not None: link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent) new_entry.link.append(link) # Add file decription if it was specified if description is not None: new_entry.summary = gdata.sites.data.Summary(type='text', text=description) return self.post(new_entry, self.make_content_feed_uri(), auth_token=auth_token, **kwargs) CreateWebAttachment = create_webattachment def upload_attachment(self, file_handle, parent, content_type=None, title=None, description=None, folder_name=None, auth_token=None, **kwargs): """Uploads an attachment to a parent page. Args: file_handle: MediaSource or string A gdata.data.MediaSource object containing the file to be uploaded or the full path name to the file on disk. parent: gdata.sites.data.ContentEntry or string The parent page to upload the file to or the full URI of the entry's self link. content_type: string (optional) The MIME type of the file (e.g 'application/pdf'). This should be provided if file is not a MediaSource object. title: string (optional) The title to name the attachment. If not included, the filepath or media source's filename is used. description: string (optional) A summary/description for the attachment. folder_name: string (optional) The name of an existing folder to upload the attachment to. This only applies when the parent parameter points to a filecabinet entry. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the user's data. kwargs: Other parameters to pass to self.__upload(). Returns: A gdata.sites.data.ContentEntry containing information about the created attachment. """ if isinstance(parent, gdata.sites.data.ContentEntry): link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent.GetSelfLink().href) else: link = atom.data.Link(rel=gdata.sites.data.SITES_PARENT_LINK_REL, type='application/atom+xml', href=parent) if not isinstance(file_handle, gdata.data.MediaSource): ms = gdata.data.MediaSource(file_path=file_handle, content_type=content_type) else: ms = file_handle # If no title specified, use the file name if title is None: title = ms.file_name new_entry = gdata.sites.data.ContentEntry(kind='attachment') new_entry.title = atom.data.Title(text=title) new_entry.link.append(link) # Add file decription if it was specified if description is not None: new_entry.summary = gdata.sites.data.Summary(type='text', text=description) # Upload the attachment to a filecabinet folder? if parent.Kind() == 'filecabinet' and folder_name is not None: folder_category = atom.data.Category( scheme=gdata.sites.data.FOLDER_KIND_TERM, term=folder_name) new_entry.category.append(folder_category) return self.__upload(new_entry, ms, auth_token=auth_token, **kwargs) UploadAttachment = upload_attachment def download_attachment(self, uri_or_entry, file_path): """Downloads an attachment file to disk. Args: uri_or_entry: string The full URL to download the file from. file_path: string The full path to save the file to. Raises: gdata.client.RequestError: on error response from server. """ uri = uri_or_entry if isinstance(uri_or_entry, gdata.sites.data.ContentEntry): uri = uri_or_entry.content.src f = open(file_path, 'wb') try: f.write(self._get_file_content(uri)) except gdata.client.RequestError, e: f.close() raise e f.flush() f.close() DownloadAttachment = download_attachment
Python
#!/usr/bin/python # # Copyright 2010 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model classes for the Provisioning API.""" __author__ = 'Shraddha Gupta shraddhag@google.com>' import atom.core import atom.data import gdata.apps import gdata.data class Login(atom.core.XmlElement): _qname = gdata.apps.APPS_TEMPLATE % 'login' user_name = 'userName' password = 'password' hash_function_name = 'hashFunctionName' suspended = 'suspended' admin = 'admin' agreed_to_terms = 'agreedToTerms' change_password = 'changePasswordAtNextLogin' ip_whitelisted = 'ipWhitelisted' class Name(atom.core.XmlElement): _qname = gdata.apps.APPS_TEMPLATE % 'name' given_name = 'givenName' family_name = 'familyName' class Quota(atom.core.XmlElement): _qname = gdata.apps.APPS_TEMPLATE % 'quota' limit = 'limit' class UserEntry(gdata.data.GDEntry): _qname = atom.data.ATOM_TEMPLATE % 'entry' login = Login name = Name quota = Quota class UserFeed(gdata.data.GDFeed): entry = [UserEntry] class Nickname(atom.core.XmlElement): _qname = gdata.apps.APPS_TEMPLATE % 'nickname' name = 'name' class NicknameEntry(gdata.data.GDEntry): _qname = atom.data.ATOM_TEMPLATE % 'entry' nickname = Nickname login = Login class NicknameFeed(gdata.data.GDFeed): entry = [NicknameEntry]
Python
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model classes for the Multidomain Provisioning API.""" __author__ = 'Claudio Cherubino <ccherubino@google.com>' import gdata.apps import gdata.apps.apps_property_entry import gdata.apps_property import gdata.data # This is required to work around a naming conflict between the Google # Spreadsheets API and Python's built-in property function pyproperty = property # The apps:property firstName of a user entry USER_FIRST_NAME = 'firstName' # The apps:property lastName of a user entry USER_LAST_NAME = 'lastName' # The apps:property userEmail of a user entry USER_EMAIL = 'userEmail' # The apps:property password of a user entry USER_PASSWORD = 'password' # The apps:property hashFunction of a user entry USER_HASH_FUNCTION = 'hashFunction' # The apps:property isChangePasswordAtNextLogin of a user entry USER_CHANGE_PASSWORD = 'isChangePasswordAtNextLogin' # The apps:property agreedToTerms of a user entry USER_AGREED_TO_TERMS = 'agreedToTerms' # The apps:property isSuspended of a user entry USER_SUSPENDED = 'isSuspended' # The apps:property isAdmin of a user entry USER_ADMIN = 'isAdmin' # The apps:property ipWhitelisted of a user entry USER_IP_WHITELISTED = 'ipWhitelisted' # The apps:property quotaInGb of a user entry USER_QUOTA = 'quotaInGb' # The apps:property newEmail of a user rename request entry USER_NEW_EMAIL = 'newEmail' # The apps:property aliasEmail of an alias entry ALIAS_EMAIL = 'aliasEmail' class UserEntry(gdata.apps.apps_property_entry.AppsPropertyEntry): """Represents an User in object form.""" def GetFirstName(self): """Get the first name of the User object. Returns: The first name of this User object as a string or None. """ return self._GetProperty(USER_FIRST_NAME) def SetFirstName(self, value): """Set the first name of this User object. Args: value: string The new first name to give this object. """ self._SetProperty(USER_FIRST_NAME, value) first_name = pyproperty(GetFirstName, SetFirstName) def GetLastName(self): """Get the last name of the User object. Returns: The last name of this User object as a string or None. """ return self._GetProperty(USER_LAST_NAME) def SetLastName(self, value): """Set the last name of this User object. Args: value: string The new last name to give this object. """ self._SetProperty(USER_LAST_NAME, value) last_name = pyproperty(GetLastName, SetLastName) def GetEmail(self): """Get the email address of the User object. Returns: The email address of this User object as a string or None. """ return self._GetProperty(USER_EMAIL) def SetEmail(self, value): """Set the email address of this User object. Args: value: string The new email address to give this object. """ self._SetProperty(USER_EMAIL, value) email = pyproperty(GetEmail, SetEmail) def GetPassword(self): """Get the password of the User object. Returns: The password of this User object as a string or None. """ return self._GetProperty(USER_PASSWORD) def SetPassword(self, value): """Set the password of this User object. Args: value: string The new password to give this object. """ self._SetProperty(USER_PASSWORD, value) password = pyproperty(GetPassword, SetPassword) def GetHashFunction(self): """Get the hash function of the User object. Returns: The hash function of this User object as a string or None. """ return self._GetProperty(USER_HASH_FUNCTION) def SetHashFunction(self, value): """Set the hash function of this User object. Args: value: string The new hash function to give this object. """ self._SetProperty(USER_HASH_FUNCTION, value) hash_function = pyproperty(GetHashFunction, SetHashFunction) def GetChangePasswordAtNextLogin(self): """Get the change password at next login flag of the User object. Returns: The change password at next login flag of this User object as a string or None. """ return self._GetProperty(USER_CHANGE_PASSWORD) def SetChangePasswordAtNextLogin(self, value): """Set the change password at next login flag of this User object. Args: value: string The new change password at next login flag to give this object. """ self._SetProperty(USER_CHANGE_PASSWORD, value) change_password_at_next_login = pyproperty(GetChangePasswordAtNextLogin, SetChangePasswordAtNextLogin) def GetAgreedToTerms(self): """Get the agreed to terms flag of the User object. Returns: The agreed to terms flag of this User object as a string or None. """ return self._GetProperty(USER_AGREED_TO_TERMS) agreed_to_terms = pyproperty(GetAgreedToTerms) def GetSuspended(self): """Get the suspended flag of the User object. Returns: The suspended flag of this User object as a string or None. """ return self._GetProperty(USER_SUSPENDED) def SetSuspended(self, value): """Set the suspended flag of this User object. Args: value: string The new suspended flag to give this object. """ self._SetProperty(USER_SUSPENDED, value) suspended = pyproperty(GetSuspended, SetSuspended) def GetIsAdmin(self): """Get the isAdmin flag of the User object. Returns: The isAdmin flag of this User object as a string or None. """ return self._GetProperty(USER_ADMIN) def SetIsAdmin(self, value): """Set the isAdmin flag of this User object. Args: value: string The new isAdmin flag to give this object. """ self._SetProperty(USER_ADMIN, value) is_admin = pyproperty(GetIsAdmin, SetIsAdmin) def GetIpWhitelisted(self): """Get the ipWhitelisted flag of the User object. Returns: The ipWhitelisted flag of this User object as a string or None. """ return self._GetProperty(USER_IP_WHITELISTED) def SetIpWhitelisted(self, value): """Set the ipWhitelisted flag of this User object. Args: value: string The new ipWhitelisted flag to give this object. """ self._SetProperty(USER_IP_WHITELISTED, value) ip_whitelisted = pyproperty(GetIpWhitelisted, SetIpWhitelisted) def GetQuota(self): """Get the quota of the User object. Returns: The quota of this User object as a string or None. """ return self._GetProperty(USER_QUOTA) def SetQuota(self, value): """Set the quota of this User object. Args: value: string The new quota to give this object. """ self._SetProperty(USER_QUOTA, value) quota = pyproperty(GetQuota, GetQuota) def __init__(self, uri=None, email=None, first_name=None, last_name=None, password=None, hash_function=None, change_password=None, agreed_to_terms=None, suspended=None, is_admin=None, ip_whitelisted=None, quota=None, *args, **kwargs): """Constructs a new UserEntry object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. email: string (optional) The email address of the user. first_name: string (optional) The first name of the user. last_name: string (optional) The last name of the user. password: string (optional) The password of the user. hash_function: string (optional) The name of the function used to hash the password. change_password: Boolean (optional) Whether or not the user must change password at first login. agreed_to_terms: Boolean (optional) Whether or not the user has agreed to the Terms of Service. suspended: Boolean (optional) Whether or not the user is suspended. is_admin: Boolean (optional) Whether or not the user has administrator privileges. ip_whitelisted: Boolean (optional) Whether or not the user's ip is whitelisted. quota: string (optional) The value (in GB) of the user's quota. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(UserEntry, self).__init__(*args, **kwargs) if uri: self.uri = uri if email: self.email = email if first_name: self.first_name = first_name if last_name: self.last_name = last_name if password: self.password = password if hash_function: self.hash_function = hash_function if change_password is not None: self.change_password_at_next_login = str(change_password) if agreed_to_terms is not None: self.agreed_to_terms = str(agreed_to_terms) if suspended is not None: self.suspended = str(suspended) if is_admin is not None: self.is_admin = str(is_admin) if ip_whitelisted is not None: self.ip_whitelisted = str(ip_whitelisted) if quota: self.quota = quota class UserFeed(gdata.data.GDFeed): """Represents a feed of UserEntry objects.""" # Override entry so that this feed knows how to type its list of entries. entry = [UserEntry] class UserRenameRequest(gdata.apps.apps_property_entry.AppsPropertyEntry): """Represents an User rename request in object form.""" def GetNewEmail(self): """Get the new email address for the User object. Returns: The new email address for the User object as a string or None. """ return self._GetProperty(USER_NEW_EMAIL) def SetNewEmail(self, value): """Set the new email address for the User object. Args: value: string The new email address to give this object. """ self._SetProperty(USER_NEW_EMAIL, value) new_email = pyproperty(GetNewEmail, SetNewEmail) def __init__(self, new_email=None, *args, **kwargs): """Constructs a new UserRenameRequest object with the given arguments. Args: new_email: string (optional) The new email address for the target user. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(UserRenameRequest, self).__init__(*args, **kwargs) if new_email: self.new_email = new_email class AliasEntry(gdata.apps.apps_property_entry.AppsPropertyEntry): """Represents an Alias in object form.""" def GetUserEmail(self): """Get the user email address of the Alias object. Returns: The user email address of this Alias object as a string or None. """ return self._GetProperty(USER_EMAIL) def SetUserEmail(self, value): """Set the user email address of this Alias object. Args: value: string The new user email address to give this object. """ self._SetProperty(USER_EMAIL, value) user_email = pyproperty(GetUserEmail, SetUserEmail) def GetAliasEmail(self): """Get the alias email address of the Alias object. Returns: The alias email address of this Alias object as a string or None. """ return self._GetProperty(ALIAS_EMAIL) def SetAliasEmail(self, value): """Set the alias email address of this Alias object. Args: value: string The new alias email address to give this object. """ self._SetProperty(ALIAS_EMAIL, value) alias_email = pyproperty(GetAliasEmail, SetAliasEmail) def __init__(self, user_email=None, alias_email=None, *args, **kwargs): """Constructs a new AliasEntry object with the given arguments. Args: user_email: string (optional) The user email address for the object. alias_email: string (optional) The alias email address for the object. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(AliasEntry, self).__init__(*args, **kwargs) if user_email: self.user_email = user_email if alias_email: self.alias_email = alias_email class AliasFeed(gdata.data.GDFeed): """Represents a feed of AliasEntry objects.""" # Override entry so that this feed knows how to type its list of entries. entry = [AliasEntry]
Python
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """MultiDomainProvisioningClient simplifies Multidomain Provisioning API calls. MultiDomainProvisioningClient extends gdata.client.GDClient to ease interaction with the Google Multidomain Provisioning API. These interactions include the ability to create, retrieve, update and delete users and aliases in multiple domains. """ __author__ = 'Claudio Cherubino <ccherubino@google.com>' import urllib import gdata.apps.multidomain.data import gdata.client # Multidomain URI templates # The strings in this template are eventually replaced with the feed type # (user/alias), API version and Google Apps domain name, respectively. MULTIDOMAIN_URI_TEMPLATE = '/a/feeds/%s/%s/%s' # The strings in this template are eventually replaced with the API version, # Google Apps domain name and old email address, respectively. MULTIDOMAIN_USER_RENAME_URI_TEMPLATE = '/a/feeds/user/userEmail/%s/%s/%s' # The value for user requests MULTIDOMAIN_USER_FEED = 'user' # The value for alias requests MULTIDOMAIN_ALIAS_FEED = 'alias' class MultiDomainProvisioningClient(gdata.client.GDClient): """Client extension for the Google MultiDomain Provisioning API service. Attributes: host: string The hostname for the MultiDomain Provisioning API service. api_version: string The version of the MultiDomain Provisioning 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 MultiDomain Provisioning API. Args: domain: string The Google Apps domain with MultiDomain Provisioning. 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_multidomain_provisioning_uri( self, feed_type, email=None, params=None): """Creates a resource feed URI for the MultiDomain Provisioning API. Using this client's Google Apps domain, create a feed URI for multidomain provisioning in that domain. If an email address is provided, return a URI for that specific resource. If params are provided, append them as GET params. Args: feed_type: string The type of feed (user/alias) email: string (optional) The email address of multidomain resource for which to make a feed URI. params: dict (optional) key -> value params to append as GET vars to the URI. Example: params={'start': 'my-resource-id'} Returns: A string giving the URI for multidomain provisioning for this client's Google Apps domain. """ uri = MULTIDOMAIN_URI_TEMPLATE % (feed_type, self.api_version, self.domain) if email: uri += '/' + email if params: uri += '?' + urllib.urlencode(params) return uri MakeMultidomainProvisioningUri = make_multidomain_provisioning_uri def make_multidomain_user_provisioning_uri(self, email=None, params=None): """Creates a resource feed URI for the MultiDomain User Provisioning API. Using this client's Google Apps domain, create a feed URI for multidomain user provisioning in that domain. If an email address is provided, return a URI for that specific resource. If params are provided, append them as GET params. Args: email: string (optional) The email address of multidomain user for which to make a feed URI. params: dict (optional) key -> value params to append as GET vars to the URI. Example: params={'start': 'my-resource-id'} Returns: A string giving the URI for multidomain user provisioning for thisis that client's Google Apps domain. """ return self.make_multidomain_provisioning_uri( MULTIDOMAIN_USER_FEED, email, params) MakeMultidomainUserProvisioningUri = make_multidomain_user_provisioning_uri def make_multidomain_alias_provisioning_uri(self, email=None, params=None): """Creates a resource feed URI for the MultiDomain Alias Provisioning API. Using this client's Google Apps domain, create a feed URI for multidomain alias provisioning in that domain. If an email address is provided, return a URI for that specific resource. If params are provided, append them as GET params. Args: email: string (optional) The email address of multidomain alias for which to make a feed URI. params: dict (optional) key -> value params to append as GET vars to the URI. Example: params={'start': 'my-resource-id'} Returns: A string giving the URI for multidomain alias provisioning for this client's Google Apps domain. """ return self.make_multidomain_provisioning_uri( MULTIDOMAIN_ALIAS_FEED, email, params) MakeMultidomainAliasProvisioningUri = make_multidomain_alias_provisioning_uri def retrieve_all_pages(self, uri, desired_class=gdata.data.GDFeed, **kwargs): """Retrieves all pages from uri. Args: uri: The uri where the first page is. desired_class: Type of feed that is retrieved. kwargs: The other parameters to pass to gdata.client.GDClient.GetFeed() Returns: A desired_class feed object. """ feed = self.GetFeed( uri, desired_class=desired_class, **kwargs) next_link = feed.GetNextLink() while next_link is not None: uri = next_link.href temp_feed = self.GetFeed( uri, desired_class=desired_class, **kwargs) feed.entry = feed.entry + temp_feed.entry next_link = temp_feed.GetNextLink() return feed RetrieveAllPages = retrieve_all_pages def retrieve_all_users(self, **kwargs): """Retrieves all users in all domains. Args: kwargs: The other parameters to pass to gdata.client.GDClient.GetFeed() Returns: A gdata.data.GDFeed of the domain users """ uri = self.MakeMultidomainUserProvisioningUri() return self.RetrieveAllPages( uri, desired_class=gdata.apps.multidomain.data.UserFeed, **kwargs) RetrieveAllUsers = retrieve_all_users def retrieve_user(self, email, **kwargs): """Retrieves a single user in the domain. Args: email: string The email address of the user to be retrieved kwargs: The other parameters to pass to gdata.client.GDClient.GetEntry() Returns: A gdata.apps.multidomain.data.UserEntry representing the user """ uri = self.MakeMultidomainUserProvisioningUri(email=email) return self.GetEntry( uri, desired_class=gdata.apps.multidomain.data.UserEntry, **kwargs) RetrieveUser = retrieve_user def create_user(self, email, first_name, last_name, password, is_admin, hash_function=None, suspended=None, change_password=None, ip_whitelisted=None, quota=None, **kwargs): """Creates an user in the domain with the given properties. Args: email: string The email address of the user. first_name: string The first name of the user. last_name: string The last name of the user. password: string The password of the user. is_admin: Boolean Whether or not the user has administrator privileges. hash_function: string (optional) The name of the function used to hash the password. suspended: Boolean (optional) Whether or not the user is suspended. change_password: Boolean (optional) Whether or not the user must change password at first login. ip_whitelisted: Boolean (optional) Whether or not the user's ip is whitelisted. quota: string (optional) The value (in GB) of the user's quota. kwargs: The other parameters to pass to gdata.client.GDClient.post(). Returns: A gdata.apps.multidomain.data.UserEntry of the new user """ new_user = gdata.apps.multidomain.data.UserEntry( email=email, first_name=first_name, last_name=last_name, password=password, is_admin=is_admin, hash_function=hash_function, suspended=suspended, change_password=change_password, ip_whitelisted=ip_whitelisted, quota=quota) return self.post(new_user, self.MakeMultidomainUserProvisioningUri(), **kwargs) CreateUser = create_user def update_user(self, email, user_entry, **kwargs): """Deletes the user with the given email address. Args: email: string The email address of the user to be updated. user_entry: UserEntry The user entry with updated values. kwargs: The other parameters to pass to gdata.client.GDClient.put() Returns: A gdata.apps.multidomain.data.UserEntry representing the user """ return self.update(user_entry, uri=self.MakeMultidomainUserProvisioningUri(email), **kwargs) UpdateUser = update_user def delete_user(self, email, **kwargs): """Deletes the user with the given email address. Args: email: string The email address of the user to delete. kwargs: The other parameters to pass to gdata.client.GDClient.delete() Returns: An HTTP response object. See gdata.client.request(). """ return self.delete(self.MakeMultidomainUserProvisioningUri(email), **kwargs) DeleteUser = delete_user def rename_user(self, old_email, new_email, **kwargs): """Renames an user's account to a different domain. Args: old_email: string The old email address of the user to rename. new_email: string The new email address for the user to be renamed. kwargs: The other parameters to pass to gdata.client.GDClient.put() Returns: A gdata.apps.multidomain.data.UserRenameRequest representing the request. """ rename_uri = MULTIDOMAIN_USER_RENAME_URI_TEMPLATE % (self.api_version, self.domain, old_email) entry = gdata.apps.multidomain.data.UserRenameRequest(new_email) return self.update(entry, uri=rename_uri, **kwargs) RenameUser = rename_user def retrieve_all_aliases(self, **kwargs): """Retrieves all aliases in the domain. Args: kwargs: The other parameters to pass to gdata.client.GDClient.GetFeed() Returns: A gdata.data.GDFeed of the domain aliases """ uri = self.MakeMultidomainAliasProvisioningUri() return self.RetrieveAllPages( uri, desired_class=gdata.apps.multidomain.data.AliasFeed, **kwargs) RetrieveAllAliases = retrieve_all_aliases def retrieve_alias(self, email, **kwargs): """Retrieves a single alias in the domain. Args: email: string The email address of the alias to be retrieved kwargs: The other parameters to pass to gdata.client.GDClient.GetEntry() Returns: A gdata.apps.multidomain.data.AliasEntry representing the alias """ uri = self.MakeMultidomainAliasProvisioningUri(email=email) return self.GetEntry( uri, desired_class=gdata.apps.multidomain.data.AliasEntry, **kwargs) RetrieveAlias = retrieve_alias def retrieve_all_user_aliases(self, user_email, **kwargs): """Retrieves all aliases for a given user in the domain. Args: user_email: string Email address of the user whose aliases are to be retrieved kwargs: The other parameters to pass to gdata.client.GDClient.GetFeed() Returns: A gdata.data.GDFeed of the user aliases """ uri = self.MakeMultidomainAliasProvisioningUri( params = {'userEmail' : user_email}) return self.RetrieveAllPages( uri, desired_class=gdata.apps.multidomain.data.AliasFeed, **kwargs) RetrieveAllUserAliases = retrieve_all_user_aliases def create_alias(self, user_email, alias_email, **kwargs): """Creates an alias in the domain with the given properties. Args: user_email: string The email address of the user. alias_email: string The first name of the user. kwargs: The other parameters to pass to gdata.client.GDClient.post(). Returns: A gdata.apps.multidomain.data.AliasEntry of the new alias """ new_alias = gdata.apps.multidomain.data.AliasEntry( user_email=user_email, alias_email=alias_email) return self.post(new_alias, self.MakeMultidomainAliasProvisioningUri(), **kwargs) CreateAlias = create_alias def delete_alias(self, email, **kwargs): """Deletes the alias with the given email address. Args: email: string The email address of the alias to delete. kwargs: The other parameters to pass to gdata.client.GDClient.delete() Returns: An HTTP response object. See gdata.client.request(). """ return self.delete(self.MakeMultidomainAliasProvisioningUri(email), **kwargs) DeleteAlias = delete_alias
Python
# Copyright 2010 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """AppsClient adds Client Architecture to Provisioning API.""" __author__ = '<Shraddha Gupta shraddhag@google.com>' import gdata.apps.data import gdata.client import gdata.service class AppsClient(gdata.client.GDClient): """Client extension for the Google Provisioning API service. Attributes: host: string The hostname for the Provisioning API service. api_version: string The version of the Provisioning API. """ host = 'apps-apis.google.com' api_version = '2.0' auth_service = 'apps' auth_scopes = gdata.gauth.AUTH_SCOPES['apps'] def __init__(self, domain, auth_token=None, **kwargs): """Constructs a new client for the Provisioning API. Args: domain: string Google Apps domain name. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes client to make calls to Provisioning API. """ gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs) self.domain = domain def _baseURL(self): return '/a/feeds/%s' % self.domain def _userURL(self): return '%s/user/%s' % (self._baseURL(), self.api_version) def _nicknameURL(self): return '%s/nickname/%s' % (self._baseURL(), self.api_version) def RetrieveAllPages(self, feed, desired_class=gdata.data.GDFeed): """Retrieve all pages and add all elements. Args: feed: gdata.data.GDFeed object with linked elements. desired_class: type of feed to be returned. Returns: desired_class: subclass of gdata.data.GDFeed. """ next = feed.GetNextLink() while next is not None: next_feed = self.GetFeed(next.href, desired_class=desired_class) for a_entry in next_feed.entry: feed.entry.append(a_entry) next = next_feed.GetNextLink() return feed def CreateUser(self, user_name, family_name, given_name, password, suspended=False, admin=None, quota_limit=None, password_hash_function=None, agreed_to_terms=None, change_password=None): """Create a user account.""" uri = self._userURL() user_entry = gdata.apps.data.UserEntry() user_entry.login = gdata.apps.data.Login(user_name=user_name, password=password, suspended=suspended, admin=admin, hash_function_name=password_hash_function, agreed_to_terms=agreed_to_terms, change_password=change_password) user_entry.name = gdata.apps.data.Name(family_name=family_name, given_name=given_name) return self.Post(user_entry, uri) def RetrieveUser(self, user_name): """Retrieve a user account. Args: user_name: string user_name to be retrieved. Returns: gdata.apps.data.UserEntry """ uri = '%s/%s' % (self._userURL(), user_name) return self.GetEntry(uri, desired_class=gdata.apps.data.UserEntry) def RetrievePageOfUsers(self, start_username=None): """Retrieve one page of users in this domain. Args: start_username: string user to start from for retrieving a page of users. Returns: gdata.apps.data.UserFeed """ uri = self._userURL() if start_username is not None: uri += '?startUsername=%s' % start_username return self.GetFeed(uri, desired_class=gdata.apps.data.UserFeed) def RetrieveAllUsers(self): """Retrieve all users in this domain. Returns: gdata.apps.data.UserFeed """ ret = self.RetrievePageOfUsers() # pagination return self.RetrieveAllPages(ret, gdata.apps.data.UserFeed) def UpdateUser(self, user_name, user_entry): """Update a user account. Args: user_name: string user_name to be updated. user_entry: gdata.apps.data.UserEntry updated user entry. Returns: gdata.apps.data.UserEntry """ uri = '%s/%s' % (self._userURL(), user_name) return self.Update(entry=user_entry, uri=uri) def DeleteUser(self, user_name): """Delete a user account.""" uri = '%s/%s' % (self._userURL(), user_name) self.Delete(uri) def CreateNickname(self, user_name, nickname): """Create a nickname for a user. Args: user_name: string user whose nickname is being created. nickname: string nickname. Returns: gdata.apps.data.NicknameEntry """ uri = self._nicknameURL() nickname_entry = gdata.apps.data.NicknameEntry() nickname_entry.login = gdata.apps.data.Login(user_name=user_name) nickname_entry.nickname = gdata.apps.data.Nickname(name=nickname) return self.Post(nickname_entry, uri) def RetrieveNickname(self, nickname): """Retrieve a nickname. Args: nickname: string nickname to be retrieved. Returns: gdata.apps.data.NicknameEntry """ uri = '%s/%s' % (self._nicknameURL(), nickname) return self.GetEntry(uri, desired_class=gdata.apps.data.NicknameEntry) def RetrieveNicknames(self, user_name): """Retrieve nicknames of the user. Args: user_name: string user whose nicknames are retrieved. Returns: gdata.apps.data.NicknameFeed """ uri = '%s?username=%s' % (self._nicknameURL(), user_name) ret = self.GetFeed(uri, desired_class=gdata.apps.data.NicknameFeed) # pagination return self.RetrieveAllPages(ret, gdata.apps.data.NicknameFeed) def DeleteNickname(self, nickname): """Delete a nickname.""" uri = '%s/%s' % (self._nicknameURL(), nickname) self.Delete(uri)
Python
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model classes for the Groups Provisioning API.""" __author__ = 'Shraddha gupta <shraddhag@google.com>' import atom.data import gdata.apps import gdata.apps.apps_property_entry import gdata.apps_property import gdata.data # This is required to work around a naming conflict between the Google # Spreadsheets API and Python's built-in property function pyproperty = property # The apps:property groupId of a group entry GROUP_ID = 'groupId' # The apps:property groupName of a group entry GROUP_NAME = 'groupName' # The apps:property description of a group entry DESCRIPTION = 'description' # The apps:property emailPermission of a group entry EMAIL_PERMISSION = 'emailPermission' # The apps:property memberId of a group member entry MEMBER_ID = 'memberId' # The apps:property memberType of a group member entry MEMBER_TYPE = 'memberType' # The apps:property directMember of a group member entry DIRECT_MEMBER = 'directMember' class GroupEntry(gdata.apps.apps_property_entry.AppsPropertyEntry): """Represents a group entry in object form.""" def GetGroupId(self): """Get groupId of the GroupEntry object. Returns: The groupId this GroupEntry object as a string or None. """ return self._GetProperty(GROUP_ID) def SetGroupId(self, value): """Set the groupId of this GroupEntry object. Args: value: string The new groupId to give this object. """ self._SetProperty(GROUP_ID, value) group_id = pyproperty(GetGroupId, SetGroupId) def GetGroupName(self): """Get the groupName of the GroupEntry object. Returns: The groupName of this GroupEntry object as a string or None. """ return self._GetProperty(GROUP_NAME) def SetGroupName(self, value): """Set the groupName of this GroupEntry object. Args: value: string The new groupName to give this object. """ self._SetProperty(GROUP_NAME, value) group_name = pyproperty(GetGroupName, SetGroupName) def GetDescription(self): """Get the description of the GroupEntry object. Returns: The description of this GroupEntry object as a string or None. """ return self._GetProperty(DESCRIPTION) def SetDescription(self, value): """Set the description of this GroupEntry object. Args: value: string The new description to give this object. """ self._SetProperty(DESCRIPTION, value) description = pyproperty(GetDescription, SetDescription) def GetEmailPermission(self): """Get the emailPermission of the GroupEntry object. Returns: The emailPermission of this GroupEntry object as a string or None. """ return self._GetProperty(EMAIL_PERMISSION) def SetEmailPermission(self, value): """Set the emailPermission of this GroupEntry object. Args: value: string The new emailPermission to give this object. """ self._SetProperty(EMAIL_PERMISSION, value) email_permission = pyproperty(GetEmailPermission, SetEmailPermission) def __init__(self, group_id=None, group_name=None, description=None, email_permission=None, *args, **kwargs): """Constructs a new GroupEntry object with the given arguments. Args: group_id: string identifier of the group. group_name: string name of the group. description: string (optional) the group description. email_permisison: string (optional) permission level of the group. """ super(GroupEntry, self).__init__(*args, **kwargs) if group_id: self.group_id = group_id if group_name: self.group_name = group_name if description: self.description = description if email_permission: self.email_permission = email_permission class GroupFeed(gdata.data.GDFeed): """Represents a feed of GroupEntry objects.""" # Override entry so that this feed knows how to type its list of entries. entry = [GroupEntry] class GroupMemberEntry(gdata.apps.apps_property_entry.AppsPropertyEntry): """Represents a group member in object form.""" def GetMemberId(self): """Get the memberId of the GroupMember object. Returns: The memberId of this GroupMember object as a string. """ return self._GetProperty(MEMBER_ID) def SetMemberId(self, value): """Set the memberId of this GroupMember object. Args: value: string The new memberId to give this object. """ self._SetProperty(MEMBER_ID, value) member_id = pyproperty(GetMemberId, SetMemberId) def GetMemberType(self): """Get the memberType(User, Group) of the GroupMember object. Returns: The memberType of this GroupMember object as a string or None. """ return self._GetProperty(MEMBER_TYPE) def SetMemberType(self, value): """Set the memberType of this GroupMember object. Args: value: string The new memberType to give this object. """ self._SetProperty(MEMBER_TYPE, value) member_type = pyproperty(GetMemberType, SetMemberType) def GetDirectMember(self): """Get the directMember of the GroupMember object. Returns: The directMember of this GroupMember object as a bool or None. """ return self._GetProperty(DIRECT_MEMBER) def SetDirectMember(self, value): """Set the memberType of this GroupMember object. Args: value: string The new memberType to give this object. """ self._SetProperty(DIRECT_MEMBER, value) direct_member = pyproperty(GetDirectMember, SetDirectMember) def __init__(self, member_id=None, member_type=None, direct_member=None, *args, **kwargs): """Constructs a new GroupMemberEntry object with the given arguments. Args: member_id: string identifier of group member object. member_type: string (optional) member type of group member object. direct_member: bool (optional) if group member object is direct member. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(GroupMemberEntry, self).__init__(*args, **kwargs) if member_id: self.member_id = member_id if member_type: self.member_type = member_type if direct_member: self.direct_member = direct_member class GroupMemberFeed(gdata.data.GDFeed): """Represents a feed of GroupMemberEntry objects.""" # Override entry so that this feed knows how to type its list of entries. entry = [GroupMemberEntry]
Python
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """GroupsClient simplifies Groups Provisioning API calls. GroupsClient extends gdata.client.GDClient to ease interaction with the Group Provisioning API. These interactions include the ability to create, retrieve, update and delete groups. """ __author__ = 'Shraddha gupta <shraddhag@google.com>' import urllib import gdata.apps.groups.data import gdata.client # Multidomain URI templates # The strings in this template are eventually replaced with the API version, # and Google Apps domain name respectively. GROUP_URI_TEMPLATE = '/a/feeds/group/%s/%s' GROUP_MEMBER = 'member' class GroupsProvisioningClient(gdata.client.GDClient): """Client extension for the Google Group Provisioning API service. Attributes: host: string The hostname for the Group Provisioning API service. api_version: string The version of the MultiDomain Provisioning 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 Groups Provisioning API. Args: domain: string The Google Apps domain with Group Provisioning. 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_group_provisioning_uri( self, feed_type=None, group_id=None, member_id=None, params=None): """Creates a resource feed URI for the Groups Provisioning API. Using this client's Google Apps domain, create a feed URI for group provisioning in that domain. If an email address is provided, return a URI for that specific resource. If params are provided, append them as GET params. Args: feed_type: string groupmember for groupmember feed else None group_id: string (optional) The identifier of group for which to make a feed URI. member_id: string (optional) The identifier of group member for which to make a feed URI. params: dict (optional) key -> value params to append as GET vars to the URI. Example: params={'start': 'my-resource-id'} Returns: A string giving the URI for group provisioning for this client's Google Apps domain. """ uri = GROUP_URI_TEMPLATE % (self.api_version, self.domain) if group_id: uri += '/' + group_id if feed_type is GROUP_MEMBER: uri += '/' + feed_type if member_id: uri += '/' + member_id if params: uri += '?' + urllib.urlencode(params) return uri MakeGroupProvisioningUri = make_group_provisioning_uri def make_group_member_uri(self, group_id, member_id=None, params=None): """Creates a resource feed URI for the Group Member Provisioning API.""" return self.make_group_provisioning_uri(GROUP_MEMBER, group_id=group_id, member_id=member_id, params=params) MakeGroupMembersUri = make_group_member_uri def RetrieveAllPages(self, feed, desired_class=gdata.data.GDFeed): """Retrieve all pages and add all elements. Args: feed: gdata.data.GDFeed object with linked elements. desired_class: type of Feed to be returned. Returns: desired_class: subclass of gdata.data.GDFeed. """ next = feed.GetNextLink() while next is not None: next_feed = self.GetFeed(next.href, desired_class=desired_class) for a_entry in next_feed.entry: feed.entry.append(a_entry) next = next_feed.GetNextLink() return feed def retrieve_page_of_groups(self, **kwargs): """Retrieves first page of groups for the given domain. Args: kwargs: The other parameters to pass to gdata.client.GDClient.GetFeed() Returns: A gdata.apps.groups.data.GroupFeed of the groups """ uri = self.MakeGroupProvisioningUri() return self.GetFeed(uri, desired_class=gdata.apps.groups.data.GroupFeed, **kwargs) RetrievePageOfGroups = retrieve_page_of_groups def retrieve_all_groups(self): """Retrieve all groups in this domain. Returns: gdata.apps.groups.data.GroupFeed of the groups """ groups_feed = self.RetrievePageOfGroups() # pagination return self.RetrieveAllPages(groups_feed, gdata.apps.groups.data.GroupFeed) RetrieveAllGroups = retrieve_all_groups def retrieve_group(self, group_id, **kwargs): """Retrieves a single group in the domain. Args: group_id: string groupId of the group to be retrieved kwargs: other parameters to pass to gdata.client.GDClient.GetEntry() Returns: A gdata.apps.groups.data.GroupEntry representing the group """ uri = self.MakeGroupProvisioningUri(group_id=group_id) return self.GetEntry(uri, desired_class=gdata.apps.groups.data.GroupEntry, **kwargs) RetrieveGroup = retrieve_group def retrieve_page_of_member_groups(self, member_id, direct_only=False, **kwargs): """Retrieve one page of 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: gdata.apps.groups.data.GroupFeed of the groups. """ uri = self.MakeGroupProvisioningUri(params={'member':member_id, 'directOnly':direct_only}) return self.GetFeed(uri, desired_class=gdata.apps.groups.data.GroupFeed, **kwargs) RetrievePageOfMemberGroups = retrieve_page_of_member_groups def retrieve_groups(self, member_id, direct_only=False, **kwargs): """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: gdata.apps.groups.data.GroupFeed of the groups """ groups_feed = self.RetrievePageOfMemberGroups(member_id=member_id, direct_only=direct_only) # pagination return self.RetrieveAllPages(groups_feed, gdata.apps.groups.data.GroupFeed) RetrieveGroups = retrieve_groups def create_group(self, group_id, group_name, description=None, email_permission=None, **kwargs): """Creates a group in the domain with the given properties. Args: group_id: string identifier of the group. group_name: string name of the group. description: string (optional) description of the group. email_permission: string (optional) email permission level for the group. kwargs: other parameters to pass to gdata.client.GDClient.post(). Returns: A gdata.apps.groups.data.GroupEntry of the new group """ new_group = gdata.apps.groups.data.GroupEntry(group_id=group_id, group_name=group_name, description=description, email_permission=email_permission) return self.post(new_group, self.MakeGroupProvisioningUri(), **kwargs) CreateGroup = create_group def update_group(self, group_id, group_entry, **kwargs): """Updates the group with the given groupID. Args: group_id: string identifier of the group. group_entry: GroupEntry The group entry with updated values. kwargs: The other parameters to pass to gdata.client.GDClient.put() Returns: A gdata.apps.groups.data.GroupEntry representing the group """ return self.update(group_entry, uri=self.MakeGroupProvisioningUri(group_id=group_id), **kwargs) UpdateGroup = update_group def delete_group(self, group_id, **kwargs): """Deletes the group with the given groupId. Args: group_id: string groupId of the group to delete. kwargs: The other parameters to pass to gdata.client.GDClient.delete() """ self.delete(self.MakeGroupProvisioningUri(group_id=group_id), **kwargs) DeleteGroup = delete_group def retrieve_page_of_members(self, group_id, **kwargs): """Retrieves first page of group members of the group. Args: group_id: string groupId of the group whose members are retrieved kwargs: The other parameters to pass to gdata.client.GDClient.GetFeed() Returns: A gdata.apps.groups.data.GroupMemberFeed of the GroupMember entries """ uri = self.MakeGroupMembersUri(group_id=group_id) return self.GetFeed(uri, desired_class=gdata.apps.groups.data.GroupMemberFeed, **kwargs) RetrievePageOfMembers = retrieve_page_of_members def retrieve_all_members(self, group_id, **kwargs): """Retrieve all members of the group. Returns: gdata.apps.groups.data.GroupMemberFeed """ group_member_feed = self.RetrievePageOfMembers(group_id=group_id) # pagination return self.RetrieveAllPages(group_member_feed, gdata.apps.groups.data.GroupMemberFeed) RetrieveAllMembers = retrieve_all_members def retrieve_group_member(self, group_id, member_id, **kwargs): """Retrieves a group member with the given id from given group. Args: group_id: string groupId of the group whose member is retrieved member_id: string memberId of the group member retrieved kwargs: The other parameters to pass to gdata.client.GDClient.GetEntry() Returns: A gdata.apps.groups.data.GroupEntry representing the group member """ uri = self.MakeGroupMembersUri(group_id=group_id, member_id=member_id) return self.GetEntry(uri, desired_class=gdata.apps.groups.data.GroupMemberEntry, **kwargs) RetrieveGroupMember = retrieve_group_member def add_member_to_group(self, group_id, member_id, member_type=None, direct_member=None, **kwargs): """Adds a member with the given id to the group. Args: group_id: string groupId of the group where member is added member_id: string memberId of the member added member_type: string (optional) type of member(user or group) direct_member: bool (optional) if member is a direct member kwargs: The other parameters to pass to gdata.client.GDClient.post(). Returns: A gdata.apps.groups.data.GroupMemberEntry of the group member """ member = gdata.apps.groups.data.GroupMemberEntry(member_id=member_id, member_type=member_type, direct_member=direct_member) return self.post(member, self.MakeGroupMembersUri(group_id=group_id), **kwargs) AddMemberToGroup = add_member_to_group def remove_member_from_group(self, group_id, member_id, **kwargs): """Remove member from the given group. Args: group_id: string groupId of the group member_id: string memberId of the member to be removed kwargs: The other parameters to pass to gdata.client.GDClient.delete() """ self.delete( self.MakeGroupMembersUri(group_id=group_id, member_id=member_id), **kwargs) RemoveMemberFromGroup = remove_member_from_group
Python
#!/usr/bin/python # # Copyright (C) 2008 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Allow Google Apps domain administrators to manage groups, group members and group owners. GroupsService: Provides methods to manage groups, members and owners. """ __author__ = 'google-apps-apis@googlegroups.com' import urllib import gdata.apps import gdata.apps.service import gdata.service API_VER = '2.0' BASE_URL = '/a/feeds/group/' + API_VER + '/%s' GROUP_MEMBER_URL = BASE_URL + '?member=%s' GROUP_MEMBER_DIRECT_URL = GROUP_MEMBER_URL + '&directOnly=%s' GROUP_ID_URL = BASE_URL + '/%s' MEMBER_URL = BASE_URL + '/%s/member' MEMBER_WITH_SUSPENDED_URL = MEMBER_URL + '?includeSuspendedUsers=%s' MEMBER_ID_URL = MEMBER_URL + '/%s' OWNER_URL = BASE_URL + '/%s/owner' OWNER_WITH_SUSPENDED_URL = OWNER_URL + '?includeSuspendedUsers=%s' OWNER_ID_URL = OWNER_URL + '/%s' PERMISSION_OWNER = 'Owner' PERMISSION_MEMBER = 'Member' PERMISSION_DOMAIN = 'Domain' PERMISSION_ANYONE = 'Anyone' class GroupsService(gdata.apps.service.PropertyService): """Client for the Google Apps Groups service.""" def _ServiceUrl(self, service_type, is_existed, group_id, member_id, owner_email, direct_only=False, domain=None, suspended_users=False): if domain is None: domain = self.domain if service_type == 'group': if group_id != '' and is_existed: return GROUP_ID_URL % (domain, group_id) elif member_id != '': if direct_only: return GROUP_MEMBER_DIRECT_URL % (domain, urllib.quote_plus(member_id), self._Bool2Str(direct_only)) else: return GROUP_MEMBER_URL % (domain, urllib.quote_plus(member_id)) else: return BASE_URL % (domain) if service_type == 'member': if member_id != '' and is_existed: return MEMBER_ID_URL % (domain, group_id, urllib.quote_plus(member_id)) elif suspended_users: return MEMBER_WITH_SUSPENDED_URL % (domain, group_id, self._Bool2Str(suspended_users)) else: return MEMBER_URL % (domain, group_id) if service_type == 'owner': if owner_email != '' and is_existed: return OWNER_ID_URL % (domain, group_id, urllib.quote_plus(owner_email)) elif suspended_users: return OWNER_WITH_SUSPENDED_URL % (domain, group_id, self._Bool2Str(suspended_users)) else: return OWNER_URL % (domain, group_id) def _Bool2Str(self, b): if b is None: return None return str(b is True).lower() def _IsExisted(self, uri): try: self._GetProperties(uri) return True except gdata.apps.service.AppsForYourDomainException, e: if e.error_code == gdata.apps.service.ENTITY_DOES_NOT_EXIST: return False else: raise e def CreateGroup(self, group_id, group_name, description, email_permission): """Create a group. Args: group_id: The ID of the group (e.g. us-sales). group_name: The name of the group. description: A description of the group email_permission: The subscription permission of the group. Returns: A dict containing the result of the create operation. """ uri = self._ServiceUrl('group', False, group_id, '', '') properties = {} properties['groupId'] = group_id properties['groupName'] = group_name properties['description'] = description properties['emailPermission'] = email_permission return self._PostProperties(uri, properties) def UpdateGroup(self, group_id, group_name, description, email_permission): """Update a group's name, description and/or permission. Args: group_id: The ID of the group (e.g. us-sales). group_name: The name of the group. description: A description of the group email_permission: The subscription permission of the group. Returns: A dict containing the result of the update operation. """ uri = self._ServiceUrl('group', True, group_id, '', '') properties = {} properties['groupId'] = group_id properties['groupName'] = group_name properties['description'] = description properties['emailPermission'] = email_permission return self._PutProperties(uri, properties) def RetrieveGroup(self, group_id): """Retrieve a group based on its ID. Args: group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the retrieve operation. """ uri = self._ServiceUrl('group', True, group_id, '', '') return self._GetProperties(uri) def RetrieveAllGroups(self): """Retrieve all groups in the domain. Args: None Returns: A list containing the result of the retrieve operation. """ uri = self._ServiceUrl('group', True, '', '', '') return self._GetPropertiesList(uri) def RetrievePageOfGroups(self, start_group=None): """Retrieve one page of groups in the domain. Args: start_group: The key to continue for pagination through all groups. Returns: A feed object containing the result of the retrieve operation. """ uri = self._ServiceUrl('group', True, '', '', '') if start_group is not None: uri += "?start="+start_group property_feed = self._GetPropertyFeed(uri) return property_feed def RetrieveGroups(self, member_id, direct_only=False): """Retrieve all groups that belong to the given member_id. Args: member_id: The member's email address (e.g. member@example.com). direct_only: Boolean whether only return groups that this member directly belongs to. Returns: A list containing the result of the retrieve operation. """ uri = self._ServiceUrl('group', True, '', member_id, '', direct_only=direct_only) return self._GetPropertiesList(uri) def DeleteGroup(self, group_id): """Delete a group based on its ID. Args: group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the delete operation. """ uri = self._ServiceUrl('group', True, group_id, '', '') return self._DeleteProperties(uri) def AddMemberToGroup(self, member_id, group_id): """Add a member to a group. Args: member_id: The member's email address (e.g. member@example.com). group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the add operation. """ uri = self._ServiceUrl('member', False, group_id, member_id, '') properties = {} properties['memberId'] = member_id return self._PostProperties(uri, properties) def IsMember(self, member_id, group_id): """Check whether the given member already exists in the given group. Args: member_id: The member's email address (e.g. member@example.com). group_id: The ID of the group (e.g. us-sales). Returns: True if the member exists in the group. False otherwise. """ uri = self._ServiceUrl('member', True, group_id, member_id, '') return self._IsExisted(uri) def RetrieveMember(self, member_id, group_id): """Retrieve the given member in the given group. Args: member_id: The member's email address (e.g. member@example.com). group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the retrieve operation. """ uri = self._ServiceUrl('member', True, group_id, member_id, '') return self._GetProperties(uri) def RetrieveAllMembers(self, group_id, suspended_users=False): """Retrieve all members in the given group. Args: group_id: The ID of the group (e.g. us-sales). suspended_users: A boolean; should we include any suspended users in the membership list returned? Returns: A list containing the result of the retrieve operation. """ uri = self._ServiceUrl('member', True, group_id, '', '', suspended_users=suspended_users) return self._GetPropertiesList(uri) def RetrievePageOfMembers(self, group_id, suspended_users=False, start=None): """Retrieve one page of members of a given group. Args: group_id: The ID of the group (e.g. us-sales). suspended_users: A boolean; should we include any suspended users in the membership list returned? start: The key to continue for pagination through all members. Returns: A feed object containing the result of the retrieve operation. """ uri = self._ServiceUrl('member', True, group_id, '', '', suspended_users=suspended_users) if start is not None: if suspended_users: uri += "&start="+start else: uri += "?start="+start property_feed = self._GetPropertyFeed(uri) return property_feed def RemoveMemberFromGroup(self, member_id, group_id): """Remove the given member from the given group. Args: member_id: The member's email address (e.g. member@example.com). group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the remove operation. """ uri = self._ServiceUrl('member', True, group_id, member_id, '') return self._DeleteProperties(uri) def AddOwnerToGroup(self, owner_email, group_id): """Add an owner to a group. Args: owner_email: The email address of a group owner. group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the add operation. """ uri = self._ServiceUrl('owner', False, group_id, '', owner_email) properties = {} properties['email'] = owner_email return self._PostProperties(uri, properties) def IsOwner(self, owner_email, group_id): """Check whether the given member an owner of the given group. Args: owner_email: The email address of a group owner. group_id: The ID of the group (e.g. us-sales). Returns: True if the member is an owner of the given group. False otherwise. """ uri = self._ServiceUrl('owner', True, group_id, '', owner_email) return self._IsExisted(uri) def RetrieveOwner(self, owner_email, group_id): """Retrieve the given owner in the given group. Args: owner_email: The email address of a group owner. group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the retrieve operation. """ uri = self._ServiceUrl('owner', True, group_id, '', owner_email) return self._GetProperties(uri) def RetrieveAllOwners(self, group_id, suspended_users=False): """Retrieve all owners of the given group. Args: group_id: The ID of the group (e.g. us-sales). suspended_users: A boolean; should we include any suspended users in the ownership list returned? Returns: A list containing the result of the retrieve operation. """ uri = self._ServiceUrl('owner', True, group_id, '', '', suspended_users=suspended_users) return self._GetPropertiesList(uri) def RetrievePageOfOwners(self, group_id, suspended_users=False, start=None): """Retrieve one page of owners of the given group. Args: group_id: The ID of the group (e.g. us-sales). suspended_users: A boolean; should we include any suspended users in the ownership list returned? start: The key to continue for pagination through all owners. Returns: A feed object containing the result of the retrieve operation. """ uri = self._ServiceUrl('owner', True, group_id, '', '', suspended_users=suspended_users) if start is not None: if suspended_users: uri += "&start="+start else: uri += "?start="+start property_feed = self._GetPropertyFeed(uri) return property_feed def RemoveOwnerFromGroup(self, owner_email, group_id): """Remove the given owner from the given group. Args: owner_email: The email address of a group owner. group_id: The ID of the group (e.g. us-sales). Returns: A dict containing the result of the remove operation. """ uri = self._ServiceUrl('owner', True, group_id, '', owner_email) return self._DeleteProperties(uri)
Python
# Copyright (C) 2008 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Allow Google Apps domain administrators to audit user data. AuditService: Set auditing.""" __author__ = 'jlee@pbu.edu' from base64 import b64encode import gdata.apps import gdata.apps.service import gdata.service class AuditService(gdata.apps.service.PropertyService): """Client for the Google Apps Audit service.""" def _serviceUrl(self, setting_id, domain=None, user=None): if domain is None: domain = self.domain if user is None: return '/a/feeds/compliance/audit/%s/%s' % (setting_id, domain) else: return '/a/feeds/compliance/audit/%s/%s/%s' % (setting_id, domain, user) def updatePGPKey(self, pgpkey): """Updates Public PGP Key Google uses to encrypt audit data Args: pgpkey: string, ASCII text of PGP Public Key to be used Returns: A dict containing the result of the POST operation.""" uri = self._serviceUrl('publickey') b64pgpkey = b64encode(pgpkey) properties = {} properties['publicKey'] = b64pgpkey return self._PostProperties(uri, properties) def createEmailMonitor(self, source_user, destination_user, end_date, begin_date=None, incoming_headers_only=False, outgoing_headers_only=False, drafts=False, drafts_headers_only=False, chats=False, chats_headers_only=False): """Creates a email monitor, forwarding the source_users emails/chats Args: source_user: string, the user whose email will be audited destination_user: string, the user to receive the audited email end_date: string, the date the audit will end in "yyyy-MM-dd HH:mm" format, required begin_date: string, the date the audit will start in "yyyy-MM-dd HH:mm" format, leave blank to use current time incoming_headers_only: boolean, whether to audit only the headers of mail delivered to source user outgoing_headers_only: boolean, whether to audit only the headers of mail sent from the source user drafts: boolean, whether to audit draft messages of the source user drafts_headers_only: boolean, whether to audit only the headers of mail drafts saved by the user chats: boolean, whether to audit archived chats of the source user chats_headers_only: boolean, whether to audit only the headers of archived chats of the source user Returns: A dict containing the result of the POST operation.""" uri = self._serviceUrl('mail/monitor', user=source_user) properties = {} properties['destUserName'] = destination_user if begin_date is not None: properties['beginDate'] = begin_date properties['endDate'] = end_date if incoming_headers_only: properties['incomingEmailMonitorLevel'] = 'HEADER_ONLY' else: properties['incomingEmailMonitorLevel'] = 'FULL_MESSAGE' if outgoing_headers_only: properties['outgoingEmailMonitorLevel'] = 'HEADER_ONLY' else: properties['outgoingEmailMonitorLevel'] = 'FULL_MESSAGE' if drafts: if drafts_headers_only: properties['draftMonitorLevel'] = 'HEADER_ONLY' else: properties['draftMonitorLevel'] = 'FULL_MESSAGE' if chats: if chats_headers_only: properties['chatMonitorLevel'] = 'HEADER_ONLY' else: properties['chatMonitorLevel'] = 'FULL_MESSAGE' return self._PostProperties(uri, properties) def getEmailMonitors(self, user): """"Gets the email monitors for the given user Args: user: string, the user to retrieve email monitors for Returns: list results of the POST operation """ uri = self._serviceUrl('mail/monitor', user=user) return self._GetPropertiesList(uri) def deleteEmailMonitor(self, source_user, destination_user): """Deletes the email monitor for the given user Args: source_user: string, the user who is being monitored destination_user: string, theuser who recieves the monitored emails Returns: Nothing """ uri = self._serviceUrl('mail/monitor', user=source_user+'/'+destination_user) try: return self._DeleteProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def createAccountInformationRequest(self, user): """Creates a request for account auditing details Args: user: string, the user to request account information for Returns: A dict containing the result of the post operation.""" uri = self._serviceUrl('account', user=user) properties = {} #XML Body is left empty try: return self._PostProperties(uri, properties) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def getAccountInformationRequestStatus(self, user, request_id): """Gets the status of an account auditing request Args: user: string, the user whose account auditing details were requested request_id: string, the request_id Returns: A dict containing the result of the get operation.""" uri = self._serviceUrl('account', user=user+'/'+request_id) try: return self._GetProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def getAllAccountInformationRequestsStatus(self): """Gets the status of all account auditing requests for the domain Args: None Returns: list results of the POST operation """ uri = self._serviceUrl('account') return self._GetPropertiesList(uri) def deleteAccountInformationRequest(self, user, request_id): """Deletes the request for account auditing information Args: user: string, the user whose account auditing details were requested request_id: string, the request_id Returns: Nothing """ uri = self._serviceUrl('account', user=user+'/'+request_id) try: return self._DeleteProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def createMailboxExportRequest(self, user, begin_date=None, end_date=None, include_deleted=False, search_query=None, headers_only=False): """Creates a mailbox export request Args: user: string, the user whose mailbox export is being requested begin_date: string, date of earliest emails to export, optional, defaults to date of account creation format is 'yyyy-MM-dd HH:mm' end_date: string, date of latest emails to export, optional, defaults to current date format is 'yyyy-MM-dd HH:mm' include_deleted: boolean, whether to include deleted emails in export, mutually exclusive with search_query search_query: string, gmail style search query, matched emails will be exported, mutually exclusive with include_deleted Returns: A dict containing the result of the post operation.""" uri = self._serviceUrl('mail/export', user=user) properties = {} if begin_date is not None: properties['beginDate'] = begin_date if end_date is not None: properties['endDate'] = end_date if include_deleted is not None: properties['includeDeleted'] = gdata.apps.service._bool2str(include_deleted) if search_query is not None: properties['searchQuery'] = search_query if headers_only is True: properties['packageContent'] = 'HEADER_ONLY' else: properties['packageContent'] = 'FULL_MESSAGE' return self._PostProperties(uri, properties) def getMailboxExportRequestStatus(self, user, request_id): """Gets the status of an mailbox export request Args: user: string, the user whose mailbox were requested request_id: string, the request_id Returns: A dict containing the result of the get operation.""" uri = self._serviceUrl('mail/export', user=user+'/'+request_id) try: return self._GetProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def getAllMailboxExportRequestsStatus(self): """Gets the status of all mailbox export requests for the domain Args: None Returns: list results of the POST operation """ uri = self._serviceUrl('mail/export') return self._GetPropertiesList(uri) def deleteMailboxExportRequest(self, user, request_id): """Deletes the request for mailbox export Args: user: string, the user whose mailbox were requested request_id: string, the request_id Returns: Nothing """ uri = self._serviceUrl('mail/export', user=user+'/'+request_id) try: return self._DeleteProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0])
Python
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Generic class for Set/Get properties of GData Provisioning clients.""" __author__ = 'Gunjan Sharma <gunjansharma@google.com>' import gdata.apps import gdata.apps_property import gdata.data class AppsPropertyEntry(gdata.data.GDEntry): """Represents a generic entry in object form.""" property = [gdata.apps_property.AppsProperty] def _GetProperty(self, name): """Get the apps:property value with the given name. Args: name: string Name of the apps:property value to get. Returns: The apps:property value with the given name, or None if the name was invalid. """ value = None for p in self.property: if p.name == name: value = p.value break return value def _SetProperty(self, name, value): """Set the apps:property value with the given name to the given value. Args: name: string Name of the apps:property value to set. value: string Value to give the apps:property value with the given name. """ found = False for i in range(len(self.property)): if self.property[i].name == name: self.property[i].value = value found = True break if not found: self.property.append( gdata.apps_property.AppsProperty(name=name, value=value))
Python
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model classes for the Organization Unit Provisioning API.""" __author__ = 'Gunjan Sharma <gunjansharma@google.com>' import gdata.apps import gdata.apps.apps_property_entry import gdata.apps_property import gdata.data # This is required to work around a naming conflict between the Google # Spreadsheets API and Python's built-in property function pyproperty = property # The apps:property name of an organization unit ORG_UNIT_NAME = 'name' # The apps:property orgUnitPath of an organization unit ORG_UNIT_PATH = 'orgUnitPath' # The apps:property parentOrgUnitPath of an organization unit PARENT_ORG_UNIT_PATH = 'parentOrgUnitPath' # The apps:property description of an organization unit ORG_UNIT_DESCRIPTION = 'description' # The apps:property blockInheritance of an organization unit ORG_UNIT_BLOCK_INHERITANCE = 'blockInheritance' # The apps:property userEmail of a user entry USER_EMAIL = 'orgUserEmail' # The apps:property list of users to move USERS_TO_MOVE = 'usersToMove' # The apps:property list of moved users MOVED_USERS = 'usersMoved' # The apps:property customerId for the domain CUSTOMER_ID = 'customerId' # The apps:property name of the customer org unit CUSTOMER_ORG_UNIT_NAME = 'customerOrgUnitName' # The apps:property description of the customer org unit CUSTOMER_ORG_UNIT_DESCRIPTION = 'customerOrgUnitDescription' # The apps:property old organization unit's path for a user OLD_ORG_UNIT_PATH = 'oldOrgUnitPath' class CustomerIdEntry(gdata.apps.apps_property_entry.AppsPropertyEntry): """Represents a customerId entry in object form.""" def GetCustomerId(self): """Get the customer ID of the customerId object. Returns: The customer ID of this customerId object as a string or None. """ return self._GetProperty(CUSTOMER_ID) customer_id = pyproperty(GetCustomerId) def GetOrgUnitName(self): """Get the Organization Unit name of the customerId object. Returns: The Organization unit name of this customerId object as a string or None. """ return self._GetProperty(ORG_UNIT_NAME) org_unit_name = pyproperty(GetOrgUnitName) def GetCustomerOrgUnitName(self): """Get the Customer Organization Unit name of the customerId object. Returns: The Customer Organization unit name of this customerId object as a string or None. """ return self._GetProperty(CUSTOMER_ORG_UNIT_NAME) customer_org_unit_name = pyproperty(GetCustomerOrgUnitName) def GetOrgUnitDescription(self): """Get the Organization Unit Description of the customerId object. Returns: The Organization Unit Description of this customerId object as a string or None. """ return self._GetProperty(ORG_UNIT_DESCRIPTION) org_unit_description = pyproperty(GetOrgUnitDescription) def GetCustomerOrgUnitDescription(self): """Get the Customer Organization Unit Description of the customerId object. Returns: The Customer Organization Unit Description of this customerId object as a string or None. """ return self._GetProperty(CUSTOMER_ORG_UNIT_DESCRIPTION) customer_org_unit_description = pyproperty(GetCustomerOrgUnitDescription) class OrgUnitEntry(gdata.apps.apps_property_entry.AppsPropertyEntry): """Represents an OrganizationUnit in object form.""" def GetOrgUnitName(self): """Get the Organization Unit name of the OrganizationUnit object. Returns: The Organization unit name of this OrganizationUnit object as a string or None. """ return self._GetProperty(ORG_UNIT_NAME) def SetOrgUnitName(self, value): """Set the Organization Unit name of the OrganizationUnit object. Args: value: [string] The new Organization Unit name to give this object. """ self._SetProperty(ORG_UNIT_NAME, value) org_unit_name = pyproperty(GetOrgUnitName, SetOrgUnitName) def GetOrgUnitPath(self): """Get the Organization Unit Path of the OrganizationUnit object. Returns: The Organization Unit Path of this OrganizationUnit object as a string or None. """ return self._GetProperty(ORG_UNIT_PATH) def SetOrgUnitPath(self, value): """Set the Organization Unit path of the OrganizationUnit object. Args: value: [string] The new Organization Unit path to give this object. """ self._SetProperty(ORG_UNIT_PATH, value) org_unit_path = pyproperty(GetOrgUnitPath, SetOrgUnitPath) def GetParentOrgUnitPath(self): """Get the Parent Organization Unit Path of the OrganizationUnit object. Returns: The Parent Organization Unit Path of this OrganizationUnit object as a string or None. """ return self._GetProperty(PARENT_ORG_UNIT_PATH) def SetParentOrgUnitPath(self, value): """Set the Parent Organization Unit path of the OrganizationUnit object. Args: value: [string] The new Parent Organization Unit path to give this object. """ self._SetProperty(PARENT_ORG_UNIT_PATH, value) parent_org_unit_path = pyproperty(GetParentOrgUnitPath, SetParentOrgUnitPath) def GetOrgUnitDescription(self): """Get the Organization Unit Description of the OrganizationUnit object. Returns: The Organization Unit Description of this OrganizationUnit object as a string or None. """ return self._GetProperty(ORG_UNIT_DESCRIPTION) def SetOrgUnitDescription(self, value): """Set the Organization Unit Description of the OrganizationUnit object. Args: value: [string] The new Organization Unit Description to give this object. """ self._SetProperty(ORG_UNIT_DESCRIPTION, value) org_unit_description = pyproperty(GetOrgUnitDescription, SetOrgUnitDescription) def GetOrgUnitBlockInheritance(self): """Get the block_inheritance flag of the OrganizationUnit object. Returns: The the block_inheritance flag of this OrganizationUnit object as a string or None. """ return self._GetProperty(ORG_UNIT_BLOCK_INHERITANCE) def SetOrgUnitBlockInheritance(self, value): """Set the block_inheritance flag of the OrganizationUnit object. Args: value: [string] The new block_inheritance flag to give this object. """ self._SetProperty(ORG_UNIT_BLOCK_INHERITANCE, value) org_unit_block_inheritance = pyproperty(GetOrgUnitBlockInheritance, SetOrgUnitBlockInheritance) def GetMovedUsers(self): """Get the moved users of the OrganizationUnit object. Returns: The the moved users of this OrganizationUnit object as a string or None. """ return self._GetProperty(MOVED_USERS) def SetUsersToMove(self, value): """Set the Users to Move of the OrganizationUnit object. Args: value: [string] The comma seperated list of users to move to give this object. """ self._SetProperty(USERS_TO_MOVE, value) move_users = pyproperty(GetMovedUsers, SetUsersToMove) def __init__( self, org_unit_name=None, org_unit_path=None, parent_org_unit_path=None, org_unit_description=None, org_unit_block_inheritance=None, move_users=None, *args, **kwargs): """Constructs a new OrganizationUnit object with the given arguments. Args: org_unit_name: string (optional) The organization unit name for the object. org_unit_path: string (optional) The organization unit path for the object. parent_org_unit_path: string (optional) The parent organization unit path for the object. org_unit_description: string (optional) The organization unit description for the object. org_unit_block_inheritance: boolean (optional) weather or not inheritance from the organization unit is blocked. move_users: string (optional) comma seperated list of users to move. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(OrgUnitEntry, self).__init__(*args, **kwargs) if org_unit_name: self.org_unit_name = org_unit_name if org_unit_path: self.org_unit_path = org_unit_path if parent_org_unit_path: self.parent_org_unit_path = parent_org_unit_path if org_unit_description: self.org_unit_description = org_unit_description if org_unit_block_inheritance is not None: self.org_unit_block_inheritance = str(org_unit_block_inheritance) if move_users: self.move_users = move_users class OrgUnitFeed(gdata.data.GDFeed): """Represents a feed of OrgUnitEntry objects.""" # Override entry so that this feed knows how to type its list of entries. entry = [OrgUnitEntry] class OrgUserEntry(gdata.apps.apps_property_entry.AppsPropertyEntry): """Represents an OrgUser in object form.""" def GetUserEmail(self): """Get the user email address of the OrgUser object. Returns: The user email address of this OrgUser object as a string or None. """ return self._GetProperty(USER_EMAIL) def SetUserEmail(self, value): """Set the user email address of this OrgUser object. Args: value: string The new user email address to give this object. """ self._SetProperty(USER_EMAIL, value) user_email = pyproperty(GetUserEmail, SetUserEmail) def GetOrgUnitPath(self): """Get the Organization Unit Path of the OrgUser object. Returns: The Organization Unit Path of this OrgUser object as a string or None. """ return self._GetProperty(ORG_UNIT_PATH) def SetOrgUnitPath(self, value): """Set the Organization Unit path of the OrgUser object. Args: value: [string] The new Organization Unit path to give this object. """ self._SetProperty(ORG_UNIT_PATH, value) org_unit_path = pyproperty(GetOrgUnitPath, SetOrgUnitPath) def GetOldOrgUnitPath(self): """Get the Old Organization Unit Path of the OrgUser object. Returns: The Old Organization Unit Path of this OrgUser object as a string or None. """ return self._GetProperty(OLD_ORG_UNIT_PATH) def SetOldOrgUnitPath(self, value): """Set the Old Organization Unit path of the OrgUser object. Args: value: [string] The new Old Organization Unit path to give this object. """ self._SetProperty(OLD_ORG_UNIT_PATH, value) old_org_unit_path = pyproperty(GetOldOrgUnitPath, SetOldOrgUnitPath) def __init__( self, user_email=None, org_unit_path=None, old_org_unit_path=None, *args, **kwargs): """Constructs a new OrgUser object with the given arguments. Args: user_email: string (optional) The user email address for the object. org_unit_path: string (optional) The organization unit path for the object. old_org_unit_path: string (optional) The old organization unit path for the object. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(OrgUserEntry, self).__init__(*args, **kwargs) if user_email: self.user_email = user_email if org_unit_path: self.org_unit_path = org_unit_path if old_org_unit_path: self.old_org_unit_path = old_org_unit_path class OrgUserFeed(gdata.data.GDFeed): """Represents a feed of OrgUserEntry objects.""" # Override entry so that this feed knows how to type its list of entries. entry = [OrgUserEntry]
Python
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """OrganizationUnitProvisioningClient simplifies OrgUnit Provisioning API calls. OrganizationUnitProvisioningClient extends gdata.client.GDClient to ease interaction with the Google Organization Unit Provisioning API. These interactions include the ability to create, retrieve, update and delete organization units, move users within organization units, retrieve customerId and update and retrieve users in organization units. """ __author__ = 'Gunjan Sharma <gunjansharma@google.com>' import urllib import gdata.apps.organization.data import gdata.client CUSTOMER_ID_URI_TEMPLATE = '/a/feeds/customer/%s/customerId' # OrganizationUnit URI templates # The strings in this template are eventually replaced with the feed type # (orgunit/orguser), API version and Google Apps domain name, respectively. ORGANIZATION_UNIT_URI_TEMPLATE = '/a/feeds/%s/%s/%s' # The value for orgunit requests ORGANIZATION_UNIT_FEED = 'orgunit' # The value for orguser requests ORGANIZATION_USER_FEED = 'orguser' class OrganizationUnitProvisioningClient(gdata.client.GDClient): """Client extension for the Google Org Unit Provisioning API service. Attributes: host: string The hostname for the MultiDomain Provisioning API service. api_version: string The version of the MultiDomain Provisioning 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 Organization Unit Provisioning API. Args: domain: string The Google Apps domain with Organization Unit Provisioning. auth_token: (optional) gdata.gauth.ClientLoginToken, AuthSubToken, or OAuthToken which authorizes this client to edit the Organization Units. """ gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs) self.domain = domain def make_organization_unit_provisioning_uri( self, feed_type, customer_id, org_unit_path_or_user_email=None, params=None): """Creates a resource feed URI for the Organization Unit Provisioning API. Using this client's Google Apps domain, create a feed URI for organization unit provisioning in that domain. If an org unit path or org user email address is provided, return a URI for that specific resource. If params are provided, append them as GET params. Args: feed_type: string The type of feed (orgunit/orguser) customer_id: string The customerId of the user. org_unit_path_or_user_email: string (optional) The org unit path or org user email address for which to make a feed URI. params: dict (optional) key -> value params to append as GET vars to the URI. Example: params={'start': 'my-resource-id'} Returns: A string giving the URI for organization unit provisioning for this client's Google Apps domain. """ uri = ORGANIZATION_UNIT_URI_TEMPLATE % (feed_type, self.api_version, customer_id) if org_unit_path_or_user_email: uri += '/' + org_unit_path_or_user_email if params: uri += '?' + urllib.urlencode(params) return uri MakeOrganizationUnitProvisioningUri = make_organization_unit_provisioning_uri def make_organization_unit_orgunit_provisioning_uri(self, customer_id, org_unit_path=None, params=None): """Creates a resource feed URI for the orgunit's Provisioning API calls. Using this client's Google Apps domain, create a feed URI for organization unit orgunit's provisioning in that domain. If an org_unit_path is provided, return a URI for that specific resource. If params are provided, append them as GET params. Args: customer_id: string The customerId of the user. org_unit_path: string (optional) The organization unit's path for which to make a feed URI. params: dict (optional) key -> value params to append as GET vars to the URI. Example: params={'start': 'my-resource-id'} Returns: A string giving the URI for organization unit provisioning for given org_unit_path """ return self.make_organization_unit_provisioning_uri( ORGANIZATION_UNIT_FEED, customer_id, org_unit_path, params) MakeOrganizationUnitOrgunitProvisioningUri = make_organization_unit_orgunit_provisioning_uri def make_organization_unit_orguser_provisioning_uri(self, customer_id, org_user_email=None, params=None): """Creates a resource feed URI for the orguser's Provisioning API calls. Using this client's Google Apps domain, create a feed URI for organization unit orguser's provisioning in that domain. If an org_user_email is provided, return a URI for that specific resource. If params are provided, append them as GET params. Args: customer_id: string The customerId of the user. org_user_email: string (optional) The organization unit's path for which to make a feed URI. params: dict (optional) key -> value params to append as GET vars to the URI. Example: params={'start': 'my-resource-id'} Returns: A string giving the URI for organization user provisioning for given org_user_email """ return self.make_organization_unit_provisioning_uri( ORGANIZATION_USER_FEED, customer_id, org_user_email, params) MakeOrganizationUnitOrguserProvisioningUri = make_organization_unit_orguser_provisioning_uri def make_customer_id_feed_uri(self): """Creates a feed uri for retrieving customerId of the user. Returns: A string giving the URI for retrieving customerId of the user. """ uri = CUSTOMER_ID_URI_TEMPLATE % (self.api_version) return uri MakeCustomerIdFeedUri = make_customer_id_feed_uri def retrieve_customer_id(self, **kwargs): """Retrieve the Customer ID for the customer domain. Returns: A gdata.apps.organization.data.CustomerIdEntry. """ uri = self.MakeCustomerIdFeedUri() return self.GetEntry( uri, desired_class=gdata.apps.organization.data.CustomerIdEntry, **kwargs) RetrieveCustomerId = retrieve_customer_id def create_org_unit(self, customer_id, name, parent_org_unit_path='/', description='', block_inheritance=False, **kwargs): """Create a Organization Unit. Args: customer_id: string The ID of the Google Apps customer. name: string The simple organization unit text name, not the full path name. parent_org_unit_path: string 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: string The human readable text description of the organization unit (optional). block_inheritance: boolean This parameter blocks policy setting inheritance from organization units higher in the organization tree (default: False). Returns: A gdata.apps.organization.data.OrgUnitEntry representing an organization unit. """ new_org_unit = gdata.apps.organization.data.OrgUnitEntry( org_unit_name=name, parent_org_unit_path=parent_org_unit_path, org_unit_description=description, org_unit_block_inheritance=block_inheritance) return self.post( new_org_unit, self.MakeOrganizationUnitOrgunitProvisioningUri(customer_id), **kwargs) CreateOrgUnit = create_org_unit def update_org_unit(self, customer_id, org_unit_path, org_unit_entry, **kwargs): """Update a Organization Unit. Args: customer_id: string The ID of the Google Apps customer. org_unit_path: string The organization's full path name. [Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)] org_unit_entry: gdata.apps.organization.data.OrgUnitEntry The updated organization unit entry. Returns: A gdata.apps.organization.data.OrgUnitEntry representing an organization unit. """ if not org_unit_entry.GetParentOrgUnitPath(): org_unit_entry.SetParentOrgUnitPath('/') return self.update(org_unit_entry, uri=self.MakeOrganizationUnitOrgunitProvisioningUri( customer_id, org_unit_path=org_unit_path), **kwargs) UpdateOrgUnit = update_org_unit def move_users_to_org_unit(self, customer_id, org_unit_path, users_to_move, **kwargs): """Move a user to an Organization Unit. Args: customer_id: string The ID of the Google Apps customer. org_unit_path: string The organization's full path name. [Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)] users_to_move: list Email addresses of users to move in list format. [Note: You can move a maximum of 25 users at one time.] Returns: A gdata.apps.organization.data.OrgUnitEntry representing an organization unit. """ org_unit_entry = self.retrieve_org_unit(customer_id, org_unit_path) org_unit_entry.SetUsersToMove(', '.join(users_to_move)) if not org_unit_entry.GetParentOrgUnitPath(): org_unit_entry.SetParentOrgUnitPath('/') return self.update(org_unit_entry, uri=self.MakeOrganizationUnitOrgunitProvisioningUri( customer_id, org_unit_path=org_unit_path), **kwargs) MoveUserToOrgUnit = move_users_to_org_unit def retrieve_org_unit(self, customer_id, org_unit_path, **kwargs): """Retrieve a Orgunit based on its path. Args: customer_id: string The ID of the Google Apps customer. org_unit_path: string The organization's full path name. [Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)] Returns: A gdata.apps.organization.data.OrgUnitEntry representing an organization unit. """ uri = self.MakeOrganizationUnitOrgunitProvisioningUri( customer_id, org_unit_path=org_unit_path) return self.GetEntry( uri, desired_class=gdata.apps.organization.data.OrgUnitEntry, **kwargs) RetrieveOrgUnit = retrieve_org_unit def retrieve_feed_from_uri(self, uri, desired_class, **kwargs): """Retrieve feed from given uri. Args: uri: string The uri from where to get the feed. desired_class: Feed The type of feed that if to be retrieved. Returns: Feed of type desired class. """ return self.GetFeed(uri, desired_class=desired_class, **kwargs) RetrieveFeedFromUri = retrieve_feed_from_uri def retrieve_all_org_units_from_uri(self, uri, **kwargs): """Retrieve all OrgUnits from given uri. Args: uri: string The uri from where to get the orgunits. Returns: gdata.apps.organisation.data.OrgUnitFeed object """ orgunit_feed = gdata.apps.organization.data.OrgUnitFeed() temp_feed = self.RetrieveFeedFromUri( uri, gdata.apps.organization.data.OrgUnitFeed) orgunit_feed.entry = temp_feed.entry next_link = temp_feed.GetNextLink() while next_link is not None: uri = next_link.GetAttributes()[0].value temp_feed = self.GetFeed( uri, desired_class=gdata.apps.organization.data.OrgUnitFeed, **kwargs) orgunit_feed.entry[0:0] = temp_feed.entry next_link = temp_feed.GetNextLink() return orgunit_feed RetrieveAllOrgUnitsFromUri = retrieve_all_org_units_from_uri def retrieve_all_org_units(self, customer_id, **kwargs): """Retrieve all OrgUnits in the customer's domain. Args: customer_id: string The ID of the Google Apps customer. Returns: gdata.apps.organisation.data.OrgUnitFeed object """ uri = self.MakeOrganizationUnitOrgunitProvisioningUri( customer_id, params={'get': 'all'}, **kwargs) return self.RetrieveAllOrgUnitsFromUri(uri) RetrieveAllOrgUnits = retrieve_all_org_units def retrieve_page_of_org_units(self, customer_id, startKey=None, **kwargs): """Retrieve one page of OrgUnits in the customer's domain. Args: customer_id: string The ID of the Google Apps customer. startKey: string The key to continue for pagination through all OrgUnits. Returns: gdata.apps.organisation.data.OrgUnitFeed object """ uri = '' if startKey is not None: uri = self.MakeOrganizationUnitOrgunitProvisioningUri( customer_id, params={'get': 'all', 'startKey': startKey}, **kwargs) else: uri = self.MakeOrganizationUnitOrgunitProvisioningUri( customer_id, params={'get': 'all'}, **kwargs) return self.GetFeed( uri, desired_class=gdata.apps.organization.data.OrgUnitFeed, **kwargs) RetrievePageOfOrgUnits = retrieve_page_of_org_units def retrieve_sub_org_units(self, customer_id, org_unit_path, **kwargs): """Retrieve all Sub-OrgUnits of the provided OrgUnit. Args: customer_id: string The ID of the Google Apps customer. org_unit_path: string The organization's full path name. [Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)] Returns: gdata.apps.organisation.data.OrgUnitFeed object """ uri = self.MakeOrganizationUnitOrgunitProvisioningUri( customer_id, params={'get': 'children', 'orgUnitPath': org_unit_path}, **kwargs) return self.RetrieveAllOrgUnitsFromUri(uri) RetrieveSubOrgUnits = retrieve_sub_org_units def delete_org_unit(self, customer_id, org_unit_path, **kwargs): """Delete a Orgunit based on its path. Args: customer_id: string The ID of the Google Apps customer. org_unit_path: string The organization's full path name. [Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)] Returns: An HTTP response object. See gdata.client.request(). """ return self.delete(self.MakeOrganizationUnitOrgunitProvisioningUri( customer_id, org_unit_path=org_unit_path), **kwargs) DeleteOrgUnit = delete_org_unit def update_org_user(self, customer_id, user_email, org_unit_path, **kwargs): """Update the OrgUnit of a OrgUser. Args: customer_id: string The ID of the Google Apps customer. user_email: string The email address of the user. org_unit_path: string The new organization's full path name. [Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)] Returns: A gdata.apps.organization.data.OrgUserEntry representing an organization user. """ old_user_entry = self.RetrieveOrgUser(customer_id, user_email) old_org_unit_path = old_user_entry.GetOrgUnitPath() if not old_org_unit_path: old_org_unit_path = '/' old_user_entry.SetOldOrgUnitPath(old_org_unit_path) old_user_entry.SetOrgUnitPath(org_unit_path) return self.update(old_user_entry, uri=self.MakeOrganizationUnitOrguserProvisioningUri( customer_id, user_email), **kwargs) UpdateOrgUser = update_org_user def retrieve_org_user(self, customer_id, user_email, **kwargs): """Retrieve an organization user. Args: customer_id: string The ID of the Google Apps customer. user_email: string The email address of the user. Returns: A gdata.apps.organization.data.OrgUserEntry representing an organization user. """ uri = self.MakeOrganizationUnitOrguserProvisioningUri(customer_id, user_email) return self.GetEntry( uri, desired_class=gdata.apps.organization.data.OrgUserEntry, **kwargs) RetrieveOrgUser = retrieve_org_user def retrieve_all_org_users_from_uri(self, uri, **kwargs): """Retrieve all OrgUsers from given uri. Args: uri: string The uri from where to get the orgusers. Returns: gdata.apps.organisation.data.OrgUserFeed object """ orguser_feed = gdata.apps.organization.data.OrgUserFeed() temp_feed = self.RetrieveFeedFromUri( uri, gdata.apps.organization.data.OrgUserFeed) orguser_feed.entry = temp_feed.entry next_link = temp_feed.GetNextLink() while next_link is not None: uri = next_link.GetAttributes()[0].value temp_feed = self.GetFeed( uri, desired_class=gdata.apps.organization.data.OrgUserFeed, **kwargs) orguser_feed.entry[0:0] = temp_feed.entry next_link = temp_feed.GetNextLink() return orguser_feed RetrieveAllOrgUsersFromUri = retrieve_all_org_users_from_uri def retrieve_all_org_users(self, customer_id, **kwargs): """Retrieve all OrgUsers in the customer's domain. Args: customer_id: string The ID of the Google Apps customer. Returns: gdata.apps.organisation.data.OrgUserFeed object """ uri = self.MakeOrganizationUnitOrguserProvisioningUri( customer_id, params={'get': 'all'}, **kwargs) return self.RetrieveAllOrgUsersFromUri(uri) RetrieveAllOrgUsers = retrieve_all_org_users def retrieve_page_of_org_users(self, customer_id, startKey=None, **kwargs): """Retrieve one page of OrgUsers in the customer's domain. Args: customer_id: string The ID of the Google Apps customer. startKey: The string key to continue for pagination through all OrgUnits. Returns: gdata.apps.organisation.data.OrgUserFeed object """ uri = '' if startKey is not None: uri = self.MakeOrganizationUnitOrguserProvisioningUri( customer_id, params={'get': 'all', 'startKey': startKey}, **kwargs) else: uri = self.MakeOrganizationUnitOrguserProvisioningUri( customer_id, params={'get': 'all'}) return self.GetFeed( uri, desired_class=gdata.apps.organization.data.OrgUserFeed, **kwargs) RetrievePageOfOrgUsers = retrieve_page_of_org_users def retrieve_org_unit_users(self, customer_id, org_unit_path, **kwargs): """Retrieve all OrgUsers of the provided OrgUnit. Args: customer_id: string The ID of the Google Apps customer. org_unit_path: string The organization's full path name. [Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization)] Returns: gdata.apps.organisation.data.OrgUserFeed object """ uri = self.MakeOrganizationUnitOrguserProvisioningUri( customer_id, params={'get': 'children', 'orgUnitPath': org_unit_path}) return self.RetrieveAllOrgUsersFromUri(uri, **kwargs) RetrieveOrgUnitUsers = retrieve_org_unit_users
Python
#!/usr/bin/python # # Copyright (C) 2008 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Allow Google Apps domain administrators to manage organization unit and organization user. OrganizationService: Provides methods to manage organization unit and organization user. """ __author__ = 'Alexandre Vivien (alex@simplecode.fr)' import gdata.apps import gdata.apps.service import gdata.service API_VER = '2.0' CUSTOMER_BASE_URL = '/a/feeds/customer/2.0/customerId' BASE_UNIT_URL = '/a/feeds/orgunit/' + API_VER + '/%s' UNIT_URL = BASE_UNIT_URL + '/%s' UNIT_ALL_URL = BASE_UNIT_URL + '?get=all' UNIT_CHILD_URL = BASE_UNIT_URL + '?get=children&orgUnitPath=%s' BASE_USER_URL = '/a/feeds/orguser/' + API_VER + '/%s' USER_URL = BASE_USER_URL + '/%s' USER_ALL_URL = BASE_USER_URL + '?get=all' USER_CHILD_URL = BASE_USER_URL + '?get=children&orgUnitPath=%s' class OrganizationService(gdata.apps.service.PropertyService): """Client for the Google Apps Organizations service.""" def _Bool2Str(self, b): if b is None: return None return str(b is True).lower() def RetrieveCustomerId(self): """Retrieve the Customer ID for the account of the authenticated administrator making this request. Args: None. Returns: A dict containing the result of the retrieve operation. """ uri = CUSTOMER_BASE_URL return self._GetProperties(uri) def CreateOrgUnit(self, customer_id, name, parent_org_unit_path='/', description='', block_inheritance=False): """Create a Organization Unit. Args: customer_id: The ID of the Google Apps customer. name: The simple organization unit text name, not the full path name. parent_org_unit_path: The full path of the parental tree to this organization unit (default: '/'). Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) description: The human readable text description of the organization unit (optional). block_inheritance: This parameter blocks policy setting inheritance from organization units higher in the organization tree (default: False). Returns: A dict containing the result of the create operation. """ uri = BASE_UNIT_URL % (customer_id) properties = {} properties['name'] = name properties['parentOrgUnitPath'] = parent_org_unit_path properties['description'] = description properties['blockInheritance'] = self._Bool2Str(block_inheritance) return self._PostProperties(uri, properties) def UpdateOrgUnit(self, customer_id, org_unit_path, name=None, parent_org_unit_path=None, description=None, block_inheritance=None): """Update a Organization Unit. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) name: The simple organization unit text name, not the full path name. parent_org_unit_path: The full path of the parental tree to this organization unit. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) description: The human readable text description of the organization unit. block_inheritance: This parameter blocks policy setting inheritance from organization units higher in the organization tree. Returns: A dict containing the result of the update operation. """ uri = UNIT_URL % (customer_id, org_unit_path) properties = {} if name: properties['name'] = name if parent_org_unit_path: properties['parentOrgUnitPath'] = parent_org_unit_path if description: properties['description'] = description if block_inheritance: properties['blockInheritance'] = self._Bool2Str(block_inheritance) return self._PutProperties(uri, properties) def MoveUserToOrgUnit(self, customer_id, org_unit_path, users_to_move): """Move a user to an Organization Unit. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) users_to_move: Email addresses list of users to move. Note: You can move a maximum of 25 users at one time. Returns: A dict containing the result of the update operation. """ uri = UNIT_URL % (customer_id, org_unit_path) properties = {} if users_to_move and isinstance(users_to_move, list): properties['usersToMove'] = ', '.join(users_to_move) return self._PutProperties(uri, properties) def RetrieveOrgUnit(self, customer_id, org_unit_path): """Retrieve a Orgunit based on its path. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) Returns: A dict containing the result of the retrieve operation. """ uri = UNIT_URL % (customer_id, org_unit_path) return self._GetProperties(uri) def DeleteOrgUnit(self, customer_id, org_unit_path): """Delete a Orgunit based on its path. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) Returns: A dict containing the result of the delete operation. """ uri = UNIT_URL % (customer_id, org_unit_path) return self._DeleteProperties(uri) def RetrieveAllOrgUnits(self, customer_id): """Retrieve all OrgUnits in the customer's domain. Args: customer_id: The ID of the Google Apps customer. Returns: A list containing the result of the retrieve operation. """ uri = UNIT_ALL_URL % (customer_id) return self._GetPropertiesList(uri) def RetrievePageOfOrgUnits(self, customer_id, startKey=None): """Retrieve one page of OrgUnits in the customer's domain. Args: customer_id: The ID of the Google Apps customer. startKey: The key to continue for pagination through all OrgUnits. Returns: A feed object containing the result of the retrieve operation. """ uri = UNIT_ALL_URL % (customer_id) if startKey is not None: uri += "&startKey=" + startKey property_feed = self._GetPropertyFeed(uri) return property_feed def RetrieveSubOrgUnits(self, customer_id, org_unit_path): """Retrieve all Sub-OrgUnits of the provided OrgUnit. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) Returns: A list containing the result of the retrieve operation. """ uri = UNIT_CHILD_URL % (customer_id, org_unit_path) return self._GetPropertiesList(uri) def RetrieveOrgUser(self, customer_id, user_email): """Retrieve the OrgUnit of the user. Args: customer_id: The ID of the Google Apps customer. user_email: The email address of the user. Returns: A dict containing the result of the retrieve operation. """ uri = USER_URL % (customer_id, user_email) return self._GetProperties(uri) def UpdateOrgUser(self, customer_id, user_email, org_unit_path): """Update the OrgUnit of a OrgUser. Args: customer_id: The ID of the Google Apps customer. user_email: The email address of the user. org_unit_path: The new organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) Returns: A dict containing the result of the update operation. """ uri = USER_URL % (customer_id, user_email) properties = {} if org_unit_path: properties['orgUnitPath'] = org_unit_path return self._PutProperties(uri, properties) def RetrieveAllOrgUsers(self, customer_id): """Retrieve all OrgUsers in the customer's domain. Args: customer_id: The ID of the Google Apps customer. Returns: A list containing the result of the retrieve operation. """ uri = USER_ALL_URL % (customer_id) return self._GetPropertiesList(uri) def RetrievePageOfOrgUsers(self, customer_id, startKey=None): """Retrieve one page of OrgUsers in the customer's domain. Args: customer_id: The ID of the Google Apps customer. startKey: The key to continue for pagination through all OrgUnits. Returns: A feed object containing the result of the retrieve operation. """ uri = USER_ALL_URL % (customer_id) if startKey is not None: uri += "&startKey=" + startKey property_feed = self._GetPropertyFeed(uri) return property_feed def RetrieveOrgUnitUsers(self, customer_id, org_unit_path): """Retrieve all OrgUsers of the provided OrgUnit. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) Returns: A list containing the result of the retrieve operation. """ uri = USER_CHILD_URL % (customer_id, org_unit_path) return self._GetPropertiesList(uri) def RetrieveOrgUnitPageOfUsers(self, customer_id, org_unit_path, startKey=None): """Retrieve one page of OrgUsers of the provided OrgUnit. Args: customer_id: The ID of the Google Apps customer. org_unit_path: The organization's full path name. Note: Each element of the path MUST be URL encoded (example: finance%2Forganization/suborganization) startKey: The key to continue for pagination through all OrgUsers. Returns: A feed object containing the result of the retrieve operation. """ uri = USER_CHILD_URL % (customer_id, org_unit_path) if startKey is not None: uri += "&startKey=" + startKey property_feed = self._GetPropertyFeed(uri) return property_feed
Python
#!/usr/bin/python # # Copyright (C) 2008 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
Python
#!/usr/bin/python # # Copyright (C) 2008 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Allow Google Apps domain administrators to set domain admin settings. AdminSettingsService: Set admin settings.""" __author__ = 'jlee@pbu.edu' import gdata.apps import gdata.apps.service import gdata.service API_VER='2.0' class AdminSettingsService(gdata.apps.service.PropertyService): """Client for the Google Apps Admin Settings service.""" def _serviceUrl(self, setting_id, domain=None): if domain is None: domain = self.domain return '/a/feeds/domain/%s/%s/%s' % (API_VER, domain, setting_id) def genericGet(self, location): """Generic HTTP Get Wrapper Args: location: relative uri to Get Returns: A dict containing the result of the get operation.""" uri = self._serviceUrl(location) try: return self._GetProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def GetDefaultLanguage(self): """Gets Domain Default Language Args: None Returns: Default Language as a string. All possible values are listed at: http://code.google.com/apis/apps/email_settings/developers_guide_protocol.html#GA_email_language_tags""" result = self.genericGet('general/defaultLanguage') return result['defaultLanguage'] def UpdateDefaultLanguage(self, defaultLanguage): """Updates Domain Default Language Args: defaultLanguage: Domain Language to set possible values are at: http://code.google.com/apis/apps/email_settings/developers_guide_protocol.html#GA_email_language_tags Returns: A dict containing the result of the put operation""" uri = self._serviceUrl('general/defaultLanguage') properties = {'defaultLanguage': defaultLanguage} return self._PutProperties(uri, properties) def GetOrganizationName(self): """Gets Domain Default Language Args: None Returns: Organization Name as a string.""" result = self.genericGet('general/organizationName') return result['organizationName'] def UpdateOrganizationName(self, organizationName): """Updates Organization Name Args: organizationName: Name of organization Returns: A dict containing the result of the put operation""" uri = self._serviceUrl('general/organizationName') properties = {'organizationName': organizationName} return self._PutProperties(uri, properties) def GetMaximumNumberOfUsers(self): """Gets Maximum Number of Users Allowed Args: None Returns: An integer, the maximum number of users""" result = self.genericGet('general/maximumNumberOfUsers') return int(result['maximumNumberOfUsers']) def GetCurrentNumberOfUsers(self): """Gets Current Number of Users Args: None Returns: An integer, the current number of users""" result = self.genericGet('general/currentNumberOfUsers') return int(result['currentNumberOfUsers']) def IsDomainVerified(self): """Is the domain verified Args: None Returns: Boolean, is domain verified""" result = self.genericGet('accountInformation/isVerified') if result['isVerified'] == 'true': return True else: return False def GetSupportPIN(self): """Gets Support PIN Args: None Returns: A string, the Support PIN""" result = self.genericGet('accountInformation/supportPIN') return result['supportPIN'] def GetEdition(self): """Gets Google Apps Domain Edition Args: None Returns: A string, the domain's edition (premier, education, partner)""" result = self.genericGet('accountInformation/edition') return result['edition'] def GetCustomerPIN(self): """Gets Customer PIN Args: None Returns: A string, the customer PIN""" result = self.genericGet('accountInformation/customerPIN') return result['customerPIN'] def GetCreationTime(self): """Gets Domain Creation Time Args: None Returns: A string, the domain's creation time""" result = self.genericGet('accountInformation/creationTime') return result['creationTime'] def GetCountryCode(self): """Gets Domain Country Code Args: None Returns: A string, the domain's country code. Possible values at: http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm""" result = self.genericGet('accountInformation/countryCode') return result['countryCode'] def GetAdminSecondaryEmail(self): """Gets Domain Admin Secondary Email Address Args: None Returns: A string, the secondary email address for domain admin""" result = self.genericGet('accountInformation/adminSecondaryEmail') return result['adminSecondaryEmail'] def UpdateAdminSecondaryEmail(self, adminSecondaryEmail): """Gets Domain Creation Time Args: adminSecondaryEmail: string, secondary email address of admin Returns: A dict containing the result of the put operation""" uri = self._serviceUrl('accountInformation/adminSecondaryEmail') properties = {'adminSecondaryEmail': adminSecondaryEmail} return self._PutProperties(uri, properties) def GetDomainLogo(self): """Gets Domain Logo This function does not make use of the Google Apps Admin Settings API, it does an HTTP Get of a url specific to the Google Apps domain. It is included for completeness sake. Args: None Returns: binary image file""" import urllib url = 'http://www.google.com/a/cpanel/'+self.domain+'/images/logo.gif' response = urllib.urlopen(url) return response.read() def UpdateDomainLogo(self, logoImage): """Update Domain's Custom Logo Args: logoImage: binary image data Returns: A dict containing the result of the put operation""" from base64 import b64encode uri = self._serviceUrl('appearance/customLogo') properties = {'logoImage': b64encode(logoImage)} return self._PutProperties(uri, properties) def GetCNAMEVerificationStatus(self): """Gets Domain CNAME Verification Status Args: None Returns: A dict {recordName, verified, verifiedMethod}""" return self.genericGet('verification/cname') def UpdateCNAMEVerificationStatus(self, verified): """Updates CNAME Verification Status Args: verified: boolean, True will retry verification process Returns: A dict containing the result of the put operation""" uri = self._serviceUrl('verification/cname') properties = self.GetCNAMEVerificationStatus() properties['verified'] = verified return self._PutProperties(uri, properties) def GetMXVerificationStatus(self): """Gets Domain MX Verification Status Args: None Returns: A dict {verified, verifiedMethod}""" return self.genericGet('verification/mx') def UpdateMXVerificationStatus(self, verified): """Updates MX Verification Status Args: verified: boolean, True will retry verification process Returns: A dict containing the result of the put operation""" uri = self._serviceUrl('verification/mx') properties = self.GetMXVerificationStatus() properties['verified'] = verified return self._PutProperties(uri, properties) def GetSSOSettings(self): """Gets Domain Single Sign-On Settings Args: None Returns: A dict {samlSignonUri, samlLogoutUri, changePasswordUri, enableSSO, ssoWhitelist, useDomainSpecificIssuer}""" return self.genericGet('sso/general') def UpdateSSOSettings(self, enableSSO=None, samlSignonUri=None, samlLogoutUri=None, changePasswordUri=None, ssoWhitelist=None, useDomainSpecificIssuer=None): """Update SSO Settings. Args: enableSSO: boolean, SSO Master on/off switch samlSignonUri: string, SSO Login Page samlLogoutUri: string, SSO Logout Page samlPasswordUri: string, SSO Password Change Page ssoWhitelist: string, Range of IP Addresses which will see SSO useDomainSpecificIssuer: boolean, Include Google Apps Domain in Issuer Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('sso/general') #Get current settings, replace Nones with '' properties = self.GetSSOSettings() if properties['samlSignonUri'] == None: properties['samlSignonUri'] = '' if properties['samlLogoutUri'] == None: properties['samlLogoutUri'] = '' if properties['changePasswordUri'] == None: properties['changePasswordUri'] = '' if properties['ssoWhitelist'] == None: properties['ssoWhitelist'] = '' #update only the values we were passed if enableSSO != None: properties['enableSSO'] = gdata.apps.service._bool2str(enableSSO) if samlSignonUri != None: properties['samlSignonUri'] = samlSignonUri if samlLogoutUri != None: properties['samlLogoutUri'] = samlLogoutUri if changePasswordUri != None: properties['changePasswordUri'] = changePasswordUri if ssoWhitelist != None: properties['ssoWhitelist'] = ssoWhitelist if useDomainSpecificIssuer != None: properties['useDomainSpecificIssuer'] = gdata.apps.service._bool2str(useDomainSpecificIssuer) return self._PutProperties(uri, properties) def GetSSOKey(self): """Gets Domain Single Sign-On Signing Key Args: None Returns: A dict {modulus, exponent, algorithm, format}""" return self.genericGet('sso/signingkey') def UpdateSSOKey(self, signingKey): """Update SSO Settings. Args: signingKey: string, public key to be uploaded Returns: A dict containing the result of the update operation.""" uri = self._serviceUrl('sso/signingkey') properties = {'signingKey': signingKey} return self._PutProperties(uri, properties) def IsUserMigrationEnabled(self): """Is User Migration Enabled Args: None Returns: boolean, is user migration enabled""" result = self.genericGet('email/migration') if result['enableUserMigration'] == 'true': return True else: return False def UpdateUserMigrationStatus(self, enableUserMigration): """Update User Migration Status Args: enableUserMigration: boolean, user migration enable/disable Returns: A dict containing the result of the update operation.""" uri = self._serviceUrl('email/migration') properties = {'enableUserMigration': enableUserMigration} return self._PutProperties(uri, properties) def GetOutboundGatewaySettings(self): """Get Outbound Gateway Settings Args: None Returns: A dict {smartHost, smtpMode}""" uri = self._serviceUrl('email/gateway') try: return self._GetProperties(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) except TypeError: #if no outbound gateway is set, we get a TypeError, #catch it and return nothing... return {'smartHost': None, 'smtpMode': None} def UpdateOutboundGatewaySettings(self, smartHost=None, smtpMode=None): """Update Outbound Gateway Settings Args: smartHost: string, ip address or hostname of outbound gateway smtpMode: string, SMTP or SMTP_TLS Returns: A dict containing the result of the update operation.""" uri = self._serviceUrl('email/gateway') #Get current settings, replace Nones with '' properties = GetOutboundGatewaySettings() if properties['smartHost'] == None: properties['smartHost'] = '' if properties['smtpMode'] == None: properties['smtpMode'] = '' #If we were passed new values for smartHost or smtpMode, update them if smartHost != None: properties['smartHost'] = smartHost if smtpMode != None: properties['smtpMode'] = smtpMode return self._PutProperties(uri, properties) def AddEmailRoute(self, routeDestination, routeRewriteTo, routeEnabled, bounceNotifications, accountHandling): """Adds Domain Email Route Args: routeDestination: string, destination ip address or hostname routeRewriteTo: boolean, rewrite smtp envelop To: routeEnabled: boolean, enable disable email routing bounceNotifications: boolean, send bound notificiations to sender accountHandling: string, which to route, "allAccounts", "provisionedAccounts", "unknownAccounts" Returns: A dict containing the result of the update operation.""" uri = self._serviceUrl('emailrouting') properties = {} properties['routeDestination'] = routeDestination properties['routeRewriteTo'] = gdata.apps.service._bool2str(routeRewriteTo) properties['routeEnabled'] = gdata.apps.service._bool2str(routeEnabled) properties['bounceNotifications'] = gdata.apps.service._bool2str(bounceNotifications) properties['accountHandling'] = accountHandling return self._PostProperties(uri, properties)
Python
#!/usr/bin/python # # Copyright (C) 2007 SIOS Technology, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains objects used with Google Apps.""" __author__ = 'tmatsuo@sios.com (Takashi MATSUO)' import atom import gdata # XML namespaces which are often used in Google Apps entity. APPS_NAMESPACE = 'http://schemas.google.com/apps/2006' APPS_TEMPLATE = '{http://schemas.google.com/apps/2006}%s' class EmailList(atom.AtomBase): """The Google Apps EmailList element""" _tag = 'emailList' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailListFromString(xml_string): return atom.CreateClassFromXMLString(EmailList, xml_string) class Who(atom.AtomBase): """The Google Apps Who element""" _tag = 'who' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['email'] = 'email' def __init__(self, rel=None, email=None, extension_elements=None, extension_attributes=None, text=None): self.rel = rel self.email = email self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def WhoFromString(xml_string): return atom.CreateClassFromXMLString(Who, xml_string) class Login(atom.AtomBase): """The Google Apps Login element""" _tag = 'login' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['userName'] = 'user_name' _attributes['password'] = 'password' _attributes['suspended'] = 'suspended' _attributes['admin'] = 'admin' _attributes['changePasswordAtNextLogin'] = 'change_password' _attributes['agreedToTerms'] = 'agreed_to_terms' _attributes['ipWhitelisted'] = 'ip_whitelisted' _attributes['hashFunctionName'] = 'hash_function_name' def __init__(self, user_name=None, password=None, suspended=None, ip_whitelisted=None, hash_function_name=None, admin=None, change_password=None, agreed_to_terms=None, extension_elements=None, extension_attributes=None, text=None): self.user_name = user_name self.password = password self.suspended = suspended self.admin = admin self.change_password = change_password self.agreed_to_terms = agreed_to_terms self.ip_whitelisted = ip_whitelisted self.hash_function_name = hash_function_name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def LoginFromString(xml_string): return atom.CreateClassFromXMLString(Login, xml_string) class Quota(atom.AtomBase): """The Google Apps Quota element""" _tag = 'quota' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['limit'] = 'limit' def __init__(self, limit=None, extension_elements=None, extension_attributes=None, text=None): self.limit = limit self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def QuotaFromString(xml_string): return atom.CreateClassFromXMLString(Quota, xml_string) class Name(atom.AtomBase): """The Google Apps Name element""" _tag = 'name' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['familyName'] = 'family_name' _attributes['givenName'] = 'given_name' def __init__(self, family_name=None, given_name=None, extension_elements=None, extension_attributes=None, text=None): self.family_name = family_name self.given_name = given_name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NameFromString(xml_string): return atom.CreateClassFromXMLString(Name, xml_string) class Nickname(atom.AtomBase): """The Google Apps Nickname element""" _tag = 'nickname' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NicknameFromString(xml_string): return atom.CreateClassFromXMLString(Nickname, xml_string) class NicknameEntry(gdata.GDataEntry): """A Google Apps flavor of an Atom Entry for Nickname""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}login' % APPS_NAMESPACE] = ('login', Login) _children['{%s}nickname' % APPS_NAMESPACE] = ('nickname', Nickname) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, login=None, nickname=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.login = login self.nickname = nickname self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NicknameEntryFromString(xml_string): return atom.CreateClassFromXMLString(NicknameEntry, xml_string) class NicknameFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps Nickname feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [NicknameEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def NicknameFeedFromString(xml_string): return atom.CreateClassFromXMLString(NicknameFeed, xml_string) class UserEntry(gdata.GDataEntry): """A Google Apps flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}login' % APPS_NAMESPACE] = ('login', Login) _children['{%s}name' % APPS_NAMESPACE] = ('name', Name) _children['{%s}quota' % APPS_NAMESPACE] = ('quota', Quota) # This child may already be defined in GDataEntry, confirm before removing. _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', [gdata.FeedLink]) _children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, login=None, name=None, quota=None, who=None, feed_link=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.login = login self.name = name self.quota = quota self.who = who self.feed_link = feed_link or [] self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def UserEntryFromString(xml_string): return atom.CreateClassFromXMLString(UserEntry, xml_string) class UserFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps User feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [UserEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def UserFeedFromString(xml_string): return atom.CreateClassFromXMLString(UserFeed, xml_string) class EmailListEntry(gdata.GDataEntry): """A Google Apps EmailList flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}emailList' % APPS_NAMESPACE] = ('email_list', EmailList) # Might be able to remove this _children entry. _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', [gdata.FeedLink]) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, email_list=None, feed_link=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.email_list = email_list self.feed_link = feed_link or [] self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailListEntryFromString(xml_string): return atom.CreateClassFromXMLString(EmailListEntry, xml_string) class EmailListFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps EmailList feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [EmailListEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def EmailListFeedFromString(xml_string): return atom.CreateClassFromXMLString(EmailListFeed, xml_string) class EmailListRecipientEntry(gdata.GDataEntry): """A Google Apps EmailListRecipient flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', Who) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, who=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.who = who self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailListRecipientEntryFromString(xml_string): return atom.CreateClassFromXMLString(EmailListRecipientEntry, xml_string) class EmailListRecipientFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps EmailListRecipient feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [EmailListRecipientEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def EmailListRecipientFeedFromString(xml_string): return atom.CreateClassFromXMLString(EmailListRecipientFeed, xml_string) class Property(atom.AtomBase): """The Google Apps Property element""" _tag = 'property' _namespace = APPS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' _attributes['value'] = 'value' def __init__(self, name=None, value=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def PropertyFromString(xml_string): return atom.CreateClassFromXMLString(Property, xml_string) class PropertyEntry(gdata.GDataEntry): """A Google Apps Property flavor of an Atom Entry""" _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}property' % APPS_NAMESPACE] = ('property', [Property]) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, property=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated) self.property = property self.extended_property = extended_property or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def PropertyEntryFromString(xml_string): return atom.CreateClassFromXMLString(PropertyEntry, xml_string) class PropertyFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Apps Property feed flavor of an Atom Feed""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [PropertyEntry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def PropertyFeedFromString(xml_string): return atom.CreateClassFromXMLString(PropertyFeed, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2007 SIOS Technology, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'tmatsuo@sios.com (Takashi MATSUO)' try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import urllib import gdata import atom.service import gdata.service import gdata.apps import atom API_VER="2.0" HTTP_OK=200 UNKOWN_ERROR=1000 USER_DELETED_RECENTLY=1100 USER_SUSPENDED=1101 DOMAIN_USER_LIMIT_EXCEEDED=1200 DOMAIN_ALIAS_LIMIT_EXCEEDED=1201 DOMAIN_SUSPENDED=1202 DOMAIN_FEATURE_UNAVAILABLE=1203 ENTITY_EXISTS=1300 ENTITY_DOES_NOT_EXIST=1301 ENTITY_NAME_IS_RESERVED=1302 ENTITY_NAME_NOT_VALID=1303 INVALID_GIVEN_NAME=1400 INVALID_FAMILY_NAME=1401 INVALID_PASSWORD=1402 INVALID_USERNAME=1403 INVALID_HASH_FUNCTION_NAME=1404 INVALID_HASH_DIGGEST_LENGTH=1405 INVALID_EMAIL_ADDRESS=1406 INVALID_QUERY_PARAMETER_VALUE=1407 TOO_MANY_RECIPIENTS_ON_EMAIL_LIST=1500 DEFAULT_QUOTA_LIMIT='2048' class Error(Exception): pass class AppsForYourDomainException(Error): def __init__(self, response): Error.__init__(self, response) try: self.element_tree = ElementTree.fromstring(response['body']) self.error_code = int(self.element_tree[0].attrib['errorCode']) self.reason = self.element_tree[0].attrib['reason'] self.invalidInput = self.element_tree[0].attrib['invalidInput'] except: self.error_code = UNKOWN_ERROR class AppsService(gdata.service.GDataService): """Client for the Google Apps Provisioning service.""" def __init__(self, email=None, password=None, domain=None, source=None, server='apps-apis.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Apps Provisioning service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. domain: string (optional) The Google Apps domain name. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'apps-apis.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='apps', source=source, server=server, additional_headers=additional_headers, **kwargs) self.ssl = True self.port = 443 self.domain = domain def _baseURL(self): return "/a/feeds/%s" % self.domain def AddAllElementsFromAllPages(self, link_finder, func): """retrieve all pages and add all elements""" next = link_finder.GetNextLink() while next is not None: next_feed = self.Get(next.href, converter=func) for a_entry in next_feed.entry: link_finder.entry.append(a_entry) next = next_feed.GetNextLink() return link_finder def RetrievePageOfEmailLists(self, start_email_list_name=None, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve one page of email list""" uri = "%s/emailList/%s" % (self._baseURL(), API_VER) if start_email_list_name is not None: uri += "?startEmailListName=%s" % start_email_list_name try: return gdata.apps.EmailListFeedFromString(str(self.GetWithRetries( uri, num_retries=num_retries, delay=delay, backoff=backoff))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def GetGeneratorForAllEmailLists( self, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve a generator for all emaillists in this domain.""" first_page = self.RetrievePageOfEmailLists(num_retries=num_retries, delay=delay, backoff=backoff) return self.GetGeneratorFromLinkFinder( first_page, gdata.apps.EmailListRecipientFeedFromString, num_retries=num_retries, delay=delay, backoff=backoff) def RetrieveAllEmailLists(self): """Retrieve all email list of a domain.""" ret = self.RetrievePageOfEmailLists() # pagination return self.AddAllElementsFromAllPages( ret, gdata.apps.EmailListFeedFromString) def RetrieveEmailList(self, list_name): """Retreive a single email list by the list's name.""" uri = "%s/emailList/%s/%s" % ( self._baseURL(), API_VER, list_name) try: return self.Get(uri, converter=gdata.apps.EmailListEntryFromString) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def RetrieveEmailLists(self, recipient): """Retrieve All Email List Subscriptions for an Email Address.""" uri = "%s/emailList/%s?recipient=%s" % ( self._baseURL(), API_VER, recipient) try: ret = gdata.apps.EmailListFeedFromString(str(self.Get(uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) # pagination return self.AddAllElementsFromAllPages( ret, gdata.apps.EmailListFeedFromString) def RemoveRecipientFromEmailList(self, recipient, list_name): """Remove recipient from email list.""" uri = "%s/emailList/%s/%s/recipient/%s" % ( self._baseURL(), API_VER, list_name, recipient) try: self.Delete(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def RetrievePageOfRecipients(self, list_name, start_recipient=None, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve one page of recipient of an email list. """ uri = "%s/emailList/%s/%s/recipient" % ( self._baseURL(), API_VER, list_name) if start_recipient is not None: uri += "?startRecipient=%s" % start_recipient try: return gdata.apps.EmailListRecipientFeedFromString(str( self.GetWithRetries( uri, num_retries=num_retries, delay=delay, backoff=backoff))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def GetGeneratorForAllRecipients( self, list_name, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve a generator for all recipients of a particular emaillist.""" first_page = self.RetrievePageOfRecipients(list_name, num_retries=num_retries, delay=delay, backoff=backoff) return self.GetGeneratorFromLinkFinder( first_page, gdata.apps.EmailListRecipientFeedFromString, num_retries=num_retries, delay=delay, backoff=backoff) def RetrieveAllRecipients(self, list_name): """Retrieve all recipient of an email list.""" ret = self.RetrievePageOfRecipients(list_name) # pagination return self.AddAllElementsFromAllPages( ret, gdata.apps.EmailListRecipientFeedFromString) def AddRecipientToEmailList(self, recipient, list_name): """Add a recipient to a email list.""" uri = "%s/emailList/%s/%s/recipient" % ( self._baseURL(), API_VER, list_name) recipient_entry = gdata.apps.EmailListRecipientEntry() recipient_entry.who = gdata.apps.Who(email=recipient) try: return gdata.apps.EmailListRecipientEntryFromString( str(self.Post(recipient_entry, uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def DeleteEmailList(self, list_name): """Delete a email list""" uri = "%s/emailList/%s/%s" % (self._baseURL(), API_VER, list_name) try: self.Delete(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def CreateEmailList(self, list_name): """Create a email list. """ uri = "%s/emailList/%s" % (self._baseURL(), API_VER) email_list_entry = gdata.apps.EmailListEntry() email_list_entry.email_list = gdata.apps.EmailList(name=list_name) try: return gdata.apps.EmailListEntryFromString( str(self.Post(email_list_entry, uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def DeleteNickname(self, nickname): """Delete a nickname""" uri = "%s/nickname/%s/%s" % (self._baseURL(), API_VER, nickname) try: self.Delete(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def RetrievePageOfNicknames(self, start_nickname=None, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve one page of nicknames in the domain""" uri = "%s/nickname/%s" % (self._baseURL(), API_VER) if start_nickname is not None: uri += "?startNickname=%s" % start_nickname try: return gdata.apps.NicknameFeedFromString(str(self.GetWithRetries( uri, num_retries=num_retries, delay=delay, backoff=backoff))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def GetGeneratorForAllNicknames( self, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve a generator for all nicknames in this domain.""" first_page = self.RetrievePageOfNicknames(num_retries=num_retries, delay=delay, backoff=backoff) return self.GetGeneratorFromLinkFinder( first_page, gdata.apps.NicknameFeedFromString, num_retries=num_retries, delay=delay, backoff=backoff) def RetrieveAllNicknames(self): """Retrieve all nicknames in the domain""" ret = self.RetrievePageOfNicknames() # pagination return self.AddAllElementsFromAllPages( ret, gdata.apps.NicknameFeedFromString) def GetGeneratorForAllNicknamesOfAUser( self, user_name, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve a generator for all nicknames of a particular user.""" uri = "%s/nickname/%s?username=%s" % (self._baseURL(), API_VER, user_name) try: first_page = gdata.apps.NicknameFeedFromString(str(self.GetWithRetries( uri, num_retries=num_retries, delay=delay, backoff=backoff))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) return self.GetGeneratorFromLinkFinder( first_page, gdata.apps.NicknameFeedFromString, num_retries=num_retries, delay=delay, backoff=backoff) def RetrieveNicknames(self, user_name): """Retrieve nicknames of the user""" uri = "%s/nickname/%s?username=%s" % (self._baseURL(), API_VER, user_name) try: ret = gdata.apps.NicknameFeedFromString(str(self.Get(uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) # pagination return self.AddAllElementsFromAllPages( ret, gdata.apps.NicknameFeedFromString) def RetrieveNickname(self, nickname): """Retrieve a nickname. Args: nickname: string The nickname to retrieve Returns: gdata.apps.NicknameEntry """ uri = "%s/nickname/%s/%s" % (self._baseURL(), API_VER, nickname) try: return gdata.apps.NicknameEntryFromString(str(self.Get(uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def CreateNickname(self, user_name, nickname): """Create a nickname""" uri = "%s/nickname/%s" % (self._baseURL(), API_VER) nickname_entry = gdata.apps.NicknameEntry() nickname_entry.login = gdata.apps.Login(user_name=user_name) nickname_entry.nickname = gdata.apps.Nickname(name=nickname) try: return gdata.apps.NicknameEntryFromString( str(self.Post(nickname_entry, uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def DeleteUser(self, user_name): """Delete a user account""" uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name) try: return self.Delete(uri) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def UpdateUser(self, user_name, user_entry): """Update a user account.""" uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name) try: return gdata.apps.UserEntryFromString(str(self.Put(user_entry, uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def CreateUser(self, user_name, family_name, given_name, password, suspended='false', quota_limit=None, password_hash_function=None, change_password=None): """Create a user account. """ uri = "%s/user/%s" % (self._baseURL(), API_VER) user_entry = gdata.apps.UserEntry() user_entry.login = gdata.apps.Login( user_name=user_name, password=password, suspended=suspended, hash_function_name=password_hash_function, change_password=change_password) user_entry.name = gdata.apps.Name(family_name=family_name, given_name=given_name) if quota_limit is not None: user_entry.quota = gdata.apps.Quota(limit=str(quota_limit)) try: return gdata.apps.UserEntryFromString(str(self.Post(user_entry, uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def SuspendUser(self, user_name): user_entry = self.RetrieveUser(user_name) if user_entry.login.suspended != 'true': user_entry.login.suspended = 'true' user_entry = self.UpdateUser(user_name, user_entry) return user_entry def RestoreUser(self, user_name): user_entry = self.RetrieveUser(user_name) if user_entry.login.suspended != 'false': user_entry.login.suspended = 'false' user_entry = self.UpdateUser(user_name, user_entry) return user_entry def RetrieveUser(self, user_name): """Retrieve an user account. Args: user_name: string The user name to retrieve Returns: gdata.apps.UserEntry """ uri = "%s/user/%s/%s" % (self._baseURL(), API_VER, user_name) try: return gdata.apps.UserEntryFromString(str(self.Get(uri))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def RetrievePageOfUsers(self, start_username=None, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve one page of users in this domain.""" uri = "%s/user/%s" % (self._baseURL(), API_VER) if start_username is not None: uri += "?startUsername=%s" % start_username try: return gdata.apps.UserFeedFromString(str(self.GetWithRetries( uri, num_retries=num_retries, delay=delay, backoff=backoff))) except gdata.service.RequestError, e: raise AppsForYourDomainException(e.args[0]) def GetGeneratorForAllUsers(self, num_retries=gdata.service.DEFAULT_NUM_RETRIES, delay=gdata.service.DEFAULT_DELAY, backoff=gdata.service.DEFAULT_BACKOFF): """Retrieve a generator for all users in this domain.""" first_page = self.RetrievePageOfUsers(num_retries=num_retries, delay=delay, backoff=backoff) return self.GetGeneratorFromLinkFinder( first_page, gdata.apps.UserFeedFromString, num_retries=num_retries, delay=delay, backoff=backoff) def RetrieveAllUsers(self): """Retrieve all users in this domain. OBSOLETE""" ret = self.RetrievePageOfUsers() # pagination return self.AddAllElementsFromAllPages( ret, gdata.apps.UserFeedFromString) class PropertyService(gdata.service.GDataService): """Client for the Google Apps Property service.""" def __init__(self, email=None, password=None, domain=None, source=None, server='apps-apis.google.com', additional_headers=None): gdata.service.GDataService.__init__(self, email=email, password=password, service='apps', source=source, server=server, additional_headers=additional_headers) self.ssl = True self.port = 443 self.domain = domain def AddAllElementsFromAllPages(self, link_finder, func): """retrieve all pages and add all elements""" next = link_finder.GetNextLink() while next is not None: next_feed = self.Get(next.href, converter=func) for a_entry in next_feed.entry: link_finder.entry.append(a_entry) next = next_feed.GetNextLink() return link_finder def _GetPropertyEntry(self, properties): property_entry = gdata.apps.PropertyEntry() property = [] for name, value in properties.iteritems(): if name is not None and value is not None: property.append(gdata.apps.Property(name=name, value=value)) property_entry.property = property return property_entry def _PropertyEntry2Dict(self, property_entry): properties = {} for i, property in enumerate(property_entry.property): properties[property.name] = property.value return properties def _GetPropertyFeed(self, uri): try: return gdata.apps.PropertyFeedFromString(str(self.Get(uri))) except gdata.service.RequestError, e: raise gdata.apps.service.AppsForYourDomainException(e.args[0]) def _GetPropertiesList(self, uri): property_feed = self._GetPropertyFeed(uri) # pagination property_feed = self.AddAllElementsFromAllPages( property_feed, gdata.apps.PropertyFeedFromString) properties_list = [] for property_entry in property_feed.entry: properties_list.append(self._PropertyEntry2Dict(property_entry)) return properties_list def _GetProperties(self, uri): try: return self._PropertyEntry2Dict(gdata.apps.PropertyEntryFromString( str(self.Get(uri)))) except gdata.service.RequestError, e: raise gdata.apps.service.AppsForYourDomainException(e.args[0]) def _PostProperties(self, uri, properties): property_entry = self._GetPropertyEntry(properties) try: return self._PropertyEntry2Dict(gdata.apps.PropertyEntryFromString( str(self.Post(property_entry, uri)))) except gdata.service.RequestError, e: raise gdata.apps.service.AppsForYourDomainException(e.args[0]) def _PutProperties(self, uri, properties): property_entry = self._GetPropertyEntry(properties) try: return self._PropertyEntry2Dict(gdata.apps.PropertyEntryFromString( str(self.Put(property_entry, uri)))) except gdata.service.RequestError, e: raise gdata.apps.service.AppsForYourDomainException(e.args[0]) def _DeleteProperties(self, uri): try: self.Delete(uri) except gdata.service.RequestError, e: raise gdata.apps.service.AppsForYourDomainException(e.args[0]) def _bool2str(b): if b is None: return None return str(b is True).lower()
Python
#!/usr/bin/python # # Copyright 2010 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Data model classes for the Email Settings API.""" __author__ = 'Claudio Cherubino <ccherubino@google.com>' import atom.data import gdata.apps import gdata.apps_property import gdata.data # This is required to work around a naming conflict between the Google # Spreadsheets API and Python's built-in property function pyproperty = property # The apps:property label of the label property LABEL_NAME = 'label' # The apps:property from of the filter property FILTER_FROM_NAME = 'from' # The apps:property to of the filter property FILTER_TO_NAME = 'to' # The apps:property subject of the filter property FILTER_SUBJECT_NAME = 'subject' # The apps:property hasTheWord of the filter property FILTER_HAS_THE_WORD_NAME = 'hasTheWord' # The apps:property doesNotHaveTheWord of the filter property FILTER_DOES_NOT_HAVE_THE_WORD_NAME = 'doesNotHaveTheWord' # The apps:property hasAttachment of the filter property FILTER_HAS_ATTACHMENTS_NAME = 'hasAttachment' # The apps:property label of the filter action property FILTER_LABEL = 'label' # The apps:property shouldMarkAsRead of the filter action property FILTER_MARK_AS_READ = 'shouldMarkAsRead' # The apps:property shouldArchive of the filter action propertylabel FILTER_ARCHIVE = 'shouldArchive' # The apps:property name of the send-as alias property SENDAS_ALIAS_NAME = 'name' # The apps:property address of theAPPS_TEMPLATE send-as alias property SENDAS_ALIAS_ADDRESS = 'address' # The apps:property replyTo of the send-as alias property SENDAS_ALIAS_REPLY_TO = 'replyTo' # The apps:property makeDefault of the send-as alias property SENDAS_ALIAS_MAKE_DEFAULT = 'makeDefault' # The apps:property enable of the webclip property WEBCLIP_ENABLE = 'enable' # The apps:property enable of the forwarding property FORWARDING_ENABLE = 'enable' # The apps:property forwardTo of the forwarding property FORWARDING_TO = 'forwardTo' # The apps:property action of the forwarding property FORWARDING_ACTION = 'action' # The apps:property enable of the POP property POP_ENABLE = 'enable' # The apps:property enableFor of the POP propertyACTION POP_ENABLE_FOR = 'enableFor' # The apps:property action of the POP property POP_ACTION = 'action' # The apps:property enable of the IMAP property IMAP_ENABLE = 'enable' # The apps:property enable of the vacation responder property VACATION_RESPONDER_ENABLE = 'enable' # The apps:property subject of the vacation responder property VACATION_RESPONDER_SUBJECT = 'subject' # The apps:property message of the vacation responder property VACATION_RESPONDER_MESSAGE = 'message' # The apps:property startDate of the vacation responder property VACATION_RESPONDER_STARTDATE = 'startDate' # The apps:property endDate of the vacation responder property VACATION_RESPONDER_ENDDATE = 'endDate' # The apps:property contactsOnly of the vacation responder property VACATION_RESPONDER_CONTACTS_ONLY = 'contactsOnly' # The apps:property domainOnly of the vacation responder property VACATION_RESPONDER_DOMAIN_ONLY = 'domainOnly' # The apps:property signature of the signature property SIGNATURE_VALUE = 'signature' # The apps:property language of the language property LANGUAGE_TAG = 'language' # The apps:property pageSize of the general settings property GENERAL_PAGE_SIZE = 'pageSize' # The apps:property shortcuts of the general settings property GENERAL_SHORTCUTS = 'shortcuts' # The apps:property arrows of the general settings property GENERAL_ARROWS = 'arrows' # The apps:prgdata.appsoperty snippets of the general settings property GENERAL_SNIPPETS = 'snippets' # The apps:property uniAppsProcode of the general settings property GENERAL_UNICODE = 'unicode' # The apps:property delegationId of the email delegation property DELEGATION_ID = 'delegationId' # The apps:property address of the email delegation property DELEGATION_ADDRESS = 'address' # The apps:property delegate of the email delegation property DELEGATION_DELEGATE = 'delegate' # The apps:property status of the email delegation property DELEGATION_STATUS = 'status' class EmailSettingsEntry(gdata.data.GDEntry): """Represents an Email Settings entry in object form.""" property = [gdata.apps_property.AppsProperty] def _GetProperty(self, name): """Get the apps:property value with the given name. Args: name: string Name of the apps:property value to get. Returns: The apps:property value with the given name, or None if the name was invalid. """ value = None for p in self.property: if p.name == name: value = p.value break return value def _SetProperty(self, name, value): """Set the apps:property value with the given name to the given value. Args: name: string Name of the apps:property value to set. value: string Value to give the apps:property value with the given name. """ found = False for i in range(len(self.property)): if self.property[i].name == name: self.property[i].value = value found = True break if not found: self.property.append(gdata.apps_property.AppsProperty(name=name, value=value)) def find_edit_link(self): return self.uri class EmailSettingsLabel(EmailSettingsEntry): """Represents a Label in object form.""" def GetName(self): """Get the name of the Label object. Returns: The name of this Label object as a string or None. """ return self._GetProperty(LABEL_NAME) def SetName(self, value): """Set the name of this Label object. Args: value: string The new label name to give this object. """ self._SetProperty(LABEL_NAME, value) name = pyproperty(GetName, SetName) def __init__(self, uri=None, name=None, *args, **kwargs): """Constructs a new EmailSettingsLabel object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. name: string (optional) The name to give this new object. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsLabel, self).__init__(*args, **kwargs) if uri: self.uri = uri if name: self.name = name class EmailSettingsFilter(EmailSettingsEntry): """Represents an Email Settings Filter in object form.""" def GetFrom(self): """Get the From value of the Filter object. Returns: The From value of this Filter object as a string or None. """ return self._GetProperty(FILTER_FROM_NAME) def SetFrom(self, value): """Set the From value of this Filter object. Args: value: string The new From value to give this object. """ self._SetProperty(FILTER_FROM_NAME, value) from_address = pyproperty(GetFrom, SetFrom) def GetTo(self): """Get the To value of the Filter object. Returns: The To value of this Filter object as a string or None. """ return self._GetProperty(FILTER_TO_NAME) def SetTo(self, value): """Set the To value of this Filter object. Args: value: string The new To value to give this object. """ self._SetProperty(FILTER_TO_NAME, value) to_address = pyproperty(GetTo, SetTo) def GetSubject(self): """Get the Subject value of the Filter object. Returns: The Subject value of this Filter object as a string or None. """ return self._GetProperty(FILTER_SUBJECT_NAME) def SetSubject(self, value): """Set the Subject value of this Filter object. Args: value: string The new Subject value to give this object. """ self._SetProperty(FILTER_SUBJECT_NAME, value) subject = pyproperty(GetSubject, SetSubject) def GetHasTheWord(self): """Get the HasTheWord value of the Filter object. Returns: The HasTheWord value of this Filter object as a string or None. """ return self._GetProperty(FILTER_HAS_THE_WORD_NAME) def SetHasTheWord(self, value): """Set the HasTheWord value of this Filter object. Args: value: string The new HasTheWord value to give this object. """ self._SetProperty(FILTER_HAS_THE_WORD_NAME, value) has_the_word = pyproperty(GetHasTheWord, SetHasTheWord) def GetDoesNotHaveTheWord(self): """Get the DoesNotHaveTheWord value of the Filter object. Returns: The DoesNotHaveTheWord value of this Filter object as a string or None. """ return self._GetProperty(FILTER_DOES_NOT_HAVE_THE_WORD_NAME) def SetDoesNotHaveTheWord(self, value): """Set the DoesNotHaveTheWord value of this Filter object. Args: value: string The new DoesNotHaveTheWord value to give this object. """ self._SetProperty(FILTER_DOES_NOT_HAVE_THE_WORD_NAME, value) does_not_have_the_word = pyproperty(GetDoesNotHaveTheWord, SetDoesNotHaveTheWord) def GetHasAttachments(self): """Get the HasAttachments value of the Filter object. Returns: The HasAttachments value of this Filter object as a string or None. """ return self._GetProperty(FILTER_HAS_ATTACHMENTS_NAME) def SetHasAttachments(self, value): """Set the HasAttachments value of this Filter object. Args: value: string The new HasAttachments value to give this object. """ self._SetProperty(FILTER_HAS_ATTACHMENTS_NAME, value) has_attachments = pyproperty(GetHasAttachments, SetHasAttachments) def GetLabel(self): """Get the Label value of the Filter object. Returns: The Label value of this Filter object as a string or None. """ return self._GetProperty(FILTER_LABEL) def SetLabel(self, value): """Set the Label value of this Filter object. Args: value: string The new Label value to give this object. """ self._SetProperty(FILTER_LABEL, value) label = pyproperty(GetLabel, SetLabel) def GetMarkAsRead(self): """Get the MarkAsRead value of the Filter object. Returns: The MarkAsRead value of this Filter object as a string or None. """ return self._GetProperty(FILTER_MARK_AS_READ) def SetMarkAsRead(self, value): """Set the MarkAsRead value of this Filter object. Args: value: string The new MarkAsRead value to give this object. """ self._SetProperty(FILTER_MARK_AS_READ, value) mark_as_read = pyproperty(GetMarkAsRead, SetMarkAsRead) def GetArchive(self): """Get the Archive value of the Filter object. Returns: The Archive value of this Filter object as a string or None. """ return self._GetProperty(FILTER_ARCHIVE) def SetArchive(self, value): """Set the Archive value of this Filter object. Args: value: string The new Archive value to give this object. """ self._SetProperty(FILTER_ARCHIVE, value) archive = pyproperty(GetArchive, SetArchive) def __init__(self, uri=None, from_address=None, to_address=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachments=None, label=None, mark_as_read=None, archive=None, *args, **kwargs): """Constructs a new EmailSettingsFilter object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. from_address: string (optional) The source email address for the filter. to_address: string (optional) The destination email address for the filter. subject: string (optional) The value the email must have in its subject to be filtered. has_the_word: string (optional) The value the email must have in its subject or body to be filtered. does_not_have_the_word: string (optional) The value the email cannot have in its subject or body to be filtered. has_attachments: Boolean (optional) Whether or not the email must have an attachment to be filtered. label: string (optional) The name of the label to apply to messages matching the filter criteria. mark_as_read: Boolean (optional) Whether or not to mark messages matching the filter criteria as read. archive: Boolean (optional) Whether or not to move messages matching to Archived state. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsFilter, self).__init__(*args, **kwargs) if uri: self.uri = uri if from_address: self.from_address = from_address if to_address: self.to_address = to_address if subject: self.subject = subject if has_the_word: self.has_the_word = has_the_word if does_not_have_the_word: self.does_not_have_the_word = does_not_have_the_word if has_attachments is not None: self.has_attachments = str(has_attachments) if label: self.label = label if mark_as_read is not None: self.mark_as_read = str(mark_as_read) if archive is not None: self.archive = str(archive) class EmailSettingsSendAsAlias(EmailSettingsEntry): """Represents an Email Settings send-as Alias in object form.""" def GetName(self): """Get the Name of the send-as Alias object. Returns: The Name of this send-as Alias object as a string or None. """ return self._GetProperty(SENDAS_ALIAS_NAME) def SetName(self, value): """Set the Name of this send-as Alias object. Args: value: string The new Name to give this object. """ self._SetProperty(SENDAS_ALIAS_NAME, value) name = pyproperty(GetName, SetName) def GetAddress(self): """Get the Address of the send-as Alias object. Returns: The Address of this send-as Alias object as a string or None. """ return self._GetProperty(SENDAS_ALIAS_ADDRESS) def SetAddress(self, value): """Set the Address of this send-as Alias object. Args: value: string The new Address to give this object. """ self._SetProperty(SENDAS_ALIAS_ADDRESS, value) address = pyproperty(GetAddress, SetAddress) def GetReplyTo(self): """Get the ReplyTo address of the send-as Alias object. Returns: The ReplyTo address of this send-as Alias object as a string or None. """ return self._GetProperty(SENDAS_ALIAS_REPLY_TO) def SetReplyTo(self, value): """Set the ReplyTo address of this send-as Alias object. Args: value: string The new ReplyTo address to give this object. """ self._SetProperty(SENDAS_ALIAS_REPLY_TO, value) reply_to = pyproperty(GetReplyTo, SetReplyTo) def GetMakeDefault(self): """Get the MakeDefault value of the send-as Alias object. Returns: The MakeDefault value of this send-as Alias object as a string or None. """ return self._GetProperty(SENDAS_ALIAS_MAKE_DEFAULT) def SetMakeDefault(self, value): """Set the MakeDefault value of this send-as Alias object. Args: value: string The new MakeDefault valueto give this object.WebClip """ self._SetProperty(SENDAS_ALIAS_MAKE_DEFAULT, value) make_default = pyproperty(GetMakeDefault, SetMakeDefault) def __init__(self, uri=None, name=None, address=None, reply_to=None, make_default=None, *args, **kwargs): """Constructs a new EmailSettingsSendAsAlias object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. name: string (optional) The name that will appear in the "From" field for this user. address: string (optional) The email address that appears as the origination address for emails sent by this user. reply_to: string (optional) The address to be used as the reply-to address in email sent using the alias. make_default: Boolean (optional) Whether or not this alias should become the default alias for this user. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsSendAsAlias, self).__init__(*args, **kwargs) if uri: self.uri = uri if name: self.name = name if address: self.address = address if reply_to: self.reply_to = reply_to if make_default is not None: self.make_default = str(make_default) class EmailSettingsWebClip(EmailSettingsEntry): """Represents a WebClip in object form.""" def GetEnable(self): """Get the Enable value of the WebClip object. Returns: The Enable value of this WebClip object as a string or None. """ return self._GetProperty(WEBCLIP_ENABLE) def SetEnable(self, value): """Set the Enable value of this WebClip object. Args: value: string The new Enable value to give this object. """ self._SetProperty(WEBCLIP_ENABLE, value) enable = pyproperty(GetEnable, SetEnable) def __init__(self, uri=None, enable=None, *args, **kwargs): """Constructs a new EmailSettingsWebClip object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. enable: Boolean (optional) Whether to enable showing Web clips. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsWebClip, self).__init__(*args, **kwargs) if uri: self.uri = uri if enable is not None: self.enable = str(enable) class EmailSettingsForwarding(EmailSettingsEntry): """Represents Forwarding settings in object form.""" def GetEnable(self): """Get the Enable value of the Forwarding object. Returns: The Enable value of this Forwarding object as a string or None. """ return self._GetProperty(FORWARDING_ENABLE) def SetEnable(self, value): """Set the Enable value of this Forwarding object. Args: value: string The new Enable value to give this object. """ self._SetProperty(FORWARDING_ENABLE, value) enable = pyproperty(GetEnable, SetEnable) def GetForwardTo(self): """Get the ForwardTo value of the Forwarding object. Returns: The ForwardTo value of this Forwarding object as a string or None. """ return self._GetProperty(FORWARDING_TO) def SetForwardTo(self, value): """Set the ForwardTo value of this Forwarding object. Args: value: string The new ForwardTo value to give this object. """ self._SetProperty(FORWARDING_TO, value) forward_to = pyproperty(GetForwardTo, SetForwardTo) def GetAction(self): """Get the Action value of the Forwarding object. Returns: The Action value of this Forwarding object as a string or None. """ return self._GetProperty(FORWARDING_ACTION) def SetAction(self, value): """Set the Action value of this Forwarding object. Args: value: string The new Action value to give this object. """ self._SetProperty(FORWARDING_ACTION, value) action = pyproperty(GetAction, SetAction) def __init__(self, uri=None, enable=None, forward_to=None, action=None, *args, **kwargs): """Constructs a new EmailSettingsForwarding object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. enable: Boolean (optional) Whether to enable incoming email forwarding. forward_to: string (optional) The address email will be forwarded to. action: string (optional) The action to perform after forwarding an email ("KEEP", "ARCHIVE", "DELETE"). args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsForwarding, self).__init__(*args, **kwargs) if uri: self.uri = uri if enable is not None: self.enable = str(enable) if forward_to: self.forward_to = forward_to if action: self.action = action class EmailSettingsPop(EmailSettingsEntry): """Represents POP settings in object form.""" def GetEnable(self): """Get the Enable value of the POP object. Returns: The Enable value of this POP object as a string or None. """ return self._GetProperty(POP_ENABLE) def SetEnable(self, value): """Set the Enable value of this POP object. Args: value: string The new Enable value to give this object. """ self._SetProperty(POP_ENABLE, value) enable = pyproperty(GetEnable, SetEnable) def GetEnableFor(self): """Get the EnableFor value of the POP object. Returns: The EnableFor value of this POP object as a string or None. """ return self._GetProperty(POP_ENABLE_FOR) def SetEnableFor(self, value): """Set the EnableFor value of this POP object. Args: value: string The new EnableFor value to give this object. """ self._SetProperty(POP_ENABLE_FOR, value) enable_for = pyproperty(GetEnableFor, SetEnableFor) def GetPopAction(self): """Get the Action value of the POP object. Returns: The Action value of this POP object as a string or None. """ return self._GetProperty(POP_ACTION) def SetPopAction(self, value): """Set the Action value of this POP object. Args: value: string The new Action value to give this object. """ self._SetProperty(POP_ACTION, value) action = pyproperty(GetPopAction, SetPopAction) def __init__(self, uri=None, enable=None, enable_for=None, action=None, *args, **kwargs): """Constructs a new EmailSettingsPOP object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. enable: Boolean (optional) Whether to enable incoming POP3 access. enable_for: string (optional) Whether to enable POP3 for all mail ("ALL_MAIL"), or mail from now on ("MAIL_FROM_NOW_ON"). action: string (optional) What Google Mail should do with its copy of the email after it is retrieved using POP ("KEEP", "ARCHIVE", or "DELETE"). args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsPop, self).__init__(*args, **kwargs) if uri: self.uri = uri if enable is not None: self.enable = str(enable) if enable_for: self.enable_for = enable_for if action: self.action = action class EmailSettingsImap(EmailSettingsEntry): """Represents IMAP settings in object form.""" def GetEnable(self): """Get the Enable value of the IMAP object. Returns: The Enable value of this IMAP object as a string or None. """ return self._GetProperty(IMAP_ENABLE) def SetEnable(self, value): """Set the Enable value of this IMAP object. Args: value: string The new Enable value to give this object. """ self._SetProperty(IMAP_ENABLE, value) enable = pyproperty(GetEnable, SetEnable) def __init__(self, uri=None, enable=None, *args, **kwargs): """Constructs a new EmailSettingsImap object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. enable: Boolean (optional) Whether to enable IMAP access. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsImap, self).__init__(*args, **kwargs) if uri: self.uri = uri if enable is not None: self.enable = str(enable) class EmailSettingsVacationResponder(EmailSettingsEntry): """Represents Vacation Responder settings in object form.""" def GetEnable(self): """Get the Enable value of the Vacation Responder object. Returns: The Enable value of this Vacation Responder object as a string or None. """ return self._GetProperty(VACATION_RESPONDER_ENABLE) def SetEnable(self, value): """Set the Enable value of this Vacation Responder object. Args: value: string The new Enable value to give this object. """ self._SetProperty(VACATION_RESPONDER_ENABLE, value) enable = pyproperty(GetEnable, SetEnable) def GetSubject(self): """Get the Subject value of the Vacation Responder object. Returns: The Subject value of this Vacation Responder object as a string or None. """ return self._GetProperty(VACATION_RESPONDER_SUBJECT) def SetSubject(self, value): """Set the Subject value of this Vacation Responder object. Args: value: string The new Subject value to give this object. """ self._SetProperty(VACATION_RESPONDER_SUBJECT, value) subject = pyproperty(GetSubject, SetSubject) def GetMessage(self): """Get the Message value of the Vacation Responder object. Returns: The Message value of this Vacation Responder object as a string or None. """ return self._GetProperty(VACATION_RESPONDER_MESSAGE) def SetMessage(self, value): """Set the Message value of this Vacation Responder object. Args: value: string The new Message value to give this object. """ self._SetProperty(VACATION_RESPONDER_MESSAGE, value) message = pyproperty(GetMessage, SetMessage) def GetStartDate(self): """Get the StartDate value of the Vacation Responder object. Returns: The StartDate value of this Vacation Responder object as a string(YYYY-MM-DD) or None. """ return self._GetProperty(VACATION_RESPONDER_STARTDATE) def SetStartDate(self, value): """Set the StartDate value of this Vacation Responder object. Args: value: string The new StartDate value to give this object. """ self._SetProperty(VACATION_RESPONDER_STARTDATE, value) start_date = pyproperty(GetStartDate, SetStartDate) def GetEndDate(self): """Get the EndDate value of the Vacation Responder object. Returns: The EndDate value of this Vacation Responder object as a string(YYYY-MM-DD) or None. """ return self._GetProperty(VACATION_RESPONDER_ENDDATE) def SetEndDate(self, value): """Set the EndDate value of this Vacation Responder object. Args: value: string The new EndDate value to give this object. """ self._SetProperty(VACATION_RESPONDER_ENDDATE, value) end_date = pyproperty(GetEndDate, SetEndDate) def GetContactsOnly(self): """Get the ContactsOnly value of the Vacation Responder object. Returns: The ContactsOnly value of this Vacation Responder object as a string or None. """ return self._GetProperty(VACATION_RESPONDER_CONTACTS_ONLY) def SetContactsOnly(self, value): """Set the ContactsOnly value of this Vacation Responder object. Args: value: string The new ContactsOnly value to give this object. """ self._SetProperty(VACATION_RESPONDER_CONTACTS_ONLY, value) contacts_only = pyproperty(GetContactsOnly, SetContactsOnly) def GetDomainOnly(self): """Get the DomainOnly value of the Vacation Responder object. Returns: The DomainOnly value of this Vacation Responder object as a string or None. """ return self._GetProperty(VACATION_RESPONDER_DOMAIN_ONLY) def SetDomainOnly(self, value): """Set the DomainOnly value of this Vacation Responder object. Args: value: string The new DomainOnly value to give this object. """ self._SetProperty(VACATION_RESPONDER_DOMAIN_ONLY, value) domain_only = pyproperty(GetDomainOnly, SetDomainOnly) def __init__(self, uri=None, enable=None, subject=None, message=None, start_date=None, end_date=None, contacts_only=None, domain_only=None, *args, **kwargs): """Constructs a new EmailSettingsVacationResponder object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. enable: Boolean (optional) Whether to enable the vacation responder. subject: string (optional) The subject line of the vacation responder autoresponse. message: string (optional) The message body of the vacation responder autoresponse. start_date: string (optional) The start date of the vacation responder autoresponse end_date: string (optional) The end date of the vacation responder autoresponse contacts_only: Boolean (optional) Whether to only send autoresponses to known contacts. domain_only: Boolean (optional) Whether to only send autoresponses to users in the same primary domain . args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsVacationResponder, self).__init__(*args, **kwargs) if uri: self.uri = uri if enable is not None: self.enable = str(enable) if subject: self.subject = subject if message: self.message = message if start_date: self.start_date = start_date if end_date: self.end_date = end_date if contacts_only is not None: self.contacts_only = str(contacts_only) if domain_only is not None: self.domain_only = str(domain_only) class EmailSettingsSignature(EmailSettingsEntry): """Represents a Signature in object form.""" def GetValue(self): """Get the value of the Signature object. Returns: The value of this Signature object as a string or None. """ value = self._GetProperty(SIGNATURE_VALUE) if value == ' ': # hack to support empty signature return '' else: return value def SetValue(self, value): """Set the name of this Signature object. Args: value: string The new signature value to give this object. """ if value == '': # hack to support empty signature value = ' ' self._SetProperty(SIGNATURE_VALUE, value) signature_value = pyproperty(GetValue, SetValue) def __init__(self, uri=None, signature=None, *args, **kwargs): """Constructs a new EmailSettingsSignature object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. signature: string (optional) The signature to be appended to outgoing messages. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsSignature, self).__init__(*args, **kwargs) if uri: self.uri = uri if signature is not None: self.signature_value = signature class EmailSettingsLanguage(EmailSettingsEntry): """Represents Language Settings in object form.""" def GetLanguage(self): """Get the tag of the Language object. Returns: The tag of this Language object as a string or None. """ return self._GetProperty(LANGUAGE_TAG) def SetLanguage(self, value): """Set the tag of this Language object. Args: value: string The new tag value to give this object. """ self._SetProperty(LANGUAGE_TAG, value) language_tag = pyproperty(GetLanguage, SetLanguage) def __init__(self, uri=None, language=None, *args, **kwargs): """Constructs a new EmailSettingsLanguage object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. language: string (optional) The language tag for Google Mail's display language. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsLanguage, self).__init__(*args, **kwargs) if uri: self.uri = uri if language: self.language_tag = language class EmailSettingsGeneral(EmailSettingsEntry): """Represents General Settings in object form.""" def GetPageSize(self): """Get the Page Size value of the General Settings object. Returns: The Page Size value of this General Settings object as a string or None. """ return self._GetProperty(GENERAL_PAGE_SIZE) def SetPageSize(self, value): """Set the Page Size value of this General Settings object. Args: value: string The new Page Size value to give this object. """ self._SetProperty(GENERAL_PAGE_SIZE, value) page_size = pyproperty(GetPageSize, SetPageSize) def GetShortcuts(self): """Get the Shortcuts value of the General Settings object. Returns: The Shortcuts value of this General Settings object as a string or None. """ return self._GetProperty(GENERAL_SHORTCUTS) def SetShortcuts(self, value): """Set the Shortcuts value of this General Settings object. Args: value: string The new Shortcuts value to give this object. """ self._SetProperty(GENERAL_SHORTCUTS, value) shortcuts = pyproperty(GetShortcuts, SetShortcuts) def GetArrows(self): """Get the Arrows value of the General Settings object. Returns: The Arrows value of this General Settings object as a string or None. """ return self._GetProperty(GENERAL_ARROWS) def SetArrows(self, value): """Set the Arrows value of this General Settings object. Args: value: string The new Arrows value to give this object. """ self._SetProperty(GENERAL_ARROWS, value) arrows = pyproperty(GetArrows, SetArrows) def GetSnippets(self): """Get the Snippets value of the General Settings object. Returns: The Snippets value of this General Settings object as a string or None. """ return self._GetProperty(GENERAL_SNIPPETS) def SetSnippets(self, value): """Set the Snippets value of this General Settings object. Args: value: string The new Snippets value to give this object. """ self._SetProperty(GENERAL_SNIPPETS, value) snippets = pyproperty(GetSnippets, SetSnippets) def GetUnicode(self): """Get the Unicode value of the General Settings object. Returns: The Unicode value of this General Settings object as a string or None. """ return self._GetProperty(GENERAL_UNICODE) def SetUnicode(self, value): """Set the Unicode value of this General Settings object. Args: value: string The new Unicode value to give this object. """ self._SetProperty(GENERAL_UNICODE, value) use_unicode = pyproperty(GetUnicode, SetUnicode) def __init__(self, uri=None, page_size=None, shortcuts=None, arrows=None, snippets=None, use_unicode=None, *args, **kwargs): """Constructs a new EmailSettingsGeneral object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. page_size: int (optional) The number of conversations to be shown per page. shortcuts: Boolean (optional) Whether to enable keyboard shortcuts. arrows: Boolean (optional) Whether to display arrow-shaped personal indicators next to email sent specifically to the user. snippets: Boolean (optional) Whether to display snippets of the messages in the inbox and when searching. use_unicode: Boolean (optional) Whether to use UTF-8 (unicode) encoding for all outgoing messages. args: The other parameters to pass to gdata.entry.GDEntry constructor. kwargs: The other parameters to pass to gdata.entry.GDEntry constructor. """ super(EmailSettingsGeneral, self).__init__(*args, **kwargs) if uri: self.uri = uri if page_size is not None: self.page_size = str(page_size) if shortcuts is not None: self.shortcuts = str(shortcuts) if arrows is not None: self.arrows = str(arrows) if snippets is not None: self.snippets = str(snippets) if use_unicode is not None: self.use_unicode = str(use_unicode) class EmailSettingsDelegation(EmailSettingsEntry): """Represents an Email Settings delegation entry in object form.""" def GetAddress(self): """Get the email address of the delegated user. Returns: The email address of the delegated user as a string or None. """ return self._GetProperty(DELEGATION_ADDRESS) def SetAddress(self, value): """Set the email address of of the delegated user. Args: value: string The email address of another user on the same domain """ self._SetProperty(DELEGATION_ADDRESS, value) address = pyproperty(GetAddress, SetAddress) def __init__(self, uri=None, address=None, *args, **kwargs): """Constructs a new EmailSettingsDelegation object with the given arguments. Args: uri: string (optional) The uri of of this object for HTTP requests. address: string The email address of the delegated user. """ super(EmailSettingsDelegation, self).__init__(*args, **kwargs) if uri: self.uri = uri if address: self.address = address
Python
#!/usr/bin/python2.4 # # Copyright 2010 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """EmailSettingsClient simplifies Email Settings API calls. EmailSettingsClient extends gdata.client.GDClient to ease interaction with the Google Apps Email Settings API. These interactions include the ability to create labels, filters, aliases, and update web-clip, forwarding, POP, IMAP, vacation-responder, signature, language, and general settings, and retrieve labels, send-as, forwarding, pop, imap, vacation and signature settings. """ __author__ = 'Claudio Cherubino <ccherubino@google.com>' import urllib 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 settingID value for the delegation requests SETTING_ID_DELEGATION = 'delegation' # 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. """ if '@' in username: username, domain = username.split('@', 1) else: domain = self.domain uri = EMAIL_SETTINGS_URI_TEMPLATE % (self.api_version, 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 retrieve_labels(self, username, **kwargs): """Retrieves email labels for the specified username Args: username: string The name of the user to get the labels for Returns: A gdata.data.GDFeed of the user's email labels """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_LABEL) return self.GetFeed(uri, auth_token=None, query=None, **kwargs) RetrieveLabels = retrieve_labels def delete_label(self, username, label, **kwargs): """Delete a label from the specified account. Args: username: string Name of the user label: string Name of the label to be deleted Returns: An atom.http_core.HttpResponse() with the result of the request """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_LABEL) uri = '/'.join([uri, urllib.quote_plus(label)]) return self.delete(uri, **kwargs) DeleteLabel = delete_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 retrieve_send_as(self, username, **kwargs): """Retrieves send-as aliases for the specified username Args: username: string The name of the user to get the send-as for Returns: A gdata.data.GDFeed of the user's send-as alias settings """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_SENDAS) return self.GetFeed(uri, auth_token=None, query=None, **kwargs) RetrieveSendAs = retrieve_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 retrieve_forwarding(self, username, **kwargs): """Retrieves forwarding settings for the specified username Args: username: string The name of the user to get the forwarding settings for Returns: A gdata.data.GDEntry of the user's email forwarding settings """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_FORWARDING) return self.GetEntry(uri, auth_token=None, query=None, **kwargs) RetrieveForwarding = retrieve_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 retrieve_pop(self, username, **kwargs): """Retrieves POP settings for the specified username Args: username: string The name of the user to get the POP settings for Returns: A gdata.data.GDEntry of the user's POP settings """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_POP) return self.GetEntry(uri, auth_token=None, query=None, **kwargs) RetrievePop = retrieve_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 retrieve_imap(self, username, **kwargs): """Retrieves imap settings for the specified username Args: username: string The name of the user to get the imap settings for Returns: A gdata.data.GDEntry of the user's IMAP settings """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_IMAP) return self.GetEntry(uri, auth_token=None, query=None, **kwargs) RetrieveImap = retrieve_imap def update_vacation(self, username, enable, subject=None, message=None, start_date=None, end_date=None, contacts_only=None, domain_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. startDate: string (optional) The start date of the vacation responder autoresponse. endDate: string (optional) The end date of the vacation responder autoresponse. contacts_only: Boolean (optional) Whether to only send autoresponses to known contacts. domain_only: Boolean (optional) Whether to only send autoresponses to users in the primary domain. 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, start_date=start_date, end_date=end_date, contacts_only=contacts_only, domain_only=domain_only) return self.update(new_vacation, **kwargs) UpdateVacation = update_vacation def retrieve_vacation(self, username, **kwargs): """Retrieves vacation settings for the specified username Args: username: string The name of the user to get the vacation settings for Returns: A gdata.data.GDEntry of the user's vacation auto-responder settings """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_VACATION_RESPONDER) return self.GetEntry(uri, auth_token=None, query=None, **kwargs) RetrieveVacation = retrieve_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 retrieve_signature(self, username, **kwargs): """Retrieves signature settings for the specified username Args: username: string The name of the user to get the signature settings for Returns: A gdata.data.GDEntry of the user's signature settings """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_SIGNATURE) return self.GetEntry(uri, auth_token=None, query=None, **kwargs) RetrieveSignature = retrieve_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 def add_email_delegate(self, username, address, **kwargs): """Add an email delegate to the mail account Args: username: string The name of the user address: string The email address of the delegated account """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_DELEGATION) new_delegation = gdata.apps.emailsettings.data.EmailSettingsDelegation( uri=uri, address=address) return self.post(new_delegation, uri, **kwargs) AddEmailDelegate = add_email_delegate def retrieve_email_delegates(self, username, **kwargs): """Retrieve a feed of the email delegates for the specified username Args: username: string The name of the user to get the email delegates for Returns: A gdata.data.GDFeed of the user's email delegates """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_DELEGATION) return self.GetFeed(uri, auth_token=None, query=None, **kwargs) RetrieveEmailDelegates = retrieve_email_delegates def delete_email_delegate(self, username, address, **kwargs): """Delete an email delegate from the specified account Args: username: string The name of the user address: string The email address of the delegated account """ uri = self.MakeEmailSettingsUri(username=username, setting_id=SETTING_ID_DELEGATION) uri = uri + '/' + address return self.delete(uri, **kwargs) DeleteEmailDelegate = delete_email_delegate
Python
#!/usr/bin/python # # Copyright (C) 2008 Google # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
Python
#!/usr/bin/python # # Copyright (C) 2008 Google, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Allow Google Apps domain administrators to set users' email settings. EmailSettingsService: Set various email settings. """ __author__ = 'google-apps-apis@googlegroups.com' import gdata.apps import gdata.apps.service import gdata.service API_VER='2.0' # Forwarding and POP3 options KEEP='KEEP' ARCHIVE='ARCHIVE' DELETE='DELETE' ALL_MAIL='ALL_MAIL' MAIL_FROM_NOW_ON='MAIL_FROM_NOW_ON' class EmailSettingsService(gdata.apps.service.PropertyService): """Client for the Google Apps Email Settings service.""" def _serviceUrl(self, setting_id, username, domain=None): if domain is None: domain = self.domain return '/a/feeds/emailsettings/%s/%s/%s/%s' % (API_VER, domain, username, setting_id) def CreateLabel(self, username, label): """Create a label. Args: username: User to create label for. label: Label to create. Returns: A dict containing the result of the create operation. """ uri = self._serviceUrl('label', username) properties = {'label': label} return self._PostProperties(uri, properties) def CreateFilter(self, username, from_=None, to=None, subject=None, has_the_word=None, does_not_have_the_word=None, has_attachment=None, label=None, should_mark_as_read=None, should_archive=None): """Create a filter. Args: username: User to create filter for. from_: Filter from string. to: Filter to string. subject: Filter subject. has_the_word: Words to filter in. does_not_have_the_word: Words to filter out. has_attachment: Boolean for message having attachment. label: Label to apply. should_mark_as_read: Boolean for marking message as read. should_archive: Boolean for archiving message. Returns: A dict containing the result of the create operation. """ uri = self._serviceUrl('filter', username) properties = {} properties['from'] = from_ properties['to'] = to properties['subject'] = subject properties['hasTheWord'] = has_the_word properties['doesNotHaveTheWord'] = does_not_have_the_word properties['hasAttachment'] = gdata.apps.service._bool2str(has_attachment) properties['label'] = label properties['shouldMarkAsRead'] = gdata.apps.service._bool2str(should_mark_as_read) properties['shouldArchive'] = gdata.apps.service._bool2str(should_archive) return self._PostProperties(uri, properties) def CreateSendAsAlias(self, username, name, address, reply_to=None, make_default=None): """Create alias to send mail as. Args: username: User to create alias for. name: Name of alias. address: Email address to send from. reply_to: Email address to reply to. make_default: Boolean for whether this is the new default sending alias. Returns: A dict containing the result of the create operation. """ uri = self._serviceUrl('sendas', username) properties = {} properties['name'] = name properties['address'] = address properties['replyTo'] = reply_to properties['makeDefault'] = gdata.apps.service._bool2str(make_default) return self._PostProperties(uri, properties) def UpdateWebClipSettings(self, username, enable): """Update WebClip Settings Args: username: User to update forwarding for. enable: Boolean whether to enable Web Clip. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('webclip', username) properties = {} properties['enable'] = gdata.apps.service._bool2str(enable) return self._PutProperties(uri, properties) def UpdateForwarding(self, username, enable, forward_to=None, action=None): """Update forwarding settings. Args: username: User to update forwarding for. enable: Boolean whether to enable this forwarding rule. forward_to: Email address to forward to. action: Action to take after forwarding. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('forwarding', username) properties = {} properties['enable'] = gdata.apps.service._bool2str(enable) if enable is True: properties['forwardTo'] = forward_to properties['action'] = action return self._PutProperties(uri, properties) def UpdatePop(self, username, enable, enable_for=None, action=None): """Update POP3 settings. Args: username: User to update POP3 settings for. enable: Boolean whether to enable POP3. enable_for: Which messages to make available via POP3. action: Action to take after user retrieves email via POP3. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('pop', username) properties = {} properties['enable'] = gdata.apps.service._bool2str(enable) if enable is True: properties['enableFor'] = enable_for properties['action'] = action return self._PutProperties(uri, properties) def UpdateImap(self, username, enable): """Update IMAP settings. Args: username: User to update IMAP settings for. enable: Boolean whether to enable IMAP. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('imap', username) properties = {'enable': gdata.apps.service._bool2str(enable)} return self._PutProperties(uri, properties) def UpdateVacation(self, username, enable, subject=None, message=None, contacts_only=None): """Update vacation settings. Args: username: User to update vacation settings for. enable: Boolean whether to enable vacation responses. subject: Vacation message subject. message: Vacation message body. contacts_only: Boolean whether to send message only to contacts. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('vacation', username) properties = {} properties['enable'] = gdata.apps.service._bool2str(enable) if enable is True: properties['subject'] = subject properties['message'] = message properties['contactsOnly'] = gdata.apps.service._bool2str(contacts_only) return self._PutProperties(uri, properties) def UpdateSignature(self, username, signature): """Update signature. Args: username: User to update signature for. signature: Signature string. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('signature', username) properties = {'signature': signature} return self._PutProperties(uri, properties) def UpdateLanguage(self, username, language): """Update user interface language. Args: username: User to update language for. language: Language code. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('language', username) properties = {'language': language} return self._PutProperties(uri, properties) def UpdateGeneral(self, username, page_size=None, shortcuts=None, arrows=None, snippets=None, unicode=None): """Update general settings. Args: username: User to update general settings for. page_size: Number of messages to show. shortcuts: Boolean whether shortcuts are enabled. arrows: Boolean whether arrows are enabled. snippets: Boolean whether snippets are enabled. unicode: Wheter unicode is enabled. Returns: A dict containing the result of the update operation. """ uri = self._serviceUrl('general', username) properties = {} if page_size != None: properties['pageSize'] = str(page_size) if shortcuts != None: properties['shortcuts'] = gdata.apps.service._bool2str(shortcuts) if arrows != None: properties['arrows'] = gdata.apps.service._bool2str(arrows) if snippets != None: properties['snippets'] = gdata.apps.service._bool2str(snippets) if unicode != None: properties['unicode'] = gdata.apps.service._bool2str(unicode) return self._PutProperties(uri, properties)
Python
#!/usr/bin/python2.4 # # Copyright 2008 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """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) class MailEntryProperties(object): """Represents a mail message and its attributes.""" def __init__(self, mail_message=None, mail_item_properties=None, mail_labels=None, identifier=None): self.mail_message = mail_message self.mail_item_properties = mail_item_properties or [] self.mail_labels = mail_labels or [] self.identifier = identifier def BatchMailEventFeedFromString(xml_string): """Parse in the BatchMailEventFeed from the XML definition.""" return atom.CreateClassFromXMLString(BatchMailEventFeed, xml_string)
Python
#!/usr/bin/python2.4 # # Copyright 2008 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the methods to import mail via Google Apps Email Migration API. MigrationService: Provides methods to import mail. """ __author__ = ('google-apps-apis@googlegroups.com', 'pti@google.com (Prashant Tiwari)') import base64 import threading import time from atom.service import deprecation from gdata.apps import migration from gdata.apps.migration import MailEntryProperties import gdata.apps.service import gdata.service 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 AddMailEntry and ImportMultipleMails to import a bunch 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() self.mail_entries = [] self.exceptions = 0 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): """Imports 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: # Store the number of failed imports when importing several at a time self.exceptions += 1 raise gdata.apps.service.AppsForYourDomainException(e.args[0]) def AddBatchEntry(self, mail_message, mail_item_properties, mail_labels): """Adds a message to the current batch that you later will submit. Deprecated, use AddMailEntry instead 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. """ deprecation("calling deprecated method AddBatchEntry") 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): """Sends all the mail items you have added to the batch to the server. Deprecated, use ImportMultipleMails instead Args: user_name: The username to import messages to. Returns: An HTTPResponse from the web service call. Raises: AppsForYourDomainException: An error occurred importing the batch. """ deprecation("calling deprecated method SubmitBatch") 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 def AddMailEntry(self, mail_message, mail_item_properties=None, mail_labels=None, identifier=None): """Prepares a list of mail messages to import using ImportMultipleMails. Args: mail_message: An RFC822 format email message as a string. mail_item_properties: List of Gmail properties to apply to the message. mail_labels: List of Gmail labels to apply to the message. identifier: The optional file identifier string Returns: The number of email messages to be imported. """ mail_entry_properties = MailEntryProperties( mail_message=mail_message, mail_item_properties=mail_item_properties, mail_labels=mail_labels, identifier=identifier) self.mail_entries.append(mail_entry_properties) return len(self.mail_entries) def ImportMultipleMails(self, user_name, threads_per_batch=20): """Launches separate threads to import every message added by AddMailEntry. Args: user_name: The user account name to import messages to. threads_per_batch: Number of messages to import at a time. Returns: The number of email messages that were successfully migrated. Raises: Exception: An error occurred while importing mails. """ num_entries = len(self.mail_entries) if not num_entries: return 0 threads = [] for mail_entry_properties in self.mail_entries: t = threading.Thread(name=mail_entry_properties.identifier, target=self.ImportMail, args=(user_name, mail_entry_properties.mail_message, mail_entry_properties.mail_item_properties, mail_entry_properties.mail_labels)) threads.append(t) try: # Determine the number of batches needed with threads_per_batch in each batches = num_entries / threads_per_batch + ( 0 if num_entries % threads_per_batch == 0 else 1) batch_min = 0 # Start the threads, one batch at a time for batch in range(batches): batch_max = ((batch + 1) * threads_per_batch if (batch + 1) * threads_per_batch < num_entries else num_entries) for i in range(batch_min, batch_max): threads[i].start() time.sleep(1) for i in range(batch_min, batch_max): threads[i].join() batch_min = batch_max self.mail_entries = [] except Exception, e: raise Exception(e.args[0]) else: return num_entries - self.exceptions
Python
#!/usr/bin/python """ requires tlslite - http://trevp.net/tlslite/ """ import binascii try: from gdata.tlslite.utils import keyfactory except ImportError: from tlslite.tlslite.utils import keyfactory try: from gdata.tlslite.utils import cryptomath except ImportError: from tlslite.tlslite.utils import cryptomath # XXX andy: ugly local import due to module name, oauth.oauth import gdata.oauth as oauth class OAuthSignatureMethod_RSA_SHA1(oauth.OAuthSignatureMethod): def get_name(self): return "RSA-SHA1" def _fetch_public_cert(self, oauth_request): # not implemented yet, ideas are: # (1) do a lookup in a table of trusted certs keyed off of consumer # (2) fetch via http using a url provided by the requester # (3) some sort of specific discovery code based on request # # either way should return a string representation of the certificate raise NotImplementedError def _fetch_private_cert(self, oauth_request): # not implemented yet, ideas are: # (1) do a lookup in a table of trusted certs keyed off of consumer # # either way should return a string representation of the certificate raise NotImplementedError def build_signature_base_string(self, oauth_request, consumer, token): sig = ( oauth.escape(oauth_request.get_normalized_http_method()), oauth.escape(oauth_request.get_normalized_http_url()), oauth.escape(oauth_request.get_normalized_parameters()), ) key = '' raw = '&'.join(sig) return key, raw def build_signature(self, oauth_request, consumer, token): key, base_string = self.build_signature_base_string(oauth_request, consumer, token) # Fetch the private key cert based on the request cert = self._fetch_private_cert(oauth_request) # Pull the private key from the certificate privatekey = keyfactory.parsePrivateKey(cert) # Convert base_string to bytes #base_string_bytes = cryptomath.createByteArraySequence(base_string) # Sign using the key signed = privatekey.hashAndSign(base_string) return binascii.b2a_base64(signed)[:-1] def check_signature(self, oauth_request, consumer, token, signature): decoded_sig = base64.b64decode(signature); key, base_string = self.build_signature_base_string(oauth_request, consumer, token) # Fetch the public key cert based on the request cert = self._fetch_public_cert(oauth_request) # Pull the public key from the certificate publickey = keyfactory.parsePEMKey(cert, public=True) # Check the signature ok = publickey.hashAndVerify(decoded_sig, base_string) return ok class TestOAuthSignatureMethod_RSA_SHA1(OAuthSignatureMethod_RSA_SHA1): def _fetch_public_cert(self, oauth_request): cert = """ -----BEGIN CERTIFICATE----- MIIBpjCCAQ+gAwIBAgIBATANBgkqhkiG9w0BAQUFADAZMRcwFQYDVQQDDA5UZXN0 IFByaW5jaXBhbDAeFw03MDAxMDEwODAwMDBaFw0zODEyMzEwODAwMDBaMBkxFzAV BgNVBAMMDlRlc3QgUHJpbmNpcGFsMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB gQC0YjCwIfYoprq/FQO6lb3asXrxLlJFuCvtinTF5p0GxvQGu5O3gYytUvtC2JlY zypSRjVxwxrsuRcP3e641SdASwfrmzyvIgP08N4S0IFzEURkV1wp/IpH7kH41Etb mUmrXSwfNZsnQRE5SYSOhh+LcK2wyQkdgcMv11l4KoBkcwIDAQABMA0GCSqGSIb3 DQEBBQUAA4GBAGZLPEuJ5SiJ2ryq+CmEGOXfvlTtEL2nuGtr9PewxkgnOjZpUy+d 4TvuXJbNQc8f4AMWL/tO9w0Fk80rWKp9ea8/df4qMq5qlFWlx6yOLQxumNOmECKb WpkUQDIDJEoFUzKMVuJf4KO/FJ345+BNLGgbJ6WujreoM1X/gYfdnJ/J -----END CERTIFICATE----- """ return cert def _fetch_private_cert(self, oauth_request): cert = """ -----BEGIN PRIVATE KEY----- MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALRiMLAh9iimur8V A7qVvdqxevEuUkW4K+2KdMXmnQbG9Aa7k7eBjK1S+0LYmVjPKlJGNXHDGuy5Fw/d 7rjVJ0BLB+ubPK8iA/Tw3hLQgXMRRGRXXCn8ikfuQfjUS1uZSatdLB81mydBETlJ hI6GH4twrbDJCR2Bwy/XWXgqgGRzAgMBAAECgYBYWVtleUzavkbrPjy0T5FMou8H X9u2AC2ry8vD/l7cqedtwMPp9k7TubgNFo+NGvKsl2ynyprOZR1xjQ7WgrgVB+mm uScOM/5HVceFuGRDhYTCObE+y1kxRloNYXnx3ei1zbeYLPCHdhxRYW7T0qcynNmw rn05/KO2RLjgQNalsQJBANeA3Q4Nugqy4QBUCEC09SqylT2K9FrrItqL2QKc9v0Z zO2uwllCbg0dwpVuYPYXYvikNHHg+aCWF+VXsb9rpPsCQQDWR9TT4ORdzoj+Nccn qkMsDmzt0EfNaAOwHOmVJ2RVBspPcxt5iN4HI7HNeG6U5YsFBb+/GZbgfBT3kpNG WPTpAkBI+gFhjfJvRw38n3g/+UeAkwMI2TJQS4n8+hid0uus3/zOjDySH3XHCUno cn1xOJAyZODBo47E+67R4jV1/gzbAkEAklJaspRPXP877NssM5nAZMU0/O/NGCZ+ 3jPgDUno6WbJn5cqm8MqWhW1xGkImgRk+fkDBquiq4gPiT898jusgQJAd5Zrr6Q8 AO/0isr/3aa6O6NLQxISLKcPDk2NOccAfS/xOtfOz4sJYM3+Bs4Io9+dZGSDCA54 Lw03eHTNQghS0A== -----END PRIVATE KEY----- """ return cert
Python
import cgi import urllib import time import random import urlparse import hmac import binascii VERSION = '1.0' # Hi Blaine! HTTP_METHOD = 'GET' SIGNATURE_METHOD = 'PLAINTEXT' # Generic exception class class OAuthError(RuntimeError): def __init__(self, message='OAuth error occured.'): self.message = message # optional WWW-Authenticate header (401 error) def build_authenticate_header(realm=''): return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} # url escape def escape(s): # escape '/' too return urllib.quote(s, safe='~') # util function: current timestamp # seconds since epoch (UTC) def generate_timestamp(): return int(time.time()) # util function: nonce # pseudorandom number def generate_nonce(length=8): return ''.join([str(random.randint(0, 9)) for i in range(length)]) # OAuthConsumer is a data type that represents the identity of the Consumer # via its shared secret with the Service Provider. class OAuthConsumer(object): key = None secret = None def __init__(self, key, secret): self.key = key self.secret = secret # OAuthToken is a data type that represents an End User via either an access # or request token. class OAuthToken(object): # access tokens and request tokens key = None secret = None ''' key = the token secret = the token secret ''' def __init__(self, key, secret): self.key = key self.secret = secret def to_string(self): return urllib.urlencode({'oauth_token': self.key, 'oauth_token_secret': self.secret}) # return a token from something like: # oauth_token_secret=digg&oauth_token=digg def from_string(s): params = cgi.parse_qs(s, keep_blank_values=False) key = params['oauth_token'][0] secret = params['oauth_token_secret'][0] return OAuthToken(key, secret) from_string = staticmethod(from_string) def __str__(self): return self.to_string() # OAuthRequest represents the request and can be serialized class OAuthRequest(object): ''' OAuth parameters: - oauth_consumer_key - oauth_token - oauth_signature_method - oauth_signature - oauth_timestamp - oauth_nonce - oauth_version ... any additional parameters, as defined by the Service Provider. ''' parameters = None # oauth parameters http_method = HTTP_METHOD http_url = None version = VERSION def __init__(self, http_method=HTTP_METHOD, http_url=None, parameters=None): self.http_method = http_method self.http_url = http_url self.parameters = parameters or {} def set_parameter(self, parameter, value): self.parameters[parameter] = value def get_parameter(self, parameter): try: return self.parameters[parameter] except: raise OAuthError('Parameter not found: %s' % parameter) def _get_timestamp_nonce(self): return self.get_parameter('oauth_timestamp'), self.get_parameter('oauth_nonce') # get any non-oauth parameters def get_nonoauth_parameters(self): parameters = {} for k, v in self.parameters.iteritems(): # ignore oauth parameters if k.find('oauth_') < 0: parameters[k] = v return parameters # serialize as a header for an HTTPAuth request def to_header(self, realm=''): auth_header = 'OAuth realm="%s"' % realm # add the oauth parameters if self.parameters: for k, v in self.parameters.iteritems(): if k[:6] == 'oauth_': auth_header += ', %s="%s"' % (k, escape(str(v))) return {'Authorization': auth_header} # serialize as post data for a POST request def to_postdata(self): return '&'.join(['%s=%s' % (escape(str(k)), escape(str(v))) for k, v in self.parameters.iteritems()]) # serialize as a url for a GET request def to_url(self): return '%s?%s' % (self.get_normalized_http_url(), self.to_postdata()) # return a string that consists of all the parameters that need to be signed def get_normalized_parameters(self): params = self.parameters try: # exclude the signature if it exists del params['oauth_signature'] except: pass key_values = params.items() # sort lexicographically, first after key, then after value key_values.sort() # combine key value pairs in string and escape return '&'.join(['%s=%s' % (escape(str(k)), escape(str(v))) for k, v in key_values]) # just uppercases the http method def get_normalized_http_method(self): return self.http_method.upper() # parses the url and rebuilds it to be scheme://host/path def get_normalized_http_url(self): parts = urlparse.urlparse(self.http_url) host = parts[1].lower() if host.endswith(':80') or host.endswith(':443'): host = host.split(':')[0] url_string = '%s://%s%s' % (parts[0], host, parts[2]) # scheme, netloc, path return url_string # set the signature parameter to the result of build_signature def sign_request(self, signature_method, consumer, token): # set the signature method self.set_parameter('oauth_signature_method', signature_method.get_name()) # set the signature self.set_parameter('oauth_signature', self.build_signature(signature_method, consumer, token)) def build_signature(self, signature_method, consumer, token): # call the build signature method within the signature method return signature_method.build_signature(self, consumer, token) def from_request(http_method, http_url, headers=None, parameters=None, query_string=None): # combine multiple parameter sources if parameters is None: parameters = {} # headers if headers and 'Authorization' in headers: auth_header = headers['Authorization'] # check that the authorization header is OAuth if auth_header.index('OAuth') > -1: try: # get the parameters from the header header_params = OAuthRequest._split_header(auth_header) parameters.update(header_params) except: raise OAuthError('Unable to parse OAuth parameters from Authorization header.') # GET or POST query string if query_string: query_params = OAuthRequest._split_url_string(query_string) parameters.update(query_params) # URL parameters param_str = urlparse.urlparse(http_url)[4] # query url_params = OAuthRequest._split_url_string(param_str) parameters.update(url_params) if parameters: return OAuthRequest(http_method, http_url, parameters) return None from_request = staticmethod(from_request) def from_consumer_and_token(oauth_consumer, token=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} defaults = { 'oauth_consumer_key': oauth_consumer.key, 'oauth_timestamp': generate_timestamp(), 'oauth_nonce': generate_nonce(), 'oauth_version': OAuthRequest.version, } defaults.update(parameters) parameters = defaults if token: parameters['oauth_token'] = token.key return OAuthRequest(http_method, http_url, parameters) from_consumer_and_token = staticmethod(from_consumer_and_token) def from_token_and_callback(token, callback=None, http_method=HTTP_METHOD, http_url=None, parameters=None): if not parameters: parameters = {} parameters['oauth_token'] = token.key if callback: parameters['oauth_callback'] = callback return OAuthRequest(http_method, http_url, parameters) from_token_and_callback = staticmethod(from_token_and_callback) # util function: turn Authorization: header into parameters, has to do some unescaping def _split_header(header): params = {} parts = header[6:].split(',') for param in parts: # ignore realm parameter if param.find('realm') > -1: continue # remove whitespace param = param.strip() # split key-value param_parts = param.split('=', 1) # remove quotes and unescape the value params[param_parts[0]] = urllib.unquote(param_parts[1].strip('\"')) return params _split_header = staticmethod(_split_header) # util function: turn url string into parameters, has to do some unescaping # even empty values should be included def _split_url_string(param_str): parameters = cgi.parse_qs(param_str, keep_blank_values=True) for k, v in parameters.iteritems(): parameters[k] = urllib.unquote(v[0]) return parameters _split_url_string = staticmethod(_split_url_string) # OAuthServer is a worker to check a requests validity against a data store class OAuthServer(object): timestamp_threshold = 300 # in seconds, five minutes version = VERSION signature_methods = None data_store = None def __init__(self, data_store=None, signature_methods=None): self.data_store = data_store self.signature_methods = signature_methods or {} def set_data_store(self, oauth_data_store): self.data_store = oauth_data_store def get_data_store(self): return self.data_store def add_signature_method(self, signature_method): self.signature_methods[signature_method.get_name()] = signature_method return self.signature_methods # process a request_token request # returns the request token on success def fetch_request_token(self, oauth_request): try: # get the request token for authorization token = self._get_token(oauth_request, 'request') except OAuthError: # no token required for the initial token request version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) self._check_signature(oauth_request, consumer, None) # fetch a new token token = self.data_store.fetch_request_token(consumer) return token # process an access_token request # returns the access token on success def fetch_access_token(self, oauth_request): version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) # get the request token token = self._get_token(oauth_request, 'request') self._check_signature(oauth_request, consumer, token) new_token = self.data_store.fetch_access_token(consumer, token) return new_token # verify an api call, checks all the parameters def verify_request(self, oauth_request): # -> consumer and token version = self._get_version(oauth_request) consumer = self._get_consumer(oauth_request) # get the access token token = self._get_token(oauth_request, 'access') self._check_signature(oauth_request, consumer, token) parameters = oauth_request.get_nonoauth_parameters() return consumer, token, parameters # authorize a request token def authorize_token(self, token, user): return self.data_store.authorize_request_token(token, user) # get the callback url def get_callback(self, oauth_request): return oauth_request.get_parameter('oauth_callback') # optional support for the authenticate header def build_authenticate_header(self, realm=''): return {'WWW-Authenticate': 'OAuth realm="%s"' % realm} # verify the correct version request for this server def _get_version(self, oauth_request): try: version = oauth_request.get_parameter('oauth_version') except: version = VERSION if version and version != self.version: raise OAuthError('OAuth version %s not supported.' % str(version)) return version # figure out the signature with some defaults def _get_signature_method(self, oauth_request): try: signature_method = oauth_request.get_parameter('oauth_signature_method') except: signature_method = SIGNATURE_METHOD try: # get the signature method object signature_method = self.signature_methods[signature_method] except: signature_method_names = ', '.join(self.signature_methods.keys()) raise OAuthError('Signature method %s not supported try one of the following: %s' % (signature_method, signature_method_names)) return signature_method def _get_consumer(self, oauth_request): consumer_key = oauth_request.get_parameter('oauth_consumer_key') if not consumer_key: raise OAuthError('Invalid consumer key.') consumer = self.data_store.lookup_consumer(consumer_key) if not consumer: raise OAuthError('Invalid consumer.') return consumer # try to find the token for the provided request token key def _get_token(self, oauth_request, token_type='access'): token_field = oauth_request.get_parameter('oauth_token') consumer = self._get_consumer(oauth_request) token = self.data_store.lookup_token(consumer, token_type, token_field) if not token: raise OAuthError('Invalid %s token: %s' % (token_type, token_field)) return token def _check_signature(self, oauth_request, consumer, token): timestamp, nonce = oauth_request._get_timestamp_nonce() self._check_timestamp(timestamp) self._check_nonce(consumer, token, nonce) signature_method = self._get_signature_method(oauth_request) try: signature = oauth_request.get_parameter('oauth_signature') except: raise OAuthError('Missing signature.') # validate the signature valid_sig = signature_method.check_signature(oauth_request, consumer, token, signature) if not valid_sig: key, base = signature_method.build_signature_base_string(oauth_request, consumer, token) raise OAuthError('Invalid signature. Expected signature base string: %s' % base) built = signature_method.build_signature(oauth_request, consumer, token) def _check_timestamp(self, timestamp): # verify that timestamp is recentish timestamp = int(timestamp) now = int(time.time()) lapsed = now - timestamp if lapsed > self.timestamp_threshold: raise OAuthError('Expired timestamp: given %d and now %s has a greater difference than threshold %d' % (timestamp, now, self.timestamp_threshold)) def _check_nonce(self, consumer, token, nonce): # verify that the nonce is uniqueish nonce = self.data_store.lookup_nonce(consumer, token, nonce) if nonce: raise OAuthError('Nonce already used: %s' % str(nonce)) # OAuthClient is a worker to attempt to execute a request class OAuthClient(object): consumer = None token = None def __init__(self, oauth_consumer, oauth_token): self.consumer = oauth_consumer self.token = oauth_token def get_consumer(self): return self.consumer def get_token(self): return self.token def fetch_request_token(self, oauth_request): # -> OAuthToken raise NotImplementedError def fetch_access_token(self, oauth_request): # -> OAuthToken raise NotImplementedError def access_resource(self, oauth_request): # -> some protected resource raise NotImplementedError # OAuthDataStore is a database abstraction used to lookup consumers and tokens class OAuthDataStore(object): def lookup_consumer(self, key): # -> OAuthConsumer raise NotImplementedError def lookup_token(self, oauth_consumer, token_type, token_token): # -> OAuthToken raise NotImplementedError def lookup_nonce(self, oauth_consumer, oauth_token, nonce, timestamp): # -> OAuthToken raise NotImplementedError def fetch_request_token(self, oauth_consumer): # -> OAuthToken raise NotImplementedError def fetch_access_token(self, oauth_consumer, oauth_token): # -> OAuthToken raise NotImplementedError def authorize_request_token(self, oauth_token, user): # -> OAuthToken raise NotImplementedError # OAuthSignatureMethod is a strategy class that implements a signature method class OAuthSignatureMethod(object): def get_name(self): # -> str raise NotImplementedError def build_signature_base_string(self, oauth_request, oauth_consumer, oauth_token): # -> str key, str raw raise NotImplementedError def build_signature(self, oauth_request, oauth_consumer, oauth_token): # -> str raise NotImplementedError def check_signature(self, oauth_request, consumer, token, signature): built = self.build_signature(oauth_request, consumer, token) return built == signature class OAuthSignatureMethod_HMAC_SHA1(OAuthSignatureMethod): def get_name(self): return 'HMAC-SHA1' def build_signature_base_string(self, oauth_request, consumer, token): sig = ( escape(oauth_request.get_normalized_http_method()), escape(oauth_request.get_normalized_http_url()), escape(oauth_request.get_normalized_parameters()), ) key = '%s&' % escape(consumer.secret) if token: key += escape(token.secret) raw = '&'.join(sig) return key, raw def build_signature(self, oauth_request, consumer, token): # build the base signature string key, raw = self.build_signature_base_string(oauth_request, consumer, token) # hmac object try: import hashlib # 2.5 hashed = hmac.new(key, raw, hashlib.sha1) except: import sha # deprecated hashed = hmac.new(key, raw, sha) # calculate the digest base 64 return binascii.b2a_base64(hashed.digest())[:-1] class OAuthSignatureMethod_PLAINTEXT(OAuthSignatureMethod): def get_name(self): return 'PLAINTEXT' def build_signature_base_string(self, oauth_request, consumer, token): # concatenate the consumer key and secret sig = escape(consumer.secret) + '&' if token: sig = sig + escape(token.secret) return sig def build_signature(self, oauth_request, consumer, token): return self.build_signature_base_string(oauth_request, consumer, token)
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Provides HTTP functions for gdata.service to use on Google App Engine AppEngineHttpClient: Provides an HTTP request method which uses App Engine's urlfetch API. Set the http_client member of a GDataService object to an instance of an AppEngineHttpClient to allow the gdata library to run on Google App Engine. run_on_appengine: Function which will modify an existing GDataService object to allow it to run on App Engine. It works by creating a new instance of the AppEngineHttpClient and replacing the GDataService object's http_client. HttpRequest: Function that wraps google.appengine.api.urlfetch.Fetch in a common interface which is used by gdata.service.GDataService. In other words, this module can be used as the gdata service request handler so that all HTTP requests will be performed by the hosting Google App Engine server. """ __author__ = 'api.jscudder (Jeff Scudder)' import StringIO import atom.service import atom.http_interface from google.appengine.api import urlfetch def run_on_appengine(gdata_service): """Modifies a GDataService object to allow it to run on App Engine. Args: gdata_service: An instance of AtomService, GDataService, or any of their subclasses which has an http_client member. """ gdata_service.http_client = AppEngineHttpClient() class AppEngineHttpClient(atom.http_interface.GenericHttpClient): def __init__(self, headers=None): self.debug = False self.headers = headers or {} def request(self, operation, url, data=None, headers=None): """Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE. Usage example, perform and HTTP GET on http://www.google.com/: import atom.http client = atom.http.HttpClient() http_response = client.request('GET', 'http://www.google.com/') Args: operation: str The HTTP operation to be performed. This is usually one of 'GET', 'POST', 'PUT', or 'DELETE' data: filestream, list of parts, or other object which can be converted to a string. Should be set to None when performing a GET or DELETE. If data is a file-like object which can be read, this method will read a chunk of 100K bytes at a time and send them. If the data is a list of parts to be sent, each part will be evaluated and sent. url: The full URL to which the request should be sent. Can be a string or atom.url.Url. headers: dict of strings. HTTP headers which should be sent in the request. """ all_headers = self.headers.copy() if headers: all_headers.update(headers) # Construct the full payload. # Assume that data is None or a string. data_str = data if data: if isinstance(data, list): # If data is a list of different objects, convert them all to strings # and join them together. converted_parts = [__ConvertDataPart(x) for x in data] data_str = ''.join(converted_parts) else: data_str = __ConvertDataPart(data) # If the list of headers does not include a Content-Length, attempt to # calculate it based on the data object. if data and 'Content-Length' not in all_headers: all_headers['Content-Length'] = len(data_str) # Set the content type to the default value if none was set. if 'Content-Type' not in all_headers: all_headers['Content-Type'] = 'application/atom+xml' # Lookup the urlfetch operation which corresponds to the desired HTTP verb. if operation == 'GET': method = urlfetch.GET elif operation == 'POST': method = urlfetch.POST elif operation == 'PUT': method = urlfetch.PUT elif operation == 'DELETE': method = urlfetch.DELETE else: method = None return HttpResponse(urlfetch.Fetch(url=str(url), payload=data_str, method=method, headers=all_headers)) def HttpRequest(service, operation, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE. This function is deprecated, use AppEngineHttpClient.request instead. To use this module with gdata.service, you can set this module to be the http_request_handler so that HTTP requests use Google App Engine's urlfetch. import gdata.service import gdata.urlfetch gdata.service.http_request_handler = gdata.urlfetch Args: service: atom.AtomService object which contains some of the parameters needed to make the request. The following members are used to construct the HTTP call: server (str), additional_headers (dict), port (int), and ssl (bool). operation: str The HTTP operation to be performed. This is usually one of 'GET', 'POST', 'PUT', or 'DELETE' data: filestream, list of parts, or other object which can be converted to a string. Should be set to None when performing a GET or PUT. If data is a file-like object which can be read, this method will read a chunk of 100K bytes at a time and send them. If the data is a list of parts to be sent, each part will be evaluated and sent. uri: The beginning of the URL to which the request should be sent. Examples: '/', '/base/feeds/snippets', '/m8/feeds/contacts/default/base' extra_headers: dict of strings. HTTP headers which should be sent in the request. These headers are in addition to those stored in service.additional_headers. url_params: dict of strings. Key value pairs to be added to the URL as URL parameters. For example {'foo':'bar', 'test':'param'} will become ?foo=bar&test=param. escape_params: bool default True. If true, the keys and values in url_params will be URL escaped when the form is constructed (Special characters converted to %XX form.) content_type: str The MIME type for the data being sent. Defaults to 'application/atom+xml', this is only used if data is set. """ full_uri = atom.service.BuildUri(uri, url_params, escape_params) (server, port, ssl, partial_uri) = atom.service.ProcessUrl(service, full_uri) # Construct the full URL for the request. if ssl: full_url = 'https://%s%s' % (server, partial_uri) else: full_url = 'http://%s%s' % (server, partial_uri) # Construct the full payload. # Assume that data is None or a string. data_str = data if data: if isinstance(data, list): # If data is a list of different objects, convert them all to strings # and join them together. converted_parts = [__ConvertDataPart(x) for x in data] data_str = ''.join(converted_parts) else: data_str = __ConvertDataPart(data) # Construct the dictionary of HTTP headers. headers = {} if isinstance(service.additional_headers, dict): headers = service.additional_headers.copy() if isinstance(extra_headers, dict): for header, value in extra_headers.iteritems(): headers[header] = value # Add the content type header (we don't need to calculate content length, # since urlfetch.Fetch will calculate for us). if content_type: headers['Content-Type'] = content_type # Lookup the urlfetch operation which corresponds to the desired HTTP verb. if operation == 'GET': method = urlfetch.GET elif operation == 'POST': method = urlfetch.POST elif operation == 'PUT': method = urlfetch.PUT elif operation == 'DELETE': method = urlfetch.DELETE else: method = None return HttpResponse(urlfetch.Fetch(url=full_url, payload=data_str, method=method, headers=headers)) def __ConvertDataPart(data): if not data or isinstance(data, str): return data elif hasattr(data, 'read'): # data is a file like object, so read it completely. return data.read() # The data object was not a file. # Try to convert to a string and send the data. return str(data) class HttpResponse(object): """Translates a urlfetch resoinse to look like an hhtplib resoinse. Used to allow the resoinse from HttpRequest to be usable by gdata.service methods. """ def __init__(self, urlfetch_response): self.body = StringIO.StringIO(urlfetch_response.content) self.headers = urlfetch_response.headers self.status = urlfetch_response.status_code self.reason = '' def read(self, length=None): if not length: return self.body.read() else: return self.body.read(length) def getheader(self, name): if not self.headers.has_key(name): return self.headers[name.lower()] return self.headers[name]
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the data classes of the Google Book Search Data API""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import atom.data import gdata.data import gdata.dublincore.data import gdata.opensearch.data GBS_TEMPLATE = '{http://schemas.google.com/books/2008/}%s' class CollectionEntry(gdata.data.GDEntry): """Describes an entry in a feed of collections.""" class CollectionFeed(gdata.data.BatchFeed): """Describes a Book Search collection feed.""" entry = [CollectionEntry] class Embeddability(atom.core.XmlElement): """Describes an embeddability.""" _qname = GBS_TEMPLATE % 'embeddability' value = 'value' class OpenAccess(atom.core.XmlElement): """Describes an open access.""" _qname = GBS_TEMPLATE % 'openAccess' value = 'value' class Review(atom.core.XmlElement): """User-provided review.""" _qname = GBS_TEMPLATE % 'review' lang = 'lang' type = 'type' class Viewability(atom.core.XmlElement): """Describes a viewability.""" _qname = GBS_TEMPLATE % 'viewability' value = 'value' class VolumeEntry(gdata.data.GDEntry): """Describes an entry in a feed of Book Search volumes.""" comments = gdata.data.Comments language = [gdata.dublincore.data.Language] open_access = OpenAccess format = [gdata.dublincore.data.Format] dc_title = [gdata.dublincore.data.Title] viewability = Viewability embeddability = Embeddability creator = [gdata.dublincore.data.Creator] rating = gdata.data.Rating description = [gdata.dublincore.data.Description] publisher = [gdata.dublincore.data.Publisher] date = [gdata.dublincore.data.Date] subject = [gdata.dublincore.data.Subject] identifier = [gdata.dublincore.data.Identifier] review = Review class VolumeFeed(gdata.data.BatchFeed): """Describes a Book Search volume feed.""" entry = [VolumeEntry]
Python
#!/usr/bin/python """ Data Models for books.service All classes can be instantiated from an xml string using their FromString class method. Notes: * Book.title displays the first dc:title because the returned XML repeats that datum as atom:title. There is an undocumented gbs:openAccess element that is not parsed. """ __author__ = "James Sams <sams.james@gmail.com>" __copyright__ = "Apache License v2.0" import atom import gdata BOOK_SEARCH_NAMESPACE = 'http://schemas.google.com/books/2008' DC_NAMESPACE = 'http://purl.org/dc/terms' ANNOTATION_REL = "http://schemas.google.com/books/2008/annotation" INFO_REL = "http://schemas.google.com/books/2008/info" LABEL_SCHEME = "http://schemas.google.com/books/2008/labels" PREVIEW_REL = "http://schemas.google.com/books/2008/preview" THUMBNAIL_REL = "http://schemas.google.com/books/2008/thumbnail" FULL_VIEW = "http://schemas.google.com/books/2008#view_all_pages" PARTIAL_VIEW = "http://schemas.google.com/books/2008#view_partial" NO_VIEW = "http://schemas.google.com/books/2008#view_no_pages" UNKNOWN_VIEW = "http://schemas.google.com/books/2008#view_unknown" EMBEDDABLE = "http://schemas.google.com/books/2008#embeddable" NOT_EMBEDDABLE = "http://schemas.google.com/books/2008#not_embeddable" class _AtomFromString(atom.AtomBase): #@classmethod def FromString(cls, s): return atom.CreateClassFromXMLString(cls, s) FromString = classmethod(FromString) class Creator(_AtomFromString): """ The <dc:creator> element identifies an author-or more generally, an entity responsible for creating the volume in question. Examples of a creator include a person, an organization, or a service. In the case of anthologies, proceedings, or other edited works, this field may be used to indicate editors or other entities responsible for collecting the volume's contents. This element appears as a child of <entry>. If there are multiple authors or contributors to the book, there may be multiple <dc:creator> elements in the volume entry (one for each creator or contributor). """ _tag = 'creator' _namespace = DC_NAMESPACE class Date(_AtomFromString): #iso 8601 / W3CDTF profile """ The <dc:date> element indicates the publication date of the specific volume in question. If the book is a reprint, this is the reprint date, not the original publication date. The date is encoded according to the ISO-8601 standard (and more specifically, the W3CDTF profile). The <dc:date> element can appear only as a child of <entry>. Usually only the year or the year and the month are given. YYYY-MM-DDThh:mm:ssTZD TZD = -hh:mm or +hh:mm """ _tag = 'date' _namespace = DC_NAMESPACE class Description(_AtomFromString): """ The <dc:description> element includes text that describes a book or book result. In a search result feed, this may be a search result "snippet" that contains the words around the user's search term. For a single volume feed, this element may contain a synopsis of the book. The <dc:description> element can appear only as a child of <entry> """ _tag = 'description' _namespace = DC_NAMESPACE class Format(_AtomFromString): """ The <dc:format> element describes the physical properties of the volume. Currently, it indicates the number of pages in the book, but more information may be added to this field in the future. This element can appear only as a child of <entry>. """ _tag = 'format' _namespace = DC_NAMESPACE class Identifier(_AtomFromString): """ The <dc:identifier> element provides an unambiguous reference to a particular book. * Every <entry> contains at least one <dc:identifier> child. * The first identifier is always the unique string Book Search has assigned to the volume (such as s1gVAAAAYAAJ). This is the ID that appears in the book's URL in the Book Search GUI, as well as in the URL of that book's single item feed. * Many books contain additional <dc:identifier> elements. These provide alternate, external identifiers to the volume. Such identifiers may include the ISBNs, ISSNs, Library of Congress Control Numbers (LCCNs), and OCLC numbers; they are prepended with a corresponding namespace prefix (such as "ISBN:"). * Any <dc:identifier> can be passed to the Dynamic Links, used to instantiate an Embedded Viewer, or even used to construct static links to Book Search. The <dc:identifier> element can appear only as a child of <entry>. """ _tag = 'identifier' _namespace = DC_NAMESPACE class Publisher(_AtomFromString): """ The <dc:publisher> element contains the name of the entity responsible for producing and distributing the volume (usually the specific edition of this book). Examples of a publisher include a person, an organization, or a service. This element can appear only as a child of <entry>. If there is more than one publisher, multiple <dc:publisher> elements may appear. """ _tag = 'publisher' _namespace = DC_NAMESPACE class Subject(_AtomFromString): """ The <dc:subject> element identifies the topic of the book. Usually this is a Library of Congress Subject Heading (LCSH) or Book Industry Standards and Communications Subject Heading (BISAC). The <dc:subject> element can appear only as a child of <entry>. There may be multiple <dc:subject> elements per entry. """ _tag = 'subject' _namespace = DC_NAMESPACE class Title(_AtomFromString): """ The <dc:title> element contains the title of a book as it was published. If a book has a subtitle, it appears as a second <dc:title> element in the book result's <entry>. """ _tag = 'title' _namespace = DC_NAMESPACE class Viewability(_AtomFromString): """ Google Book Search respects the user's local copyright restrictions. As a result, previews or full views of some books are not available in all locations. The <gbs:viewability> element indicates whether a book is fully viewable, can be previewed, or only has "about the book" information. These three "viewability modes" are the same ones returned by the Dynamic Links API. The <gbs:viewability> element can appear only as a child of <entry>. The value attribute will take the form of the following URIs to represent the relevant viewing capability: Full View: http://schemas.google.com/books/2008#view_all_pages Limited Preview: http://schemas.google.com/books/2008#view_partial Snippet View/No Preview: http://schemas.google.com/books/2008#view_no_pages Unknown view: http://schemas.google.com/books/2008#view_unknown """ _tag = 'viewability' _namespace = BOOK_SEARCH_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, text=None, extension_elements=None, extension_attributes=None): self.value = value _AtomFromString.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Embeddability(_AtomFromString): """ Many of the books found on Google Book Search can be embedded on third-party sites using the Embedded Viewer. The <gbs:embeddability> element indicates whether a particular book result is available for embedding. By definition, a book that cannot be previewed on Book Search cannot be embedded on third- party sites. The <gbs:embeddability> element can appear only as a child of <entry>. The value attribute will take on one of the following URIs: embeddable: http://schemas.google.com/books/2008#embeddable not embeddable: http://schemas.google.com/books/2008#not_embeddable """ _tag = 'embeddability' _namespace = BOOK_SEARCH_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, text=None, extension_elements=None, extension_attributes=None): self.value = value _AtomFromString.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Review(_AtomFromString): """ When present, the <gbs:review> element contains a user-generated review for a given book. This element currently appears only in the user library and user annotation feeds, as a child of <entry>. type: text, html, xhtml xml:lang: id of the language, a guess, (always two letters?) """ _tag = 'review' _namespace = BOOK_SEARCH_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' _attributes['{http://www.w3.org/XML/1998/namespace}lang'] = 'lang' def __init__(self, type=None, lang=None, text=None, extension_elements=None, extension_attributes=None): self.type = type self.lang = lang _AtomFromString.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Rating(_AtomFromString): """All attributes must take an integral string between 1 and 5. The min, max, and average attributes represent 'community' ratings. The value attribute is the user's (of the feed from which the item is fetched, not necessarily the authenticated user) rating of the book. """ _tag = 'rating' _namespace = gdata.GDATA_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['min'] = 'min' _attributes['max'] = 'max' _attributes['average'] = 'average' _attributes['value'] = 'value' def __init__(self, min=None, max=None, average=None, value=None, text=None, extension_elements=None, extension_attributes=None): self.min = min self.max = max self.average = average self.value = value _AtomFromString.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Book(_AtomFromString, gdata.GDataEntry): """ Represents an <entry> from either a search, annotation, library, or single item feed. Note that dc_title attribute is the proper title of the volume, title is an atom element and may not represent the full title. """ _tag = 'entry' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() for i in (Creator, Identifier, Publisher, Subject,): _children['{%s}%s' % (i._namespace, i._tag)] = (i._tag, [i]) for i in (Date, Description, Format, Viewability, Embeddability, Review, Rating): # Review, Rating maybe only in anno/lib entrys _children['{%s}%s' % (i._namespace, i._tag)] = (i._tag, i) # there is an atom title as well, should we clobber that? del(i) _children['{%s}%s' % (Title._namespace, Title._tag)] = ('dc_title', [Title]) def to_dict(self): """Returns a dictionary of the book's available metadata. If the data cannot be discovered, it is not included as a key in the returned dict. The possible keys are: authors, embeddability, date, description, format, identifiers, publishers, rating, review, subjects, title, and viewability. Notes: * Plural keys will be lists * Singular keys will be strings * Title, despite usually being a list, joins the title and subtitle with a space as a single string. * embeddability and viewability only return the portion of the URI after # * identifiers is a list of tuples, where the first item of each tuple is the type of identifier and the second item is the identifying string. Note that while doing dict() on this tuple may be possible, some items may have multiple of the same identifier and converting to a dict may resulted in collisions/dropped data. * Rating returns only the user's rating. See Rating class for precise definition. """ d = {} if self.GetAnnotationLink(): d['annotation'] = self.GetAnnotationLink().href if self.creator: d['authors'] = [x.text for x in self.creator] if self.embeddability: d['embeddability'] = self.embeddability.value.split('#')[-1] if self.date: d['date'] = self.date.text if self.description: d['description'] = self.description.text if self.format: d['format'] = self.format.text if self.identifier: d['identifiers'] = [('google_id', self.identifier[0].text)] for x in self.identifier[1:]: l = x.text.split(':') # should we lower the case of the ids? d['identifiers'].append((l[0], ':'.join(l[1:]))) if self.GetInfoLink(): d['info'] = self.GetInfoLink().href if self.GetPreviewLink(): d['preview'] = self.GetPreviewLink().href if self.publisher: d['publishers'] = [x.text for x in self.publisher] if self.rating: d['rating'] = self.rating.value if self.review: d['review'] = self.review.text if self.subject: d['subjects'] = [x.text for x in self.subject] if self.GetThumbnailLink(): d['thumbnail'] = self.GetThumbnailLink().href if self.dc_title: d['title'] = ' '.join([x.text for x in self.dc_title]) if self.viewability: d['viewability'] = self.viewability.value.split('#')[-1] return d def __init__(self, creator=None, date=None, description=None, format=None, author=None, identifier=None, publisher=None, subject=None, dc_title=None, viewability=None, embeddability=None, review=None, rating=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, title=None, control=None, updated=None, text=None, extension_elements=None, extension_attributes=None): self.creator = creator self.date = date self.description = description self.format = format self.identifier = identifier self.publisher = publisher self.subject = subject self.dc_title = dc_title or [] self.viewability = viewability self.embeddability = embeddability self.review = review self.rating = rating gdata.GDataEntry.__init__(self, author=author, category=category, content=content, contributor=contributor, atom_id=atom_id, link=link, published=published, rights=rights, source=source, summary=summary, title=title, control=control, updated=updated, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) def GetThumbnailLink(self): """Returns the atom.Link object representing the thumbnail URI.""" for i in self.link: if i.rel == THUMBNAIL_REL: return i def GetInfoLink(self): """ Returns the atom.Link object representing the human-readable info URI. """ for i in self.link: if i.rel == INFO_REL: return i def GetPreviewLink(self): """Returns the atom.Link object representing the preview URI.""" for i in self.link: if i.rel == PREVIEW_REL: return i def GetAnnotationLink(self): """ Returns the atom.Link object representing the Annotation URI. Note that the use of www.books in the href of this link seems to make this information useless. Using books.service.ANNOTATION_FEED and BOOK_SERVER to construct your URI seems to work better. """ for i in self.link: if i.rel == ANNOTATION_REL: return i def set_rating(self, value): """Set user's rating. Must be an integral string between 1 nad 5""" assert (value in ('1','2','3','4','5')) if not isinstance(self.rating, Rating): self.rating = Rating() self.rating.value = value def set_review(self, text, type='text', lang='en'): """Set user's review text""" self.review = Review(text=text, type=type, lang=lang) def get_label(self): """Get users label for the item as a string""" for i in self.category: if i.scheme == LABEL_SCHEME: return i.term def set_label(self, term): """Clear pre-existing label for the item and set term as the label.""" self.remove_label() self.category.append(atom.Category(term=term, scheme=LABEL_SCHEME)) def remove_label(self): """Clear the user's label for the item""" ln = len(self.category) for i, j in enumerate(self.category[::-1]): if j.scheme == LABEL_SCHEME: del(self.category[ln-1-i]) def clean_annotations(self): """Clear all annotations from an item. Useful for taking an item from another user's library/annotation feed and adding it to the authenticated user's library without adopting annotations.""" self.remove_label() self.review = None self.rating = None def get_google_id(self): """Get Google's ID of the item.""" return self.id.text.split('/')[-1] class BookFeed(_AtomFromString, gdata.GDataFeed): """Represents a feed of entries from a search.""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataFeed._children.copy() _children['{%s}%s' % (Book._namespace, Book._tag)] = (Book._tag, [Book]) if __name__ == '__main__': import doctest doctest.testfile('datamodels.txt')
Python
#!/usr/bin/python """ Extend gdata.service.GDataService to support authenticated CRUD ops on Books API http://code.google.com/apis/books/docs/getting-started.html http://code.google.com/apis/books/docs/gdata/developers_guide_protocol.html TODO: (here and __init__) * search based on label, review, or other annotations (possible?) * edit (specifically, Put requests) seem to fail effect a change Problems With API: * Adding a book with a review to the library adds a note, not a review. This does not get included in the returned item. You see this by looking at My Library through the website. * Editing a review never edits a review (unless it is freshly added, but see above). More generally, * a Put request with changed annotations (label/rating/review) does NOT change the data. Note: Put requests only work on the href from GetEditLink (as per the spec). Do not try to PUT to the annotate or library feeds, this will cause a 400 Invalid URI Bad Request response. Attempting to Post to one of the feeds with the updated annotations does not update them. See the following for (hopefully) a follow up: google.com/support/forum/p/booksearch-apis/thread?tid=27fd7f68de438fc8 * Attempts to workaround the edit problem continue to fail. For example, removing the item, editing the data, readding the item, gives us only our originally added data (annotations). This occurs even if we completely shut python down, refetch the book from the public feed, and re-add it. There is some kind of persistence going on that I cannot change. This is likely due to the annotations being cached in the annotation feed and the inability to edit (see Put, above) * GetAnnotationLink has www.books.... as the server, but hitting www... results in a bad URI error. * Spec indicates there may be multiple labels, but there does not seem to be a way to get the server to accept multiple labels, nor does the web interface have an obvious way to have multiple labels. Multiple labels are never returned. """ __author__ = "James Sams <sams.james@gmail.com>" __copyright__ = "Apache License v2.0" from shlex import split import gdata.service try: import books except ImportError: import gdata.books as books BOOK_SERVER = "books.google.com" GENERAL_FEED = "/books/feeds/volumes" ITEM_FEED = "/books/feeds/volumes/" LIBRARY_FEED = "/books/feeds/users/%s/collections/library/volumes" ANNOTATION_FEED = "/books/feeds/users/%s/volumes" PARTNER_FEED = "/books/feeds/p/%s/volumes" BOOK_SERVICE = "print" ACCOUNT_TYPE = "HOSTED_OR_GOOGLE" class BookService(gdata.service.GDataService): def __init__(self, email=None, password=None, source=None, server=BOOK_SERVER, account_type=ACCOUNT_TYPE, exception_handlers=tuple(), **kwargs): """source should be of form 'ProgramCompany - ProgramName - Version'""" gdata.service.GDataService.__init__(self, email=email, password=password, service=BOOK_SERVICE, source=source, server=server, **kwargs) self.exception_handlers = exception_handlers def search(self, q, start_index="1", max_results="10", min_viewability="none", feed=GENERAL_FEED, converter=books.BookFeed.FromString): """ Query the Public search feed. q is either a search string or a gdata.service.Query instance with a query set. min_viewability must be "none", "partial", or "full". If you change the feed to a single item feed, note that you will probably need to change the converter to be Book.FromString """ if not isinstance(q, gdata.service.Query): q = gdata.service.Query(text_query=q) if feed: q.feed = feed q['start-index'] = start_index q['max-results'] = max_results q['min-viewability'] = min_viewability return self.Get(uri=q.ToUri(),converter=converter) def search_by_keyword(self, q='', feed=GENERAL_FEED, start_index="1", max_results="10", min_viewability="none", **kwargs): """ Query the Public Search Feed by keyword. Non-keyword strings can be set in q. This is quite fragile. Is there a function somewhere in the Google library that will parse a query the same way that Google does? Legal Identifiers are listed below and correspond to their meaning at http://books.google.com/advanced_book_search: all_words exact_phrase at_least_one without_words title author publisher subject isbn lccn oclc seemingly unsupported: publication_date: a sequence of two, two tuples: ((min_month,min_year),(max_month,max_year)) where month is one/two digit month, year is 4 digit, eg: (('1','2000'),('10','2003')). Lower bound is inclusive, upper bound is exclusive """ for k, v in kwargs.items(): if not v: continue k = k.lower() if k == 'all_words': q = "%s %s" % (q, v) elif k == 'exact_phrase': q = '%s "%s"' % (q, v.strip('"')) elif k == 'at_least_one': q = '%s %s' % (q, ' '.join(['OR "%s"' % x for x in split(v)])) elif k == 'without_words': q = '%s %s' % (q, ' '.join(['-"%s"' % x for x in split(v)])) elif k in ('author','title', 'publisher'): q = '%s %s' % (q, ' '.join(['in%s:"%s"'%(k,x) for x in split(v)])) elif k == 'subject': q = '%s %s' % (q, ' '.join(['%s:"%s"' % (k,x) for x in split(v)])) elif k == 'isbn': q = '%s ISBN%s' % (q, v) elif k == 'issn': q = '%s ISSN%s' % (q,v) elif k == 'oclc': q = '%s OCLC%s' % (q,v) else: raise ValueError("Unsupported search keyword") return self.search(q.strip(),start_index=start_index, feed=feed, max_results=max_results, min_viewability=min_viewability) def search_library(self, q, id='me', **kwargs): """Like search, but in a library feed. Default is the authenticated user's feed. Change by setting id.""" if 'feed' in kwargs: raise ValueError("kwarg 'feed' conflicts with library_id") feed = LIBRARY_FEED % id return self.search(q, feed=feed, **kwargs) def search_library_by_keyword(self, id='me', **kwargs): """Hybrid of search_by_keyword and search_library """ if 'feed' in kwargs: raise ValueError("kwarg 'feed' conflicts with library_id") feed = LIBRARY_FEED % id return self.search_by_keyword(feed=feed,**kwargs) def search_annotations(self, q, id='me', **kwargs): """Like search, but in an annotation feed. Default is the authenticated user's feed. Change by setting id.""" if 'feed' in kwargs: raise ValueError("kwarg 'feed' conflicts with library_id") feed = ANNOTATION_FEED % id return self.search(q, feed=feed, **kwargs) def search_annotations_by_keyword(self, id='me', **kwargs): """Hybrid of search_by_keyword and search_annotations """ if 'feed' in kwargs: raise ValueError("kwarg 'feed' conflicts with library_id") feed = ANNOTATION_FEED % id return self.search_by_keyword(feed=feed,**kwargs) def add_item_to_library(self, item): """Add the item, either an XML string or books.Book instance, to the user's library feed""" feed = LIBRARY_FEED % 'me' return self.Post(data=item, uri=feed, converter=books.Book.FromString) def remove_item_from_library(self, item): """ Remove the item, a books.Book instance, from the authenticated user's library feed. Using an item retrieved from a public search will fail. """ return self.Delete(item.GetEditLink().href) def add_annotation(self, item): """ Add the item, either an XML string or books.Book instance, to the user's annotation feed. """ # do not use GetAnnotationLink, results in 400 Bad URI due to www return self.Post(data=item, uri=ANNOTATION_FEED % 'me', converter=books.Book.FromString) def edit_annotation(self, item): """ Send an edited item, a books.Book instance, to the user's annotation feed. Note that whereas extra annotations in add_annotations, minus ratings which are immutable once set, are simply added to the item in the annotation feed, if an annotation has been removed from the item, sending an edit request will remove that annotation. This should not happen with add_annotation. """ return self.Put(data=item, uri=item.GetEditLink().href, converter=books.Book.FromString) def get_by_google_id(self, id): return self.Get(ITEM_FEED + id, converter=books.Book.FromString) def get_library(self, id='me',feed=LIBRARY_FEED, start_index="1", max_results="100", min_viewability="none", converter=books.BookFeed.FromString): """ Return a generator object that will return gbook.Book instances until the search feed no longer returns an item from the GetNextLink method. Thus max_results is not the maximum number of items that will be returned, but rather the number of items per page of searches. This has been set high to reduce the required number of network requests. """ q = gdata.service.Query() q.feed = feed % id q['start-index'] = start_index q['max-results'] = max_results q['min-viewability'] = min_viewability x = self.Get(uri=q.ToUri(), converter=converter) while 1: for entry in x.entry: yield entry else: l = x.GetNextLink() if l: # hope the server preserves our preferences x = self.Get(uri=l.href, converter=converter) else: break def get_annotations(self, id='me', start_index="1", max_results="100", min_viewability="none", converter=books.BookFeed.FromString): """ Like get_library, but for the annotation feed """ return self.get_library(id=id, feed=ANNOTATION_FEED, max_results=max_results, min_viewability = min_viewability, converter=converter)
Python
#!/usr/bin/env python # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. """Provides a base class to represent property elements in feeds. This module is used for version 2 of the Google Data APIs. The primary class in this module is AppsProperty. """ __author__ = 'Vic Fryzel <vicfryzel@google.com>' import atom.core import gdata.apps class AppsProperty(atom.core.XmlElement): """Represents an <apps:property> element in a feed.""" _qname = gdata.apps.APPS_TEMPLATE % 'property' name = 'name' value = 'value'
Python
# -*-*- encoding: utf-8 -*-*- # # This is gdata.photos.exif, implementing the exif namespace in gdata # # $Id: __init__.py 81 2007-10-03 14:41:42Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # Portions copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module maps elements from the {EXIF} namespace[1] to GData objects. These elements describe image data, using exif attributes[2]. Picasa Web Albums uses the exif namespace to represent Exif data encoded in a photo [3]. Picasa Web Albums uses the following exif elements: exif:distance exif:exposure exif:flash exif:focallength exif:fstop exif:imageUniqueID exif:iso exif:make exif:model exif:tags exif:time [1]: http://schemas.google.com/photos/exif/2007. [2]: http://en.wikipedia.org/wiki/Exif [3]: http://code.google.com/apis/picasaweb/reference.html#exif_reference """ __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' import atom import gdata EXIF_NAMESPACE = 'http://schemas.google.com/photos/exif/2007' class ExifBaseElement(atom.AtomBase): """Base class for elements in the EXIF_NAMESPACE (%s). To add new elements, you only need to add the element tag name to self._tag """ % EXIF_NAMESPACE _tag = '' _namespace = EXIF_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Distance(ExifBaseElement): "(float) The distance to the subject, e.g. 0.0" _tag = 'distance' def DistanceFromString(xml_string): return atom.CreateClassFromXMLString(Distance, xml_string) class Exposure(ExifBaseElement): "(float) The exposure time used, e.g. 0.025 or 8.0E4" _tag = 'exposure' def ExposureFromString(xml_string): return atom.CreateClassFromXMLString(Exposure, xml_string) class Flash(ExifBaseElement): """(string) Boolean value indicating whether the flash was used. The .text attribute will either be `true' or `false' As a convenience, this object's .bool method will return what you want, so you can say: flash_used = bool(Flash) """ _tag = 'flash' def __bool__(self): if self.text.lower() in ('true','false'): return self.text.lower() == 'true' def FlashFromString(xml_string): return atom.CreateClassFromXMLString(Flash, xml_string) class Focallength(ExifBaseElement): "(float) The focal length used, e.g. 23.7" _tag = 'focallength' def FocallengthFromString(xml_string): return atom.CreateClassFromXMLString(Focallength, xml_string) class Fstop(ExifBaseElement): "(float) The fstop value used, e.g. 5.0" _tag = 'fstop' def FstopFromString(xml_string): return atom.CreateClassFromXMLString(Fstop, xml_string) class ImageUniqueID(ExifBaseElement): "(string) The unique image ID for the photo. Generated by Google Photo servers" _tag = 'imageUniqueID' def ImageUniqueIDFromString(xml_string): return atom.CreateClassFromXMLString(ImageUniqueID, xml_string) class Iso(ExifBaseElement): "(int) The iso equivalent value used, e.g. 200" _tag = 'iso' def IsoFromString(xml_string): return atom.CreateClassFromXMLString(Iso, xml_string) class Make(ExifBaseElement): "(string) The make of the camera used, e.g. Fictitious Camera Company" _tag = 'make' def MakeFromString(xml_string): return atom.CreateClassFromXMLString(Make, xml_string) class Model(ExifBaseElement): "(string) The model of the camera used,e.g AMAZING-100D" _tag = 'model' def ModelFromString(xml_string): return atom.CreateClassFromXMLString(Model, xml_string) class Time(ExifBaseElement): """(int) The date/time the photo was taken, e.g. 1180294337000. Represented as the number of milliseconds since January 1st, 1970. The value of this element will always be identical to the value of the <gphoto:timestamp>. Look at this object's .isoformat() for a human friendly datetime string: photo_epoch = Time.text # 1180294337000 photo_isostring = Time.isoformat() # '2007-05-27T19:32:17.000Z' Alternatively: photo_datetime = Time.datetime() # (requires python >= 2.3) """ _tag = 'time' def isoformat(self): """(string) Return the timestamp as a ISO 8601 formatted string, e.g. '2007-05-27T19:32:17.000Z' """ import time epoch = float(self.text)/1000 return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(epoch)) def datetime(self): """(datetime.datetime) Return the timestamp as a datetime.datetime object Requires python 2.3 """ import datetime epoch = float(self.text)/1000 return datetime.datetime.fromtimestamp(epoch) def TimeFromString(xml_string): return atom.CreateClassFromXMLString(Time, xml_string) class Tags(ExifBaseElement): """The container for all exif elements. The <exif:tags> element can appear as a child of a photo entry. """ _tag = 'tags' _children = atom.AtomBase._children.copy() _children['{%s}fstop' % EXIF_NAMESPACE] = ('fstop', Fstop) _children['{%s}make' % EXIF_NAMESPACE] = ('make', Make) _children['{%s}model' % EXIF_NAMESPACE] = ('model', Model) _children['{%s}distance' % EXIF_NAMESPACE] = ('distance', Distance) _children['{%s}exposure' % EXIF_NAMESPACE] = ('exposure', Exposure) _children['{%s}flash' % EXIF_NAMESPACE] = ('flash', Flash) _children['{%s}focallength' % EXIF_NAMESPACE] = ('focallength', Focallength) _children['{%s}iso' % EXIF_NAMESPACE] = ('iso', Iso) _children['{%s}time' % EXIF_NAMESPACE] = ('time', Time) _children['{%s}imageUniqueID' % EXIF_NAMESPACE] = ('imageUniqueID', ImageUniqueID) def __init__(self, extension_elements=None, extension_attributes=None, text=None): ExifBaseElement.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.fstop=None self.make=None self.model=None self.distance=None self.exposure=None self.flash=None self.focallength=None self.iso=None self.time=None self.imageUniqueID=None def TagsFromString(xml_string): return atom.CreateClassFromXMLString(Tags, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the data classes of the Google Notebook Data API""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import atom.data import gdata.data import gdata.opensearch.data NB_TEMPLATE = '{http://schemas.google.com/notes/2008/}%s' class ComesAfter(atom.core.XmlElement): """Preceding element.""" _qname = NB_TEMPLATE % 'comesAfter' id = 'id' class NoteEntry(gdata.data.GDEntry): """Describes a note entry in the feed of a user's notebook.""" class NotebookFeed(gdata.data.GDFeed): """Describes a notebook feed.""" entry = [NoteEntry] class NotebookListEntry(gdata.data.GDEntry): """Describes a note list entry in the feed of a user's list of public notebooks.""" class NotebookListFeed(gdata.data.GDFeed): """Describes a notebook list feed.""" entry = [NotebookListEntry]
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.
Python
# -*-*- encoding: utf-8 -*-*- # # This is the base file for the PicasaWeb python client. # It is used for lower level operations. # # $Id: __init__.py 148 2007-10-28 15:09:19Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # Portions (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module provides a pythonic, gdata-centric interface to Google Photos (a.k.a. Picasa Web Services. It is modelled after the gdata/* interfaces from the gdata-python-client project[1] by Google. You'll find the user-friendly api in photos.service. Please see the documentation or live help() system for available methods. [1]: http://gdata-python-client.googlecode.com/ """ __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' __version__ = '$Revision: 164 $'[11:-2] import re try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata # importing google photo submodules import gdata.media as Media, gdata.exif as Exif, gdata.geo as Geo # XML namespaces which are often used in Google Photo elements PHOTOS_NAMESPACE = 'http://schemas.google.com/photos/2007' MEDIA_NAMESPACE = 'http://search.yahoo.com/mrss/' EXIF_NAMESPACE = 'http://schemas.google.com/photos/exif/2007' OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/' GEO_NAMESPACE = 'http://www.w3.org/2003/01/geo/wgs84_pos#' GML_NAMESPACE = 'http://www.opengis.net/gml' GEORSS_NAMESPACE = 'http://www.georss.org/georss' PHEED_NAMESPACE = 'http://www.pheed.com/pheed/' BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch' class PhotosBaseElement(atom.AtomBase): """Base class for elements in the PHOTO_NAMESPACE. To add new elements, you only need to add the element tag name to self._tag """ _tag = '' _namespace = PHOTOS_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, name=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} #def __str__(self): #return str(self.text) #def __unicode__(self): #return unicode(self.text) def __int__(self): return int(self.text) def bool(self): return self.text == 'true' class GPhotosBaseFeed(gdata.GDataFeed, gdata.LinkFinder): "Base class for all Feeds in gdata.photos" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _attributes = gdata.GDataFeed._attributes.copy() _children = gdata.GDataFeed._children.copy() # We deal with Entry elements ourselves del _children['{%s}entry' % atom.ATOM_NAMESPACE] 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 kind(self): "(string) Returns the kind" try: return self.category[0].term.split('#')[1] except IndexError: return None def _feedUri(self, kind): "Convenience method to return a uri to a feed of a special kind" assert(kind in ('album', 'tag', 'photo', 'comment', 'user')) here_href = self.GetSelfLink().href if 'kind=%s' % kind in here_href: return here_href if not 'kind=' in here_href: sep = '?' if '?' in here_href: sep = '&' return here_href + "%skind=%s" % (sep, kind) rx = re.match('.*(kind=)(album|tag|photo|comment)', here_href) return here_href[:rx.end(1)] + kind + here_href[rx.end(2):] def _ConvertElementTreeToMember(self, child_tree): """Re-implementing the method from AtomBase, since we deal with Entry elements specially""" category = child_tree.find('{%s}category' % atom.ATOM_NAMESPACE) if category is None: return atom.AtomBase._ConvertElementTreeToMember(self, child_tree) namespace, kind = category.get('term').split('#') if namespace != PHOTOS_NAMESPACE: return atom.AtomBase._ConvertElementTreeToMember(self, child_tree) ## TODO: is it safe to use getattr on gdata.photos? entry_class = getattr(gdata.photos, '%sEntry' % kind.title()) if not hasattr(self, 'entry') or self.entry is None: self.entry = [] self.entry.append(atom._CreateClassFromElementTree( entry_class, child_tree)) class GPhotosBaseEntry(gdata.GDataEntry, gdata.LinkFinder): "Base class for all Entry elements in gdata.photos" _tag = 'entry' _kind = '' _namespace = atom.ATOM_NAMESPACE _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=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, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.category.append( atom.Category(scheme='http://schemas.google.com/g/2005#kind', term = 'http://schemas.google.com/photos/2007#%s' % self._kind)) def kind(self): "(string) Returns the kind" try: return self.category[0].term.split('#')[1] except IndexError: return None def _feedUri(self, kind): "Convenience method to get the uri to this entry's feed of the some kind" try: href = self.GetFeedLink().href except AttributeError: return None sep = '?' if '?' in href: sep = '&' return '%s%skind=%s' % (href, sep, kind) class PhotosBaseEntry(GPhotosBaseEntry): pass class PhotosBaseFeed(GPhotosBaseFeed): pass class GPhotosBaseData(object): pass class Access(PhotosBaseElement): """The Google Photo `Access' element. The album's access level. Valid values are `public' or `private'. In documentation, access level is also referred to as `visibility.'""" _tag = 'access' def AccessFromString(xml_string): return atom.CreateClassFromXMLString(Access, xml_string) class Albumid(PhotosBaseElement): "The Google Photo `Albumid' element" _tag = 'albumid' def AlbumidFromString(xml_string): return atom.CreateClassFromXMLString(Albumid, xml_string) class BytesUsed(PhotosBaseElement): "The Google Photo `BytesUsed' element" _tag = 'bytesUsed' def BytesUsedFromString(xml_string): return atom.CreateClassFromXMLString(BytesUsed, xml_string) class Client(PhotosBaseElement): "The Google Photo `Client' element" _tag = 'client' def ClientFromString(xml_string): return atom.CreateClassFromXMLString(Client, xml_string) class Checksum(PhotosBaseElement): "The Google Photo `Checksum' element" _tag = 'checksum' def ChecksumFromString(xml_string): return atom.CreateClassFromXMLString(Checksum, xml_string) class CommentCount(PhotosBaseElement): "The Google Photo `CommentCount' element" _tag = 'commentCount' def CommentCountFromString(xml_string): return atom.CreateClassFromXMLString(CommentCount, xml_string) class CommentingEnabled(PhotosBaseElement): "The Google Photo `CommentingEnabled' element" _tag = 'commentingEnabled' def CommentingEnabledFromString(xml_string): return atom.CreateClassFromXMLString(CommentingEnabled, xml_string) class Height(PhotosBaseElement): "The Google Photo `Height' element" _tag = 'height' def HeightFromString(xml_string): return atom.CreateClassFromXMLString(Height, xml_string) class Id(PhotosBaseElement): "The Google Photo `Id' element" _tag = 'id' def IdFromString(xml_string): return atom.CreateClassFromXMLString(Id, xml_string) class Location(PhotosBaseElement): "The Google Photo `Location' element" _tag = 'location' def LocationFromString(xml_string): return atom.CreateClassFromXMLString(Location, xml_string) class MaxPhotosPerAlbum(PhotosBaseElement): "The Google Photo `MaxPhotosPerAlbum' element" _tag = 'maxPhotosPerAlbum' def MaxPhotosPerAlbumFromString(xml_string): return atom.CreateClassFromXMLString(MaxPhotosPerAlbum, xml_string) class Name(PhotosBaseElement): "The Google Photo `Name' element" _tag = 'name' def NameFromString(xml_string): return atom.CreateClassFromXMLString(Name, xml_string) class Nickname(PhotosBaseElement): "The Google Photo `Nickname' element" _tag = 'nickname' def NicknameFromString(xml_string): return atom.CreateClassFromXMLString(Nickname, xml_string) class Numphotos(PhotosBaseElement): "The Google Photo `Numphotos' element" _tag = 'numphotos' def NumphotosFromString(xml_string): return atom.CreateClassFromXMLString(Numphotos, xml_string) class Numphotosremaining(PhotosBaseElement): "The Google Photo `Numphotosremaining' element" _tag = 'numphotosremaining' def NumphotosremainingFromString(xml_string): return atom.CreateClassFromXMLString(Numphotosremaining, xml_string) class Position(PhotosBaseElement): "The Google Photo `Position' element" _tag = 'position' def PositionFromString(xml_string): return atom.CreateClassFromXMLString(Position, xml_string) class Photoid(PhotosBaseElement): "The Google Photo `Photoid' element" _tag = 'photoid' def PhotoidFromString(xml_string): return atom.CreateClassFromXMLString(Photoid, xml_string) class Quotacurrent(PhotosBaseElement): "The Google Photo `Quotacurrent' element" _tag = 'quotacurrent' def QuotacurrentFromString(xml_string): return atom.CreateClassFromXMLString(Quotacurrent, xml_string) class Quotalimit(PhotosBaseElement): "The Google Photo `Quotalimit' element" _tag = 'quotalimit' def QuotalimitFromString(xml_string): return atom.CreateClassFromXMLString(Quotalimit, xml_string) class Rotation(PhotosBaseElement): "The Google Photo `Rotation' element" _tag = 'rotation' def RotationFromString(xml_string): return atom.CreateClassFromXMLString(Rotation, xml_string) class Size(PhotosBaseElement): "The Google Photo `Size' element" _tag = 'size' def SizeFromString(xml_string): return atom.CreateClassFromXMLString(Size, xml_string) class Snippet(PhotosBaseElement): """The Google Photo `snippet' element. When searching, the snippet element will contain a string with the word you're looking for, highlighted in html markup E.g. when your query is `hafjell', this element may contain: `... here at <b>Hafjell</b>.' You'll find this element in searches -- that is, feeds that combine the `kind=photo' and `q=yoursearch' parameters in the request. See also gphoto:truncated and gphoto:snippettype. """ _tag = 'snippet' def SnippetFromString(xml_string): return atom.CreateClassFromXMLString(Snippet, xml_string) class Snippettype(PhotosBaseElement): """The Google Photo `Snippettype' element When searching, this element will tell you the type of element that matches. You'll find this element in searches -- that is, feeds that combine the `kind=photo' and `q=yoursearch' parameters in the request. See also gphoto:snippet and gphoto:truncated. Possible values and their interpretation: o ALBUM_TITLE - The album title matches o PHOTO_TAGS - The match is a tag/keyword o PHOTO_DESCRIPTION - The match is in the photo's description If you discover a value not listed here, please submit a patch to update this docstring. """ _tag = 'snippettype' def SnippettypeFromString(xml_string): return atom.CreateClassFromXMLString(Snippettype, xml_string) class Thumbnail(PhotosBaseElement): """The Google Photo `Thumbnail' element Used to display user's photo thumbnail (hackergotchi). (Not to be confused with the <media:thumbnail> element, which gives you small versions of the photo object.)""" _tag = 'thumbnail' def ThumbnailFromString(xml_string): return atom.CreateClassFromXMLString(Thumbnail, xml_string) class Timestamp(PhotosBaseElement): """The Google Photo `Timestamp' element Represented as the number of milliseconds since January 1st, 1970. Take a look at the convenience methods .isoformat() and .datetime(): photo_epoch = Time.text # 1180294337000 photo_isostring = Time.isoformat() # '2007-05-27T19:32:17.000Z' Alternatively: photo_datetime = Time.datetime() # (requires python >= 2.3) """ _tag = 'timestamp' def isoformat(self): """(string) Return the timestamp as a ISO 8601 formatted string, e.g. '2007-05-27T19:32:17.000Z' """ import time epoch = float(self.text)/1000 return time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(epoch)) def datetime(self): """(datetime.datetime) Return the timestamp as a datetime.datetime object Requires python 2.3 """ import datetime epoch = float(self.text)/1000 return datetime.datetime.fromtimestamp(epoch) def TimestampFromString(xml_string): return atom.CreateClassFromXMLString(Timestamp, xml_string) class Truncated(PhotosBaseElement): """The Google Photo `Truncated' element You'll find this element in searches -- that is, feeds that combine the `kind=photo' and `q=yoursearch' parameters in the request. See also gphoto:snippet and gphoto:snippettype. Possible values and their interpretation: 0 -- unknown """ _tag = 'Truncated' def TruncatedFromString(xml_string): return atom.CreateClassFromXMLString(Truncated, xml_string) class User(PhotosBaseElement): "The Google Photo `User' element" _tag = 'user' def UserFromString(xml_string): return atom.CreateClassFromXMLString(User, xml_string) class Version(PhotosBaseElement): "The Google Photo `Version' element" _tag = 'version' def VersionFromString(xml_string): return atom.CreateClassFromXMLString(Version, xml_string) class Width(PhotosBaseElement): "The Google Photo `Width' element" _tag = 'width' def WidthFromString(xml_string): return atom.CreateClassFromXMLString(Width, xml_string) class Weight(PhotosBaseElement): """The Google Photo `Weight' element. The weight of the tag is the number of times the tag appears in the collection of tags currently being viewed. The default weight is 1, in which case this tags is omitted.""" _tag = 'weight' def WeightFromString(xml_string): return atom.CreateClassFromXMLString(Weight, xml_string) class CommentAuthor(atom.Author): """The Atom `Author' element in CommentEntry entries is augmented to contain elements from the PHOTOS_NAMESPACE http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38 """ _children = atom.Author._children.copy() _children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User) _children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname) _children['{%s}thumbnail' % PHOTOS_NAMESPACE] = ('thumbnail', Thumbnail) def CommentAuthorFromString(xml_string): return atom.CreateClassFromXMLString(CommentAuthor, xml_string) ########################## ################################ class AlbumData(object): _children = {} _children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id) _children['{%s}name' % PHOTOS_NAMESPACE] = ('name', Name) _children['{%s}location' % PHOTOS_NAMESPACE] = ('location', Location) _children['{%s}access' % PHOTOS_NAMESPACE] = ('access', Access) _children['{%s}bytesUsed' % PHOTOS_NAMESPACE] = ('bytesUsed', BytesUsed) _children['{%s}timestamp' % PHOTOS_NAMESPACE] = ('timestamp', Timestamp) _children['{%s}numphotos' % PHOTOS_NAMESPACE] = ('numphotos', Numphotos) _children['{%s}numphotosremaining' % PHOTOS_NAMESPACE] = \ ('numphotosremaining', Numphotosremaining) _children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User) _children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname) _children['{%s}commentingEnabled' % PHOTOS_NAMESPACE] = \ ('commentingEnabled', CommentingEnabled) _children['{%s}commentCount' % PHOTOS_NAMESPACE] = \ ('commentCount', CommentCount) ## NOTE: storing media:group as self.media, to create a self-explaining api gphoto_id = None name = None location = None access = None bytesUsed = None timestamp = None numphotos = None numphotosremaining = None user = None nickname = None commentingEnabled = None commentCount = None class AlbumEntry(GPhotosBaseEntry, AlbumData): """All metadata for a Google Photos Album Take a look at AlbumData for metadata accessible as attributes to this object. Notes: To avoid name clashes, and to create a more sensible api, some objects have names that differ from the original elements: o media:group -> self.media, o geo:where -> self.geo, o photo:id -> self.gphoto_id """ _kind = 'album' _children = GPhotosBaseEntry._children.copy() _children.update(AlbumData._children.copy()) # child tags only for Album entries, not feeds _children['{%s}where' % GEORSS_NAMESPACE] = ('geo', Geo.Where) _children['{%s}group' % MEDIA_NAMESPACE] = ('media', Media.Group) media = Media.Group() geo = Geo.Where() def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, #GPHOTO NAMESPACE: gphoto_id=None, name=None, location=None, access=None, timestamp=None, numphotos=None, user=None, nickname=None, commentingEnabled=None, commentCount=None, thumbnail=None, # MEDIA NAMESPACE: media=None, # GEORSS NAMESPACE: geo=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): GPhotosBaseEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) ## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id self.gphoto_id = gphoto_id self.name = name self.location = location self.access = access self.timestamp = timestamp self.numphotos = numphotos self.user = user self.nickname = nickname self.commentingEnabled = commentingEnabled self.commentCount = commentCount self.thumbnail = thumbnail self.extended_property = extended_property or [] self.text = text ## NOTE: storing media:group as self.media, and geo:where as geo, ## to create a self-explaining api self.media = media or Media.Group() self.geo = geo or Geo.Where() def GetAlbumId(self): "Return the id of this album" return self.GetFeedLink().href.split('/')[-1] def GetPhotosUri(self): "(string) Return the uri to this albums feed of the PhotoEntry kind" return self._feedUri('photo') def GetCommentsUri(self): "(string) Return the uri to this albums feed of the CommentEntry kind" return self._feedUri('comment') def GetTagsUri(self): "(string) Return the uri to this albums feed of the TagEntry kind" return self._feedUri('tag') def AlbumEntryFromString(xml_string): return atom.CreateClassFromXMLString(AlbumEntry, xml_string) class AlbumFeed(GPhotosBaseFeed, AlbumData): """All metadata for a Google Photos Album, including its sub-elements This feed represents an album as the container for other objects. A Album feed contains entries of PhotoEntry, CommentEntry or TagEntry, depending on the `kind' parameter in the original query. Take a look at AlbumData for accessible attributes. """ _children = GPhotosBaseFeed._children.copy() _children.update(AlbumData._children.copy()) def GetPhotosUri(self): "(string) Return the uri to the same feed, but of the PhotoEntry kind" return self._feedUri('photo') def GetTagsUri(self): "(string) Return the uri to the same feed, but of the TagEntry kind" return self._feedUri('tag') def GetCommentsUri(self): "(string) Return the uri to the same feed, but of the CommentEntry kind" return self._feedUri('comment') def AlbumFeedFromString(xml_string): return atom.CreateClassFromXMLString(AlbumFeed, xml_string) class PhotoData(object): _children = {} ## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id _children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id) _children['{%s}albumid' % PHOTOS_NAMESPACE] = ('albumid', Albumid) _children['{%s}checksum' % PHOTOS_NAMESPACE] = ('checksum', Checksum) _children['{%s}client' % PHOTOS_NAMESPACE] = ('client', Client) _children['{%s}height' % PHOTOS_NAMESPACE] = ('height', Height) _children['{%s}position' % PHOTOS_NAMESPACE] = ('position', Position) _children['{%s}rotation' % PHOTOS_NAMESPACE] = ('rotation', Rotation) _children['{%s}size' % PHOTOS_NAMESPACE] = ('size', Size) _children['{%s}timestamp' % PHOTOS_NAMESPACE] = ('timestamp', Timestamp) _children['{%s}version' % PHOTOS_NAMESPACE] = ('version', Version) _children['{%s}width' % PHOTOS_NAMESPACE] = ('width', Width) _children['{%s}commentingEnabled' % PHOTOS_NAMESPACE] = \ ('commentingEnabled', CommentingEnabled) _children['{%s}commentCount' % PHOTOS_NAMESPACE] = \ ('commentCount', CommentCount) ## NOTE: storing media:group as self.media, exif:tags as self.exif, and ## geo:where as self.geo, to create a self-explaining api _children['{%s}tags' % EXIF_NAMESPACE] = ('exif', Exif.Tags) _children['{%s}where' % GEORSS_NAMESPACE] = ('geo', Geo.Where) _children['{%s}group' % MEDIA_NAMESPACE] = ('media', Media.Group) # These elements show up in search feeds _children['{%s}snippet' % PHOTOS_NAMESPACE] = ('snippet', Snippet) _children['{%s}snippettype' % PHOTOS_NAMESPACE] = ('snippettype', Snippettype) _children['{%s}truncated' % PHOTOS_NAMESPACE] = ('truncated', Truncated) gphoto_id = None albumid = None checksum = None client = None height = None position = None rotation = None size = None timestamp = None version = None width = None commentingEnabled = None commentCount = None snippet=None snippettype=None truncated=None media = Media.Group() geo = Geo.Where() tags = Exif.Tags() class PhotoEntry(GPhotosBaseEntry, PhotoData): """All metadata for a Google Photos Photo Take a look at PhotoData for metadata accessible as attributes to this object. Notes: To avoid name clashes, and to create a more sensible api, some objects have names that differ from the original elements: o media:group -> self.media, o exif:tags -> self.exif, o geo:where -> self.geo, o photo:id -> self.gphoto_id """ _kind = 'photo' _children = GPhotosBaseEntry._children.copy() _children.update(PhotoData._children.copy()) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, text=None, # GPHOTO NAMESPACE: gphoto_id=None, albumid=None, checksum=None, client=None, height=None, position=None, rotation=None, size=None, timestamp=None, version=None, width=None, commentCount=None, commentingEnabled=None, # MEDIARSS NAMESPACE: media=None, # EXIF_NAMESPACE: exif=None, # GEORSS NAMESPACE: geo=None, extension_elements=None, extension_attributes=None): GPhotosBaseEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) ## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id self.gphoto_id = gphoto_id self.albumid = albumid self.checksum = checksum self.client = client self.height = height self.position = position self.rotation = rotation self.size = size self.timestamp = timestamp self.version = version self.width = width self.commentingEnabled = commentingEnabled self.commentCount = commentCount ## NOTE: storing media:group as self.media, to create a self-explaining api self.media = media or Media.Group() self.exif = exif or Exif.Tags() self.geo = geo or Geo.Where() def GetPostLink(self): "Return the uri to this photo's `POST' link (use it for updates of the object)" return self.GetFeedLink() def GetCommentsUri(self): "Return the uri to this photo's feed of CommentEntry comments" return self._feedUri('comment') def GetTagsUri(self): "Return the uri to this photo's feed of TagEntry tags" return self._feedUri('tag') def GetAlbumUri(self): """Return the uri to the AlbumEntry containing this photo""" href = self.GetSelfLink().href return href[:href.find('/photoid')] def PhotoEntryFromString(xml_string): return atom.CreateClassFromXMLString(PhotoEntry, xml_string) class PhotoFeed(GPhotosBaseFeed, PhotoData): """All metadata for a Google Photos Photo, including its sub-elements This feed represents a photo as the container for other objects. A Photo feed contains entries of CommentEntry or TagEntry, depending on the `kind' parameter in the original query. Take a look at PhotoData for metadata accessible as attributes to this object. """ _children = GPhotosBaseFeed._children.copy() _children.update(PhotoData._children.copy()) def GetTagsUri(self): "(string) Return the uri to the same feed, but of the TagEntry kind" return self._feedUri('tag') def GetCommentsUri(self): "(string) Return the uri to the same feed, but of the CommentEntry kind" return self._feedUri('comment') def PhotoFeedFromString(xml_string): return atom.CreateClassFromXMLString(PhotoFeed, xml_string) class TagData(GPhotosBaseData): _children = {} _children['{%s}weight' % PHOTOS_NAMESPACE] = ('weight', Weight) weight=None class TagEntry(GPhotosBaseEntry, TagData): """All metadata for a Google Photos Tag The actual tag is stored in the .title.text attribute """ _kind = 'tag' _children = GPhotosBaseEntry._children.copy() _children.update(TagData._children.copy()) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, # GPHOTO NAMESPACE: weight=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): GPhotosBaseEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=text, extension_elements=extension_elements, extension_attributes=extension_attributes) self.weight = weight def GetAlbumUri(self): """Return the uri to the AlbumEntry containing this tag""" href = self.GetSelfLink().href pos = href.find('/photoid') if pos == -1: return None return href[:pos] def GetPhotoUri(self): """Return the uri to the PhotoEntry containing this tag""" href = self.GetSelfLink().href pos = href.find('/tag') if pos == -1: return None return href[:pos] def TagEntryFromString(xml_string): return atom.CreateClassFromXMLString(TagEntry, xml_string) class TagFeed(GPhotosBaseFeed, TagData): """All metadata for a Google Photos Tag, including its sub-elements""" _children = GPhotosBaseFeed._children.copy() _children.update(TagData._children.copy()) def TagFeedFromString(xml_string): return atom.CreateClassFromXMLString(TagFeed, xml_string) class CommentData(GPhotosBaseData): _children = {} ## NOTE: storing photo:id as self.gphoto_id, to avoid name clash with atom:id _children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id) _children['{%s}albumid' % PHOTOS_NAMESPACE] = ('albumid', Albumid) _children['{%s}photoid' % PHOTOS_NAMESPACE] = ('photoid', Photoid) _children['{%s}author' % atom.ATOM_NAMESPACE] = ('author', [CommentAuthor,]) gphoto_id=None albumid=None photoid=None author=None class CommentEntry(GPhotosBaseEntry, CommentData): """All metadata for a Google Photos Comment The comment is stored in the .content.text attribute, with a content type in .content.type. """ _kind = 'comment' _children = GPhotosBaseEntry._children.copy() _children.update(CommentData._children.copy()) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, # GPHOTO NAMESPACE: gphoto_id=None, albumid=None, photoid=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): GPhotosBaseEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.gphoto_id = gphoto_id self.albumid = albumid self.photoid = photoid def GetCommentId(self): """Return the globally unique id of this comment""" return self.GetSelfLink().href.split('/')[-1] def GetAlbumUri(self): """Return the uri to the AlbumEntry containing this comment""" href = self.GetSelfLink().href return href[:href.find('/photoid')] def GetPhotoUri(self): """Return the uri to the PhotoEntry containing this comment""" href = self.GetSelfLink().href return href[:href.find('/commentid')] def CommentEntryFromString(xml_string): return atom.CreateClassFromXMLString(CommentEntry, xml_string) class CommentFeed(GPhotosBaseFeed, CommentData): """All metadata for a Google Photos Comment, including its sub-elements""" _children = GPhotosBaseFeed._children.copy() _children.update(CommentData._children.copy()) def CommentFeedFromString(xml_string): return atom.CreateClassFromXMLString(CommentFeed, xml_string) class UserData(GPhotosBaseData): _children = {} _children['{%s}maxPhotosPerAlbum' % PHOTOS_NAMESPACE] = ('maxPhotosPerAlbum', MaxPhotosPerAlbum) _children['{%s}nickname' % PHOTOS_NAMESPACE] = ('nickname', Nickname) _children['{%s}quotalimit' % PHOTOS_NAMESPACE] = ('quotalimit', Quotalimit) _children['{%s}quotacurrent' % PHOTOS_NAMESPACE] = ('quotacurrent', Quotacurrent) _children['{%s}thumbnail' % PHOTOS_NAMESPACE] = ('thumbnail', Thumbnail) _children['{%s}user' % PHOTOS_NAMESPACE] = ('user', User) _children['{%s}id' % PHOTOS_NAMESPACE] = ('gphoto_id', Id) maxPhotosPerAlbum=None nickname=None quotalimit=None quotacurrent=None thumbnail=None user=None gphoto_id=None class UserEntry(GPhotosBaseEntry, UserData): """All metadata for a Google Photos User This entry represents an album owner and all appropriate metadata. Take a look at at the attributes of the UserData for metadata available. """ _children = GPhotosBaseEntry._children.copy() _children.update(UserData._children.copy()) _kind = 'user' def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, # GPHOTO NAMESPACE: gphoto_id=None, maxPhotosPerAlbum=None, nickname=None, quotalimit=None, quotacurrent=None, thumbnail=None, user=None, extended_property=None, extension_elements=None, extension_attributes=None, text=None): GPhotosBaseEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.gphoto_id=gphoto_id self.maxPhotosPerAlbum=maxPhotosPerAlbum self.nickname=nickname self.quotalimit=quotalimit self.quotacurrent=quotacurrent self.thumbnail=thumbnail self.user=user def GetAlbumsUri(self): "(string) Return the uri to this user's feed of the AlbumEntry kind" return self._feedUri('album') def GetPhotosUri(self): "(string) Return the uri to this user's feed of the PhotoEntry kind" return self._feedUri('photo') def GetCommentsUri(self): "(string) Return the uri to this user's feed of the CommentEntry kind" return self._feedUri('comment') def GetTagsUri(self): "(string) Return the uri to this user's feed of the TagEntry kind" return self._feedUri('tag') def UserEntryFromString(xml_string): return atom.CreateClassFromXMLString(UserEntry, xml_string) class UserFeed(GPhotosBaseFeed, UserData): """Feed for a User in the google photos api. This feed represents a user as the container for other objects. A User feed contains entries of AlbumEntry, PhotoEntry, CommentEntry, UserEntry or TagEntry, depending on the `kind' parameter in the original query. The user feed itself also contains all of the metadata available as part of a UserData object.""" _children = GPhotosBaseFeed._children.copy() _children.update(UserData._children.copy()) def GetAlbumsUri(self): """Get the uri to this feed, but with entries of the AlbumEntry kind.""" return self._feedUri('album') def GetTagsUri(self): """Get the uri to this feed, but with entries of the TagEntry kind.""" return self._feedUri('tag') def GetPhotosUri(self): """Get the uri to this feed, but with entries of the PhotosEntry kind.""" return self._feedUri('photo') def GetCommentsUri(self): """Get the uri to this feed, but with entries of the CommentsEntry kind.""" return self._feedUri('comment') def UserFeedFromString(xml_string): return atom.CreateClassFromXMLString(UserFeed, xml_string) def AnyFeedFromString(xml_string): """Creates an instance of the appropriate feed class from the xml string contents. Args: xml_string: str A string which contains valid XML. The root element of the XML string should match the tag and namespace of the desired class. Returns: An instance of the target class with members assigned according to the contents of the XML - or a basic gdata.GDataFeed instance if it is impossible to determine the appropriate class (look for extra elements in GDataFeed's .FindExtensions() and extension_elements[] ). """ tree = ElementTree.fromstring(xml_string) category = tree.find('{%s}category' % atom.ATOM_NAMESPACE) if category is None: # TODO: is this the best way to handle this? return atom._CreateClassFromElementTree(GPhotosBaseFeed, tree) namespace, kind = category.get('term').split('#') if namespace != PHOTOS_NAMESPACE: # TODO: is this the best way to handle this? return atom._CreateClassFromElementTree(GPhotosBaseFeed, tree) ## TODO: is getattr safe this way? feed_class = getattr(gdata.photos, '%sFeed' % kind.title()) return atom._CreateClassFromElementTree(feed_class, tree) def AnyEntryFromString(xml_string): """Creates an instance of the appropriate entry class from the xml string contents. Args: xml_string: str A string which contains valid XML. The root element of the XML string should match the tag and namespace of the desired class. Returns: An instance of the target class with members assigned according to the contents of the XML - or a basic gdata.GDataEndry instance if it is impossible to determine the appropriate class (look for extra elements in GDataEntry's .FindExtensions() and extension_elements[] ). """ tree = ElementTree.fromstring(xml_string) category = tree.find('{%s}category' % atom.ATOM_NAMESPACE) if category is None: # TODO: is this the best way to handle this? return atom._CreateClassFromElementTree(GPhotosBaseEntry, tree) namespace, kind = category.get('term').split('#') if namespace != PHOTOS_NAMESPACE: # TODO: is this the best way to handle this? return atom._CreateClassFromElementTree(GPhotosBaseEntry, tree) ## TODO: is getattr safe this way? feed_class = getattr(gdata.photos, '%sEntry' % kind.title()) return atom._CreateClassFromElementTree(feed_class, tree)
Python
#!/usr/bin/env python # -*-*- encoding: utf-8 -*-*- # # This is the service file for the Google Photo python client. # It is used for higher level operations. # # $Id: service.py 144 2007-10-25 21:03:34Z havard.gulldahl $ # # Copyright 2007 Håvard Gulldahl # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Google PhotoService provides a human-friendly interface to Google Photo (a.k.a Picasa Web) services[1]. It extends gdata.service.GDataService and as such hides all the nasty details about authenticating, parsing and communicating with Google Photos. [1]: http://code.google.com/apis/picasaweb/gdata.html Example: import gdata.photos, gdata.photos.service pws = gdata.photos.service.PhotosService() pws.ClientLogin(username, password) #Get all albums albums = pws.GetUserFeed().entry # Get all photos in second album photos = pws.GetFeed(albums[1].GetPhotosUri()).entry # Get all tags for photos in second album and print them tags = pws.GetFeed(albums[1].GetTagsUri()).entry print [ tag.summary.text for tag in tags ] # Get all comments for the first photos in list and print them comments = pws.GetCommentFeed(photos[0].GetCommentsUri()).entry print [ c.summary.text for c in comments ] # Get a photo to work with photo = photos[0] # Update metadata # Attributes from the <gphoto:*> namespace photo.summary.text = u'A nice view from my veranda' photo.title.text = u'Verandaview.jpg' # Attributes from the <media:*> namespace photo.media.keywords.text = u'Home, Long-exposure, Sunset' # Comma-separated # Adding attributes to media object # Rotate 90 degrees clockwise photo.rotation = gdata.photos.Rotation(text='90') # Submit modified photo object photo = pws.UpdatePhotoMetadata(photo) # Make sure you only modify the newly returned object, else you'll get # versioning errors. See Optimistic-concurrency # Add comment to a picture comment = pws.InsertComment(photo, u'I wish the water always was this warm') # Remove comment because it was silly print "*blush*" pws.Delete(comment.GetEditLink().href) """ __author__ = u'havard@gulldahl.no'# (Håvard Gulldahl)' #BUG: pydoc chokes on non-ascii chars in __author__ __license__ = 'Apache License v2' __version__ = '$Revision: 176 $'[11:-2] import sys, os.path, StringIO import time import gdata.service import gdata import atom.service import atom import gdata.photos SUPPORTED_UPLOAD_TYPES = ('bmp', 'jpeg', 'jpg', 'gif', 'png') UNKOWN_ERROR=1000 GPHOTOS_BAD_REQUEST=400 GPHOTOS_CONFLICT=409 GPHOTOS_INTERNAL_SERVER_ERROR=500 GPHOTOS_INVALID_ARGUMENT=601 GPHOTOS_INVALID_CONTENT_TYPE=602 GPHOTOS_NOT_AN_IMAGE=603 GPHOTOS_INVALID_KIND=604 class GooglePhotosException(Exception): def __init__(self, response): self.error_code = response['status'] self.reason = response['reason'].strip() if '<html>' in str(response['body']): #general html message, discard it response['body'] = "" self.body = response['body'].strip() self.message = "(%(status)s) %(body)s -- %(reason)s" % response #return explicit error codes error_map = { '(12) Not an image':GPHOTOS_NOT_AN_IMAGE, 'kind: That is not one of the acceptable values': GPHOTOS_INVALID_KIND, } for msg, code in error_map.iteritems(): if self.body == msg: self.error_code = code break self.args = [self.error_code, self.reason, self.body] class PhotosService(gdata.service.GDataService): ssl = True userUri = '/data/feed/api/user/%s' def __init__(self, email=None, password=None, source=None, server='picasaweb.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Photos service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'picasaweb.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ self.email = email self.client = source gdata.service.GDataService.__init__( self, email=email, password=password, service='lh2', source=source, server=server, additional_headers=additional_headers, **kwargs) def GetFeed(self, uri, limit=None, start_index=None): """Get a feed. The results are ordered by the values of their `updated' elements, with the most recently updated entry appearing first in the feed. Arguments: uri: the uri to fetch limit (optional): the maximum number of entries to return. Defaults to what the server returns. Returns: one of gdata.photos.AlbumFeed, gdata.photos.UserFeed, gdata.photos.PhotoFeed, gdata.photos.CommentFeed, gdata.photos.TagFeed, depending on the results of the query. Raises: GooglePhotosException See: http://code.google.com/apis/picasaweb/gdata.html#Get_Album_Feed_Manual """ if limit is not None: uri += '&max-results=%s' % limit if start_index is not None: uri += '&start-index=%s' % start_index try: return self.Get(uri, converter=gdata.photos.AnyFeedFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def GetEntry(self, uri, limit=None, start_index=None): """Get an Entry. Arguments: uri: the uri to the entry limit (optional): the maximum number of entries to return. Defaults to what the server returns. Returns: one of gdata.photos.AlbumEntry, gdata.photos.UserEntry, gdata.photos.PhotoEntry, gdata.photos.CommentEntry, gdata.photos.TagEntry, depending on the results of the query. Raises: GooglePhotosException """ if limit is not None: uri += '&max-results=%s' % limit if start_index is not None: uri += '&start-index=%s' % start_index try: return self.Get(uri, converter=gdata.photos.AnyEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def GetUserFeed(self, kind='album', user='default', limit=None): """Get user-based feed, containing albums, photos, comments or tags; defaults to albums. The entries are ordered by the values of their `updated' elements, with the most recently updated entry appearing first in the feed. Arguments: kind: the kind of entries to get, either `album', `photo', `comment' or `tag', or a python list of these. Defaults to `album'. user (optional): whose albums we're querying. Defaults to current user. limit (optional): the maximum number of entries to return. Defaults to everything the server returns. Returns: gdata.photos.UserFeed, containing appropriate Entry elements See: http://code.google.com/apis/picasaweb/gdata.html#Get_Album_Feed_Manual http://googledataapis.blogspot.com/2007/07/picasa-web-albums-adds-new-api-features.html """ if isinstance(kind, (list, tuple) ): kind = ",".join(kind) uri = '/data/feed/api/user/%s?kind=%s' % (user, kind) return self.GetFeed(uri, limit=limit) def GetTaggedPhotos(self, tag, user='default', limit=None): """Get all photos belonging to a specific user, tagged by the given keyword Arguments: tag: The tag you're looking for, e.g. `dog' user (optional): Whose images/videos you want to search, defaults to current user limit (optional): the maximum number of entries to return. Defaults to everything the server returns. Returns: gdata.photos.UserFeed containing PhotoEntry elements """ # Lower-casing because of # http://code.google.com/p/gdata-issues/issues/detail?id=194 uri = '/data/feed/api/user/%s?kind=photo&tag=%s' % (user, tag.lower()) return self.GetFeed(uri, limit) def SearchUserPhotos(self, query, user='default', limit=100): """Search through all photos for a specific user and return a feed. This will look for matches in file names and image tags (a.k.a. keywords) Arguments: query: The string you're looking for, e.g. `vacation' user (optional): The username of whose photos you want to search, defaults to current user. limit (optional): Don't return more than `limit' hits, defaults to 100 Only public photos are searched, unless you are authenticated and searching through your own photos. Returns: gdata.photos.UserFeed with PhotoEntry elements """ uri = '/data/feed/api/user/%s?kind=photo&q=%s' % (user, query) return self.GetFeed(uri, limit=limit) def SearchCommunityPhotos(self, query, limit=100): """Search through all public photos and return a feed. This will look for matches in file names and image tags (a.k.a. keywords) Arguments: query: The string you're looking for, e.g. `vacation' limit (optional): Don't return more than `limit' hits, defaults to 100 Returns: gdata.GDataFeed with PhotoEntry elements """ uri='/data/feed/api/all?q=%s' % query return self.GetFeed(uri, limit=limit) def GetContacts(self, user='default', limit=None): """Retrieve a feed that contains a list of your contacts Arguments: user: Username of the user whose contacts you want Returns gdata.photos.UserFeed, with UserEntry entries See: http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38 """ uri = '/data/feed/api/user/%s/contacts?kind=user' % user return self.GetFeed(uri, limit=limit) def SearchContactsPhotos(self, user='default', search=None, limit=None): """Search over your contacts' photos and return a feed Arguments: user: Username of the user whose contacts you want search (optional): What to search for (photo title, description and keywords) Returns gdata.photos.UserFeed, with PhotoEntry elements See: http://groups.google.com/group/Google-Picasa-Data-API/msg/819b0025b5ff5e38 """ uri = '/data/feed/api/user/%s/contacts?kind=photo&q=%s' % (user, search) return self.GetFeed(uri, limit=limit) def InsertAlbum(self, title, summary, location=None, access='public', commenting_enabled='true', timestamp=None): """Add an album. Needs authentication, see self.ClientLogin() Arguments: title: Album title summary: Album summary / description access (optional): `private' or `public'. Public albums are searchable by everyone on the internet. Defaults to `public' commenting_enabled (optional): `true' or `false'. Defaults to `true'. timestamp (optional): A date and time for the album, in milliseconds since Unix epoch[1] UTC. Defaults to now. Returns: The newly created gdata.photos.AlbumEntry See: http://code.google.com/apis/picasaweb/gdata.html#Add_Album_Manual_Installed [1]: http://en.wikipedia.org/wiki/Unix_epoch """ album = gdata.photos.AlbumEntry() album.title = atom.Title(text=title, title_type='text') album.summary = atom.Summary(text=summary, summary_type='text') if location is not None: album.location = gdata.photos.Location(text=location) album.access = gdata.photos.Access(text=access) if commenting_enabled in ('true', 'false'): album.commentingEnabled = gdata.photos.CommentingEnabled(text=commenting_enabled) if timestamp is None: timestamp = '%i' % int(time.time() * 1000) album.timestamp = gdata.photos.Timestamp(text=timestamp) try: return self.Post(album, uri=self.userUri % self.email, converter=gdata.photos.AlbumEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertPhoto(self, album_or_uri, photo, filename_or_handle, content_type='image/jpeg'): """Add a PhotoEntry Needs authentication, see self.ClientLogin() Arguments: album_or_uri: AlbumFeed or uri of the album where the photo should go photo: PhotoEntry to add filename_or_handle: A file-like object or file name where the image/video will be read from content_type (optional): Internet media type (a.k.a. mime type) of media object. Currently Google Photos supports these types: o image/bmp o image/gif o image/jpeg o image/png Images will be converted to jpeg on upload. Defaults to `image/jpeg' """ try: assert(isinstance(photo, gdata.photos.PhotoEntry)) except AssertionError: raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT, 'body':'`photo` must be a gdata.photos.PhotoEntry instance', 'reason':'Found %s, not PhotoEntry' % type(photo) }) try: majtype, mintype = content_type.split('/') assert(mintype in SUPPORTED_UPLOAD_TYPES) except (ValueError, AssertionError): raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE, 'body':'This is not a valid content type: %s' % content_type, 'reason':'Accepted content types: %s' % \ ['image/'+t for t in SUPPORTED_UPLOAD_TYPES] }) if isinstance(filename_or_handle, (str, unicode)) and \ os.path.exists(filename_or_handle): # it's a file name mediasource = gdata.MediaSource() mediasource.setFile(filename_or_handle, content_type) elif hasattr(filename_or_handle, 'read'):# it's a file-like resource if hasattr(filename_or_handle, 'seek'): filename_or_handle.seek(0) # rewind pointer to the start of the file # gdata.MediaSource needs the content length, so read the whole image file_handle = StringIO.StringIO(filename_or_handle.read()) name = 'image' if hasattr(filename_or_handle, 'name'): name = filename_or_handle.name mediasource = gdata.MediaSource(file_handle, content_type, content_length=file_handle.len, file_name=name) else: #filename_or_handle is not valid raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT, 'body':'`filename_or_handle` must be a path name or a file-like object', 'reason':'Found %s, not path name or object with a .read() method' % \ filename_or_handle }) if isinstance(album_or_uri, (str, unicode)): # it's a uri feed_uri = album_or_uri elif hasattr(album_or_uri, 'GetFeedLink'): # it's a AlbumFeed object feed_uri = album_or_uri.GetFeedLink().href try: return self.Post(photo, uri=feed_uri, media_source=mediasource, converter=gdata.photos.PhotoEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertPhotoSimple(self, album_or_uri, title, summary, filename_or_handle, content_type='image/jpeg', keywords=None): """Add a photo without constructing a PhotoEntry. Needs authentication, see self.ClientLogin() Arguments: album_or_uri: AlbumFeed or uri of the album where the photo should go title: Photo title summary: Photo summary / description filename_or_handle: A file-like object or file name where the image/video will be read from content_type (optional): Internet media type (a.k.a. mime type) of media object. Currently Google Photos supports these types: o image/bmp o image/gif o image/jpeg o image/png Images will be converted to jpeg on upload. Defaults to `image/jpeg' keywords (optional): a 1) comma separated string or 2) a python list() of keywords (a.k.a. tags) to add to the image. E.g. 1) `dog, vacation, happy' 2) ['dog', 'happy', 'vacation'] Returns: The newly created gdata.photos.PhotoEntry or GooglePhotosException on errors See: http://code.google.com/apis/picasaweb/gdata.html#Add_Album_Manual_Installed [1]: http://en.wikipedia.org/wiki/Unix_epoch """ metadata = gdata.photos.PhotoEntry() metadata.title=atom.Title(text=title) metadata.summary = atom.Summary(text=summary, summary_type='text') if keywords is not None: if isinstance(keywords, list): keywords = ','.join(keywords) metadata.media.keywords = gdata.media.Keywords(text=keywords) return self.InsertPhoto(album_or_uri, metadata, filename_or_handle, content_type) def UpdatePhotoMetadata(self, photo): """Update a photo's metadata. Needs authentication, see self.ClientLogin() You can update any or all of the following metadata properties: * <title> * <media:description> * <gphoto:checksum> * <gphoto:client> * <gphoto:rotation> * <gphoto:timestamp> * <gphoto:commentingEnabled> Arguments: photo: a gdata.photos.PhotoEntry object with updated elements Returns: The modified gdata.photos.PhotoEntry Example: p = GetFeed(uri).entry[0] p.title.text = u'My new text' p.commentingEnabled.text = 'false' p = UpdatePhotoMetadata(p) It is important that you don't keep the old object around, once it has been updated. See http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency """ try: return self.Put(data=photo, uri=photo.GetEditLink().href, converter=gdata.photos.PhotoEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def UpdatePhotoBlob(self, photo_or_uri, filename_or_handle, content_type = 'image/jpeg'): """Update a photo's binary data. Needs authentication, see self.ClientLogin() Arguments: photo_or_uri: a gdata.photos.PhotoEntry that will be updated, or a `edit-media' uri pointing to it filename_or_handle: A file-like object or file name where the image/video will be read from content_type (optional): Internet media type (a.k.a. mime type) of media object. Currently Google Photos supports these types: o image/bmp o image/gif o image/jpeg o image/png Images will be converted to jpeg on upload. Defaults to `image/jpeg' Returns: The modified gdata.photos.PhotoEntry Example: p = GetFeed(PhotoUri) p = UpdatePhotoBlob(p, '/tmp/newPic.jpg') It is important that you don't keep the old object around, once it has been updated. See http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency """ try: majtype, mintype = content_type.split('/') assert(mintype in SUPPORTED_UPLOAD_TYPES) except (ValueError, AssertionError): raise GooglePhotosException({'status':GPHOTOS_INVALID_CONTENT_TYPE, 'body':'This is not a valid content type: %s' % content_type, 'reason':'Accepted content types: %s' % \ ['image/'+t for t in SUPPORTED_UPLOAD_TYPES] }) if isinstance(filename_or_handle, (str, unicode)) and \ os.path.exists(filename_or_handle): # it's a file name photoblob = gdata.MediaSource() photoblob.setFile(filename_or_handle, content_type) elif hasattr(filename_or_handle, 'read'):# it's a file-like resource if hasattr(filename_or_handle, 'seek'): filename_or_handle.seek(0) # rewind pointer to the start of the file # gdata.MediaSource needs the content length, so read the whole image file_handle = StringIO.StringIO(filename_or_handle.read()) name = 'image' if hasattr(filename_or_handle, 'name'): name = filename_or_handle.name mediasource = gdata.MediaSource(file_handle, content_type, content_length=file_handle.len, file_name=name) else: #filename_or_handle is not valid raise GooglePhotosException({'status':GPHOTOS_INVALID_ARGUMENT, 'body':'`filename_or_handle` must be a path name or a file-like object', 'reason':'Found %s, not path name or an object with .read() method' % \ type(filename_or_handle) }) if isinstance(photo_or_uri, (str, unicode)): entry_uri = photo_or_uri # it's a uri elif hasattr(photo_or_uri, 'GetEditMediaLink'): entry_uri = photo_or_uri.GetEditMediaLink().href try: return self.Put(photoblob, entry_uri, converter=gdata.photos.PhotoEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertTag(self, photo_or_uri, tag): """Add a tag (a.k.a. keyword) to a photo. Needs authentication, see self.ClientLogin() Arguments: photo_or_uri: a gdata.photos.PhotoEntry that will be tagged, or a `post' uri pointing to it (string) tag: The tag/keyword Returns: The new gdata.photos.TagEntry Example: p = GetFeed(PhotoUri) tag = InsertTag(p, 'Beautiful sunsets') """ tag = gdata.photos.TagEntry(title=atom.Title(text=tag)) if isinstance(photo_or_uri, (str, unicode)): post_uri = photo_or_uri # it's a uri elif hasattr(photo_or_uri, 'GetEditMediaLink'): post_uri = photo_or_uri.GetPostLink().href try: return self.Post(data=tag, uri=post_uri, converter=gdata.photos.TagEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def InsertComment(self, photo_or_uri, comment): """Add a comment to a photo. Needs authentication, see self.ClientLogin() Arguments: photo_or_uri: a gdata.photos.PhotoEntry that is about to be commented , or a `post' uri pointing to it (string) comment: The actual comment Returns: The new gdata.photos.CommentEntry Example: p = GetFeed(PhotoUri) tag = InsertComment(p, 'OOOH! I would have loved to be there. Who's that in the back?') """ comment = gdata.photos.CommentEntry(content=atom.Content(text=comment)) if isinstance(photo_or_uri, (str, unicode)): post_uri = photo_or_uri # it's a uri elif hasattr(photo_or_uri, 'GetEditMediaLink'): post_uri = photo_or_uri.GetPostLink().href try: return self.Post(data=comment, uri=post_uri, converter=gdata.photos.CommentEntryFromString) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def Delete(self, object_or_uri, *args, **kwargs): """Delete an object. Re-implementing the GDataService.Delete method, to add some convenience. Arguments: object_or_uri: Any object that has a GetEditLink() method that returns a link, or a uri to that object. Returns: ? or GooglePhotosException on errors """ try: uri = object_or_uri.GetEditLink().href except AttributeError: uri = object_or_uri try: return gdata.service.GDataService.Delete(self, uri, *args, **kwargs) except gdata.service.RequestError, e: raise GooglePhotosException(e.args[0]) def GetSmallestThumbnail(media_thumbnail_list): """Helper function to get the smallest thumbnail of a list of gdata.media.Thumbnail. Returns gdata.media.Thumbnail """ r = {} for thumb in media_thumbnail_list: r[int(thumb.width)*int(thumb.height)] = thumb keys = r.keys() keys.sort() return r[keys[0]] def ConvertAtomTimestampToEpoch(timestamp): """Helper function to convert a timestamp string, for instance from atom:updated or atom:published, to milliseconds since Unix epoch (a.k.a. POSIX time). `2007-07-22T00:45:10.000Z' -> """ return time.mktime(time.strptime(timestamp, '%Y-%m-%dT%H:%M:%S.000Z')) ## TODO: Timezone aware
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains classes representing Google Data elements. Extends Atom classes to add Google Data specific elements. """ __author__ = 'j.s@google.com (Jeffrey Scudder)' import os import atom 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 # XML namespaces which are often used in GData entities. GDATA_NAMESPACE = 'http://schemas.google.com/g/2005' GDATA_TEMPLATE = '{http://schemas.google.com/g/2005}%s' OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/' OPENSEARCH_TEMPLATE = '{http://a9.com/-/spec/opensearchrss/1.0/}%s' BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch' GACL_NAMESPACE = 'http://schemas.google.com/acl/2007' GACL_TEMPLATE = '{http://schemas.google.com/acl/2007}%s' # Labels used in batch request entries to specify the desired CRUD operation. BATCH_INSERT = 'insert' BATCH_UPDATE = 'update' BATCH_DELETE = 'delete' BATCH_QUERY = 'query' class Error(Exception): pass class MissingRequiredParameters(Error): pass class MediaSource(object): """GData Entries can refer to media sources, so this class provides a place to store references to these objects along with some metadata. """ def __init__(self, file_handle=None, content_type=None, content_length=None, file_path=None, file_name=None): """Creates an object of type MediaSource. Args: file_handle: A file handle pointing to the file to be encapsulated in the MediaSource content_type: string The MIME type of the file. Required if a file_handle is given. content_length: int The size of the file. Required if a file_handle is given. file_path: string (optional) A full path name to the file. Used in place of a file_handle. file_name: string The name of the file without any path information. Required if a file_handle is given. """ self.file_handle = file_handle self.content_type = content_type self.content_length = content_length self.file_name = file_name if (file_handle is None and content_type is not None and file_path is not None): self.setFile(file_path, content_type) def setFile(self, file_name, content_type): """A helper function which can create a file handle from a given filename and set the content type and length all at once. Args: file_name: string The path and file name to the file containing the media content_type: string A MIME type representing the type of the media """ self.file_handle = open(file_name, 'rb') self.content_type = content_type self.content_length = os.path.getsize(file_name) self.file_name = os.path.basename(file_name) class LinkFinder(atom.LinkFinder): """An "interface" providing methods to find link elements GData Entry elements often contain multiple links which differ in the rel attribute or content type. Often, developers are interested in a specific type of link so this class provides methods to find specific classes of links. This class is used as a mixin in GData entries. """ def GetSelfLink(self): """Find the first link with rel set to 'self' Returns: An atom.Link or none if none of the links had rel equal to 'self' """ for a_link in self.link: if a_link.rel == 'self': return a_link return None def GetEditLink(self): for a_link in self.link: if a_link.rel == 'edit': return a_link return None def GetEditMediaLink(self): """The Picasa API mistakenly returns media-edit rather than edit-media, but this may change soon. """ for a_link in self.link: if a_link.rel == 'edit-media': return a_link if a_link.rel == 'media-edit': return a_link return None def GetHtmlLink(self): """Find the first link with rel of alternate and type of text/html Returns: An atom.Link or None if no links matched """ for a_link in self.link: if a_link.rel == 'alternate' and a_link.type == 'text/html': return a_link return None def GetPostLink(self): """Get a link containing the POST target URL. The POST target URL is used to insert new entries. Returns: A link object with a rel matching the POST type. """ for a_link in self.link: if a_link.rel == 'http://schemas.google.com/g/2005#post': return a_link return None def GetAclLink(self): for a_link in self.link: if a_link.rel == 'http://schemas.google.com/acl/2007#accessControlList': return a_link return None def GetFeedLink(self): for a_link in self.link: if a_link.rel == 'http://schemas.google.com/g/2005#feed': return a_link return None def GetNextLink(self): for a_link in self.link: if a_link.rel == 'next': return a_link return None def GetPrevLink(self): for a_link in self.link: if a_link.rel == 'previous': return a_link return None class TotalResults(atom.AtomBase): """opensearch:TotalResults for a GData feed""" _tag = 'totalResults' _namespace = OPENSEARCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def TotalResultsFromString(xml_string): return atom.CreateClassFromXMLString(TotalResults, xml_string) class StartIndex(atom.AtomBase): """The opensearch:startIndex element in GData feed""" _tag = 'startIndex' _namespace = OPENSEARCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def StartIndexFromString(xml_string): return atom.CreateClassFromXMLString(StartIndex, xml_string) class ItemsPerPage(atom.AtomBase): """The opensearch:itemsPerPage element in GData feed""" _tag = 'itemsPerPage' _namespace = OPENSEARCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def ItemsPerPageFromString(xml_string): return atom.CreateClassFromXMLString(ItemsPerPage, xml_string) class ExtendedProperty(atom.AtomBase): """The Google Data extendedProperty element. Used to store arbitrary key-value information specific to your application. The value can either be a text string stored as an XML attribute (.value), or an XML node (XmlBlob) as a child element. This element is used in the Google Calendar data API and the Google Contacts data API. """ _tag = 'extendedProperty' _namespace = GDATA_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 GetXmlBlobExtensionElement(self): """Returns the XML blob as an atom.ExtensionElement. Returns: An atom.ExtensionElement representing the blob's XML, or None if no blob was set. """ if len(self.extension_elements) < 1: return None else: return self.extension_elements[0] def GetXmlBlobString(self): """Returns the XML blob as a string. Returns: A string containing the blob's XML, or None if no blob was set. """ blob = self.GetXmlBlobExtensionElement() if blob: return blob.ToString() return None def SetXmlBlob(self, blob): """Sets the contents of the extendedProperty to XML as a child node. Since the extendedProperty is only allowed one child element as an XML blob, setting the XML blob will erase any preexisting extension elements in this object. Args: blob: str, ElementTree Element or atom.ExtensionElement representing the XML blob stored in the extendedProperty. """ # Erase any existing extension_elements, clears the child nodes from the # extendedProperty. self.extension_elements = [] if isinstance(blob, atom.ExtensionElement): self.extension_elements.append(blob) elif ElementTree.iselement(blob): self.extension_elements.append(atom._ExtensionElementFromElementTree( blob)) else: self.extension_elements.append(atom.ExtensionElementFromString(blob)) def ExtendedPropertyFromString(xml_string): return atom.CreateClassFromXMLString(ExtendedProperty, xml_string) class GDataEntry(atom.Entry, LinkFinder): """Extends Atom Entry to provide data processing""" _tag = atom.Entry._tag _namespace = atom.Entry._namespace _children = atom.Entry._children.copy() _attributes = atom.Entry._attributes.copy() def __GetId(self): return self.__id # This method was created to strip the unwanted whitespace from the id's # text node. def __SetId(self, id): self.__id = id if id is not None and id.text is not None: self.__id.text = id.text.strip() id = property(__GetId, __SetId) def IsMedia(self): """Determines whether or not an entry is a GData Media entry. """ if (self.GetEditMediaLink()): return True else: return False def GetMediaURL(self): """Returns the URL to the media content, if the entry is a media entry. Otherwise returns None. """ if not self.IsMedia(): return None else: return self.content.src def GDataEntryFromString(xml_string): """Creates a new GDataEntry instance given a string of XML.""" return atom.CreateClassFromXMLString(GDataEntry, xml_string) class GDataFeed(atom.Feed, LinkFinder): """A Feed from a GData service""" _tag = 'feed' _namespace = atom.ATOM_NAMESPACE _children = atom.Feed._children.copy() _attributes = atom.Feed._attributes.copy() _children['{%s}totalResults' % OPENSEARCH_NAMESPACE] = ('total_results', TotalResults) _children['{%s}startIndex' % OPENSEARCH_NAMESPACE] = ('start_index', StartIndex) _children['{%s}itemsPerPage' % OPENSEARCH_NAMESPACE] = ('items_per_page', ItemsPerPage) # Add a conversion rule for atom:entry to make it into a GData # Entry. _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GDataEntry]) def __GetId(self): return self.__id def __SetId(self, id): self.__id = id if id is not None and id.text is not None: self.__id.text = id.text.strip() id = property(__GetId, __SetId) def __GetGenerator(self): return self.__generator def __SetGenerator(self, generator): self.__generator = generator if generator is not None: self.__generator.text = generator.text.strip() generator = property(__GetGenerator, __SetGenerator) 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): """Constructor for Source Args: author: list (optional) A list of Author instances which belong to this class. category: list (optional) A list of Category instances contributor: list (optional) A list on Contributor instances generator: Generator (optional) icon: Icon (optional) id: Id (optional) The entry's Id element link: list (optional) A list of Link instances logo: Logo (optional) rights: Rights (optional) The entry's Rights element subtitle: Subtitle (optional) The entry's subtitle element title: Title (optional) the entry's title element updated: Updated (optional) the entry's updated element entry: list (optional) A list of the Entry instances contained in the feed. text: String (optional) The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) extension_elements: list (optional) A list of ExtensionElement instances which are children of this element. extension_attributes: dict (optional) A dictionary of strings which are the values for additional XML attributes of this element. """ self.author = author or [] self.category = category or [] self.contributor = contributor or [] self.generator = generator self.icon = icon self.id = atom_id self.link = link or [] self.logo = logo self.rights = rights self.subtitle = subtitle self.title = title self.updated = updated self.entry = entry or [] self.total_results = total_results self.start_index = start_index self.items_per_page = items_per_page self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def GDataFeedFromString(xml_string): return atom.CreateClassFromXMLString(GDataFeed, xml_string) class BatchId(atom.AtomBase): _tag = 'id' _namespace = BATCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def BatchIdFromString(xml_string): return atom.CreateClassFromXMLString(BatchId, xml_string) class BatchOperation(atom.AtomBase): _tag = 'operation' _namespace = BATCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['type'] = 'type' def __init__(self, op_type=None, extension_elements=None, extension_attributes=None, text=None): self.type = op_type atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def BatchOperationFromString(xml_string): return atom.CreateClassFromXMLString(BatchOperation, xml_string) class BatchStatus(atom.AtomBase): """The batch:status element present in a batch response entry. A status element contains the code (HTTP response code) and reason as elements. In a single request these fields would be part of the HTTP response, but in a batch request each Entry operation has a corresponding Entry in the response feed which includes status information. See http://code.google.com/apis/gdata/batch.html#Handling_Errors """ _tag = 'status' _namespace = BATCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['code'] = 'code' _attributes['reason'] = 'reason' _attributes['content-type'] = 'content_type' def __init__(self, code=None, reason=None, content_type=None, extension_elements=None, extension_attributes=None, text=None): self.code = code self.reason = reason self.content_type = content_type atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def BatchStatusFromString(xml_string): return atom.CreateClassFromXMLString(BatchStatus, xml_string) class BatchEntry(GDataEntry): """An atom:entry for use in batch requests. The BatchEntry contains additional members to specify the operation to be performed on this entry and a batch ID so that the server can reference individual operations in the response feed. For more information, see: http://code.google.com/apis/gdata/batch.html """ _tag = GDataEntry._tag _namespace = GDataEntry._namespace _children = GDataEntry._children.copy() _children['{%s}operation' % BATCH_NAMESPACE] = ('batch_operation', BatchOperation) _children['{%s}id' % BATCH_NAMESPACE] = ('batch_id', BatchId) _children['{%s}status' % BATCH_NAMESPACE] = ('batch_status', BatchStatus) _attributes = GDataEntry._attributes.copy() def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, control=None, title=None, updated=None, batch_operation=None, batch_id=None, batch_status=None, extension_elements=None, extension_attributes=None, text=None): self.batch_operation = batch_operation self.batch_id = batch_id self.batch_status = batch_status GDataEntry.__init__(self, author=author, category=category, content=content, contributor=contributor, atom_id=atom_id, link=link, published=published, rights=rights, source=source, summary=summary, control=control, title=title, updated=updated, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def BatchEntryFromString(xml_string): return atom.CreateClassFromXMLString(BatchEntry, xml_string) class BatchInterrupted(atom.AtomBase): """The batch:interrupted element sent if batch request was interrupted. Only appears in a feed if some of the batch entries could not be processed. See: http://code.google.com/apis/gdata/batch.html#Handling_Errors """ _tag = 'interrupted' _namespace = BATCH_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['reason'] = 'reason' _attributes['success'] = 'success' _attributes['failures'] = 'failures' _attributes['parsed'] = 'parsed' def __init__(self, reason=None, success=None, failures=None, parsed=None, extension_elements=None, extension_attributes=None, text=None): self.reason = reason self.success = success self.failures = failures self.parsed = parsed atom.AtomBase.__init__(self, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) def BatchInterruptedFromString(xml_string): return atom.CreateClassFromXMLString(BatchInterrupted, xml_string) class BatchFeed(GDataFeed): """A feed containing a list of batch request entries.""" _tag = GDataFeed._tag _namespace = GDataFeed._namespace _children = GDataFeed._children.copy() _attributes = GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BatchEntry]) _children['{%s}interrupted' % BATCH_NAMESPACE] = ('interrupted', BatchInterrupted) 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): self.interrupted = interrupted 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 AddBatchEntry(self, entry=None, id_url_string=None, batch_id_string=None, operation_string=None): """Logic for populating members of a BatchEntry and adding to the feed. If the entry is not a BatchEntry, it is converted to a BatchEntry so that the batch specific members will be present. The id_url_string can be used in place of an entry if the batch operation applies to a URL. For example query and delete operations require just the URL of an entry, no body is sent in the HTTP request. If an id_url_string is sent instead of an entry, a BatchEntry is created and added to the feed. This method also assigns the desired batch id to the entry so that it can be referenced in the server's response. If the batch_id_string is None, this method will assign a batch_id to be the index at which this entry will be in the feed's entry list. Args: entry: BatchEntry, atom.Entry, or another Entry flavor (optional) The entry which will be sent to the server as part of the batch request. The item must have a valid atom id so that the server knows which entry this request references. id_url_string: str (optional) The URL of the entry to be acted on. You can find this URL in the text member of the atom id for an entry. If an entry is not sent, this id will be used to construct a new BatchEntry which will be added to the request feed. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. Note that batch_ids should either always be specified or never, mixing could potentially result in duplicate batch ids. operation_string: str (optional) The desired batch operation which will set the batch_operation.type member of the entry. Options are 'insert', 'update', 'delete', and 'query' Raises: MissingRequiredParameters: Raised if neither an id_ url_string nor an entry are provided in the request. Returns: The added entry. """ if entry is None and id_url_string is None: raise MissingRequiredParameters('supply either an entry or URL string') if entry is None and id_url_string is not None: entry = BatchEntry(atom_id=atom.Id(text=id_url_string)) # TODO: handle cases in which the entry lacks batch_... members. #if not isinstance(entry, BatchEntry): # Convert the entry to a batch entry. if batch_id_string is not None: entry.batch_id = BatchId(text=batch_id_string) elif entry.batch_id is None or entry.batch_id.text is None: entry.batch_id = BatchId(text=str(len(self.entry))) if operation_string is not None: entry.batch_operation = BatchOperation(op_type=operation_string) self.entry.append(entry) return entry def AddInsert(self, entry, batch_id_string=None): """Add an insert request to the operations in this batch request feed. If the entry doesn't yet have an operation or a batch id, these will be set to the insert operation and a batch_id specified as a parameter. Args: entry: BatchEntry The entry which will be sent in the batch feed as an insert request. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. Note that batch_ids should either always be specified or never, mixing could potentially result in duplicate batch ids. """ entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string, operation_string=BATCH_INSERT) def AddUpdate(self, entry, batch_id_string=None): """Add an update request to the list of batch operations in this feed. Sets the operation type of the entry to insert if it is not already set and assigns the desired batch id to the entry so that it can be referenced in the server's response. Args: entry: BatchEntry The entry which will be sent to the server as an update (HTTP PUT) request. The item must have a valid atom id so that the server knows which entry to replace. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. See also comments for AddInsert. """ entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string, operation_string=BATCH_UPDATE) def AddDelete(self, url_string=None, entry=None, batch_id_string=None): """Adds a delete request to the batch request feed. This method takes either the url_string which is the atom id of the item to be deleted, or the entry itself. The atom id of the entry must be present so that the server knows which entry should be deleted. Args: url_string: str (optional) The URL of the entry to be deleted. You can find this URL in the text member of the atom id for an entry. entry: BatchEntry (optional) The entry to be deleted. batch_id_string: str (optional) Raises: MissingRequiredParameters: Raised if neither a url_string nor an entry are provided in the request. """ entry = self.AddBatchEntry(entry=entry, id_url_string=url_string, batch_id_string=batch_id_string, operation_string=BATCH_DELETE) def AddQuery(self, url_string=None, entry=None, batch_id_string=None): """Adds a query request to the batch request feed. This method takes either the url_string which is the query URL whose results will be added to the result feed. The query URL will be encapsulated in a BatchEntry, and you may pass in the BatchEntry with a query URL instead of sending a url_string. Args: url_string: str (optional) entry: BatchEntry (optional) batch_id_string: str (optional) Raises: MissingRequiredParameters """ entry = self.AddBatchEntry(entry=entry, id_url_string=url_string, batch_id_string=batch_id_string, operation_string=BATCH_QUERY) def GetBatchLink(self): for link in self.link: if link.rel == 'http://schemas.google.com/g/2005#batch': return link return None def BatchFeedFromString(xml_string): return atom.CreateClassFromXMLString(BatchFeed, xml_string) class EntryLink(atom.AtomBase): """The gd:entryLink element""" _tag = 'entryLink' _namespace = GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() # The entry used to be an atom.Entry, now it is a GDataEntry. _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', GDataEntry) _attributes['rel'] = 'rel' _attributes['readOnly'] = 'read_only' _attributes['href'] = 'href' def __init__(self, href=None, read_only=None, rel=None, entry=None, extension_elements=None, extension_attributes=None, text=None): self.href = href self.read_only = read_only self.rel = rel self.entry = entry self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EntryLinkFromString(xml_string): return atom.CreateClassFromXMLString(EntryLink, xml_string) class FeedLink(atom.AtomBase): """The gd:feedLink element""" _tag = 'feedLink' _namespace = GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}feed' % atom.ATOM_NAMESPACE] = ('feed', GDataFeed) _attributes['rel'] = 'rel' _attributes['readOnly'] = 'read_only' _attributes['countHint'] = 'count_hint' _attributes['href'] = 'href' def __init__(self, count_hint=None, href=None, read_only=None, rel=None, feed=None, extension_elements=None, extension_attributes=None, text=None): self.count_hint = count_hint self.href = href self.read_only = read_only self.rel = rel self.feed = feed self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def FeedLinkFromString(xml_string): return atom.CreateClassFromXMLString(FeedLink, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2006,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. """GDataService provides CRUD ops. and programmatic login for GData services. Error: A base exception class for all exceptions in the gdata_client module. CaptchaRequired: This exception is thrown when a login attempt results in a captcha challenge from the ClientLogin service. When this exception is thrown, the captcha_token and captcha_url are set to the values provided in the server's response. BadAuthentication: Raised when a login attempt is made with an incorrect username or password. NotAuthenticated: Raised if an operation requiring authentication is called before a user has authenticated. NonAuthSubToken: Raised if a method to modify an AuthSub token is used when the user is either not authenticated or is authenticated through another authentication mechanism. NonOAuthToken: Raised if a method to modify an OAuth token is used when the user is either not authenticated or is authenticated through another authentication mechanism. RequestError: Raised if a CRUD request returned a non-success code. UnexpectedReturnType: Raised if the response from the server was not of the desired type. For example, this would be raised if the server sent a feed when the client requested an entry. GDataService: Encapsulates user credentials needed to perform insert, update and delete operations with the GData API. An instance can perform user authentication, query, insertion, deletion, and update. Query: Eases query URI creation by allowing URI parameters to be set as dictionary attributes. For example a query with a feed of '/base/feeds/snippets' and ['bq'] set to 'digital camera' will produce '/base/feeds/snippets?bq=digital+camera' when .ToUri() is called on it. """ __author__ = 'api.jscudder (Jeffrey Scudder)' import re import urllib import urlparse try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom.service import gdata import atom import atom.http_interface import atom.token_store import gdata.auth import gdata.gauth AUTH_SERVER_HOST = 'https://www.google.com' # When requesting an AuthSub token, it is often helpful to track the scope # which is being requested. One way to accomplish this is to add a URL # parameter to the 'next' URL which contains the requested scope. This # constant is the default name (AKA key) for the URL parameter. SCOPE_URL_PARAM_NAME = 'authsub_token_scope' # When requesting an OAuth access token or authorization of an existing OAuth # request token, it is often helpful to track the scope(s) which is/are being # requested. One way to accomplish this is to add a URL parameter to the # 'callback' URL which contains the requested scope. This constant is the # default name (AKA key) for the URL parameter. OAUTH_SCOPE_URL_PARAM_NAME = 'oauth_token_scope' # Maps the service names used in ClientLogin to scope URLs. CLIENT_LOGIN_SCOPES = gdata.gauth.AUTH_SCOPES # Default parameters for GDataService.GetWithRetries method DEFAULT_NUM_RETRIES = 3 DEFAULT_DELAY = 1 DEFAULT_BACKOFF = 2 def lookup_scopes(service_name): """Finds the scope URLs for the desired service. In some cases, an unknown service may be used, and in those cases this function will return None. """ if service_name in CLIENT_LOGIN_SCOPES: return CLIENT_LOGIN_SCOPES[service_name] return None # Module level variable specifies which module should be used by GDataService # objects to make HttpRequests. This setting can be overridden on each # instance of GDataService. # This module level variable is deprecated. Reassign the http_client member # of a GDataService object instead. http_request_handler = atom.service class Error(Exception): pass class CaptchaRequired(Error): pass class BadAuthentication(Error): pass class NotAuthenticated(Error): pass class NonAuthSubToken(Error): pass class NonOAuthToken(Error): pass class RequestError(Error): pass class UnexpectedReturnType(Error): pass class BadAuthenticationServiceURL(Error): pass class FetchingOAuthRequestTokenFailed(RequestError): pass class TokenUpgradeFailed(RequestError): pass class RevokingOAuthTokenFailed(RequestError): pass class AuthorizationRequired(Error): pass class TokenHadNoScope(Error): pass class RanOutOfTries(Error): pass class GDataService(atom.service.AtomService): """Contains elements needed for GData login and CRUD request headers. Maintains additional headers (tokens for example) needed for the GData services to allow a user to perform inserts, updates, and deletes. """ # The hander member is deprecated, use http_client instead. handler = None # The auth_token member is deprecated, use the token_store instead. auth_token = None # The tokens dict is deprecated in favor of the token_store. tokens = None def __init__(self, email=None, password=None, account_type='HOSTED_OR_GOOGLE', service=None, auth_service_url=None, source=None, server=None, additional_headers=None, handler=None, tokens=None, http_client=None, token_store=None): """Creates an object of type GDataService. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. account_type: string (optional) The type of account to use. Use 'GOOGLE' for regular Google accounts or 'HOSTED' for Google Apps accounts, or 'HOSTED_OR_GOOGLE' to try finding a HOSTED account first and, if it doesn't exist, try finding a regular GOOGLE account. Default value: 'HOSTED_OR_GOOGLE'. service: string (optional) The desired service for which credentials will be obtained. auth_service_url: string (optional) User-defined auth token request URL allows users to explicitly specify where to send auth token requests. 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: 'base.google.com'. additional_headers: dictionary (optional) Any additional headers which should be included with CRUD operations. handler: module (optional) This parameter is deprecated and has been replaced by http_client. tokens: This parameter is deprecated, calls should be made to token_store instead. http_client: An object responsible for making HTTP requests using a request method. If none is provided, a new instance of atom.http.ProxiedHttpClient will be used. token_store: Keeps a collection of authorization tokens which can be applied to requests for a specific URLs. Critical methods are find_token based on a URL (atom.url.Url or a string), add_token, and remove_token. """ atom.service.AtomService.__init__(self, http_client=http_client, token_store=token_store) self.email = email self.password = password self.account_type = account_type self.service = service self.auth_service_url = auth_service_url self.server = server self.additional_headers = additional_headers or {} self._oauth_input_params = None self.__SetSource(source) self.__captcha_token = None self.__captcha_url = None self.__gsessionid = None if http_request_handler.__name__ == 'gdata.urlfetch': import gdata.alt.appengine self.http_client = gdata.alt.appengine.AppEngineHttpClient() def _SetSessionId(self, session_id): """Used in unit tests to simulate a 302 which sets a gsessionid.""" self.__gsessionid = session_id # Define properties for GDataService def _SetAuthSubToken(self, auth_token, scopes=None): """Deprecated, use SetAuthSubToken instead.""" self.SetAuthSubToken(auth_token, scopes=scopes) def __SetAuthSubToken(self, auth_token, scopes=None): """Deprecated, use SetAuthSubToken instead.""" self._SetAuthSubToken(auth_token, scopes=scopes) def _GetAuthToken(self): """Returns the auth token used for authenticating requests. Returns: string """ current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if hasattr(token, 'auth_header'): return token.auth_header return None def _GetCaptchaToken(self): """Returns a captcha token if the most recent login attempt generated one. The captcha token is only set if the Programmatic Login attempt failed because the Google service issued a captcha challenge. Returns: string """ return self.__captcha_token def __GetCaptchaToken(self): return self._GetCaptchaToken() captcha_token = property(__GetCaptchaToken, doc="""Get the captcha token for a login request.""") def _GetCaptchaURL(self): """Returns the URL of the captcha image if a login attempt generated one. The captcha URL is only set if the Programmatic Login attempt failed because the Google service issued a captcha challenge. Returns: string """ return self.__captcha_url def __GetCaptchaURL(self): return self._GetCaptchaURL() captcha_url = property(__GetCaptchaURL, doc="""Get the captcha URL for a login request.""") def GetGeneratorFromLinkFinder(self, link_finder, func, num_retries=DEFAULT_NUM_RETRIES, delay=DEFAULT_DELAY, backoff=DEFAULT_BACKOFF): """returns a generator for pagination""" yield link_finder next = link_finder.GetNextLink() while next is not None: next_feed = func(str(self.GetWithRetries( next.href, num_retries=num_retries, delay=delay, backoff=backoff))) yield next_feed next = next_feed.GetNextLink() def _GetElementGeneratorFromLinkFinder(self, link_finder, func, num_retries=DEFAULT_NUM_RETRIES, delay=DEFAULT_DELAY, backoff=DEFAULT_BACKOFF): for element in self.GetGeneratorFromLinkFinder(link_finder, func, num_retries=num_retries, delay=delay, backoff=backoff).entry: yield element def GetOAuthInputParameters(self): return self._oauth_input_params def SetOAuthInputParameters(self, signature_method, consumer_key, consumer_secret=None, rsa_key=None, two_legged_oauth=False, requestor_id=None): """Sets parameters required for using OAuth authentication mechanism. NOTE: Though consumer_secret and rsa_key are optional, either of the two is required depending on the value of the signature_method. Args: signature_method: class which provides implementation for strategy class oauth.oauth.OAuthSignatureMethod. Signature method to be used for signing each request. Valid implementations are provided as the constants defined by gdata.auth.OAuthSignatureMethod. Currently they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and gdata.auth.OAuthSignatureMethod.HMAC_SHA1 consumer_key: string Domain identifying third_party web application. consumer_secret: string (optional) Secret generated during registration. Required only for HMAC_SHA1 signature method. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. two_legged_oauth: boolean (optional) Enables two-legged OAuth process. requestor_id: string (optional) User email adress to make requests on their behalf. This parameter should only be set when two_legged_oauth is True. """ self._oauth_input_params = gdata.auth.OAuthInputParams( signature_method, consumer_key, consumer_secret=consumer_secret, rsa_key=rsa_key, requestor_id=requestor_id) if two_legged_oauth: oauth_token = gdata.auth.OAuthToken( oauth_input_params=self._oauth_input_params) self.SetOAuthToken(oauth_token) def FetchOAuthRequestToken(self, scopes=None, extra_parameters=None, request_url='%s/accounts/OAuthGetRequestToken' % \ AUTH_SERVER_HOST, oauth_callback=None): """Fetches and sets the OAuth request token and returns it. Args: scopes: string or list of string base URL(s) of the service(s) to be accessed. If None, then this method tries to determine the scope(s) from the current service. extra_parameters: dict (optional) key-value pairs as any additional parameters to be included in the URL and signature while making a request for fetching an OAuth request token. All the OAuth parameters are added by default. But if provided through this argument, any default parameters will be overwritten. For e.g. a default parameter oauth_version 1.0 can be overwritten if extra_parameters = {'oauth_version': '2.0'} request_url: Request token URL. The default is 'https://www.google.com/accounts/OAuthGetRequestToken'. oauth_callback: str (optional) If set, it is assume the client is using the OAuth v1.0a protocol where the callback url is sent in the request token step. If the oauth_callback is also set in extra_params, this value will override that one. Returns: The fetched request token as a gdata.auth.OAuthToken object. Raises: FetchingOAuthRequestTokenFailed if the server responded to the request with an error. """ if scopes is None: scopes = lookup_scopes(self.service) if not isinstance(scopes, (list, tuple)): scopes = [scopes,] if oauth_callback: if extra_parameters is not None: extra_parameters['oauth_callback'] = oauth_callback else: extra_parameters = {'oauth_callback': oauth_callback} request_token_url = gdata.auth.GenerateOAuthRequestTokenUrl( self._oauth_input_params, scopes, request_token_url=request_url, extra_parameters=extra_parameters) response = self.http_client.request('GET', str(request_token_url)) if response.status == 200: token = gdata.auth.OAuthToken() token.set_token_string(response.read()) token.scopes = scopes token.oauth_input_params = self._oauth_input_params self.SetOAuthToken(token) return token error = { 'status': response.status, 'reason': 'Non 200 response on fetch request token', 'body': response.read() } raise FetchingOAuthRequestTokenFailed(error) def SetOAuthToken(self, oauth_token): """Attempts to set the current token and add it to the token store. The oauth_token can be any OAuth token i.e. unauthorized request token, authorized request token or access token. This method also attempts to add the token to the token store. Use this method any time you want the current token to point to the oauth_token passed. For e.g. call this method with the request token you receive from FetchOAuthRequestToken. Args: request_token: gdata.auth.OAuthToken OAuth request token. """ if self.auto_set_current_token: self.current_token = oauth_token if self.auto_store_tokens: self.token_store.add_token(oauth_token) def GenerateOAuthAuthorizationURL( self, request_token=None, callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix=OAUTH_SCOPE_URL_PARAM_NAME, request_url='%s/accounts/OAuthAuthorizeToken' % AUTH_SERVER_HOST): """Generates URL at which user will login to authorize the request token. Args: request_token: gdata.auth.OAuthToken (optional) OAuth request token. If not specified, then the current token will be used if it is of type <gdata.auth.OAuthToken>, else it is found by looking in the token_store by looking for a token for the current scope. callback_url: string (optional) The URL user will be sent to after logging in and granting access. extra_params: dict (optional) Additional parameters to be sent. include_scopes_in_callback: Boolean (default=False) if set to True, and if 'callback_url' is present, the 'callback_url' will be modified to include the scope(s) from the request token as a URL parameter. The key for the 'callback' URL's scope parameter will be OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as a parameter to the 'callback' URL, is that the page which receives the OAuth token will be able to tell which URLs the token grants access to. scopes_param_prefix: string (default='oauth_token_scope') The URL parameter key which maps to the list of valid scopes for the token. This URL parameter will be included in the callback URL along with the scopes of the token as value if include_scopes_in_callback=True. request_url: Authorization URL. The default is 'https://www.google.com/accounts/OAuthAuthorizeToken'. Returns: A string URL at which the user is required to login. Raises: NonOAuthToken if the user's request token is not an OAuth token or if a request token was not available. """ if request_token and not isinstance(request_token, gdata.auth.OAuthToken): raise NonOAuthToken if not request_token: if isinstance(self.current_token, gdata.auth.OAuthToken): request_token = self.current_token else: current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.OAuthToken): request_token = token if not request_token: raise NonOAuthToken return str(gdata.auth.GenerateOAuthAuthorizationUrl( request_token, authorization_url=request_url, callback_url=callback_url, extra_params=extra_params, include_scopes_in_callback=include_scopes_in_callback, scopes_param_prefix=scopes_param_prefix)) def UpgradeToOAuthAccessToken(self, authorized_request_token=None, request_url='%s/accounts/OAuthGetAccessToken' \ % AUTH_SERVER_HOST, oauth_version='1.0', oauth_verifier=None): """Upgrades the authorized request token to an access token and returns it Args: authorized_request_token: gdata.auth.OAuthToken (optional) OAuth request token. If not specified, then the current token will be used if it is of type <gdata.auth.OAuthToken>, else it is found by looking in the token_store by looking for a token for the current scope. request_url: Access token URL. The default is 'https://www.google.com/accounts/OAuthGetAccessToken'. oauth_version: str (default='1.0') oauth_version parameter. All other 'oauth_' parameters are added by default. This parameter too, is added by default but here you can override it's value. oauth_verifier: str (optional) If present, it is assumed that the client will use the OAuth v1.0a protocol which includes passing the oauth_verifier (as returned by the SP) in the access token step. Returns: Access token Raises: NonOAuthToken if the user's authorized request token is not an OAuth token or if an authorized request token was not available. TokenUpgradeFailed if the server responded to the request with an error. """ if (authorized_request_token and not isinstance(authorized_request_token, gdata.auth.OAuthToken)): raise NonOAuthToken if not authorized_request_token: if isinstance(self.current_token, gdata.auth.OAuthToken): authorized_request_token = self.current_token else: current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.OAuthToken): authorized_request_token = token if not authorized_request_token: raise NonOAuthToken access_token_url = gdata.auth.GenerateOAuthAccessTokenUrl( authorized_request_token, self._oauth_input_params, access_token_url=request_url, oauth_version=oauth_version, oauth_verifier=oauth_verifier) response = self.http_client.request('GET', str(access_token_url)) if response.status == 200: token = gdata.auth.OAuthTokenFromHttpBody(response.read()) token.scopes = authorized_request_token.scopes token.oauth_input_params = authorized_request_token.oauth_input_params self.SetOAuthToken(token) return token else: raise TokenUpgradeFailed({'status': response.status, 'reason': 'Non 200 response on upgrade', 'body': response.read()}) def RevokeOAuthToken(self, request_url='%s/accounts/AuthSubRevokeToken' % \ AUTH_SERVER_HOST): """Revokes an existing OAuth token. request_url: Token revoke URL. The default is 'https://www.google.com/accounts/AuthSubRevokeToken'. Raises: NonOAuthToken if the user's auth token is not an OAuth token. RevokingOAuthTokenFailed if request for revoking an OAuth token failed. """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.OAuthToken): raise NonOAuthToken response = token.perform_request(self.http_client, 'GET', request_url, headers={'Content-Type':'application/x-www-form-urlencoded'}) if response.status == 200: self.token_store.remove_token(token) else: raise RevokingOAuthTokenFailed def GetAuthSubToken(self): """Returns the AuthSub token as a string. If the token is an gdta.auth.AuthSubToken, the Authorization Label ("AuthSub token") is removed. This method examines the current_token to see if it is an AuthSubToken or SecureAuthSubToken. If not, it searches the token_store for a token which matches the current scope. The current scope is determined by the service name string member. Returns: If the current_token is set to an AuthSubToken/SecureAuthSubToken, return the token string. If there is no current_token, a token string for a token which matches the service object's default scope is returned. If there are no tokens valid for the scope, returns None. """ if isinstance(self.current_token, gdata.auth.AuthSubToken): return self.current_token.get_token_string() current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.AuthSubToken): return token.get_token_string() else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() return None def SetAuthSubToken(self, token, scopes=None, rsa_key=None): """Sets the token sent in requests to an AuthSub token. Sets the current_token and attempts to add the token to the token_store. Only use this method if you have received a token from the AuthSub service. The auth token is set automatically when UpgradeToSessionToken() is used. See documentation for Google AuthSub here: http://code.google.com/apis/accounts/AuthForWebApps.html Args: token: gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken or string The token returned by the AuthSub service. If the token is an AuthSubToken or SecureAuthSubToken, the scope information stored in the token is used. If the token is a string, the scopes parameter is used to determine the valid scopes. scopes: list of URLs for which the token is valid. This is only used if the token parameter is a string. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. This parameter is necessary if the token is a string representing a secure token. """ if not isinstance(token, gdata.auth.AuthSubToken): token_string = token if rsa_key: token = gdata.auth.SecureAuthSubToken(rsa_key) else: token = gdata.auth.AuthSubToken() token.set_token_string(token_string) # If no scopes were set for the token, use the scopes passed in, or # try to determine the scopes based on the current service name. If # all else fails, set the token to match all requests. if not token.scopes: if scopes is None: scopes = lookup_scopes(self.service) if scopes is None: scopes = [atom.token_store.SCOPE_ALL] token.scopes = scopes if self.auto_set_current_token: self.current_token = token if self.auto_store_tokens: self.token_store.add_token(token) def GetClientLoginToken(self): """Returns the token string for the current token or a token matching the service scope. If the current_token is a ClientLoginToken, the token string for the current token is returned. If the current_token is not set, this method searches for a token in the token_store which is valid for the service object's current scope. The current scope is determined by the service name string member. The token string is the end of the Authorization header, it doesn not include the ClientLogin label. """ if isinstance(self.current_token, gdata.auth.ClientLoginToken): return self.current_token.get_token_string() current_scopes = lookup_scopes(self.service) if current_scopes: token = self.token_store.find_token(current_scopes[0]) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if isinstance(token, gdata.auth.ClientLoginToken): return token.get_token_string() return None def SetClientLoginToken(self, token, scopes=None): """Sets the token sent in requests to a ClientLogin token. This method sets the current_token to a new ClientLoginToken and it also attempts to add the ClientLoginToken to the token_store. Only use this method if you have received a token from the ClientLogin service. The auth_token is set automatically when ProgrammaticLogin() is used. See documentation for Google ClientLogin here: http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html Args: token: string or instance of a ClientLoginToken. """ if not isinstance(token, gdata.auth.ClientLoginToken): token_string = token token = gdata.auth.ClientLoginToken() token.set_token_string(token_string) if not token.scopes: if scopes is None: scopes = lookup_scopes(self.service) if scopes is None: scopes = [atom.token_store.SCOPE_ALL] token.scopes = scopes if self.auto_set_current_token: self.current_token = token if self.auto_store_tokens: self.token_store.add_token(token) # Private methods to create the source property. def __GetSource(self): return self.__source def __SetSource(self, new_source): self.__source = new_source # Update the UserAgent header to include the new application name. self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % ( self.__source,) source = property(__GetSource, __SetSource, doc="""The source is the name of the application making the request. It should be in the form company_id-app_name-app_version""") # Authentication operations def ProgrammaticLogin(self, captcha_token=None, captcha_response=None): """Authenticates the user and sets the GData Auth token. Login retreives a temporary auth token which must be used with all requests to GData services. The auth token is stored in the GData client object. Login is also used to respond to a captcha challenge. If the user's login attempt failed with a CaptchaRequired error, the user can respond by calling Login with the captcha token and the answer to the challenge. Args: captcha_token: string (optional) The identifier for the captcha challenge which was presented to the user. captcha_response: string (optional) The user's answer to the captch challenge. Raises: CaptchaRequired if the login service will require a captcha response BadAuthentication if the login service rejected the username or password Error if the login service responded with a 403 different from the above """ request_body = gdata.auth.generate_client_login_request_body(self.email, self.password, self.service, self.source, self.account_type, captcha_token, captcha_response) # If the user has defined their own authentication service URL, # send the ClientLogin requests to this URL: if not self.auth_service_url: auth_request_url = AUTH_SERVER_HOST + '/accounts/ClientLogin' else: auth_request_url = self.auth_service_url auth_response = self.http_client.request('POST', auth_request_url, data=request_body, headers={'Content-Type':'application/x-www-form-urlencoded'}) response_body = auth_response.read() if auth_response.status == 200: # TODO: insert the token into the token_store directly. self.SetClientLoginToken( gdata.auth.get_client_login_token(response_body)) self.__captcha_token = None self.__captcha_url = None elif auth_response.status == 403: # Examine each line to find the error type and the captcha token and # captch URL if they are present. captcha_parameters = gdata.auth.get_captcha_challenge(response_body, captcha_base_url='%s/accounts/' % AUTH_SERVER_HOST) if captcha_parameters: self.__captcha_token = captcha_parameters['token'] self.__captcha_url = captcha_parameters['url'] raise CaptchaRequired, 'Captcha Required' elif response_body.splitlines()[0] == 'Error=BadAuthentication': self.__captcha_token = None self.__captcha_url = None raise BadAuthentication, 'Incorrect username or password' else: self.__captcha_token = None self.__captcha_url = None raise Error, 'Server responded with a 403 code' elif auth_response.status == 302: self.__captcha_token = None self.__captcha_url = None # Google tries to redirect all bad URLs back to # http://www.google.<locale>. If a redirect # attempt is made, assume the user has supplied an incorrect authentication URL raise BadAuthenticationServiceURL, 'Server responded with a 302 code.' def ClientLogin(self, username, password, account_type=None, service=None, auth_service_url=None, source=None, captcha_token=None, captcha_response=None): """Convenience method for authenticating using ProgrammaticLogin. Sets values for email, password, and other optional members. Args: username: password: account_type: string (optional) service: string (optional) auth_service_url: string (optional) captcha_token: string (optional) captcha_response: string (optional) """ self.email = username self.password = password if account_type: self.account_type = account_type if service: self.service = service if source: self.source = source if auth_service_url: self.auth_service_url = auth_service_url self.ProgrammaticLogin(captcha_token, captcha_response) def GenerateAuthSubURL(self, next, scope, secure=False, session=True, domain='default'): """Generate a URL at which the user will login and be redirected back. Users enter their credentials on a Google login page and a token is sent to the URL specified in next. See documentation for AuthSub login at: http://code.google.com/apis/accounts/docs/AuthSub.html Args: next: string The URL user will be sent to after logging in. scope: string or list of strings. The URLs of the services to be accessed. secure: boolean (optional) Determines whether or not the issued token is a secure token. session: boolean (optional) Determines whether or not the issued token can be upgraded to a session token. """ if not isinstance(scope, (list, tuple)): scope = (scope,) return gdata.auth.generate_auth_sub_url(next, scope, secure=secure, session=session, request_url='%s/accounts/AuthSubRequest' % AUTH_SERVER_HOST, domain=domain) def UpgradeToSessionToken(self, token=None): """Upgrades a single use AuthSub token to a session token. Args: token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken (optional) which is good for a single use but can be upgraded to a session token. If no token is passed in, the token is found by looking in the token_store by looking for a token for the current scope. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token TokenUpgradeFailed if the server responded to the request with an error. """ if token is None: scopes = lookup_scopes(self.service) if scopes: token = self.token_store.find_token(scopes[0]) else: token = self.token_store.find_token(atom.token_store.SCOPE_ALL) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken self.SetAuthSubToken(self.upgrade_to_session_token(token)) def upgrade_to_session_token(self, token): """Upgrades a single use AuthSub token to a session token. Args: token: A gdata.auth.AuthSubToken or gdata.auth.SecureAuthSubToken which is good for a single use but can be upgraded to a session token. Returns: The upgraded token as a gdata.auth.AuthSubToken object. Raises: TokenUpgradeFailed if the server responded to the request with an error. """ response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubSessionToken', headers={'Content-Type':'application/x-www-form-urlencoded'}) response_body = response.read() if response.status == 200: token.set_token_string( gdata.auth.token_from_http_body(response_body)) return token else: raise TokenUpgradeFailed({'status': response.status, 'reason': 'Non 200 response on upgrade', 'body': response_body}) def RevokeAuthSubToken(self): """Revokes an existing AuthSub token. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubRevokeToken', headers={'Content-Type':'application/x-www-form-urlencoded'}) if response.status == 200: self.token_store.remove_token(token) def AuthSubTokenInfo(self): """Fetches the AuthSub token's metadata from the server. Raises: NonAuthSubToken if the user's auth token is not an AuthSub token """ scopes = lookup_scopes(self.service) token = self.token_store.find_token(scopes[0]) if not isinstance(token, gdata.auth.AuthSubToken): raise NonAuthSubToken response = token.perform_request(self.http_client, 'GET', AUTH_SERVER_HOST + '/accounts/AuthSubTokenInfo', headers={'Content-Type':'application/x-www-form-urlencoded'}) result_body = response.read() if response.status == 200: return result_body else: raise RequestError, {'status': response.status, 'body': result_body} def GetWithRetries(self, uri, extra_headers=None, redirects_remaining=4, encoding='UTF-8', converter=None, num_retries=DEFAULT_NUM_RETRIES, delay=DEFAULT_DELAY, backoff=DEFAULT_BACKOFF, logger=None): """This is a wrapper method for Get with retrying capability. To avoid various errors while retrieving bulk entities by retrying specified times. Note this method relies on the time module and so may not be usable by default in Python2.2. Args: num_retries: Integer; the retry count. delay: Integer; the initial delay for retrying. backoff: Integer; how much the delay should lengthen after each failure. logger: An object which has a debug(str) method to receive logging messages. Recommended that you pass in the logging module. Raises: ValueError if any of the parameters has an invalid value. RanOutOfTries on failure after number of retries. """ # Moved import for time module inside this method since time is not a # default module in Python2.2. This method will not be usable in # Python2.2. import time if backoff <= 1: raise ValueError("backoff must be greater than 1") num_retries = int(num_retries) if num_retries < 0: raise ValueError("num_retries must be 0 or greater") if delay <= 0: raise ValueError("delay must be greater than 0") # Let's start mtries, mdelay = num_retries, delay while mtries > 0: if mtries != num_retries: if logger: logger.debug("Retrying: %s" % uri) try: rv = self.Get(uri, extra_headers=extra_headers, redirects_remaining=redirects_remaining, encoding=encoding, converter=converter) except SystemExit: # Allow this error raise except RequestError, e: # Error 500 is 'internal server error' and warrants a retry # Error 503 is 'service unavailable' and warrants a retry if e[0]['status'] not in [500, 503]: raise e # Else, fall through to the retry code... except Exception, e: if logger: logger.debug(e) # Fall through to the retry code... else: # This is the right path. return rv mtries -= 1 time.sleep(mdelay) mdelay *= backoff raise RanOutOfTries('Ran out of tries.') # CRUD operations def Get(self, uri, extra_headers=None, redirects_remaining=4, encoding='UTF-8', converter=None): """Query the GData API with the given URI The uri is the portion of the URI after the server value (ex: www.google.com). To perform a query against Google Base, set the server to 'base.google.com' and set the uri to '/base/feeds/...', where ... is your query. For example, to find snippets for all digital cameras uri should be set to: '/base/feeds/snippets?bq=digital+camera' Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. redirects_remaining: int (optional) Tracks the number of additional redirects this method will allow. If the service object receives a redirect and remaining is 0, it will not follow the redirect. This was added to avoid infinite redirect loops. encoding: string (optional) The character encoding for the server's response. Default is UTF-8 converter: func (optional) A function which will transform the server's results before it is returned. Example: use GDataFeedFromString to parse the server response as if it were a GDataFeed. Returns: If there is no ResultsTransformer specified in the call, a GDataFeed or GDataEntry depending on which is sent from the server. If the response is niether a feed or entry and there is no ResultsTransformer, return a string. If there is a ResultsTransformer, the returned value will be that of the ResultsTransformer function. """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if uri.find('?') > -1: uri += '&gsessionid=%s' % (self.__gsessionid,) else: uri += '?gsessionid=%s' % (self.__gsessionid,) server_response = self.request('GET', uri, headers=extra_headers) result_body = server_response.read() if server_response.status == 200: if converter: return converter(result_body) # There was no ResultsTransformer specified, so try to convert the # server's response into a GDataFeed. feed = gdata.GDataFeedFromString(result_body) if not feed: # If conversion to a GDataFeed failed, try to convert the server's # response to a GDataEntry. entry = gdata.GDataEntryFromString(result_body) if not entry: # The server's response wasn't a feed, or an entry, so return the # response body as a string. return result_body return entry return feed elif server_response.status == 302: if redirects_remaining > 0: location = (server_response.getheader('Location') or server_response.getheader('location')) if location is not None: m = re.compile('[\?\&]gsessionid=(\w*\-)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.Get(self, location, extra_headers, redirects_remaining - 1, encoding=encoding, converter=converter) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def GetMedia(self, uri, extra_headers=None): """Returns a MediaSource containing media and its metadata from the given URI string. """ response_handle = self.request('GET', uri, headers=extra_headers) return gdata.MediaSource(response_handle, response_handle.getheader( 'Content-Type'), response_handle.getheader('Content-Length')) def GetEntry(self, uri, extra_headers=None): """Query the GData API with the given URI and receive an Entry. See also documentation for gdata.service.Get Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. Returns: A GDataEntry built from the XML in the server's response. """ result = GDataService.Get(self, uri, extra_headers, converter=atom.EntryFromString) if isinstance(result, atom.Entry): return result else: raise UnexpectedReturnType, 'Server did not send an entry' def GetFeed(self, uri, extra_headers=None, converter=gdata.GDataFeedFromString): """Query the GData API with the given URI and receive a Feed. See also documentation for gdata.service.Get Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dictionary (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. Returns: A GDataFeed built from the XML in the server's response. """ result = GDataService.Get(self, uri, extra_headers, converter=converter) if isinstance(result, atom.Feed): return result else: raise UnexpectedReturnType, 'Server did not send a feed' def GetNext(self, feed): """Requests the next 'page' of results in the feed. This method uses the feed's next link to request an additional feed and uses the class of the feed to convert the results of the GET request. Args: feed: atom.Feed or a subclass. The feed should contain a next link and the type of the feed will be applied to the results from the server. The new feed which is returned will be of the same class as this feed which was passed in. Returns: A new feed representing the next set of results in the server's feed. The type of this feed will match that of the feed argument. """ next_link = feed.GetNextLink() # Create a closure which will convert an XML string to the class of # the feed object passed in. def ConvertToFeedClass(xml_string): return atom.CreateClassFromXMLString(feed.__class__, xml_string) # Make a GET request on the next link and use the above closure for the # converted which processes the XML string from the server. if next_link and next_link.href: return GDataService.Get(self, next_link.href, converter=ConvertToFeedClass) else: return None def Post(self, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4, media_source=None, converter=None): """Insert or update data into a GData service at the given URI. Args: data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The XML to be sent to the uri. uri: string The location (feed) to which the data should be inserted. Example: '/base/feeds/items'. extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. media_source: MediaSource (optional) Container for the media to be sent along with the entry, if provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the post succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ return GDataService.PostOrPut(self, 'POST', data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, redirects_remaining=redirects_remaining, media_source=media_source, converter=converter) def PostOrPut(self, verb, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4, media_source=None, converter=None): """Insert data into a GData service at the given URI. Args: verb: string, either 'POST' or 'PUT' data: string, ElementTree._Element, atom.Entry, or gdata.GDataEntry The XML to be sent to the uri. uri: string The location (feed) to which the data should be inserted. Example: '/base/feeds/items'. extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. media_source: MediaSource (optional) Container for the media to be sent along with the entry, if provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the post succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if url_params is None: url_params = {} url_params['gsessionid'] = self.__gsessionid if data and media_source: if ElementTree.iselement(data): data_str = ElementTree.tostring(data) else: data_str = str(data) multipart = [] multipart.append('Media multipart posting\r\n--END_OF_PART\r\n' + \ 'Content-Type: application/atom+xml\r\n\r\n') multipart.append('\r\n--END_OF_PART\r\nContent-Type: ' + \ media_source.content_type+'\r\n\r\n') multipart.append('\r\n--END_OF_PART--\r\n') extra_headers['MIME-version'] = '1.0' extra_headers['Content-Length'] = str(len(multipart[0]) + len(multipart[1]) + len(multipart[2]) + len(data_str) + media_source.content_length) extra_headers['Content-Type'] = 'multipart/related; boundary=END_OF_PART' server_response = self.request(verb, uri, data=[multipart[0], data_str, multipart[1], media_source.file_handle, multipart[2]], headers=extra_headers, url_params=url_params) result_body = server_response.read() elif media_source or isinstance(data, gdata.MediaSource): if isinstance(data, gdata.MediaSource): media_source = data extra_headers['Content-Length'] = str(media_source.content_length) extra_headers['Content-Type'] = media_source.content_type server_response = self.request(verb, uri, data=media_source.file_handle, headers=extra_headers, url_params=url_params) result_body = server_response.read() else: http_data = data if 'Content-Type' not in extra_headers: content_type = 'application/atom+xml' extra_headers['Content-Type'] = content_type server_response = self.request(verb, uri, data=http_data, headers=extra_headers, url_params=url_params) result_body = server_response.read() # Server returns 201 for most post requests, but when performing a batch # request the server responds with a 200 on success. if server_response.status == 201 or server_response.status == 200: if converter: return converter(result_body) feed = gdata.GDataFeedFromString(result_body) if not feed: entry = gdata.GDataEntryFromString(result_body) if not entry: return result_body return entry return feed elif server_response.status == 302: if redirects_remaining > 0: location = (server_response.getheader('Location') or server_response.getheader('location')) if location is not None: m = re.compile('[\?\&]gsessionid=(\w*\-)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.PostOrPut(self, verb, data, location, extra_headers, url_params, escape_params, redirects_remaining - 1, media_source, converter=converter) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def Put(self, data, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=3, media_source=None, converter=None): """Updates an entry at the given URI. Args: data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The XML containing the updated data. uri: string A URI indicating entry to which the update will be applied. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. converter: func (optional) A function which will be executed on the server's response. Often this is a function like GDataEntryFromString which will parse the body of the server's response and return a GDataEntry. Returns: If the put succeeded, this method will return a GDataFeed, GDataEntry, or the results of running converter on the server's result body (if converter was specified). """ return GDataService.PostOrPut(self, 'PUT', data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, redirects_remaining=redirects_remaining, media_source=media_source, converter=converter) def Delete(self, uri, extra_headers=None, url_params=None, escape_params=True, redirects_remaining=4): """Deletes the entry at the given URI. Args: uri: string The URI of the entry to be deleted. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type and Authorization headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: True if the entry was deleted. """ if extra_headers is None: extra_headers = {} if self.__gsessionid is not None: if uri.find('gsessionid=') < 0: if url_params is None: url_params = {} url_params['gsessionid'] = self.__gsessionid server_response = self.request('DELETE', uri, headers=extra_headers, url_params=url_params) result_body = server_response.read() if server_response.status == 200: return True elif server_response.status == 302: if redirects_remaining > 0: location = (server_response.getheader('Location') or server_response.getheader('location')) if location is not None: m = re.compile('[\?\&]gsessionid=(\w*\-)').search(location) if m is not None: self.__gsessionid = m.group(1) return GDataService.Delete(self, location, extra_headers, url_params, escape_params, redirects_remaining - 1) else: raise RequestError, {'status': server_response.status, 'reason': '302 received without Location header', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': 'Redirect received, but redirects_remaining <= 0', 'body': result_body} else: raise RequestError, {'status': server_response.status, 'reason': server_response.reason, 'body': result_body} def ExtractToken(url, scopes_included_in_next=True): """Gets the AuthSub token from the current page's URL. Designed to be used on the URL that the browser is sent to after the user authorizes this application at the page given by GenerateAuthSubRequestUrl. Args: url: The current page's URL. It should contain the token as a URL parameter. Example: 'http://example.com/?...&token=abcd435' scopes_included_in_next: If True, this function looks for a scope value associated with the token. The scope is a URL parameter with the key set to SCOPE_URL_PARAM_NAME. This parameter should be present if the AuthSub request URL was generated using GenerateAuthSubRequestUrl with include_scope_in_next set to True. Returns: A tuple containing the token string and a list of scope strings for which this token should be valid. If the scope was not included in the URL, the tuple will contain (token, None). """ parsed = urlparse.urlparse(url) token = gdata.auth.AuthSubTokenFromUrl(parsed[4]) scopes = '' if scopes_included_in_next: for pair in parsed[4].split('&'): if pair.startswith('%s=' % SCOPE_URL_PARAM_NAME): scopes = urllib.unquote_plus(pair.split('=')[1]) return (token, scopes.split(' ')) def GenerateAuthSubRequestUrl(next, scopes, hd='default', secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', include_scopes_in_next=True): """Creates a URL to request an AuthSub token to access Google services. For more details on AuthSub, see the documentation here: http://code.google.com/apis/accounts/docs/AuthSub.html Args: next: The URL where the browser should be sent after the user authorizes the application. This page is responsible for receiving the token which is embeded in the URL as a parameter. scopes: The base URL to which access will be granted. Example: 'http://www.google.com/calendar/feeds' will grant access to all URLs in the Google Calendar data API. If you would like a token for multiple scopes, pass in a list of URL strings. hd: The domain to which the user's account belongs. This is set to the domain name if you are using Google Apps. Example: 'example.org' Defaults to 'default' secure: If set to True, all requests should be signed. The default is False. session: If set to True, the token received by the 'next' URL can be upgraded to a multiuse session token. If session is set to False, the token may only be used once and cannot be upgraded. Default is True. request_url: The base of the URL to which the user will be sent to authorize this application to access their data. The default is 'https://www.google.com/accounts/AuthSubRequest'. include_scopes_in_next: Boolean if set to true, the 'next' parameter will be modified to include the requested scope as a URL parameter. The key for the next's scope parameter will be SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as a parameter to the next URL, is that the page which receives the AuthSub token will be able to tell which URLs the token grants access to. Returns: A URL string to which the browser should be sent. """ if isinstance(scopes, list): scope = ' '.join(scopes) else: scope = scopes if include_scopes_in_next: if next.find('?') > -1: next += '&%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope}) else: next += '?%s' % urllib.urlencode({SCOPE_URL_PARAM_NAME:scope}) return gdata.auth.GenerateAuthSubUrl(next=next, scope=scope, secure=secure, session=session, request_url=request_url, domain=hd) class Query(dict): """Constructs a query URL to be used in GET requests Url parameters are created by adding key-value pairs to this object as a dict. For example, to add &max-results=25 to the URL do my_query['max-results'] = 25 Category queries are created by adding category strings to the categories member. All items in the categories list will be concatenated with the / symbol (symbolizing a category x AND y restriction). If you would like to OR 2 categories, append them as one string with a | between the categories. For example, do query.categories.append('Fritz|Laurie') to create a query like this feed/-/Fritz%7CLaurie . This query will look for results in both categories. """ def __init__(self, feed=None, text_query=None, params=None, categories=None): """Constructor for Query Args: feed: str (optional) The path for the feed (Examples: '/base/feeds/snippets' or 'calendar/feeds/jo@gmail.com/private/full' text_query: str (optional) The contents of the q query parameter. The contents of the text_query are URL escaped upon conversion to a URI. params: dict (optional) Parameter value string pairs which become URL params when translated to a URI. These parameters are added to the query's items (key-value pairs). categories: list (optional) List of category strings which should be included as query categories. See http://code.google.com/apis/gdata/reference.html#Queries for details. If you want to get results from category A or B (both categories), specify a single list item 'A|B'. """ self.feed = feed self.categories = [] if text_query: self.text_query = text_query if isinstance(params, dict): for param in params: self[param] = params[param] if isinstance(categories, list): for category in categories: self.categories.append(category) def _GetTextQuery(self): if 'q' in self.keys(): return self['q'] else: return None def _SetTextQuery(self, query): self['q'] = query text_query = property(_GetTextQuery, _SetTextQuery, doc="""The feed query's q parameter""") def _GetAuthor(self): if 'author' in self.keys(): return self['author'] else: return None def _SetAuthor(self, query): self['author'] = query author = property(_GetAuthor, _SetAuthor, doc="""The feed query's author parameter""") def _GetAlt(self): if 'alt' in self.keys(): return self['alt'] else: return None def _SetAlt(self, query): self['alt'] = query alt = property(_GetAlt, _SetAlt, doc="""The feed query's alt parameter""") def _GetUpdatedMin(self): if 'updated-min' in self.keys(): return self['updated-min'] else: return None def _SetUpdatedMin(self, query): self['updated-min'] = query updated_min = property(_GetUpdatedMin, _SetUpdatedMin, doc="""The feed query's updated-min parameter""") def _GetUpdatedMax(self): if 'updated-max' in self.keys(): return self['updated-max'] else: return None def _SetUpdatedMax(self, query): self['updated-max'] = query updated_max = property(_GetUpdatedMax, _SetUpdatedMax, doc="""The feed query's updated-max parameter""") def _GetPublishedMin(self): if 'published-min' in self.keys(): return self['published-min'] else: return None def _SetPublishedMin(self, query): self['published-min'] = query published_min = property(_GetPublishedMin, _SetPublishedMin, doc="""The feed query's published-min parameter""") def _GetPublishedMax(self): if 'published-max' in self.keys(): return self['published-max'] else: return None def _SetPublishedMax(self, query): self['published-max'] = query published_max = property(_GetPublishedMax, _SetPublishedMax, doc="""The feed query's published-max parameter""") def _GetStartIndex(self): if 'start-index' in self.keys(): return self['start-index'] else: return None def _SetStartIndex(self, query): if not isinstance(query, str): query = str(query) self['start-index'] = query start_index = property(_GetStartIndex, _SetStartIndex, doc="""The feed query's start-index parameter""") def _GetMaxResults(self): if 'max-results' in self.keys(): return self['max-results'] else: return None def _SetMaxResults(self, query): if not isinstance(query, str): query = str(query) self['max-results'] = query max_results = property(_GetMaxResults, _SetMaxResults, doc="""The feed query's max-results parameter""") def _GetOrderBy(self): if 'orderby' in self.keys(): return self['orderby'] else: return None def _SetOrderBy(self, query): self['orderby'] = query orderby = property(_GetOrderBy, _SetOrderBy, doc="""The feed query's orderby parameter""") def ToUri(self): q_feed = self.feed or '' category_string = '/'.join( [urllib.quote_plus(c) for c in self.categories]) # Add categories to the feed if there are any. if len(self.categories) > 0: q_feed = q_feed + '/-/' + category_string return atom.service.BuildUri(q_feed, self) def __str__(self): return self.ToUri()
Python
#!/usr/bin/env python # # Copyright 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. """Provides classes and constants for XML in the Google Project Hosting API. Canonical documentation for the raw XML which these classes represent can be found here: http://code.google.com/p/support/wiki/IssueTrackerAPI """ __author__ = 'jlapenna@google.com (Joe LaPenna)' import atom.core import gdata.data ISSUES_TEMPLATE = '{http://schemas.google.com/projecthosting/issues/2009}%s' ISSUES_FULL_FEED = '/feeds/issues/p/%s/issues/full' COMMENTS_FULL_FEED = '/feeds/issues/p/%s/issues/%s/comments/full' class Uri(atom.core.XmlElement): """The issues:uri element.""" _qname = ISSUES_TEMPLATE % 'uri' class Username(atom.core.XmlElement): """The issues:username element.""" _qname = ISSUES_TEMPLATE % 'username' class Cc(atom.core.XmlElement): """The issues:cc element.""" _qname = ISSUES_TEMPLATE % 'cc' uri = Uri username = Username class Label(atom.core.XmlElement): """The issues:label element.""" _qname = ISSUES_TEMPLATE % 'label' class Owner(atom.core.XmlElement): """The issues:owner element.""" _qname = ISSUES_TEMPLATE % 'owner' uri = Uri username = Username class Stars(atom.core.XmlElement): """The issues:stars element.""" _qname = ISSUES_TEMPLATE % 'stars' class State(atom.core.XmlElement): """The issues:state element.""" _qname = ISSUES_TEMPLATE % 'state' class Status(atom.core.XmlElement): """The issues:status element.""" _qname = ISSUES_TEMPLATE % 'status' class Summary(atom.core.XmlElement): """The issues:summary element.""" _qname = ISSUES_TEMPLATE % 'summary' class OwnerUpdate(atom.core.XmlElement): """The issues:ownerUpdate element.""" _qname = ISSUES_TEMPLATE % 'ownerUpdate' class CcUpdate(atom.core.XmlElement): """The issues:ccUpdate element.""" _qname = ISSUES_TEMPLATE % 'ccUpdate' class Updates(atom.core.XmlElement): """The issues:updates element.""" _qname = ISSUES_TEMPLATE % 'updates' summary = Summary status = Status ownerUpdate = OwnerUpdate label = [Label] ccUpdate = [CcUpdate] class IssueEntry(gdata.data.GDEntry): """Represents the information of one issue.""" _qname = atom.data.ATOM_TEMPLATE % 'entry' owner = Owner cc = [Cc] label = [Label] stars = Stars state = State status = Status class IssuesFeed(gdata.data.GDFeed): """An Atom feed listing a project's issues.""" entry = [IssueEntry] class CommentEntry(gdata.data.GDEntry): """An entry detailing one comment on an issue.""" _qname = atom.data.ATOM_TEMPLATE % 'entry' updates = Updates class CommentsFeed(gdata.data.GDFeed): """An Atom feed listing a project's issue's comments.""" entry = [CommentEntry]
Python
#!/usr/bin/env python # # Copyright 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import atom.data import gdata.client import gdata.gauth import gdata.projecthosting.data class ProjectHostingClient(gdata.client.GDClient): """Client to interact with the Project Hosting GData API.""" api_version = '1.0' auth_service = 'code' auth_scopes = gdata.gauth.AUTH_SCOPES['code'] host = 'code.google.com' ssl = True def get_issues(self, project_name, desired_class=gdata.projecthosting.data.IssuesFeed, **kwargs): """Get a feed of issues for a particular project. Args: project_name str The name of the project. query Query Set returned issues parameters. Returns: data.IssuesFeed """ return self.get_feed(gdata.projecthosting.data.ISSUES_FULL_FEED % project_name, desired_class=desired_class, **kwargs) def add_issue(self, project_name, title, content, author, status=None, owner=None, labels=None, ccs=None, **kwargs): """Create a new issue for the project. Args: project_name str The name of the project. title str The title of the new issue. content str The summary of the new issue. author str The authenticated user's username. status str The status of the new issue, Accepted, etc. owner str The username of new issue's owner. labels [str] Labels to associate with the new issue. ccs [str] usernames to Cc on the new issue. Returns: data.IssueEntry """ new_entry = gdata.projecthosting.data.IssueEntry( title=atom.data.Title(text=title), content=atom.data.Content(text=content), author=[atom.data.Author(name=atom.data.Name(text=author))]) if status: new_entry.status = gdata.projecthosting.data.Status(text=status) if owner: owner = [gdata.projecthosting.data.Owner( username=gdata.projecthosting.data.Username(text=owner))] if labels: new_entry.label = [gdata.projecthosting.data.Label(text=label) for label in labels] if ccs: new_entry.cc = [ gdata.projecthosting.data.Cc( username=gdata.projecthosting.data.Username(text=cc)) for cc in ccs] return self.post( new_entry, gdata.projecthosting.data.ISSUES_FULL_FEED % project_name, **kwargs) def update_issue(self, project_name, issue_id, author, comment=None, summary=None, status=None, owner=None, labels=None, ccs=None, **kwargs): """Update or comment on one issue for the project. Args: project_name str The name of the issue's project. issue_id str The issue number needing updated. author str The authenticated user's username. comment str A comment to append to the issue summary str Rewrite the summary of the issue. status str A new status for the issue. owner str The username of the new owner. labels [str] Labels to set on the issue (prepend issue with - to remove a label). ccs [str] Ccs to set on th enew issue (prepend cc with - to remove a cc). Returns: data.CommentEntry """ updates = gdata.projecthosting.data.Updates() if summary: updates.summary = gdata.projecthosting.data.Summary(text=summary) if status: updates.status = gdata.projecthosting.data.Status(text=status) if owner: updates.ownerUpdate = gdata.projecthosting.data.OwnerUpdate(text=owner) if labels: updates.label = [gdata.projecthosting.data.Label(text=label) for label in labels] if ccs: updates.ccUpdate = [gdata.projecthosting.data.CcUpdate(text=cc) for cc in ccs] update_entry = gdata.projecthosting.data.CommentEntry( content=atom.data.Content(text=comment), author=[atom.data.Author(name=atom.data.Name(text=author))], updates=updates) return self.post( update_entry, gdata.projecthosting.data.COMMENTS_FULL_FEED % (project_name, issue_id), **kwargs) def get_comments(self, project_name, issue_id, desired_class=gdata.projecthosting.data.CommentsFeed, **kwargs): """Get a feed of all updates to an issue. Args: project_name str The name of the issue's project. issue_id str The issue number needing updated. Returns: data.CommentsFeed """ return self.get_feed( gdata.projecthosting.data.COMMENTS_FULL_FEED % (project_name, issue_id), desired_class=desired_class, **kwargs) def update(self, entry, auth_token=None, force=False, **kwargs): """Unsupported GData update method. Use update_*() instead. """ raise NotImplementedError( 'GData Update operation unsupported, try update_*') def delete(self, entry_or_uri, auth_token=None, force=False, **kwargs): """Unsupported GData delete method. Use update_issue(status='Closed') instead. """ raise NotImplementedError( 'GData Delete API unsupported, try closing the issue instead.') class Query(gdata.client.Query): def __init__(self, issue_id=None, label=None, canned_query=None, owner=None, status=None, **kwargs): """Constructs a Google Data Query to filter feed contents serverside. Args: issue_id: int or str The issue to return based on the issue id. label: str A label returned issues must have. canned_query: str Return issues based on a canned query identifier owner: str Return issues based on the owner of the issue. For Gmail users, this will be the part of the email preceding the '@' sign. status: str Return issues based on the status of the issue. """ super(Query, self).__init__(**kwargs) self.label = label self.issue_id = issue_id self.canned_query = canned_query self.owner = owner self.status = status def modify_request(self, http_request): if self.issue_id: gdata.client._add_query_param('id', self.issue_id, http_request) if self.label: gdata.client._add_query_param('label', self.label, http_request) if self.canned_query: gdata.client._add_query_param('can', self.canned_query, http_request) if self.owner: gdata.client._add_query_param('owner', self.owner, http_request) if self.status: gdata.client._add_query_param('status', self.status, http_request) super(Query, self).modify_request(http_request) ModifyRequest = modify_request
Python
#!/usr/bin/python # # Copyright (C) 2010-2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """GData definitions for Content API for Shopping""" __author__ = 'afshar (Ali Afshar), dhermes (Daniel Hermes)' import atom.core import atom.data import gdata.data SC_NAMESPACE_TEMPLATE = ('{http://schemas.google.com/' 'structuredcontent/2009}%s') SCP_NAMESPACE_TEMPLATE = ('{http://schemas.google.com/' 'structuredcontent/2009/products}%s') # Content API for Shopping, general (sc) attributes class ProductId(atom.core.XmlElement): """sc:id element It is required that all inserted products are provided with a unique alphanumeric ID, in this element. """ _qname = SC_NAMESPACE_TEMPLATE % 'id' class ImageLink(atom.core.XmlElement): """sc:image_link element This is the URL of an associated image for a product. Please use full size images (400x400 pixels or larger), not thumbnails. """ _qname = SC_NAMESPACE_TEMPLATE % 'image_link' class AdditionalImageLink(atom.core.XmlElement): """sc:additional_image_link element The URLs of any additional images for the product. This tag may be repeated. """ _qname = SC_NAMESPACE_TEMPLATE % 'additional_image_link' class ContentLanguage(atom.core.XmlElement): """ sc:content_language element Language used in the item content for the product """ _qname = SC_NAMESPACE_TEMPLATE % 'content_language' class TargetCountry(atom.core.XmlElement): """ sc:target_country element The target country of the product """ _qname = SC_NAMESPACE_TEMPLATE % 'target_country' class ExpirationDate(atom.core.XmlElement): """sc:expiration_date This is the date when the product listing will expire. If omitted, this will default to 30 days after the product was created. """ _qname = SC_NAMESPACE_TEMPLATE % 'expiration_date' class Adult(atom.core.XmlElement): """sc:adult element Indicates whether the content is targeted towards adults, with possible values of "true" or "false". Defaults to "false". """ _qname = SC_NAMESPACE_TEMPLATE % 'adult' # Destination Attributes (to be used with app:control element) class RequiredDestination(atom.core.XmlElement): """sc:required_destination element This element defines the required destination for a product, namely "ProductSearch", "ProductAds" or "CommerceSearch". It should be added to the app:control element (ProductEntry's "control" attribute) to specify where the product should appear in search APIs. By default, when omitted, the api attempts to upload to as many destinations as possible. """ _qname = SC_NAMESPACE_TEMPLATE % 'required_destination' dest = 'dest' class ExcludedDestination(atom.core.XmlElement): """sc:excluded_destination element This element defines the required destination for a product, namely "ProductSearch", "ProductAds" or "CommerceSearch". It should be added to the app:control element (ProductEntry's "control" attribute) to specify where the product should not appear in search APIs. By default, when omitted, the api attempts to upload to as many destinations as possible. """ _qname = SC_NAMESPACE_TEMPLATE % 'excluded_destination' dest = 'dest' # Warning Attributes (to be used with app:control element) class Code(atom.core.XmlElement): """sc:code element The warning code. Currently validation/missing_recommended is the only code used. """ _qname = SC_NAMESPACE_TEMPLATE % 'code' class Domain(atom.core.XmlElement): """sc:domain element The scope of the warning. A comma-separated list of destinations, for example: ProductSearch. """ _qname = SC_NAMESPACE_TEMPLATE % 'domain' class Location(atom.core.XmlElement): """sc:location element The name of the product element that has raised the warning. This may be any valid product element. """ _qname = SC_NAMESPACE_TEMPLATE % 'location' class Message(atom.core.XmlElement): """sc:message element A plain text description of the warning. """ _qname = SC_NAMESPACE_TEMPLATE % 'message' class WarningElement(atom.core.XmlElement): """sc:warning element Container element for an individual warning. """ _qname = SC_NAMESPACE_TEMPLATE % 'warning' code = Code domain = Domain location = Location message = Message class Warnings(atom.core.XmlElement): """sc:warnings element Container element for the list of warnings. """ _qname = SC_NAMESPACE_TEMPLATE % 'warnings' warnings = [WarningElement] class ProductControl(atom.data.Control): """ app:control element overridden to provide additional elements in the sc namespace. """ required_destination = RequiredDestination excluded_destination = ExcludedDestination warnings = Warnings # Content API for Shopping, product (scp) attributes class Author(atom.core.XmlElement): """ scp:author element Defines the author of the information, recommended for books. """ _qname = SCP_NAMESPACE_TEMPLATE % 'author' class Availability(atom.core.XmlElement): """ scp:availability element The retailer's suggested label for product availability. Supported values include: 'in stock', 'out of stock', 'limited availability', 'available for order', and 'preorder'. """ _qname = SCP_NAMESPACE_TEMPLATE % 'availability' class Brand(atom.core.XmlElement): """ scp:brand element The brand of the product """ _qname = SCP_NAMESPACE_TEMPLATE % 'brand' class Channel(atom.core.XmlElement): """ scp:channel element The channel for the product. Supported values are: 'online', 'local' """ _qname = SCP_NAMESPACE_TEMPLATE % 'channel' class Color(atom.core.XmlElement): """scp:color element The color of the product. """ _qname = SCP_NAMESPACE_TEMPLATE % 'color' class Condition(atom.core.XmlElement): """scp:condition element The condition of the product, one of "new", "used", "refurbished" """ _qname = SCP_NAMESPACE_TEMPLATE % 'condition' class Edition(atom.core.XmlElement): """scp:edition element The edition of the product. Recommended for products with multiple editions such as collectors' editions etc, such as books. """ _qname = SCP_NAMESPACE_TEMPLATE % 'edition' class Feature(atom.core.XmlElement): """scp:feature element A product feature. A product may have multiple features, each being text, for example a smartphone may have features: "wifi", "gps" etc. """ _qname = SCP_NAMESPACE_TEMPLATE % 'feature' class FeaturedProduct(atom.core.XmlElement): """scp:featured_product element Used to indicate that this item is a special, featured product; Supported values are: "true", "false". """ _qname = SCP_NAMESPACE_TEMPLATE % 'featured_product' class Gender(atom.core.XmlElement): """scp:gender element The gender for the item. Supported values are: 'unisex', 'female', 'male' Note: This tag is required if the google product type is part of Apparel & Accessories. """ _qname = SCP_NAMESPACE_TEMPLATE % 'gender' class Genre(atom.core.XmlElement): """scp:genre element Describes the genre of a product, eg "comedy". Strongly recommended for media. """ _qname = SCP_NAMESPACE_TEMPLATE % 'genre' class GoogleProductCategory(atom.core.XmlElement): """scp:google_product_category element The product's google category. The value must be one of the categories listed in the Product type taxonomy, which can be found at http://www.google.com/support/merchants/bin/answer.py?answer=160081. Note that & and > characters must be encoded as &amp; and &gt; """ _qname = SCP_NAMESPACE_TEMPLATE % 'google_product_category' class Gtin(atom.core.XmlElement): """scp:gtin element GTIN of the product (isbn/upc/ean) """ _qname = SCP_NAMESPACE_TEMPLATE % 'gtin' class ItemGroupID(atom.core.XmlElement): """scp:item_group_id element The identifier for products with variants. This id is used to link items which have different values for the fields: 'color', 'material', 'pattern', 'size' but are the same item, for example a shirt with different sizes. Note: This tag is required for all product variants. """ _qname = SCP_NAMESPACE_TEMPLATE % 'item_group_id' class Manufacturer(atom.core.XmlElement): """scp:manufacturer element Manufacturer of the product. """ _qname = SCP_NAMESPACE_TEMPLATE % 'manufacturer' class Material(atom.core.XmlElement): """scp:material element The material the product is made of. """ _qname = SCP_NAMESPACE_TEMPLATE % 'material' class Mpn(atom.core.XmlElement): """scp:mpn element Manufacturer's Part Number. A unique code determined by the manufacturer for the product. """ _qname = SCP_NAMESPACE_TEMPLATE % 'mpn' class Pattern(atom.core.XmlElement): """scp:pattern element The pattern of the product. (e.g. polka dots) """ _qname = SCP_NAMESPACE_TEMPLATE % 'pattern' class Price(atom.core.XmlElement): """scp:price element The price of the product. The unit attribute must be set, and should represent the currency. Note: Required Element """ _qname = SCP_NAMESPACE_TEMPLATE % 'price' unit = 'unit' class ProductType(atom.core.XmlElement): """scp:product_type element Describes the type of product. A taxonomy of available product types is listed at http://www.google.com/basepages/producttype/taxonomy.txt and the entire line in the taxonomy should be included, for example "Electronics > Video > Projectors". """ _qname = SCP_NAMESPACE_TEMPLATE % 'product_type' class Quantity(atom.core.XmlElement): """scp:quantity element The number of items available. A value of 0 indicates items that are currently out of stock. """ _qname = SCP_NAMESPACE_TEMPLATE % 'quantity' class ShippingPrice(atom.core.XmlElement): """scp:shipping_price element Fixed shipping price, represented as a number. Specify the currency as the "unit" attribute". This element should be placed inside the scp:shipping element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'shipping_price' unit = 'unit' class ShippingCountry(atom.core.XmlElement): """scp:shipping_country element The two-letter ISO 3166 country code for the country to which an item will ship. This element should be placed inside the scp:shipping element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'shipping_country' class ShippingRegion(atom.core.XmlElement): """scp:shipping_region element The geographic region to which a shipping rate applies, e.g., in the US, the two-letter state abbreviation, ZIP code, or ZIP code range using * wildcard. This element should be placed inside the scp:shipping element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'shipping_region' class ShippingService(atom.core.XmlElement): """scp:shipping_service element A free-form description of the service class or delivery speed. This element should be placed inside the scp:shipping element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'shipping_service' class Shipping(atom.core.XmlElement): """scp:shipping element Container for the shipping rules as provided by the shipping_country, shipping_price, shipping_region and shipping_service tags. """ _qname = SCP_NAMESPACE_TEMPLATE % 'shipping' shipping_price = ShippingPrice shipping_country = ShippingCountry shipping_service = ShippingService shipping_region = ShippingRegion class ShippingWeight(atom.core.XmlElement): """scp:shipping_weight element The shipping weight of a product. Requires a value and a unit using the unit attribute. Valid units include lb, pound, oz, ounce, g, gram, kg, kilogram. """ _qname = SCP_NAMESPACE_TEMPLATE % 'shipping_weight' unit = 'unit' class Size(atom.core.XmlElement): """scp:size element Available sizes of an item. Appropriate values include: "small", "medium", "large", etc. The product enttry may contain multiple sizes, to indicate the available sizes. """ _qname = SCP_NAMESPACE_TEMPLATE % 'size' class TaxRate(atom.core.XmlElement): """scp:tax_rate element The tax rate as a percent of the item price, i.e., number, as a percentage. This element should be placed inside the scp:tax (Tax class) element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'tax_rate' class TaxCountry(atom.core.XmlElement): """scp:tax_country element The country an item is taxed in (as a two-letter ISO 3166 country code). This element should be placed inside the scp:tax (Tax class) element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'tax_country' class TaxRegion(atom.core.XmlElement): """scp:tax_region element The geographic region that a tax rate applies to, e.g., in the US, the two-letter state abbreviation, ZIP code, or ZIP code range using * wildcard. This element should be placed inside the scp:tax (Tax class) element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'tax_region' class TaxShip(atom.core.XmlElement): """scp:tax_ship element Whether tax is charged on shipping for this product. The default value is "false". This element should be placed inside the scp:tax (Tax class) element. """ _qname = SCP_NAMESPACE_TEMPLATE % 'tax_ship' class Tax(atom.core.XmlElement): """scp:tax element Container for the tax rules for this product. Containing the tax_rate, tax_country, tax_region, and tax_ship elements """ _qname = SCP_NAMESPACE_TEMPLATE % 'tax' tax_rate = TaxRate tax_country = TaxCountry tax_region = TaxRegion tax_ship = TaxShip class Year(atom.core.XmlElement): """scp:year element The year the product was produced. Expects four digits """ _qname = SCP_NAMESPACE_TEMPLATE % 'year' class ProductEntry(gdata.data.BatchEntry): """Product entry containing product information The elements of this entry that are used are made up of five different namespaces. They are: atom: - Atom app: - Atom Publishing Protocol gd: - Google Data API sc: - Content API for Shopping, general attributes scp: - Content API for Shopping, product attributes Only the sc and scp namespace elements are defined here, but additional useful elements are defined in superclasses. The following attributes are encoded as XML elements in the Atomn (atom:) namespace: title, link, entry, id, category, content, author, created updated. Among these, the title, content and link tags are part of the required Content for Shopping API so we document them here. .. attribute:: title The title of the product. This should be a :class:`atom.data.Title` element, for example:: entry = ProductEntry() entry.title = atom.data.Title(u'32GB MP3 Player') .. attribute:: content The description of the item. This should be a :class:`atom.data.Content` element, for example:: entry = ProductEntry() entry.content = atom.data.Content('My item description') .. attribute:: link A link to a page where the item can be purchased. This should be a :class:`atom.data.Link` element, for example:: link = atom.data.Link(rel='alternate', type='text/html', href='http://www.somehost.com/123456jsh9') entry = ProductEntry() entry.link.append(link) .. attribute:: additional_image_link A list of additional links to images of the product. Each link should be an :class:`AdditionalImageLink` element, for example:: entry = ProductEntry() entry.additional_image_link.append( AdditionalImageLink('http://myshop/cdplayer.jpg')) .. attribute:: author The author of the product. This should be a :class:`Author` element, for example:: entry = ProductEntry() entry.author = atom.data.Author(u'Isaac Asimov') .. attribute:: availability The avilability of a product. This should be an :class:`Availability` instance, for example:: entry = ProductEntry() entry.availability = Availability('in stock') .. attribute:: brand The brand of a product. This should be a :class:`Brand` element, for example:: entry = ProductEntry() entry.brand = Brand(u'Sony') .. attribute:: channel The channel for the product. Supported values are: 'online', 'local' This should be a :class:`Channel` element, for example:: entry = ProductEntry() entry.channel = Channel('online') .. attribute:: color The color of a product. This should be a :class:`Color` element, for example:: entry = ProductEntry() entry.color = Color(u'purple') .. attribute:: condition The condition of a product. This should be a :class:`Condition` element, for example:: entry = ProductEntry() entry.condition = Condition(u'new') .. attribute:: content_language The language for the product. This should be a :class:`ContentLanguage` element, for example:: entry = ProductEntry() entry.content_language = ContentLanguage('EN') .. attribute:: control Overrides :class:`atom.data.Control` to provide additional elements required_destination and excluded_destination in the sc namespace This should be a :class:`ProductControl` element. .. attribute:: edition The edition of the product. This should be a :class:`Edition` element, for example:: entry = ProductEntry() entry.edition = Edition('1') .. attribute:: expiration_date The expiration date of this product listing. This should be a :class:`ExpirationDate` element, for example:: entry = ProductEntry() entry.expiration_date = ExpirationDate('2011-22-03') .. attribute:: feature A list of features for this product. Each feature should be a :class:`Feature` element, for example:: entry = ProductEntry() entry.feature.append(Feature(u'wifi')) entry.feature.append(Feature(u'gps')) .. attribute:: featured_product Whether the product is featured. This should be a :class:`FeaturedProduct` element, for example:: entry = ProductEntry() entry.featured_product = FeaturedProduct('true') .. attribute:: gender The gender for the item. Supported values are: 'unisex', 'female', 'male' This should be a :class:`Gender` element, for example:: entry = ProductEntry() entry.gender = Gender('female') .. attribute:: genre The genre of the product. This should be a :class:`Genre` element, for example:: entry = ProductEntry() entry.genre = Genre(u'comedy') .. attribute:: google_product_category The product's google category. Value must come from taxonomy listed at http://www.google.com/support/merchants/bin/answer.py?answer=160081 This should be a :class:`GoogleProductCategory` element, for example:: entry = ProductEntry() entry.google_product_category = GoogleProductCategory( 'Animals &gt; Live Animals') .. attribute:: gtin The gtin for this product. This should be a :class:`Gtin` element, for example:: entry = ProductEntry() entry.gtin = Gtin('A888998877997') .. attribute:: image_link A link to the product image. This link should be an :class:`ImageLink` element, for example:: entry = ProductEntry() entry.image_link = ImageLink('http://myshop/cdplayer.jpg') .. attribute:: item_group_id The identifier for products with variants. This id is used to link items which have different values for the fields: 'color', 'material', 'pattern', 'size' but are the same item, for example a shirt with different sizes. This should be a :class:`ItemGroupID` element, for example:: entry = ProductEntry() entry.item_group_id = ItemGroupID('R1726122') .. attribute:: manufacturer The manufacturer of the product. This should be a :class:`Manufacturer` element, for example:: entry = ProductEntry() entry.manufacturer = Manufacturer('Sony') .. attribute:: material The material the product is made of. This should be a :class:`Material` element, for example:: entry = ProductEntry() entry.material = Material('cotton') .. attribute:: mpn The manufacturer's part number for this product. This should be a :class:`Mpn` element, for example:: entry = ProductEntry() entry.mpn = Mpn('cd700199US') .. attribute:: pattern The pattern of the product. This should be a :class:`Pattern` element, for example:: entry = ProductEntry() entry.pattern = Pattern('polka dots') .. attribute:: price The price for this product. This should be a :class:`Price` element, including a unit argument to indicate the currency, for example:: entry = ProductEntry() entry.price = Price('20.00', unit='USD') .. attribute:: product_id A link to the product image. This link should be an :class:`ProductId` element, for example:: entry = ProductEntry() entry.product_id = ProductId('ABC1234') .. attribute:: product_type The type of product. This should be a :class:`ProductType` element, for example:: entry = ProductEntry() entry.product_type = ProductType("Electronics > Video > Projectors") .. attribute:: quantity The quantity of product available in stock. This should be a :class:`Quantity` element, for example:: entry = ProductEntry() entry.quantity = Quantity('100') .. attribute:: shipping The shipping rules for the product. This should be a :class:`Shipping` with the necessary rules embedded as elements, for example:: entry = ProductEntry() entry.shipping = Shipping() entry.shipping.shipping_price = ShippingPrice('10.00', unit='USD') .. attribute:: shipping_weight The shipping weight for this product. This should be a :class:`ShippingWeight` element, including a unit parameter for the unit of weight, for example:: entry = ProductEntry() entry.shipping_weight = ShippingWeight('10.45', unit='kg') .. attribute:: size A list of the available sizes for this product. Each item in this list should be a :class:`Size` element, for example:: entry = ProductEntry() entry.size.append(Size('Small')) entry.size.append(Size('Medium')) entry.size.append(Size('Large')) .. attribute:: target_country The target country for the product. This should be a :class:`TargetCountry` element, for example:: entry = ProductEntry() entry.target_country = TargetCountry('US') .. attribute:: tax The tax rules for this product. This should be a :class:`Tax` element, with the tax rule elements embedded within, for example:: tax = Tax() tax.tax_rate = TaxRate('17.5') entry = ProductEntry() entry.tax.append(tax) .. attribute:: year The year the product was created. This should be a :class:`Year` element, for example:: entry = ProductEntry() entry.year = Year('2001') """ additional_image_link = [AdditionalImageLink] author = Author availability = Availability brand = Brand channel = Channel color = Color condition = Condition content_language = ContentLanguage control = ProductControl edition = Edition expiration_date = ExpirationDate feature = [Feature] featured_product = FeaturedProduct gender = Gender genre = Genre google_product_category = GoogleProductCategory gtin = Gtin image_link = ImageLink item_group_id = ItemGroupID manufacturer = Manufacturer material = Material mpn = Mpn pattern = Pattern price = Price product_id = ProductId product_type = ProductType quantity = Quantity shipping = Shipping shipping_weight = ShippingWeight size = [Size] target_country = TargetCountry tax = [Tax] year = Year # opensearch needs overriding for wrong version # see http://code.google.com/p/gdata-python-client/issues/detail?id=483 class TotalResults(gdata.data.TotalResults): _qname = gdata.data.TotalResults._qname[1] class ItemsPerPage(gdata.data.ItemsPerPage): _qname = gdata.data.ItemsPerPage._qname[1] class StartIndex(gdata.data.StartIndex): _qname = gdata.data.StartIndex._qname[1] class ProductFeed(gdata.data.BatchFeed): """Represents a feed of a merchant's products.""" entry = [ProductEntry] total_results = TotalResults items_per_page = ItemsPerPage start_index = StartIndex class Edited(atom.core.XmlElement): """sc:edited element """ _qname = SC_NAMESPACE_TEMPLATE % 'edited' class AttributeLanguage(atom.core.XmlElement): """sc:attribute_language element """ _qname = SC_NAMESPACE_TEMPLATE % 'attribute_language' class FeedFileName(atom.core.XmlElement): """sc:feed_file_name element """ _qname = SC_NAMESPACE_TEMPLATE % 'feed_file_name' class FeedType(atom.core.XmlElement): """sc:feed_type element """ _qname = SC_NAMESPACE_TEMPLATE % 'feed_type' class UseQuotedFields(atom.core.XmlElement): """sc:use_quoted_fields element """ _qname = SC_NAMESPACE_TEMPLATE % 'use_quoted_fields' class FileFormat(atom.core.XmlElement): """sc:file_format element """ _qname = SC_NAMESPACE_TEMPLATE % 'file_format' use_quoted_fields = UseQuotedFields format = 'format' class ProcessingStatus(atom.core.XmlElement): """sc:processing_status element """ _qname = SC_NAMESPACE_TEMPLATE % 'processing_status' class DatafeedEntry(gdata.data.GDEntry): """An entry for a Datafeed """ content_language = ContentLanguage target_country = TargetCountry feed_file_name = FeedFileName file_format = FileFormat attribute_language = AttributeLanguage processing_status = ProcessingStatus edited = Edited feed_type = FeedType class DatafeedFeed(gdata.data.GDFeed): """A datafeed feed """ entry = [DatafeedEntry] class AdultContent(atom.core.XmlElement): """sc:adult_content element """ _qname = SC_NAMESPACE_TEMPLATE % 'adult_content' class InternalId(atom.core.XmlElement): """sc:internal_id element """ _qname = SC_NAMESPACE_TEMPLATE % 'internal_id' class ReviewsUrl(atom.core.XmlElement): """sc:reviews_url element """ _qname = SC_NAMESPACE_TEMPLATE % 'reviews_url' class ClientAccount(gdata.data.GDEntry): """A multiclient account entry """ adult_content = AdultContent internal_id = InternalId reviews_url = ReviewsUrl class ClientAccountFeed(gdata.data.GDFeed): """A multiclient account feed """ entry = [ClientAccount]
Python
#!/usr/bin/python # # Copyright (C) 2010-2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Extend the gdata client for the Content API for Shopping. TODO: 1. Proper MCA Support. 2. Add classes for datafeed functions instead of asking for raw XML. """ __author__ = 'afshar (Ali Afshar), dhermes (Daniel Hermes)' import atom.data import gdata.client from gdata.contentforshopping.data import ClientAccount from gdata.contentforshopping.data import ClientAccountFeed from gdata.contentforshopping.data import DatafeedEntry from gdata.contentforshopping.data import DatafeedFeed from gdata.contentforshopping.data import ProductEntry from gdata.contentforshopping.data import ProductFeed CFS_VERSION = 'v1' CFS_HOST = 'content.googleapis.com' CFS_URI = 'https://%s/content' % CFS_HOST CFS_PROJECTION = 'generic' class ContentForShoppingClient(gdata.client.GDClient): """Client for Content for Shopping API. :param account_id: Merchant account ID. This value will be used by default for all requests, but may be overridden on a request-by-request basis. :param api_version: The version of the API to target. Default value: 'v1'. :param **kwargs: Pass all addtional keywords to the GDClient constructor. """ api_version = '1.0' def __init__(self, account_id=None, api_version=CFS_VERSION, **kwargs): self.cfs_account_id = account_id self.cfs_api_version = api_version gdata.client.GDClient.__init__(self, **kwargs) def _create_uri(self, account_id, resource, path=(), use_projection=True, dry_run=False, warnings=False): """Create a request uri from the given arguments. If arguments are None, use the default client attributes. """ account_id = account_id or self.cfs_account_id if account_id is None: raise ValueError('No Account ID set. ' 'Either set for the client, or per request') segments = [CFS_URI, self.cfs_api_version, account_id, resource] if use_projection: segments.append(CFS_PROJECTION) segments.extend(path) result = '/'.join(segments) request_params = [] if dry_run: request_params.append('dry-run') if warnings: request_params.append('warnings') request_params = '&'.join(request_params) if request_params: result = '%s?%s' % (result, request_params) return result def _create_product_id(self, id, country, language): return 'online:%s:%s:%s' % (language, country, id) def _create_batch_feed(self, entries, operation, feed=None): if feed is None: feed = ProductFeed() for entry in entries: entry.batch_operation = gdata.data.BatchOperation(type=operation) feed.entry.append(entry) return feed # Operations on a single product def get_product(self, id, country, language, account_id=None, auth_token=None): """Get a product by id, country and language. :param id: The product ID :param country: The country (target_country) :param language: The language (content_language) :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. """ pid = self._create_product_id(id, country, language) uri = self._create_uri(account_id, 'items/products', path=[pid]) return self.get_entry(uri, desired_class=ProductEntry, auth_token=auth_token) def insert_product(self, product, account_id=None, auth_token=None, dry_run=False, warnings=False): """Create a new product, by posting the product entry feed. :param product: A :class:`gdata.contentforshopping.data.ProductEntry` with the required product data. :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. :param dry_run: Flag to run all requests that modify persistent data in dry-run mode. False by default. :param warnings: Flag to include warnings in response. False by default. """ uri = self._create_uri(account_id, 'items/products', dry_run=dry_run, warnings=warnings) return self.post(product, uri=uri, auth_token=auth_token) def update_product(self, product, account_id=None, auth_token=None, dry_run=False, warnings=False): """Update a product, by putting the product entry feed. :param product: A :class:`gdata.contentforshopping.data.ProductEntry` with the required product data. :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. :param dry_run: Flag to run all requests that modify persistent data in dry-run mode. False by default. :param warnings: Flag to include warnings in response. False by default. """ pid = self._create_product_id(product.product_id.text, product.target_country.text, product.content_language.text) uri = self._create_uri(account_id, 'items/products', path=[pid], dry_run=dry_run, warnings=warnings) return self.update(product, uri=uri, auth_token=auth_token) def delete_product(self, product, account_id=None, auth_token=None, dry_run=False, warnings=False): """Delete a product :param product: A :class:`gdata.contentforshopping.data.ProductEntry` with the required product data. :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. :param dry_run: Flag to run all requests that modify persistent data in dry-run mode. False by default. :param warnings: Flag to include warnings in response. False by default. """ pid = self._create_product_id(product.product_id.text, product.target_country.text, product.content_language.text) uri = self._create_uri(account_id, 'items/products', path=[pid], dry_run=dry_run, warnings=warnings) return self.delete(uri, auth_token=auth_token) # Operations on multiple products def get_products(self, start_index=None, max_results=None, account_id=None, auth_token=None): """Get a feed of products for the account. :param max_results: The maximum number of results to return (default 25, maximum 250). :param start_index: The starting index of the feed to return (default 1, maximum 10000) :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. """ uri = self._create_uri(account_id, 'items/products') return self.get_feed(uri, auth_token=auth_token, desired_class=gdata.contentforshopping.data.ProductFeed) def batch(self, feed, account_id=None, auth_token=None, dry_run=False, warnings=False): """Send a batch request. :param feed: The feed of batch entries to send. :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. :param dry_run: Flag to run all requests that modify persistent data in dry-run mode. False by default. :param warnings: Flag to include warnings in response. False by default. """ uri = self._create_uri(account_id, 'items/products', path=['batch'], dry_run=dry_run, warnings=warnings) return self.post(feed, uri=uri, auth_token=auth_token, desired_class=ProductFeed) def insert_products(self, products, account_id=None, auth_token=None, dry_run=False, warnings=False): """Insert the products using a batch request :param products: A list of product entries :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. :param dry_run: Flag to run all requests that modify persistent data in dry-run mode. False by default. :param warnings: Flag to include warnings in response. False by default. """ feed = self._create_batch_feed(products, 'insert') return self.batch(feed) def update_products(self, products, account_id=None, auth_token=None, dry_run=False, warnings=False): """Update the products using a batch request :param products: A list of product entries :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. :param dry_run: Flag to run all requests that modify persistent data in dry-run mode. False by default. :param warnings: Flag to include warnings in response. False by default. .. note:: Entries must have the atom:id element set. """ feed = self._create_batch_feed(products, 'update') return self.batch(feed) def delete_products(self, products, account_id=None, auth_token=None, dry_run=False, warnings=False): """Delete the products using a batch request. :param products: A list of product entries :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. :param dry_run: Flag to run all requests that modify persistent data in dry-run mode. False by default. :param warnings: Flag to include warnings in response. False by default. .. note:: Entries must have the atom:id element set. """ feed = self._create_batch_feed(products, 'delete') return self.batch(feed) # Operations on datafeeds def get_datafeeds(self, account_id=None): """Get the feed of datafeeds. :param account_id: The Sub-Account ID. If ommitted the default Account ID will be used for this client. """ uri = self._create_uri(account_id, 'datafeeds/products', use_projection=False) return self.get_feed(uri, desired_class=DatafeedFeed) # Operations on a single datafeed def get_datafeed(self, feed_id, account_id=None, auth_token=None): """Get the feed of a single datafeed. :param feed_id: The ID of the desired datafeed. :param account_id: The Sub-Account ID. If ommitted the default Account ID will be used for this client. :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. """ uri = self._create_uri(account_id, 'datafeeds/products', path=[feed_id], use_projection=False) return self.get_feed(uri, auth_token=auth_token, desired_class=DatafeedEntry) def insert_datafeed(self, entry, account_id=None, auth_token=None, dry_run=False, warnings=False): """Insert a datafeed. :param entry: XML Content of post request required for registering a datafeed. :param account_id: The Sub-Account ID. If ommitted the default Account ID will be used for this client. :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. :param dry_run: Flag to run all requests that modify persistent data in dry-run mode. False by default. :param warnings: Flag to include warnings in response. False by default. """ uri = self._create_uri(account_id, 'datafeeds/products', use_projection=False, dry_run=dry_run, warnings=warnings) return self.post(entry, uri=uri, auth_token=auth_token) def update_datafeed(self, entry, feed_id, account_id=None, auth_token=None, dry_run=False, warnings=False): """Update the feed of a single datafeed. :param entry: XML Content of put request required for updating a datafeed. :param feed_id: The ID of the desired datafeed. :param account_id: The Sub-Account ID. If ommitted the default Account ID will be used for this client. :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. :param dry_run: Flag to run all requests that modify persistent data in dry-run mode. False by default. :param warnings: Flag to include warnings in response. False by default. """ uri = self._create_uri(account_id, 'datafeeds/products', path=[feed_id], use_projection=False, dry_run=dry_run, warnings=warnings) return self.update(entry, auth_token=auth_token, uri=uri) def delete_datafeed(self, feed_id, account_id=None, auth_token=None): """Delete a single datafeed. :param feed_id: The ID of the desired datafeed. :param account_id: The Sub-Account ID. If ommitted the default Account ID will be used for this client. :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. """ uri = self._create_uri(account_id, 'datafeeds/products', path=[feed_id], use_projection=False) return self.delete(uri, auth_token=auth_token) # Operations on client accounts def get_client_accounts(self, account_id=None, auth_token=None): """Get the feed of managed accounts :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. """ uri = self._create_uri(account_id, 'managedaccounts/products', use_projection=False) return self.get_feed(uri, desired_class=ClientAccountFeed, auth_token=auth_token) def insert_client_account(self, entry, account_id=None, auth_token=None, dry_run=False, warnings=False): """Insert a client account entry :param entry: An entry of type ClientAccount :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. :param dry_run: Flag to run all requests that modify persistent data in dry-run mode. False by default. :param warnings: Flag to include warnings in response. False by default. """ uri = self._create_uri(account_id, 'managedaccounts/products', use_projection=False, dry_run=dry_run, warnings=warnings) return self.post(entry, uri=uri, auth_token=auth_token) def update_client_account(self, entry, client_account_id, account_id=None, auth_token=None, dry_run=False, warnings=False): """Update a client account :param entry: An entry of type ClientAccount to update to :param client_account_id: The client account ID :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. :param dry_run: Flag to run all requests that modify persistent data in dry-run mode. False by default. :param warnings: Flag to include warnings in response. False by default. """ uri = self._create_uri(account_id, 'managedaccounts/products', path=[client_account_id], use_projection=False, dry_run=dry_run, warnings=warnings) return self.update(entry, uri=uri, auth_token=auth_token) def delete_client_account(self, client_account_id, account_id=None, auth_token=None, dry_run=False, warnings=False): """Delete a client account :param client_account_id: The client account ID :param account_id: The Merchant Center Account ID. If ommitted the default Account ID will be used for this client :param auth_token: An object which sets the Authorization HTTP header in its modify_request method. :param dry_run: Flag to run all requests that modify persistent data in dry-run mode. False by default. :param warnings: Flag to include warnings in response. False by default. """ uri = self._create_uri(account_id, 'managedaccounts/products', path=[client_account_id], use_projection=False, dry_run=dry_run, warnings=warnings) return self.delete(uri, auth_token=auth_token)
Python
#!/usr/bin/python # # Copyright (C) 2010-2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Support for the Content API for Shopping See: http://code.google.com/apis/shopping/content/index.html """
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Provides utility functions used with command line samples.""" # This module is used for version 2 of the Google Data APIs. import sys import getpass import urllib import gdata.gauth __author__ = 'j.s@google.com (Jeff Scudder)' CLIENT_LOGIN = 1 AUTHSUB = 2 OAUTH = 3 HMAC = 1 RSA = 2 class SettingsUtil(object): """Gather's user preferences from flags or command prompts. An instance of this object stores the choices made by the user. At some point it might be useful to save the user's preferences so that they do not need to always set flags or answer preference prompts. """ def __init__(self, prefs=None): self.prefs = prefs or {} def get_param(self, name, prompt='', secret=False, ask=True, reuse=False): # First, check in this objects stored preferences. if name in self.prefs: return self.prefs[name] # Second, check for a command line parameter. value = None for i in xrange(len(sys.argv)): if sys.argv[i].startswith('--%s=' % name): value = sys.argv[i].split('=')[1] elif sys.argv[i] == '--%s' % name: value = sys.argv[i + 1] # Third, if it was not on the command line, ask the user to input the # value. if value is None and ask: prompt = '%s: ' % prompt if secret: value = getpass.getpass(prompt) else: value = raw_input(prompt) # If we want to save the preference for reuse in future requests, add it # to this object's prefs. if value is not None and reuse: self.prefs[name] = value return value def authorize_client(self, client, auth_type=None, service=None, source=None, scopes=None, oauth_type=None, consumer_key=None, consumer_secret=None): """Uses command line arguments, or prompts user for token values.""" if 'client_auth_token' in self.prefs: return if auth_type is None: auth_type = int(self.get_param( 'auth_type', 'Please choose the authorization mechanism you want' ' to use.\n' '1. to use your email address and password (ClientLogin)\n' '2. to use a web browser to visit an auth web page (AuthSub)\n' '3. if you have registed to use OAuth\n', reuse=True)) # Get the scopes for the services we want to access. if auth_type == AUTHSUB or auth_type == OAUTH: if scopes is None: scopes = self.get_param( 'scopes', 'Enter the URL prefixes (scopes) for the resources you ' 'would like to access.\nFor multiple scope URLs, place a comma ' 'between each URL.\n' 'Example: http://www.google.com/calendar/feeds/,' 'http://www.google.com/m8/feeds/\n', reuse=True).split(',') elif isinstance(scopes, (str, unicode)): scopes = scopes.split(',') if auth_type == CLIENT_LOGIN: email = self.get_param('email', 'Please enter your username', reuse=False) password = self.get_param('password', 'Password', True, reuse=False) if service is None: service = self.get_param( 'service', 'What is the name of the service you wish to access?' '\n(See list:' ' http://code.google.com/apis/gdata/faq.html#clientlogin)', reuse=True) if source is None: source = self.get_param('source', ask=False, reuse=True) client.client_login(email, password, source=source, service=service) elif auth_type == AUTHSUB: auth_sub_token = self.get_param('auth_sub_token', ask=False, reuse=True) session_token = self.get_param('session_token', ask=False, reuse=True) private_key = None auth_url = None single_use_token = None rsa_private_key = self.get_param( 'rsa_private_key', 'If you want to use secure mode AuthSub, please provide the\n' ' location of your RSA private key which corresponds to the\n' ' certificate you have uploaded for your domain. If you do not\n' ' have an RSA key, simply press enter', reuse=True) if rsa_private_key: try: private_key_file = open(rsa_private_key, 'rb') private_key = private_key_file.read() private_key_file.close() except IOError: print 'Unable to read private key from file' if private_key is not None: if client.auth_token is None: if session_token: client.auth_token = gdata.gauth.SecureAuthSubToken( session_token, private_key, scopes) self.prefs['client_auth_token'] = gdata.gauth.token_to_blob( client.auth_token) return elif auth_sub_token: client.auth_token = gdata.gauth.SecureAuthSubToken( auth_sub_token, private_key, scopes) client.upgrade_token() self.prefs['client_auth_token'] = gdata.gauth.token_to_blob( client.auth_token) return auth_url = gdata.gauth.generate_auth_sub_url( 'http://gauthmachine.appspot.com/authsub', scopes, True) print 'with a private key, get ready for this URL', auth_url else: if client.auth_token is None: if session_token: client.auth_token = gdata.gauth.AuthSubToken(session_token, scopes) self.prefs['client_auth_token'] = gdata.gauth.token_to_blob( client.auth_token) return elif auth_sub_token: client.auth_token = gdata.gauth.AuthSubToken(auth_sub_token, scopes) client.upgrade_token() self.prefs['client_auth_token'] = gdata.gauth.token_to_blob( client.auth_token) return auth_url = gdata.gauth.generate_auth_sub_url( 'http://gauthmachine.appspot.com/authsub', scopes) print 'Visit the following URL in your browser to authorize this app:' print str(auth_url) print 'After agreeing to authorize the app, copy the token value from' print ' the URL. Example: "www.google.com/?token=ab12" token value is' print ' ab12' token_value = raw_input('Please enter the token value: ') if private_key is not None: single_use_token = gdata.gauth.SecureAuthSubToken( token_value, private_key, scopes) else: single_use_token = gdata.gauth.AuthSubToken(token_value, scopes) client.auth_token = single_use_token client.upgrade_token() elif auth_type == OAUTH: if oauth_type is None: oauth_type = int(self.get_param( 'oauth_type', 'Please choose the authorization mechanism you want' ' to use.\n' '1. use an HMAC signature using your consumer key and secret\n' '2. use RSA with your private key to sign requests\n', reuse=True)) consumer_key = self.get_param( 'consumer_key', 'Please enter your OAuth conumer key ' 'which identifies your app', reuse=True) if oauth_type == HMAC: consumer_secret = self.get_param( 'consumer_secret', 'Please enter your OAuth conumer secret ' 'which you share with the OAuth provider', True, reuse=False) # Swap out this code once the client supports requesting an oauth # token. # Get a request token. request_token = client.get_oauth_token( scopes, 'http://gauthmachine.appspot.com/oauth', consumer_key, consumer_secret=consumer_secret) elif oauth_type == RSA: rsa_private_key = self.get_param( 'rsa_private_key', 'Please provide the location of your RSA private key which\n' ' corresponds to the certificate you have uploaded for your' ' domain.', reuse=True) try: private_key_file = open(rsa_private_key, 'rb') private_key = private_key_file.read() private_key_file.close() except IOError: print 'Unable to read private key from file' request_token = client.get_oauth_token( scopes, 'http://gauthmachine.appspot.com/oauth', consumer_key, rsa_private_key=private_key) else: print 'Invalid OAuth signature type' return None # Authorize the request token in the browser. print 'Visit the following URL in your browser to authorize this app:' print str(request_token.generate_authorization_url()) print 'After agreeing to authorize the app, copy URL from the browser\'s' print ' address bar.' url = raw_input('Please enter the url: ') gdata.gauth.authorize_request_token(request_token, url) # Exchange for an access token. client.auth_token = client.get_access_token(request_token) else: print 'Invalid authorization type.' return None if client.auth_token: self.prefs['client_auth_token'] = gdata.gauth.token_to_blob( client.auth_token) def get_param(name, prompt='', secret=False, ask=True): settings = SettingsUtil() return settings.get_param(name=name, prompt=prompt, secret=secret, ask=ask) def authorize_client(client, auth_type=None, service=None, source=None, scopes=None, oauth_type=None, consumer_key=None, consumer_secret=None): """Uses command line arguments, or prompts user for token values.""" settings = SettingsUtil() return settings.authorize_client(client=client, auth_type=auth_type, service=service, source=source, scopes=scopes, oauth_type=oauth_type, consumer_key=consumer_key, consumer_secret=consumer_secret) def print_options(): """Displays usage information, available command line params.""" # TODO: fill in the usage description for authorizing the client. print ''
Python
""" MAIN CLASS FOR TLS LITE (START HERE!). """ from __future__ import generators import socket from utils.compat import formatExceptionTrace from TLSRecordLayer import TLSRecordLayer from Session import Session from constants import * from utils.cryptomath import getRandomBytes from errors import * from messages import * from mathtls import * from HandshakeSettings import HandshakeSettings class TLSConnection(TLSRecordLayer): """ This class wraps a socket and provides TLS handshaking and data transfer. To use this class, create a new instance, passing a connected socket into the constructor. Then call some handshake function. If the handshake completes without raising an exception, then a TLS connection has been negotiated. You can transfer data over this connection as if it were a socket. This class provides both synchronous and asynchronous versions of its key functions. The synchronous versions should be used when writing single-or multi-threaded code using blocking sockets. The asynchronous versions should be used when performing asynchronous, event-based I/O with non-blocking sockets. Asynchronous I/O is a complicated subject; typically, you should not use the asynchronous functions directly, but should use some framework like asyncore or Twisted which TLS Lite integrates with (see L{tlslite.integration.TLSAsyncDispatcherMixIn.TLSAsyncDispatcherMixIn} or L{tlslite.integration.TLSTwistedProtocolWrapper.TLSTwistedProtocolWrapper}). """ def __init__(self, sock): """Create a new TLSConnection instance. @param sock: The socket data will be transmitted on. The socket should already be connected. It may be in blocking or non-blocking mode. @type sock: L{socket.socket} """ TLSRecordLayer.__init__(self, sock) def handshakeClientSRP(self, username, password, session=None, settings=None, checker=None, async=False): """Perform an SRP handshake in the role of client. This function performs a TLS/SRP handshake. SRP mutually authenticates both parties to each other using only a username and password. This function may also perform a combined SRP and server-certificate handshake, if the server chooses to authenticate itself with a certificate chain in addition to doing SRP. TLS/SRP is non-standard. Most TLS implementations don't support it. See U{http://www.ietf.org/html.charters/tls-charter.html} or U{http://trevp.net/tlssrp/} for the latest information on TLS/SRP. Like any handshake function, this can be called on a closed TLS connection, or on a TLS connection that is already open. If called on an open connection it performs a re-handshake. If the function completes without raising an exception, the TLS connection will be open and available for data transfer. If an exception is raised, the connection will have been automatically closed (if it was ever open). @type username: str @param username: The SRP username. @type password: str @param password: The SRP password. @type session: L{tlslite.Session.Session} @param session: A TLS session to attempt to resume. This session must be an SRP session performed with the same username and password as were passed in. If the resumption does not succeed, a full SRP handshake will be performed. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. @type checker: L{tlslite.Checker.Checker} @param checker: A Checker instance. This instance will be invoked to examine the other party's authentication credentials, if the handshake completes succesfully. @type async: bool @param async: If False, this function will block until the handshake is completed. If True, this function will return a generator. Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or will raise StopIteration if the handshake operation is completed. @rtype: None or an iterable @return: If 'async' is True, a generator object will be returned. @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. @raise tlslite.errors.TLSAuthenticationError: If the checker doesn't like the other party's authentication credentials. """ handshaker = self._handshakeClientAsync(srpParams=(username, password), session=session, settings=settings, checker=checker) if async: return handshaker for result in handshaker: pass def handshakeClientCert(self, certChain=None, privateKey=None, session=None, settings=None, checker=None, async=False): """Perform a certificate-based handshake in the role of client. This function performs an SSL or TLS handshake. The server will authenticate itself using an X.509 or cryptoID certificate chain. If the handshake succeeds, the server's certificate chain will be stored in the session's serverCertChain attribute. Unless a checker object is passed in, this function does no validation or checking of the server's certificate chain. If the server requests client authentication, the client will send the passed-in certificate chain, and use the passed-in private key to authenticate itself. If no certificate chain and private key were passed in, the client will attempt to proceed without client authentication. The server may or may not allow this. Like any handshake function, this can be called on a closed TLS connection, or on a TLS connection that is already open. If called on an open connection it performs a re-handshake. If the function completes without raising an exception, the TLS connection will be open and available for data transfer. If an exception is raised, the connection will have been automatically closed (if it was ever open). @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: The certificate chain to be used if the server requests client authentication. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: The private key to be used if the server requests client authentication. @type session: L{tlslite.Session.Session} @param session: A TLS session to attempt to resume. If the resumption does not succeed, a full handshake will be performed. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. @type checker: L{tlslite.Checker.Checker} @param checker: A Checker instance. This instance will be invoked to examine the other party's authentication credentials, if the handshake completes succesfully. @type async: bool @param async: If False, this function will block until the handshake is completed. If True, this function will return a generator. Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or will raise StopIteration if the handshake operation is completed. @rtype: None or an iterable @return: If 'async' is True, a generator object will be returned. @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. @raise tlslite.errors.TLSAuthenticationError: If the checker doesn't like the other party's authentication credentials. """ handshaker = self._handshakeClientAsync(certParams=(certChain, privateKey), session=session, settings=settings, checker=checker) if async: return handshaker for result in handshaker: pass def handshakeClientUnknown(self, srpCallback=None, certCallback=None, session=None, settings=None, checker=None, async=False): """Perform a to-be-determined type of handshake in the role of client. This function performs an SSL or TLS handshake. If the server requests client certificate authentication, the certCallback will be invoked and should return a (certChain, privateKey) pair. If the callback returns None, the library will attempt to proceed without client authentication. The server may or may not allow this. If the server requests SRP authentication, the srpCallback will be invoked and should return a (username, password) pair. If the callback returns None, the local implementation will signal a user_canceled error alert. After the handshake completes, the client can inspect the connection's session attribute to determine what type of authentication was performed. Like any handshake function, this can be called on a closed TLS connection, or on a TLS connection that is already open. If called on an open connection it performs a re-handshake. If the function completes without raising an exception, the TLS connection will be open and available for data transfer. If an exception is raised, the connection will have been automatically closed (if it was ever open). @type srpCallback: callable @param srpCallback: The callback to be used if the server requests SRP authentication. If None, the client will not offer support for SRP ciphersuites. @type certCallback: callable @param certCallback: The callback to be used if the server requests client certificate authentication. @type session: L{tlslite.Session.Session} @param session: A TLS session to attempt to resume. If the resumption does not succeed, a full handshake will be performed. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. @type checker: L{tlslite.Checker.Checker} @param checker: A Checker instance. This instance will be invoked to examine the other party's authentication credentials, if the handshake completes succesfully. @type async: bool @param async: If False, this function will block until the handshake is completed. If True, this function will return a generator. Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or will raise StopIteration if the handshake operation is completed. @rtype: None or an iterable @return: If 'async' is True, a generator object will be returned. @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. @raise tlslite.errors.TLSAuthenticationError: If the checker doesn't like the other party's authentication credentials. """ handshaker = self._handshakeClientAsync(unknownParams=(srpCallback, certCallback), session=session, settings=settings, checker=checker) if async: return handshaker for result in handshaker: pass def handshakeClientSharedKey(self, username, sharedKey, settings=None, checker=None, async=False): """Perform a shared-key handshake in the role of client. This function performs a shared-key handshake. Using shared symmetric keys of high entropy (128 bits or greater) mutually authenticates both parties to each other. TLS with shared-keys is non-standard. Most TLS implementations don't support it. See U{http://www.ietf.org/html.charters/tls-charter.html} for the latest information on TLS with shared-keys. If the shared-keys Internet-Draft changes or is superceded, TLS Lite will track those changes, so the shared-key support in later versions of TLS Lite may become incompatible with this version. Like any handshake function, this can be called on a closed TLS connection, or on a TLS connection that is already open. If called on an open connection it performs a re-handshake. If the function completes without raising an exception, the TLS connection will be open and available for data transfer. If an exception is raised, the connection will have been automatically closed (if it was ever open). @type username: str @param username: The shared-key username. @type sharedKey: str @param sharedKey: The shared key. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. @type checker: L{tlslite.Checker.Checker} @param checker: A Checker instance. This instance will be invoked to examine the other party's authentication credentials, if the handshake completes succesfully. @type async: bool @param async: If False, this function will block until the handshake is completed. If True, this function will return a generator. Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or will raise StopIteration if the handshake operation is completed. @rtype: None or an iterable @return: If 'async' is True, a generator object will be returned. @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. @raise tlslite.errors.TLSAuthenticationError: If the checker doesn't like the other party's authentication credentials. """ handshaker = self._handshakeClientAsync(sharedKeyParams=(username, sharedKey), settings=settings, checker=checker) if async: return handshaker for result in handshaker: pass def _handshakeClientAsync(self, srpParams=(), certParams=(), unknownParams=(), sharedKeyParams=(), session=None, settings=None, checker=None, recursive=False): handshaker = self._handshakeClientAsyncHelper(srpParams=srpParams, certParams=certParams, unknownParams=unknownParams, sharedKeyParams=sharedKeyParams, session=session, settings=settings, recursive=recursive) for result in self._handshakeWrapperAsync(handshaker, checker): yield result def _handshakeClientAsyncHelper(self, srpParams, certParams, unknownParams, sharedKeyParams, session, settings, recursive): if not recursive: self._handshakeStart(client=True) #Unpack parameters srpUsername = None # srpParams password = None # srpParams clientCertChain = None # certParams privateKey = None # certParams srpCallback = None # unknownParams certCallback = None # unknownParams #session # sharedKeyParams (or session) #settings # settings if srpParams: srpUsername, password = srpParams elif certParams: clientCertChain, privateKey = certParams elif unknownParams: srpCallback, certCallback = unknownParams elif sharedKeyParams: session = Session()._createSharedKey(*sharedKeyParams) if not settings: settings = HandshakeSettings() settings = settings._filter() #Validate parameters if srpUsername and not password: raise ValueError("Caller passed a username but no password") if password and not srpUsername: raise ValueError("Caller passed a password but no username") if clientCertChain and not privateKey: raise ValueError("Caller passed a certChain but no privateKey") if privateKey and not clientCertChain: raise ValueError("Caller passed a privateKey but no certChain") if clientCertChain: foundType = False try: import cryptoIDlib.CertChain if isinstance(clientCertChain, cryptoIDlib.CertChain.CertChain): if "cryptoID" not in settings.certificateTypes: raise ValueError("Client certificate doesn't "\ "match Handshake Settings") settings.certificateTypes = ["cryptoID"] foundType = True except ImportError: pass if not foundType and isinstance(clientCertChain, X509CertChain): if "x509" not in settings.certificateTypes: raise ValueError("Client certificate doesn't match "\ "Handshake Settings") settings.certificateTypes = ["x509"] foundType = True if not foundType: raise ValueError("Unrecognized certificate type") if session: if not session.valid(): session = None #ignore non-resumable sessions... elif session.resumable and \ (session.srpUsername != srpUsername): raise ValueError("Session username doesn't match") #Add Faults to parameters if srpUsername and self.fault == Fault.badUsername: srpUsername += "GARBAGE" if password and self.fault == Fault.badPassword: password += "GARBAGE" if sharedKeyParams: identifier = sharedKeyParams[0] sharedKey = sharedKeyParams[1] if self.fault == Fault.badIdentifier: identifier += "GARBAGE" session = Session()._createSharedKey(identifier, sharedKey) elif self.fault == Fault.badSharedKey: sharedKey += "GARBAGE" session = Session()._createSharedKey(identifier, sharedKey) #Initialize locals serverCertChain = None cipherSuite = 0 certificateType = CertificateType.x509 premasterSecret = None #Get client nonce clientRandom = getRandomBytes(32) #Initialize acceptable ciphersuites cipherSuites = [] if srpParams: cipherSuites += CipherSuite.getSrpRsaSuites(settings.cipherNames) cipherSuites += CipherSuite.getSrpSuites(settings.cipherNames) elif certParams: cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames) elif unknownParams: if srpCallback: cipherSuites += \ CipherSuite.getSrpRsaSuites(settings.cipherNames) cipherSuites += \ CipherSuite.getSrpSuites(settings.cipherNames) cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames) elif sharedKeyParams: cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames) else: cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames) #Initialize acceptable certificate types certificateTypes = settings._getCertificateTypes() #Tentatively set the version to the client's minimum version. #We'll use this for the ClientHello, and if an error occurs #parsing the Server Hello, we'll use this version for the response self.version = settings.maxVersion #Either send ClientHello (with a resumable session)... if session: #If it's a resumable (i.e. not a shared-key session), then its #ciphersuite must be one of the acceptable ciphersuites if (not sharedKeyParams) and \ session.cipherSuite not in cipherSuites: raise ValueError("Session's cipher suite not consistent "\ "with parameters") else: clientHello = ClientHello() clientHello.create(settings.maxVersion, clientRandom, session.sessionID, cipherSuites, certificateTypes, session.srpUsername) #Or send ClientHello (without) else: clientHello = ClientHello() clientHello.create(settings.maxVersion, clientRandom, createByteArraySequence([]), cipherSuites, certificateTypes, srpUsername) for result in self._sendMsg(clientHello): yield result #Get ServerHello (or missing_srp_username) for result in self._getMsg((ContentType.handshake, ContentType.alert), HandshakeType.server_hello): if result in (0,1): yield result else: break msg = result if isinstance(msg, ServerHello): serverHello = msg elif isinstance(msg, Alert): alert = msg #If it's not a missing_srp_username, re-raise if alert.description != AlertDescription.missing_srp_username: self._shutdown(False) raise TLSRemoteAlert(alert) #If we're not in SRP callback mode, we won't have offered SRP #without a username, so we shouldn't get this alert if not srpCallback: for result in self._sendError(\ AlertDescription.unexpected_message): yield result srpParams = srpCallback() #If the callback returns None, cancel the handshake if srpParams == None: for result in self._sendError(AlertDescription.user_canceled): yield result #Recursively perform handshake for result in self._handshakeClientAsyncHelper(srpParams, None, None, None, None, settings, True): yield result return #Get the server version. Do this before anything else, so any #error alerts will use the server's version self.version = serverHello.server_version #Future responses from server must use this version self._versionCheck = True #Check ServerHello if serverHello.server_version < settings.minVersion: for result in self._sendError(\ AlertDescription.protocol_version, "Too old version: %s" % str(serverHello.server_version)): yield result if serverHello.server_version > settings.maxVersion: for result in self._sendError(\ AlertDescription.protocol_version, "Too new version: %s" % str(serverHello.server_version)): yield result if serverHello.cipher_suite not in cipherSuites: for result in self._sendError(\ AlertDescription.illegal_parameter, "Server responded with incorrect ciphersuite"): yield result if serverHello.certificate_type not in certificateTypes: for result in self._sendError(\ AlertDescription.illegal_parameter, "Server responded with incorrect certificate type"): yield result if serverHello.compression_method != 0: for result in self._sendError(\ AlertDescription.illegal_parameter, "Server responded with incorrect compression method"): yield result #Get the server nonce serverRandom = serverHello.random #If the server agrees to resume if session and session.sessionID and \ serverHello.session_id == session.sessionID: #If a shared-key, we're flexible about suites; otherwise the #server-chosen suite has to match the session's suite if sharedKeyParams: session.cipherSuite = serverHello.cipher_suite elif serverHello.cipher_suite != session.cipherSuite: for result in self._sendError(\ AlertDescription.illegal_parameter,\ "Server's ciphersuite doesn't match session"): yield result #Set the session for this connection self.session = session #Calculate pending connection states self._calcPendingStates(clientRandom, serverRandom, settings.cipherImplementations) #Exchange ChangeCipherSpec and Finished messages for result in self._getFinished(): yield result for result in self._sendFinished(): yield result #Mark the connection as open self._handshakeDone(resumed=True) #If server DOES NOT agree to resume else: if sharedKeyParams: for result in self._sendError(\ AlertDescription.user_canceled, "Was expecting a shared-key resumption"): yield result #We've already validated these cipherSuite = serverHello.cipher_suite certificateType = serverHello.certificate_type #If the server chose an SRP suite... if cipherSuite in CipherSuite.srpSuites: #Get ServerKeyExchange, ServerHelloDone for result in self._getMsg(ContentType.handshake, HandshakeType.server_key_exchange, cipherSuite): if result in (0,1): yield result else: break serverKeyExchange = result for result in self._getMsg(ContentType.handshake, HandshakeType.server_hello_done): if result in (0,1): yield result else: break serverHelloDone = result #If the server chose an SRP+RSA suite... elif cipherSuite in CipherSuite.srpRsaSuites: #Get Certificate, ServerKeyExchange, ServerHelloDone for result in self._getMsg(ContentType.handshake, HandshakeType.certificate, certificateType): if result in (0,1): yield result else: break serverCertificate = result for result in self._getMsg(ContentType.handshake, HandshakeType.server_key_exchange, cipherSuite): if result in (0,1): yield result else: break serverKeyExchange = result for result in self._getMsg(ContentType.handshake, HandshakeType.server_hello_done): if result in (0,1): yield result else: break serverHelloDone = result #If the server chose an RSA suite... elif cipherSuite in CipherSuite.rsaSuites: #Get Certificate[, CertificateRequest], ServerHelloDone for result in self._getMsg(ContentType.handshake, HandshakeType.certificate, certificateType): if result in (0,1): yield result else: break serverCertificate = result for result in self._getMsg(ContentType.handshake, (HandshakeType.server_hello_done, HandshakeType.certificate_request)): if result in (0,1): yield result else: break msg = result certificateRequest = None if isinstance(msg, CertificateRequest): certificateRequest = msg for result in self._getMsg(ContentType.handshake, HandshakeType.server_hello_done): if result in (0,1): yield result else: break serverHelloDone = result elif isinstance(msg, ServerHelloDone): serverHelloDone = msg else: raise AssertionError() #Calculate SRP premaster secret, if server chose an SRP or #SRP+RSA suite if cipherSuite in CipherSuite.srpSuites + \ CipherSuite.srpRsaSuites: #Get and check the server's group parameters and B value N = serverKeyExchange.srp_N g = serverKeyExchange.srp_g s = serverKeyExchange.srp_s B = serverKeyExchange.srp_B if (g,N) not in goodGroupParameters: for result in self._sendError(\ AlertDescription.untrusted_srp_parameters, "Unknown group parameters"): yield result if numBits(N) < settings.minKeySize: for result in self._sendError(\ AlertDescription.untrusted_srp_parameters, "N value is too small: %d" % numBits(N)): yield result if numBits(N) > settings.maxKeySize: for result in self._sendError(\ AlertDescription.untrusted_srp_parameters, "N value is too large: %d" % numBits(N)): yield result if B % N == 0: for result in self._sendError(\ AlertDescription.illegal_parameter, "Suspicious B value"): yield result #Check the server's signature, if server chose an #SRP+RSA suite if cipherSuite in CipherSuite.srpRsaSuites: #Hash ServerKeyExchange/ServerSRPParams hashBytes = serverKeyExchange.hash(clientRandom, serverRandom) #Extract signature bytes from ServerKeyExchange sigBytes = serverKeyExchange.signature if len(sigBytes) == 0: for result in self._sendError(\ AlertDescription.illegal_parameter, "Server sent an SRP ServerKeyExchange "\ "message without a signature"): yield result #Get server's public key from the Certificate message for result in self._getKeyFromChain(serverCertificate, settings): if result in (0,1): yield result else: break publicKey, serverCertChain = result #Verify signature if not publicKey.verify(sigBytes, hashBytes): for result in self._sendError(\ AlertDescription.decrypt_error, "Signature failed to verify"): yield result #Calculate client's ephemeral DH values (a, A) a = bytesToNumber(getRandomBytes(32)) A = powMod(g, a, N) #Calculate client's static DH values (x, v) x = makeX(bytesToString(s), srpUsername, password) v = powMod(g, x, N) #Calculate u u = makeU(N, A, B) #Calculate premaster secret k = makeK(N, g) S = powMod((B - (k*v)) % N, a+(u*x), N) if self.fault == Fault.badA: A = N S = 0 premasterSecret = numberToBytes(S) #Send ClientKeyExchange for result in self._sendMsg(\ ClientKeyExchange(cipherSuite).createSRP(A)): yield result #Calculate RSA premaster secret, if server chose an RSA suite elif cipherSuite in CipherSuite.rsaSuites: #Handle the presence of a CertificateRequest if certificateRequest: if unknownParams and certCallback: certParamsNew = certCallback() if certParamsNew: clientCertChain, privateKey = certParamsNew #Get server's public key from the Certificate message for result in self._getKeyFromChain(serverCertificate, settings): if result in (0,1): yield result else: break publicKey, serverCertChain = result #Calculate premaster secret premasterSecret = getRandomBytes(48) premasterSecret[0] = settings.maxVersion[0] premasterSecret[1] = settings.maxVersion[1] if self.fault == Fault.badPremasterPadding: premasterSecret[0] = 5 if self.fault == Fault.shortPremasterSecret: premasterSecret = premasterSecret[:-1] #Encrypt premaster secret to server's public key encryptedPreMasterSecret = publicKey.encrypt(premasterSecret) #If client authentication was requested, send Certificate #message, either with certificates or empty if certificateRequest: clientCertificate = Certificate(certificateType) if clientCertChain: #Check to make sure we have the same type of #certificates the server requested wrongType = False if certificateType == CertificateType.x509: if not isinstance(clientCertChain, X509CertChain): wrongType = True elif certificateType == CertificateType.cryptoID: if not isinstance(clientCertChain, cryptoIDlib.CertChain.CertChain): wrongType = True if wrongType: for result in self._sendError(\ AlertDescription.handshake_failure, "Client certificate is of wrong type"): yield result clientCertificate.create(clientCertChain) for result in self._sendMsg(clientCertificate): yield result else: #The server didn't request client auth, so we #zeroize these so the clientCertChain won't be #stored in the session. privateKey = None clientCertChain = None #Send ClientKeyExchange clientKeyExchange = ClientKeyExchange(cipherSuite, self.version) clientKeyExchange.createRSA(encryptedPreMasterSecret) for result in self._sendMsg(clientKeyExchange): yield result #If client authentication was requested and we have a #private key, send CertificateVerify if certificateRequest and privateKey: if self.version == (3,0): #Create a temporary session object, just for the #purpose of creating the CertificateVerify session = Session() session._calcMasterSecret(self.version, premasterSecret, clientRandom, serverRandom) verifyBytes = self._calcSSLHandshakeHash(\ session.masterSecret, "") elif self.version in ((3,1), (3,2)): verifyBytes = stringToBytes(\ self._handshake_md5.digest() + \ self._handshake_sha.digest()) if self.fault == Fault.badVerifyMessage: verifyBytes[0] = ((verifyBytes[0]+1) % 256) signedBytes = privateKey.sign(verifyBytes) certificateVerify = CertificateVerify() certificateVerify.create(signedBytes) for result in self._sendMsg(certificateVerify): yield result #Create the session object self.session = Session() self.session._calcMasterSecret(self.version, premasterSecret, clientRandom, serverRandom) self.session.sessionID = serverHello.session_id self.session.cipherSuite = cipherSuite self.session.srpUsername = srpUsername self.session.clientCertChain = clientCertChain self.session.serverCertChain = serverCertChain #Calculate pending connection states self._calcPendingStates(clientRandom, serverRandom, settings.cipherImplementations) #Exchange ChangeCipherSpec and Finished messages for result in self._sendFinished(): yield result for result in self._getFinished(): yield result #Mark the connection as open self.session._setResumable(True) self._handshakeDone(resumed=False) def handshakeServer(self, sharedKeyDB=None, verifierDB=None, certChain=None, privateKey=None, reqCert=False, sessionCache=None, settings=None, checker=None): """Perform a handshake in the role of server. This function performs an SSL or TLS handshake. Depending on the arguments and the behavior of the client, this function can perform a shared-key, SRP, or certificate-based handshake. It can also perform a combined SRP and server-certificate handshake. Like any handshake function, this can be called on a closed TLS connection, or on a TLS connection that is already open. If called on an open connection it performs a re-handshake. This function does not send a Hello Request message before performing the handshake, so if re-handshaking is required, the server must signal the client to begin the re-handshake through some other means. If the function completes without raising an exception, the TLS connection will be open and available for data transfer. If an exception is raised, the connection will have been automatically closed (if it was ever open). @type sharedKeyDB: L{tlslite.SharedKeyDB.SharedKeyDB} @param sharedKeyDB: A database of shared symmetric keys associated with usernames. If the client performs a shared-key handshake, the session's sharedKeyUsername attribute will be set. @type verifierDB: L{tlslite.VerifierDB.VerifierDB} @param verifierDB: A database of SRP password verifiers associated with usernames. If the client performs an SRP handshake, the session's srpUsername attribute will be set. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: The certificate chain to be used if the client requests server certificate authentication. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: The private key to be used if the client requests server certificate authentication. @type reqCert: bool @param reqCert: Whether to request client certificate authentication. This only applies if the client chooses server certificate authentication; if the client chooses SRP or shared-key authentication, this will be ignored. If the client performs a client certificate authentication, the sessions's clientCertChain attribute will be set. @type sessionCache: L{tlslite.SessionCache.SessionCache} @param sessionCache: An in-memory cache of resumable sessions. The client can resume sessions from this cache. Alternatively, if the client performs a full handshake, a new session will be added to the cache. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites and SSL/TLS version chosen by the server. @type checker: L{tlslite.Checker.Checker} @param checker: A Checker instance. This instance will be invoked to examine the other party's authentication credentials, if the handshake completes succesfully. @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. @raise tlslite.errors.TLSAuthenticationError: If the checker doesn't like the other party's authentication credentials. """ for result in self.handshakeServerAsync(sharedKeyDB, verifierDB, certChain, privateKey, reqCert, sessionCache, settings, checker): pass def handshakeServerAsync(self, sharedKeyDB=None, verifierDB=None, certChain=None, privateKey=None, reqCert=False, sessionCache=None, settings=None, checker=None): """Start a server handshake operation on the TLS connection. This function returns a generator which behaves similarly to handshakeServer(). Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or it will raise StopIteration if the handshake operation is complete. @rtype: iterable @return: A generator; see above for details. """ handshaker = self._handshakeServerAsyncHelper(\ sharedKeyDB=sharedKeyDB, verifierDB=verifierDB, certChain=certChain, privateKey=privateKey, reqCert=reqCert, sessionCache=sessionCache, settings=settings) for result in self._handshakeWrapperAsync(handshaker, checker): yield result def _handshakeServerAsyncHelper(self, sharedKeyDB, verifierDB, certChain, privateKey, reqCert, sessionCache, settings): self._handshakeStart(client=False) if (not sharedKeyDB) and (not verifierDB) and (not certChain): raise ValueError("Caller passed no authentication credentials") if certChain and not privateKey: raise ValueError("Caller passed a certChain but no privateKey") if privateKey and not certChain: raise ValueError("Caller passed a privateKey but no certChain") if not settings: settings = HandshakeSettings() settings = settings._filter() #Initialize acceptable cipher suites cipherSuites = [] if verifierDB: if certChain: cipherSuites += \ CipherSuite.getSrpRsaSuites(settings.cipherNames) cipherSuites += CipherSuite.getSrpSuites(settings.cipherNames) if sharedKeyDB or certChain: cipherSuites += CipherSuite.getRsaSuites(settings.cipherNames) #Initialize acceptable certificate type certificateType = None if certChain: try: import cryptoIDlib.CertChain if isinstance(certChain, cryptoIDlib.CertChain.CertChain): certificateType = CertificateType.cryptoID except ImportError: pass if isinstance(certChain, X509CertChain): certificateType = CertificateType.x509 if certificateType == None: raise ValueError("Unrecognized certificate type") #Initialize locals clientCertChain = None serverCertChain = None #We may set certChain to this later postFinishedError = None #Tentatively set version to most-desirable version, so if an error #occurs parsing the ClientHello, this is what we'll use for the #error alert self.version = settings.maxVersion #Get ClientHello for result in self._getMsg(ContentType.handshake, HandshakeType.client_hello): if result in (0,1): yield result else: break clientHello = result #If client's version is too low, reject it if clientHello.client_version < settings.minVersion: self.version = settings.minVersion for result in self._sendError(\ AlertDescription.protocol_version, "Too old version: %s" % str(clientHello.client_version)): yield result #If client's version is too high, propose my highest version elif clientHello.client_version > settings.maxVersion: self.version = settings.maxVersion else: #Set the version to the client's version self.version = clientHello.client_version #Get the client nonce; create server nonce clientRandom = clientHello.random serverRandom = getRandomBytes(32) #Calculate the first cipher suite intersection. #This is the 'privileged' ciphersuite. We'll use it if we're #doing a shared-key resumption or a new negotiation. In fact, #the only time we won't use it is if we're resuming a non-sharedkey #session, in which case we use the ciphersuite from the session. # #Given the current ciphersuite ordering, this means we prefer SRP #over non-SRP. for cipherSuite in cipherSuites: if cipherSuite in clientHello.cipher_suites: break else: for result in self._sendError(\ AlertDescription.handshake_failure): yield result #If resumption was requested... if clientHello.session_id and (sharedKeyDB or sessionCache): session = None #Check in the sharedKeys container if sharedKeyDB and len(clientHello.session_id)==16: try: #Trim off zero padding, if any for x in range(16): if clientHello.session_id[x]==0: break self.allegedSharedKeyUsername = bytesToString(\ clientHello.session_id[:x]) session = sharedKeyDB[self.allegedSharedKeyUsername] if not session.sharedKey: raise AssertionError() #use privileged ciphersuite session.cipherSuite = cipherSuite except KeyError: pass #Then check in the session cache if sessionCache and not session: try: session = sessionCache[bytesToString(\ clientHello.session_id)] if session.sharedKey: raise AssertionError() if not session.resumable: raise AssertionError() #Check for consistency with ClientHello if session.cipherSuite not in cipherSuites: for result in self._sendError(\ AlertDescription.handshake_failure): yield result if session.cipherSuite not in clientHello.cipher_suites: for result in self._sendError(\ AlertDescription.handshake_failure): yield result if clientHello.srp_username: if clientHello.srp_username != session.srpUsername: for result in self._sendError(\ AlertDescription.handshake_failure): yield result except KeyError: pass #If a session is found.. if session: #Set the session self.session = session #Send ServerHello serverHello = ServerHello() serverHello.create(self.version, serverRandom, session.sessionID, session.cipherSuite, certificateType) for result in self._sendMsg(serverHello): yield result #From here on, the client's messages must have the right version self._versionCheck = True #Calculate pending connection states self._calcPendingStates(clientRandom, serverRandom, settings.cipherImplementations) #Exchange ChangeCipherSpec and Finished messages for result in self._sendFinished(): yield result for result in self._getFinished(): yield result #Mark the connection as open self._handshakeDone(resumed=True) return #If not a resumption... #TRICKY: we might have chosen an RSA suite that was only deemed #acceptable because of the shared-key resumption. If the shared- #key resumption failed, because the identifier wasn't recognized, #we might fall through to here, where we have an RSA suite #chosen, but no certificate. if cipherSuite in CipherSuite.rsaSuites and not certChain: for result in self._sendError(\ AlertDescription.handshake_failure): yield result #If an RSA suite is chosen, check for certificate type intersection #(We do this check down here because if the mismatch occurs but the # client is using a shared-key session, it's okay) if cipherSuite in CipherSuite.rsaSuites + \ CipherSuite.srpRsaSuites: if certificateType not in clientHello.certificate_types: for result in self._sendError(\ AlertDescription.handshake_failure, "the client doesn't support my certificate type"): yield result #Move certChain -> serverCertChain, now that we're using it serverCertChain = certChain #Create sessionID if sessionCache: sessionID = getRandomBytes(32) else: sessionID = createByteArraySequence([]) #If we've selected an SRP suite, exchange keys and calculate #premaster secret: if cipherSuite in CipherSuite.srpSuites + CipherSuite.srpRsaSuites: #If there's no SRP username... if not clientHello.srp_username: #Ask the client to re-send ClientHello with one for result in self._sendMsg(Alert().create(\ AlertDescription.missing_srp_username, AlertLevel.warning)): yield result #Get ClientHello for result in self._getMsg(ContentType.handshake, HandshakeType.client_hello): if result in (0,1): yield result else: break clientHello = result #Check ClientHello #If client's version is too low, reject it (COPIED CODE; BAD!) if clientHello.client_version < settings.minVersion: self.version = settings.minVersion for result in self._sendError(\ AlertDescription.protocol_version, "Too old version: %s" % str(clientHello.client_version)): yield result #If client's version is too high, propose my highest version elif clientHello.client_version > settings.maxVersion: self.version = settings.maxVersion else: #Set the version to the client's version self.version = clientHello.client_version #Recalculate the privileged cipher suite, making sure to #pick an SRP suite cipherSuites = [c for c in cipherSuites if c in \ CipherSuite.srpSuites + \ CipherSuite.srpRsaSuites] for cipherSuite in cipherSuites: if cipherSuite in clientHello.cipher_suites: break else: for result in self._sendError(\ AlertDescription.handshake_failure): yield result #Get the client nonce; create server nonce clientRandom = clientHello.random serverRandom = getRandomBytes(32) #The username better be there, this time if not clientHello.srp_username: for result in self._sendError(\ AlertDescription.illegal_parameter, "Client resent a hello, but without the SRP"\ " username"): yield result #Get username self.allegedSrpUsername = clientHello.srp_username #Get parameters from username try: entry = verifierDB[self.allegedSrpUsername] except KeyError: for result in self._sendError(\ AlertDescription.unknown_srp_username): yield result (N, g, s, v) = entry #Calculate server's ephemeral DH values (b, B) b = bytesToNumber(getRandomBytes(32)) k = makeK(N, g) B = (powMod(g, b, N) + (k*v)) % N #Create ServerKeyExchange, signing it if necessary serverKeyExchange = ServerKeyExchange(cipherSuite) serverKeyExchange.createSRP(N, g, stringToBytes(s), B) if cipherSuite in CipherSuite.srpRsaSuites: hashBytes = serverKeyExchange.hash(clientRandom, serverRandom) serverKeyExchange.signature = privateKey.sign(hashBytes) #Send ServerHello[, Certificate], ServerKeyExchange, #ServerHelloDone msgs = [] serverHello = ServerHello() serverHello.create(self.version, serverRandom, sessionID, cipherSuite, certificateType) msgs.append(serverHello) if cipherSuite in CipherSuite.srpRsaSuites: certificateMsg = Certificate(certificateType) certificateMsg.create(serverCertChain) msgs.append(certificateMsg) msgs.append(serverKeyExchange) msgs.append(ServerHelloDone()) for result in self._sendMsgs(msgs): yield result #From here on, the client's messages must have the right version self._versionCheck = True #Get and check ClientKeyExchange for result in self._getMsg(ContentType.handshake, HandshakeType.client_key_exchange, cipherSuite): if result in (0,1): yield result else: break clientKeyExchange = result A = clientKeyExchange.srp_A if A % N == 0: postFinishedError = (AlertDescription.illegal_parameter, "Suspicious A value") #Calculate u u = makeU(N, A, B) #Calculate premaster secret S = powMod((A * powMod(v,u,N)) % N, b, N) premasterSecret = numberToBytes(S) #If we've selected an RSA suite, exchange keys and calculate #premaster secret: elif cipherSuite in CipherSuite.rsaSuites: #Send ServerHello, Certificate[, CertificateRequest], #ServerHelloDone msgs = [] msgs.append(ServerHello().create(self.version, serverRandom, sessionID, cipherSuite, certificateType)) msgs.append(Certificate(certificateType).create(serverCertChain)) if reqCert: msgs.append(CertificateRequest()) msgs.append(ServerHelloDone()) for result in self._sendMsgs(msgs): yield result #From here on, the client's messages must have the right version self._versionCheck = True #Get [Certificate,] (if was requested) if reqCert: if self.version == (3,0): for result in self._getMsg((ContentType.handshake, ContentType.alert), HandshakeType.certificate, certificateType): if result in (0,1): yield result else: break msg = result if isinstance(msg, Alert): #If it's not a no_certificate alert, re-raise alert = msg if alert.description != \ AlertDescription.no_certificate: self._shutdown(False) raise TLSRemoteAlert(alert) elif isinstance(msg, Certificate): clientCertificate = msg if clientCertificate.certChain and \ clientCertificate.certChain.getNumCerts()!=0: clientCertChain = clientCertificate.certChain else: raise AssertionError() elif self.version in ((3,1), (3,2)): for result in self._getMsg(ContentType.handshake, HandshakeType.certificate, certificateType): if result in (0,1): yield result else: break clientCertificate = result if clientCertificate.certChain and \ clientCertificate.certChain.getNumCerts()!=0: clientCertChain = clientCertificate.certChain else: raise AssertionError() #Get ClientKeyExchange for result in self._getMsg(ContentType.handshake, HandshakeType.client_key_exchange, cipherSuite): if result in (0,1): yield result else: break clientKeyExchange = result #Decrypt ClientKeyExchange premasterSecret = privateKey.decrypt(\ clientKeyExchange.encryptedPreMasterSecret) randomPreMasterSecret = getRandomBytes(48) versionCheck = (premasterSecret[0], premasterSecret[1]) if not premasterSecret: premasterSecret = randomPreMasterSecret elif len(premasterSecret)!=48: premasterSecret = randomPreMasterSecret elif versionCheck != clientHello.client_version: if versionCheck != self.version: #Tolerate buggy IE clients premasterSecret = randomPreMasterSecret #Get and check CertificateVerify, if relevant if clientCertChain: if self.version == (3,0): #Create a temporary session object, just for the purpose #of checking the CertificateVerify session = Session() session._calcMasterSecret(self.version, premasterSecret, clientRandom, serverRandom) verifyBytes = self._calcSSLHandshakeHash(\ session.masterSecret, "") elif self.version in ((3,1), (3,2)): verifyBytes = stringToBytes(self._handshake_md5.digest() +\ self._handshake_sha.digest()) for result in self._getMsg(ContentType.handshake, HandshakeType.certificate_verify): if result in (0,1): yield result else: break certificateVerify = result publicKey = clientCertChain.getEndEntityPublicKey() if len(publicKey) < settings.minKeySize: postFinishedError = (AlertDescription.handshake_failure, "Client's public key too small: %d" % len(publicKey)) if len(publicKey) > settings.maxKeySize: postFinishedError = (AlertDescription.handshake_failure, "Client's public key too large: %d" % len(publicKey)) if not publicKey.verify(certificateVerify.signature, verifyBytes): postFinishedError = (AlertDescription.decrypt_error, "Signature failed to verify") #Create the session object self.session = Session() self.session._calcMasterSecret(self.version, premasterSecret, clientRandom, serverRandom) self.session.sessionID = sessionID self.session.cipherSuite = cipherSuite self.session.srpUsername = self.allegedSrpUsername self.session.clientCertChain = clientCertChain self.session.serverCertChain = serverCertChain #Calculate pending connection states self._calcPendingStates(clientRandom, serverRandom, settings.cipherImplementations) #Exchange ChangeCipherSpec and Finished messages for result in self._getFinished(): yield result #If we were holding a post-finished error until receiving the client #finished message, send it now. We delay the call until this point #because calling sendError() throws an exception, and our caller might #shut down the socket upon receiving the exception. If he did, and the #client was still sending its ChangeCipherSpec or Finished messages, it #would cause a socket error on the client side. This is a lot of #consideration to show to misbehaving clients, but this would also #cause problems with fault-testing. if postFinishedError: for result in self._sendError(*postFinishedError): yield result for result in self._sendFinished(): yield result #Add the session object to the session cache if sessionCache and sessionID: sessionCache[bytesToString(sessionID)] = self.session #Mark the connection as open self.session._setResumable(True) self._handshakeDone(resumed=False) def _handshakeWrapperAsync(self, handshaker, checker): if not self.fault: try: for result in handshaker: yield result if checker: try: checker(self) except TLSAuthenticationError: alert = Alert().create(AlertDescription.close_notify, AlertLevel.fatal) for result in self._sendMsg(alert): yield result raise except: self._shutdown(False) raise else: try: for result in handshaker: yield result if checker: try: checker(self) except TLSAuthenticationError: alert = Alert().create(AlertDescription.close_notify, AlertLevel.fatal) for result in self._sendMsg(alert): yield result raise except socket.error, e: raise TLSFaultError("socket error!") except TLSAbruptCloseError, e: raise TLSFaultError("abrupt close error!") except TLSAlert, alert: if alert.description not in Fault.faultAlerts[self.fault]: raise TLSFaultError(str(alert)) else: pass except: self._shutdown(False) raise else: raise TLSFaultError("No error!") def _getKeyFromChain(self, certificate, settings): #Get and check cert chain from the Certificate message certChain = certificate.certChain if not certChain or certChain.getNumCerts() == 0: for result in self._sendError(AlertDescription.illegal_parameter, "Other party sent a Certificate message without "\ "certificates"): yield result #Get and check public key from the cert chain publicKey = certChain.getEndEntityPublicKey() if len(publicKey) < settings.minKeySize: for result in self._sendError(AlertDescription.handshake_failure, "Other party's public key too small: %d" % len(publicKey)): yield result if len(publicKey) > settings.maxKeySize: for result in self._sendError(AlertDescription.handshake_failure, "Other party's public key too large: %d" % len(publicKey)): yield result yield publicKey, certChain
Python
"""Helper class for TLSConnection.""" from __future__ import generators from utils.compat import * from utils.cryptomath import * from utils.cipherfactory import createAES, createRC4, createTripleDES from utils.codec import * from errors import * from messages import * from mathtls import * from constants import * from utils.cryptomath import getRandomBytes from utils import hmac from FileObject import FileObject import sha import md5 import socket import errno import traceback class _ConnectionState: def __init__(self): self.macContext = None self.encContext = None self.seqnum = 0 def getSeqNumStr(self): w = Writer(8) w.add(self.seqnum, 8) seqnumStr = bytesToString(w.bytes) self.seqnum += 1 return seqnumStr class TLSRecordLayer: """ This class handles data transmission for a TLS connection. Its only subclass is L{tlslite.TLSConnection.TLSConnection}. We've separated the code in this class from TLSConnection to make things more readable. @type sock: socket.socket @ivar sock: The underlying socket object. @type session: L{tlslite.Session.Session} @ivar session: The session corresponding to this connection. Due to TLS session resumption, multiple connections can correspond to the same underlying session. @type version: tuple @ivar version: The TLS version being used for this connection. (3,0) means SSL 3.0, and (3,1) means TLS 1.0. @type closed: bool @ivar closed: If this connection is closed. @type resumed: bool @ivar resumed: If this connection is based on a resumed session. @type allegedSharedKeyUsername: str or None @ivar allegedSharedKeyUsername: This is set to the shared-key username asserted by the client, whether the handshake succeeded or not. If the handshake fails, this can be inspected to determine if a guessing attack is in progress against a particular user account. @type allegedSrpUsername: str or None @ivar allegedSrpUsername: This is set to the SRP username asserted by the client, whether the handshake succeeded or not. If the handshake fails, this can be inspected to determine if a guessing attack is in progress against a particular user account. @type closeSocket: bool @ivar closeSocket: If the socket should be closed when the connection is closed (writable). If you set this to True, TLS Lite will assume the responsibility of closing the socket when the TLS Connection is shutdown (either through an error or through the user calling close()). The default is False. @type ignoreAbruptClose: bool @ivar ignoreAbruptClose: If an abrupt close of the socket should raise an error (writable). If you set this to True, TLS Lite will not raise a L{tlslite.errors.TLSAbruptCloseError} exception if the underlying socket is unexpectedly closed. Such an unexpected closure could be caused by an attacker. However, it also occurs with some incorrect TLS implementations. You should set this to True only if you're not worried about an attacker truncating the connection, and only if necessary to avoid spurious errors. The default is False. @sort: __init__, read, readAsync, write, writeAsync, close, closeAsync, getCipherImplementation, getCipherName """ def __init__(self, sock): self.sock = sock #My session object (Session instance; read-only) self.session = None #Am I a client or server? self._client = None #Buffers for processing messages self._handshakeBuffer = [] self._readBuffer = "" #Handshake digests self._handshake_md5 = md5.md5() self._handshake_sha = sha.sha() #TLS Protocol Version self.version = (0,0) #read-only self._versionCheck = False #Once we choose a version, this is True #Current and Pending connection states self._writeState = _ConnectionState() self._readState = _ConnectionState() self._pendingWriteState = _ConnectionState() self._pendingReadState = _ConnectionState() #Is the connection open? self.closed = True #read-only self._refCount = 0 #Used to trigger closure #Is this a resumed (or shared-key) session? self.resumed = False #read-only #What username did the client claim in his handshake? self.allegedSharedKeyUsername = None self.allegedSrpUsername = None #On a call to close(), do we close the socket? (writeable) self.closeSocket = False #If the socket is abruptly closed, do we ignore it #and pretend the connection was shut down properly? (writeable) self.ignoreAbruptClose = False #Fault we will induce, for testing purposes self.fault = None #********************************************************* # Public Functions START #********************************************************* def read(self, max=None, min=1): """Read some data from the TLS connection. This function will block until at least 'min' bytes are available (or the connection is closed). If an exception is raised, the connection will have been automatically closed. @type max: int @param max: The maximum number of bytes to return. @type min: int @param min: The minimum number of bytes to return @rtype: str @return: A string of no more than 'max' bytes, and no fewer than 'min' (unless the connection has been closed, in which case fewer than 'min' bytes may be returned). @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. """ for result in self.readAsync(max, min): pass return result def readAsync(self, max=None, min=1): """Start a read operation on the TLS connection. This function returns a generator which behaves similarly to read(). Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or a string if the read operation has completed. @rtype: iterable @return: A generator; see above for details. """ try: while len(self._readBuffer)<min and not self.closed: try: for result in self._getMsg(ContentType.application_data): if result in (0,1): yield result applicationData = result self._readBuffer += bytesToString(applicationData.write()) except TLSRemoteAlert, alert: if alert.description != AlertDescription.close_notify: raise except TLSAbruptCloseError: if not self.ignoreAbruptClose: raise else: self._shutdown(True) if max == None: max = len(self._readBuffer) returnStr = self._readBuffer[:max] self._readBuffer = self._readBuffer[max:] yield returnStr except: self._shutdown(False) raise def write(self, s): """Write some data to the TLS connection. This function will block until all the data has been sent. If an exception is raised, the connection will have been automatically closed. @type s: str @param s: The data to transmit to the other party. @raise socket.error: If a socket error occurs. """ for result in self.writeAsync(s): pass def writeAsync(self, s): """Start a write operation on the TLS connection. This function returns a generator which behaves similarly to write(). Successive invocations of the generator will return 1 if it is waiting to write to the socket, or will raise StopIteration if the write operation has completed. @rtype: iterable @return: A generator; see above for details. """ try: if self.closed: raise ValueError() index = 0 blockSize = 16384 skipEmptyFrag = False while 1: startIndex = index * blockSize endIndex = startIndex + blockSize if startIndex >= len(s): break if endIndex > len(s): endIndex = len(s) block = stringToBytes(s[startIndex : endIndex]) applicationData = ApplicationData().create(block) for result in self._sendMsg(applicationData, skipEmptyFrag): yield result skipEmptyFrag = True #only send an empy fragment on 1st message index += 1 except: self._shutdown(False) raise def close(self): """Close the TLS connection. This function will block until it has exchanged close_notify alerts with the other party. After doing so, it will shut down the TLS connection. Further attempts to read through this connection will return "". Further attempts to write through this connection will raise ValueError. If makefile() has been called on this connection, the connection will be not be closed until the connection object and all file objects have been closed. Even if an exception is raised, the connection will have been closed. @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. """ if not self.closed: for result in self._decrefAsync(): pass def closeAsync(self): """Start a close operation on the TLS connection. This function returns a generator which behaves similarly to close(). Successive invocations of the generator will return 0 if it is waiting to read from the socket, 1 if it is waiting to write to the socket, or will raise StopIteration if the close operation has completed. @rtype: iterable @return: A generator; see above for details. """ if not self.closed: for result in self._decrefAsync(): yield result def _decrefAsync(self): self._refCount -= 1 if self._refCount == 0 and not self.closed: try: for result in self._sendMsg(Alert().create(\ AlertDescription.close_notify, AlertLevel.warning)): yield result alert = None while not alert: for result in self._getMsg((ContentType.alert, \ ContentType.application_data)): if result in (0,1): yield result if result.contentType == ContentType.alert: alert = result if alert.description == AlertDescription.close_notify: self._shutdown(True) else: raise TLSRemoteAlert(alert) except (socket.error, TLSAbruptCloseError): #If the other side closes the socket, that's okay self._shutdown(True) except: self._shutdown(False) raise def getCipherName(self): """Get the name of the cipher used with this connection. @rtype: str @return: The name of the cipher used with this connection. Either 'aes128', 'aes256', 'rc4', or '3des'. """ if not self._writeState.encContext: return None return self._writeState.encContext.name def getCipherImplementation(self): """Get the name of the cipher implementation used with this connection. @rtype: str @return: The name of the cipher implementation used with this connection. Either 'python', 'cryptlib', 'openssl', or 'pycrypto'. """ if not self._writeState.encContext: return None return self._writeState.encContext.implementation #Emulate a socket, somewhat - def send(self, s): """Send data to the TLS connection (socket emulation). @raise socket.error: If a socket error occurs. """ self.write(s) return len(s) def sendall(self, s): """Send data to the TLS connection (socket emulation). @raise socket.error: If a socket error occurs. """ self.write(s) def recv(self, bufsize): """Get some data from the TLS connection (socket emulation). @raise socket.error: If a socket error occurs. @raise tlslite.errors.TLSAbruptCloseError: If the socket is closed without a preceding alert. @raise tlslite.errors.TLSAlert: If a TLS alert is signalled. """ return self.read(bufsize) def makefile(self, mode='r', bufsize=-1): """Create a file object for the TLS connection (socket emulation). @rtype: L{tlslite.FileObject.FileObject} """ self._refCount += 1 return FileObject(self, mode, bufsize) def getsockname(self): """Return the socket's own address (socket emulation).""" return self.sock.getsockname() def getpeername(self): """Return the remote address to which the socket is connected (socket emulation).""" return self.sock.getpeername() def settimeout(self, value): """Set a timeout on blocking socket operations (socket emulation).""" return self.sock.settimeout(value) def gettimeout(self): """Return the timeout associated with socket operations (socket emulation).""" return self.sock.gettimeout() def setsockopt(self, level, optname, value): """Set the value of the given socket option (socket emulation).""" return self.sock.setsockopt(level, optname, value) #********************************************************* # Public Functions END #********************************************************* def _shutdown(self, resumable): self._writeState = _ConnectionState() self._readState = _ConnectionState() #Don't do this: self._readBuffer = "" self.version = (0,0) self._versionCheck = False self.closed = True if self.closeSocket: self.sock.close() #Even if resumable is False, we'll never toggle this on if not resumable and self.session: self.session.resumable = False def _sendError(self, alertDescription, errorStr=None): alert = Alert().create(alertDescription, AlertLevel.fatal) for result in self._sendMsg(alert): yield result self._shutdown(False) raise TLSLocalAlert(alert, errorStr) def _sendMsgs(self, msgs): skipEmptyFrag = False for msg in msgs: for result in self._sendMsg(msg, skipEmptyFrag): yield result skipEmptyFrag = True def _sendMsg(self, msg, skipEmptyFrag=False): bytes = msg.write() contentType = msg.contentType #Whenever we're connected and asked to send a message, #we first send an empty Application Data message. This prevents #an attacker from launching a chosen-plaintext attack based on #knowing the next IV. if not self.closed and not skipEmptyFrag and self.version == (3,1): if self._writeState.encContext: if self._writeState.encContext.isBlockCipher: for result in self._sendMsg(ApplicationData(), skipEmptyFrag=True): yield result #Update handshake hashes if contentType == ContentType.handshake: bytesStr = bytesToString(bytes) self._handshake_md5.update(bytesStr) self._handshake_sha.update(bytesStr) #Calculate MAC if self._writeState.macContext: seqnumStr = self._writeState.getSeqNumStr() bytesStr = bytesToString(bytes) mac = self._writeState.macContext.copy() mac.update(seqnumStr) mac.update(chr(contentType)) if self.version == (3,0): mac.update( chr( int(len(bytes)/256) ) ) mac.update( chr( int(len(bytes)%256) ) ) elif self.version in ((3,1), (3,2)): mac.update(chr(self.version[0])) mac.update(chr(self.version[1])) mac.update( chr( int(len(bytes)/256) ) ) mac.update( chr( int(len(bytes)%256) ) ) else: raise AssertionError() mac.update(bytesStr) macString = mac.digest() macBytes = stringToBytes(macString) if self.fault == Fault.badMAC: macBytes[0] = (macBytes[0]+1) % 256 #Encrypt for Block or Stream Cipher if self._writeState.encContext: #Add padding and encrypt (for Block Cipher): if self._writeState.encContext.isBlockCipher: #Add TLS 1.1 fixed block if self.version == (3,2): bytes = self.fixedIVBlock + bytes #Add padding: bytes = bytes + (macBytes + paddingBytes) currentLength = len(bytes) + len(macBytes) + 1 blockLength = self._writeState.encContext.block_size paddingLength = blockLength-(currentLength % blockLength) paddingBytes = createByteArraySequence([paddingLength] * \ (paddingLength+1)) if self.fault == Fault.badPadding: paddingBytes[0] = (paddingBytes[0]+1) % 256 endBytes = concatArrays(macBytes, paddingBytes) bytes = concatArrays(bytes, endBytes) #Encrypt plaintext = stringToBytes(bytes) ciphertext = self._writeState.encContext.encrypt(plaintext) bytes = stringToBytes(ciphertext) #Encrypt (for Stream Cipher) else: bytes = concatArrays(bytes, macBytes) plaintext = bytesToString(bytes) ciphertext = self._writeState.encContext.encrypt(plaintext) bytes = stringToBytes(ciphertext) #Add record header and send r = RecordHeader3().create(self.version, contentType, len(bytes)) s = bytesToString(concatArrays(r.write(), bytes)) while 1: try: bytesSent = self.sock.send(s) #Might raise socket.error except socket.error, why: if why[0] == errno.EWOULDBLOCK: yield 1 continue else: raise if bytesSent == len(s): return s = s[bytesSent:] yield 1 def _getMsg(self, expectedType, secondaryType=None, constructorType=None): try: if not isinstance(expectedType, tuple): expectedType = (expectedType,) #Spin in a loop, until we've got a non-empty record of a type we #expect. The loop will be repeated if: # - we receive a renegotiation attempt; we send no_renegotiation, # then try again # - we receive an empty application-data fragment; we try again while 1: for result in self._getNextRecord(): if result in (0,1): yield result recordHeader, p = result #If this is an empty application-data fragment, try again if recordHeader.type == ContentType.application_data: if p.index == len(p.bytes): continue #If we received an unexpected record type... if recordHeader.type not in expectedType: #If we received an alert... if recordHeader.type == ContentType.alert: alert = Alert().parse(p) #We either received a fatal error, a warning, or a #close_notify. In any case, we're going to close the #connection. In the latter two cases we respond with #a close_notify, but ignore any socket errors, since #the other side might have already closed the socket. if alert.level == AlertLevel.warning or \ alert.description == AlertDescription.close_notify: #If the sendMsg() call fails because the socket has #already been closed, we will be forgiving and not #report the error nor invalidate the "resumability" #of the session. try: alertMsg = Alert() alertMsg.create(AlertDescription.close_notify, AlertLevel.warning) for result in self._sendMsg(alertMsg): yield result except socket.error: pass if alert.description == \ AlertDescription.close_notify: self._shutdown(True) elif alert.level == AlertLevel.warning: self._shutdown(False) else: #Fatal alert: self._shutdown(False) #Raise the alert as an exception raise TLSRemoteAlert(alert) #If we received a renegotiation attempt... if recordHeader.type == ContentType.handshake: subType = p.get(1) reneg = False if self._client: if subType == HandshakeType.hello_request: reneg = True else: if subType == HandshakeType.client_hello: reneg = True #Send no_renegotiation, then try again if reneg: alertMsg = Alert() alertMsg.create(AlertDescription.no_renegotiation, AlertLevel.warning) for result in self._sendMsg(alertMsg): yield result continue #Otherwise: this is an unexpected record, but neither an #alert nor renegotiation for result in self._sendError(\ AlertDescription.unexpected_message, "received type=%d" % recordHeader.type): yield result break #Parse based on content_type if recordHeader.type == ContentType.change_cipher_spec: yield ChangeCipherSpec().parse(p) elif recordHeader.type == ContentType.alert: yield Alert().parse(p) elif recordHeader.type == ContentType.application_data: yield ApplicationData().parse(p) elif recordHeader.type == ContentType.handshake: #Convert secondaryType to tuple, if it isn't already if not isinstance(secondaryType, tuple): secondaryType = (secondaryType,) #If it's a handshake message, check handshake header if recordHeader.ssl2: subType = p.get(1) if subType != HandshakeType.client_hello: for result in self._sendError(\ AlertDescription.unexpected_message, "Can only handle SSLv2 ClientHello messages"): yield result if HandshakeType.client_hello not in secondaryType: for result in self._sendError(\ AlertDescription.unexpected_message): yield result subType = HandshakeType.client_hello else: subType = p.get(1) if subType not in secondaryType: for result in self._sendError(\ AlertDescription.unexpected_message, "Expecting %s, got %s" % (str(secondaryType), subType)): yield result #Update handshake hashes sToHash = bytesToString(p.bytes) self._handshake_md5.update(sToHash) self._handshake_sha.update(sToHash) #Parse based on handshake type if subType == HandshakeType.client_hello: yield ClientHello(recordHeader.ssl2).parse(p) elif subType == HandshakeType.server_hello: yield ServerHello().parse(p) elif subType == HandshakeType.certificate: yield Certificate(constructorType).parse(p) elif subType == HandshakeType.certificate_request: yield CertificateRequest().parse(p) elif subType == HandshakeType.certificate_verify: yield CertificateVerify().parse(p) elif subType == HandshakeType.server_key_exchange: yield ServerKeyExchange(constructorType).parse(p) elif subType == HandshakeType.server_hello_done: yield ServerHelloDone().parse(p) elif subType == HandshakeType.client_key_exchange: yield ClientKeyExchange(constructorType, \ self.version).parse(p) elif subType == HandshakeType.finished: yield Finished(self.version).parse(p) else: raise AssertionError() #If an exception was raised by a Parser or Message instance: except SyntaxError, e: for result in self._sendError(AlertDescription.decode_error, formatExceptionTrace(e)): yield result #Returns next record or next handshake message def _getNextRecord(self): #If there's a handshake message waiting, return it if self._handshakeBuffer: recordHeader, bytes = self._handshakeBuffer[0] self._handshakeBuffer = self._handshakeBuffer[1:] yield (recordHeader, Parser(bytes)) return #Otherwise... #Read the next record header bytes = createByteArraySequence([]) recordHeaderLength = 1 ssl2 = False while 1: try: s = self.sock.recv(recordHeaderLength-len(bytes)) except socket.error, why: if why[0] == errno.EWOULDBLOCK: yield 0 continue else: raise #If the connection was abruptly closed, raise an error if len(s)==0: raise TLSAbruptCloseError() bytes += stringToBytes(s) if len(bytes)==1: if bytes[0] in ContentType.all: ssl2 = False recordHeaderLength = 5 elif bytes[0] == 128: ssl2 = True recordHeaderLength = 2 else: raise SyntaxError() if len(bytes) == recordHeaderLength: break #Parse the record header if ssl2: r = RecordHeader2().parse(Parser(bytes)) else: r = RecordHeader3().parse(Parser(bytes)) #Check the record header fields if r.length > 18432: for result in self._sendError(AlertDescription.record_overflow): yield result #Read the record contents bytes = createByteArraySequence([]) while 1: try: s = self.sock.recv(r.length - len(bytes)) except socket.error, why: if why[0] == errno.EWOULDBLOCK: yield 0 continue else: raise #If the connection is closed, raise a socket error if len(s)==0: raise TLSAbruptCloseError() bytes += stringToBytes(s) if len(bytes) == r.length: break #Check the record header fields (2) #We do this after reading the contents from the socket, so that #if there's an error, we at least don't leave extra bytes in the #socket.. # # THIS CHECK HAS NO SECURITY RELEVANCE (?), BUT COULD HURT INTEROP. # SO WE LEAVE IT OUT FOR NOW. # #if self._versionCheck and r.version != self.version: # for result in self._sendError(AlertDescription.protocol_version, # "Version in header field: %s, should be %s" % (str(r.version), # str(self.version))): # yield result #Decrypt the record for result in self._decryptRecord(r.type, bytes): if result in (0,1): yield result else: break bytes = result p = Parser(bytes) #If it doesn't contain handshake messages, we can just return it if r.type != ContentType.handshake: yield (r, p) #If it's an SSLv2 ClientHello, we can return it as well elif r.ssl2: yield (r, p) else: #Otherwise, we loop through and add the handshake messages to the #handshake buffer while 1: if p.index == len(bytes): #If we're at the end if not self._handshakeBuffer: for result in self._sendError(\ AlertDescription.decode_error, \ "Received empty handshake record"): yield result break #There needs to be at least 4 bytes to get a header if p.index+4 > len(bytes): for result in self._sendError(\ AlertDescription.decode_error, "A record has a partial handshake message (1)"): yield result p.get(1) # skip handshake type msgLength = p.get(3) if p.index+msgLength > len(bytes): for result in self._sendError(\ AlertDescription.decode_error, "A record has a partial handshake message (2)"): yield result handshakePair = (r, bytes[p.index-4 : p.index+msgLength]) self._handshakeBuffer.append(handshakePair) p.index += msgLength #We've moved at least one handshake message into the #handshakeBuffer, return the first one recordHeader, bytes = self._handshakeBuffer[0] self._handshakeBuffer = self._handshakeBuffer[1:] yield (recordHeader, Parser(bytes)) def _decryptRecord(self, recordType, bytes): if self._readState.encContext: #Decrypt if it's a block cipher if self._readState.encContext.isBlockCipher: blockLength = self._readState.encContext.block_size if len(bytes) % blockLength != 0: for result in self._sendError(\ AlertDescription.decryption_failed, "Encrypted data not a multiple of blocksize"): yield result ciphertext = bytesToString(bytes) plaintext = self._readState.encContext.decrypt(ciphertext) if self.version == (3,2): #For TLS 1.1, remove explicit IV plaintext = plaintext[self._readState.encContext.block_size : ] bytes = stringToBytes(plaintext) #Check padding paddingGood = True paddingLength = bytes[-1] if (paddingLength+1) > len(bytes): paddingGood=False totalPaddingLength = 0 else: if self.version == (3,0): totalPaddingLength = paddingLength+1 elif self.version in ((3,1), (3,2)): totalPaddingLength = paddingLength+1 paddingBytes = bytes[-totalPaddingLength:-1] for byte in paddingBytes: if byte != paddingLength: paddingGood = False totalPaddingLength = 0 else: raise AssertionError() #Decrypt if it's a stream cipher else: paddingGood = True ciphertext = bytesToString(bytes) plaintext = self._readState.encContext.decrypt(ciphertext) bytes = stringToBytes(plaintext) totalPaddingLength = 0 #Check MAC macGood = True macLength = self._readState.macContext.digest_size endLength = macLength + totalPaddingLength if endLength > len(bytes): macGood = False else: #Read MAC startIndex = len(bytes) - endLength endIndex = startIndex + macLength checkBytes = bytes[startIndex : endIndex] #Calculate MAC seqnumStr = self._readState.getSeqNumStr() bytes = bytes[:-endLength] bytesStr = bytesToString(bytes) mac = self._readState.macContext.copy() mac.update(seqnumStr) mac.update(chr(recordType)) if self.version == (3,0): mac.update( chr( int(len(bytes)/256) ) ) mac.update( chr( int(len(bytes)%256) ) ) elif self.version in ((3,1), (3,2)): mac.update(chr(self.version[0])) mac.update(chr(self.version[1])) mac.update( chr( int(len(bytes)/256) ) ) mac.update( chr( int(len(bytes)%256) ) ) else: raise AssertionError() mac.update(bytesStr) macString = mac.digest() macBytes = stringToBytes(macString) #Compare MACs if macBytes != checkBytes: macGood = False if not (paddingGood and macGood): for result in self._sendError(AlertDescription.bad_record_mac, "MAC failure (or padding failure)"): yield result yield bytes def _handshakeStart(self, client): self._client = client self._handshake_md5 = md5.md5() self._handshake_sha = sha.sha() self._handshakeBuffer = [] self.allegedSharedKeyUsername = None self.allegedSrpUsername = None self._refCount = 1 def _handshakeDone(self, resumed): self.resumed = resumed self.closed = False def _calcPendingStates(self, clientRandom, serverRandom, implementations): if self.session.cipherSuite in CipherSuite.aes128Suites: macLength = 20 keyLength = 16 ivLength = 16 createCipherFunc = createAES elif self.session.cipherSuite in CipherSuite.aes256Suites: macLength = 20 keyLength = 32 ivLength = 16 createCipherFunc = createAES elif self.session.cipherSuite in CipherSuite.rc4Suites: macLength = 20 keyLength = 16 ivLength = 0 createCipherFunc = createRC4 elif self.session.cipherSuite in CipherSuite.tripleDESSuites: macLength = 20 keyLength = 24 ivLength = 8 createCipherFunc = createTripleDES else: raise AssertionError() if self.version == (3,0): createMACFunc = MAC_SSL elif self.version in ((3,1), (3,2)): createMACFunc = hmac.HMAC outputLength = (macLength*2) + (keyLength*2) + (ivLength*2) #Calculate Keying Material from Master Secret if self.version == (3,0): keyBlock = PRF_SSL(self.session.masterSecret, concatArrays(serverRandom, clientRandom), outputLength) elif self.version in ((3,1), (3,2)): keyBlock = PRF(self.session.masterSecret, "key expansion", concatArrays(serverRandom,clientRandom), outputLength) else: raise AssertionError() #Slice up Keying Material clientPendingState = _ConnectionState() serverPendingState = _ConnectionState() p = Parser(keyBlock) clientMACBlock = bytesToString(p.getFixBytes(macLength)) serverMACBlock = bytesToString(p.getFixBytes(macLength)) clientKeyBlock = bytesToString(p.getFixBytes(keyLength)) serverKeyBlock = bytesToString(p.getFixBytes(keyLength)) clientIVBlock = bytesToString(p.getFixBytes(ivLength)) serverIVBlock = bytesToString(p.getFixBytes(ivLength)) clientPendingState.macContext = createMACFunc(clientMACBlock, digestmod=sha) serverPendingState.macContext = createMACFunc(serverMACBlock, digestmod=sha) clientPendingState.encContext = createCipherFunc(clientKeyBlock, clientIVBlock, implementations) serverPendingState.encContext = createCipherFunc(serverKeyBlock, serverIVBlock, implementations) #Assign new connection states to pending states if self._client: self._pendingWriteState = clientPendingState self._pendingReadState = serverPendingState else: self._pendingWriteState = serverPendingState self._pendingReadState = clientPendingState if self.version == (3,2) and ivLength: #Choose fixedIVBlock for TLS 1.1 (this is encrypted with the CBC #residue to create the IV for each sent block) self.fixedIVBlock = getRandomBytes(ivLength) def _changeWriteState(self): self._writeState = self._pendingWriteState self._pendingWriteState = _ConnectionState() def _changeReadState(self): self._readState = self._pendingReadState self._pendingReadState = _ConnectionState() def _sendFinished(self): #Send ChangeCipherSpec for result in self._sendMsg(ChangeCipherSpec()): yield result #Switch to pending write state self._changeWriteState() #Calculate verification data verifyData = self._calcFinished(True) if self.fault == Fault.badFinished: verifyData[0] = (verifyData[0]+1)%256 #Send Finished message under new state finished = Finished(self.version).create(verifyData) for result in self._sendMsg(finished): yield result def _getFinished(self): #Get and check ChangeCipherSpec for result in self._getMsg(ContentType.change_cipher_spec): if result in (0,1): yield result changeCipherSpec = result if changeCipherSpec.type != 1: for result in self._sendError(AlertDescription.illegal_parameter, "ChangeCipherSpec type incorrect"): yield result #Switch to pending read state self._changeReadState() #Calculate verification data verifyData = self._calcFinished(False) #Get and check Finished message under new state for result in self._getMsg(ContentType.handshake, HandshakeType.finished): if result in (0,1): yield result finished = result if finished.verify_data != verifyData: for result in self._sendError(AlertDescription.decrypt_error, "Finished message is incorrect"): yield result def _calcFinished(self, send=True): if self.version == (3,0): if (self._client and send) or (not self._client and not send): senderStr = "\x43\x4C\x4E\x54" else: senderStr = "\x53\x52\x56\x52" verifyData = self._calcSSLHandshakeHash(self.session.masterSecret, senderStr) return verifyData elif self.version in ((3,1), (3,2)): if (self._client and send) or (not self._client and not send): label = "client finished" else: label = "server finished" handshakeHashes = stringToBytes(self._handshake_md5.digest() + \ self._handshake_sha.digest()) verifyData = PRF(self.session.masterSecret, label, handshakeHashes, 12) return verifyData else: raise AssertionError() #Used for Finished messages and CertificateVerify messages in SSL v3 def _calcSSLHandshakeHash(self, masterSecret, label): masterSecretStr = bytesToString(masterSecret) imac_md5 = self._handshake_md5.copy() imac_sha = self._handshake_sha.copy() imac_md5.update(label + masterSecretStr + '\x36'*48) imac_sha.update(label + masterSecretStr + '\x36'*40) md5Str = md5.md5(masterSecretStr + ('\x5c'*48) + \ imac_md5.digest()).digest() shaStr = sha.sha(masterSecretStr + ('\x5c'*40) + \ imac_sha.digest()).digest() return stringToBytes(md5Str + shaStr)
Python
"""Class representing an X.509 certificate.""" from utils.ASN1Parser import ASN1Parser from utils.cryptomath import * from utils.keyfactory import _createPublicRSAKey class X509: """This class represents an X.509 certificate. @type bytes: L{array.array} of unsigned bytes @ivar bytes: The DER-encoded ASN.1 certificate @type publicKey: L{tlslite.utils.RSAKey.RSAKey} @ivar publicKey: The subject public key from the certificate. """ def __init__(self): self.bytes = createByteArraySequence([]) self.publicKey = None def parse(self, s): """Parse a PEM-encoded X.509 certificate. @type s: str @param s: A PEM-encoded X.509 certificate (i.e. a base64-encoded certificate wrapped with "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----" tags). """ start = s.find("-----BEGIN CERTIFICATE-----") end = s.find("-----END CERTIFICATE-----") if start == -1: raise SyntaxError("Missing PEM prefix") if end == -1: raise SyntaxError("Missing PEM postfix") s = s[start+len("-----BEGIN CERTIFICATE-----") : end] bytes = base64ToBytes(s) self.parseBinary(bytes) return self def parseBinary(self, bytes): """Parse a DER-encoded X.509 certificate. @type bytes: str or L{array.array} of unsigned bytes @param bytes: A DER-encoded X.509 certificate. """ if isinstance(bytes, type("")): bytes = stringToBytes(bytes) self.bytes = bytes p = ASN1Parser(bytes) #Get the tbsCertificate tbsCertificateP = p.getChild(0) #Is the optional version field present? #This determines which index the key is at. if tbsCertificateP.value[0]==0xA0: subjectPublicKeyInfoIndex = 6 else: subjectPublicKeyInfoIndex = 5 #Get the subjectPublicKeyInfo subjectPublicKeyInfoP = tbsCertificateP.getChild(\ subjectPublicKeyInfoIndex) #Get the algorithm algorithmP = subjectPublicKeyInfoP.getChild(0) rsaOID = algorithmP.value if list(rsaOID) != [6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0]: raise SyntaxError("Unrecognized AlgorithmIdentifier") #Get the subjectPublicKey subjectPublicKeyP = subjectPublicKeyInfoP.getChild(1) #Adjust for BIT STRING encapsulation if (subjectPublicKeyP.value[0] !=0): raise SyntaxError() subjectPublicKeyP = ASN1Parser(subjectPublicKeyP.value[1:]) #Get the modulus and exponent modulusP = subjectPublicKeyP.getChild(0) publicExponentP = subjectPublicKeyP.getChild(1) #Decode them into numbers n = bytesToNumber(modulusP.value) e = bytesToNumber(publicExponentP.value) #Create a public key instance self.publicKey = _createPublicRSAKey(n, e) def getFingerprint(self): """Get the hex-encoded fingerprint of this certificate. @rtype: str @return: A hex-encoded fingerprint. """ return sha.sha(self.bytes).hexdigest() def getCommonName(self): """Get the Subject's Common Name from the certificate. The cryptlib_py module must be installed in order to use this function. @rtype: str or None @return: The CN component of the certificate's subject DN, if present. """ import cryptlib_py import array c = cryptlib_py.cryptImportCert(self.bytes, cryptlib_py.CRYPT_UNUSED) name = cryptlib_py.CRYPT_CERTINFO_COMMONNAME try: try: length = cryptlib_py.cryptGetAttributeString(c, name, None) returnVal = array.array('B', [0] * length) cryptlib_py.cryptGetAttributeString(c, name, returnVal) returnVal = returnVal.tostring() except cryptlib_py.CryptException, e: if e[0] == cryptlib_py.CRYPT_ERROR_NOTFOUND: returnVal = None return returnVal finally: cryptlib_py.cryptDestroyCert(c) def writeBytes(self): return self.bytes
Python
"""Class returned by TLSConnection.makefile().""" class FileObject: """This class provides a file object interface to a L{tlslite.TLSConnection.TLSConnection}. Call makefile() on a TLSConnection to create a FileObject instance. This class was copied, with minor modifications, from the _fileobject class in socket.py. Note that fileno() is not implemented.""" default_bufsize = 16384 #TREV: changed from 8192 def __init__(self, sock, mode='rb', bufsize=-1): self._sock = sock self.mode = mode # Not actually used in this version if bufsize < 0: bufsize = self.default_bufsize self.bufsize = bufsize self.softspace = False if bufsize == 0: self._rbufsize = 1 elif bufsize == 1: self._rbufsize = self.default_bufsize else: self._rbufsize = bufsize self._wbufsize = bufsize self._rbuf = "" # A string self._wbuf = [] # A list of strings def _getclosed(self): return self._sock is not None closed = property(_getclosed, doc="True if the file is closed") def close(self): try: if self._sock: for result in self._sock._decrefAsync(): #TREV pass finally: self._sock = None def __del__(self): try: self.close() except: # close() may fail if __init__ didn't complete pass def flush(self): if self._wbuf: buffer = "".join(self._wbuf) self._wbuf = [] self._sock.sendall(buffer) #def fileno(self): # raise NotImplementedError() #TREV def write(self, data): data = str(data) # XXX Should really reject non-string non-buffers if not data: return self._wbuf.append(data) if (self._wbufsize == 0 or self._wbufsize == 1 and '\n' in data or self._get_wbuf_len() >= self._wbufsize): self.flush() def writelines(self, list): # XXX We could do better here for very long lists # XXX Should really reject non-string non-buffers self._wbuf.extend(filter(None, map(str, list))) if (self._wbufsize <= 1 or self._get_wbuf_len() >= self._wbufsize): self.flush() def _get_wbuf_len(self): buf_len = 0 for x in self._wbuf: buf_len += len(x) return buf_len def read(self, size=-1): data = self._rbuf if size < 0: # Read until EOF buffers = [] if data: buffers.append(data) self._rbuf = "" if self._rbufsize <= 1: recv_size = self.default_bufsize else: recv_size = self._rbufsize while True: data = self._sock.recv(recv_size) if not data: break buffers.append(data) return "".join(buffers) else: # Read until size bytes or EOF seen, whichever comes first buf_len = len(data) if buf_len >= size: self._rbuf = data[size:] return data[:size] buffers = [] if data: buffers.append(data) self._rbuf = "" while True: left = size - buf_len recv_size = max(self._rbufsize, left) data = self._sock.recv(recv_size) if not data: break buffers.append(data) n = len(data) if n >= left: self._rbuf = data[left:] buffers[-1] = data[:left] break buf_len += n return "".join(buffers) def readline(self, size=-1): data = self._rbuf if size < 0: # Read until \n or EOF, whichever comes first if self._rbufsize <= 1: # Speed up unbuffered case assert data == "" buffers = [] recv = self._sock.recv while data != "\n": data = recv(1) if not data: break buffers.append(data) return "".join(buffers) nl = data.find('\n') if nl >= 0: nl += 1 self._rbuf = data[nl:] return data[:nl] buffers = [] if data: buffers.append(data) self._rbuf = "" while True: data = self._sock.recv(self._rbufsize) if not data: break buffers.append(data) nl = data.find('\n') if nl >= 0: nl += 1 self._rbuf = data[nl:] buffers[-1] = data[:nl] break return "".join(buffers) else: # Read until size bytes or \n or EOF seen, whichever comes first nl = data.find('\n', 0, size) if nl >= 0: nl += 1 self._rbuf = data[nl:] return data[:nl] buf_len = len(data) if buf_len >= size: self._rbuf = data[size:] return data[:size] buffers = [] if data: buffers.append(data) self._rbuf = "" while True: data = self._sock.recv(self._rbufsize) if not data: break buffers.append(data) left = size - buf_len nl = data.find('\n', 0, left) if nl >= 0: nl += 1 self._rbuf = data[nl:] buffers[-1] = data[:nl] break n = len(data) if n >= left: self._rbuf = data[left:] buffers[-1] = data[:left] break buf_len += n return "".join(buffers) def readlines(self, sizehint=0): total = 0 list = [] while True: line = self.readline() if not line: break list.append(line) total += len(line) if sizehint and total >= sizehint: break return list # Iterator protocols def __iter__(self): return self def next(self): line = self.readline() if not line: raise StopIteration return line
Python
"""Miscellaneous helper functions.""" from utils.compat import * from utils.cryptomath import * import hmac import md5 import sha #1024, 1536, 2048, 3072, 4096, 6144, and 8192 bit groups] goodGroupParameters = [(2,0xEEAF0AB9ADB38DD69C33F80AFA8FC5E86072618775FF3C0B9EA2314C9C256576D674DF7496EA81D3383B4813D692C6E0E0D5D8E250B98BE48E495C1D6089DAD15DC7D7B46154D6B6CE8EF4AD69B15D4982559B297BCF1885C529F566660E57EC68EDBC3C05726CC02FD4CBF4976EAA9AFD5138FE8376435B9FC61D2FC0EB06E3),\ (2,0x9DEF3CAFB939277AB1F12A8617A47BBBDBA51DF499AC4C80BEEEA9614B19CC4D5F4F5F556E27CBDE51C6A94BE4607A291558903BA0D0F84380B655BB9A22E8DCDF028A7CEC67F0D08134B1C8B97989149B609E0BE3BAB63D47548381DBC5B1FC764E3F4B53DD9DA1158BFD3E2B9C8CF56EDF019539349627DB2FD53D24B7C48665772E437D6C7F8CE442734AF7CCB7AE837C264AE3A9BEB87F8A2FE9B8B5292E5A021FFF5E91479E8CE7A28C2442C6F315180F93499A234DCF76E3FED135F9BB),\ (2,0xAC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC3192943DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310DCD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FBD5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF747359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E7303CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB694B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73),\ (2,0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF),\ (5,0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199FFFFFFFFFFFFFFFF),\ (5,0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DCC4024FFFFFFFFFFFFFFFF),\ (5,0xFFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF6955817183995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E208E24FA074E5AB3143DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D788719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA993B4EA988D8FDDC186FFB7DC90A6C08F4DF435C93402849236C3FAB4D27C7026C1D4DCB2602646DEC9751E763DBA37BDF8FF9406AD9E530EE5DB382F413001AEB06A53ED9027D831179727B0865A8918DA3EDBEBCF9B14ED44CE6CBACED4BB1BDB7F1447E6CC254B332051512BD7AF426FB8F401378CD2BF5983CA01C64B92ECF032EA15D1721D03F482D7CE6E74FEF6D55E702F46980C82B5A84031900B1C9E59E7C97FBEC7E8F323A97A7E36CC88BE0F1D45B7FF585AC54BD407B22B4154AACC8F6D7EBF48E1D814CC5ED20F8037E0A79715EEF29BE32806A1D58BB7C5DA76F550AA3D8A1FBFF0EB19CCB1A313D55CDA56C9EC2EF29632387FE8D76E3C0468043E8F663F4860EE12BF2D5B0B7474D6E694F91E6DBE115974A3926F12FEE5E438777CB6A932DF8CD8BEC4D073B931BA3BC832B68D9DD300741FA7BF8AFC47ED2576F6936BA424663AAB639C5AE4F5683423B4742BF1C978238F16CBE39D652DE3FDB8BEFC848AD922222E04A4037C0713EB57A81A23F0C73473FC646CEA306B4BCBC8862F8385DDFA9D4B7FA2C087E879683303ED5BDD3A062B3CF5B3A278A66D2A13F83F44F82DDF310EE074AB6A364597E899A0255DC164F31CC50846851DF9AB48195DED7EA1B1D510BD7EE74D73FAF36BC31ECFA268359046F4EB879F924009438B481C6CD7889A002ED5EE382BC9190DA6FC026E479558E4475677E9AA9E3050E2765694DFC81F56E880B96E7160C980DD98EDD3DFFFFFFFFFFFFFFFFF)] def P_hash(hashModule, secret, seed, length): bytes = createByteArrayZeros(length) secret = bytesToString(secret) seed = bytesToString(seed) A = seed index = 0 while 1: A = hmac.HMAC(secret, A, hashModule).digest() output = hmac.HMAC(secret, A+seed, hashModule).digest() for c in output: if index >= length: return bytes bytes[index] = ord(c) index += 1 return bytes def PRF(secret, label, seed, length): #Split the secret into left and right halves S1 = secret[ : int(math.ceil(len(secret)/2.0))] S2 = secret[ int(math.floor(len(secret)/2.0)) : ] #Run the left half through P_MD5 and the right half through P_SHA1 p_md5 = P_hash(md5, S1, concatArrays(stringToBytes(label), seed), length) p_sha1 = P_hash(sha, S2, concatArrays(stringToBytes(label), seed), length) #XOR the output values and return the result for x in range(length): p_md5[x] ^= p_sha1[x] return p_md5 def PRF_SSL(secret, seed, length): secretStr = bytesToString(secret) seedStr = bytesToString(seed) bytes = createByteArrayZeros(length) index = 0 for x in range(26): A = chr(ord('A')+x) * (x+1) # 'A', 'BB', 'CCC', etc.. input = secretStr + sha.sha(A + secretStr + seedStr).digest() output = md5.md5(input).digest() for c in output: if index >= length: return bytes bytes[index] = ord(c) index += 1 return bytes def makeX(salt, username, password): if len(username)>=256: raise ValueError("username too long") if len(salt)>=256: raise ValueError("salt too long") return stringToNumber(sha.sha(salt + sha.sha(username + ":" + password)\ .digest()).digest()) #This function is used by VerifierDB.makeVerifier def makeVerifier(username, password, bits): bitsIndex = {1024:0, 1536:1, 2048:2, 3072:3, 4096:4, 6144:5, 8192:6}[bits] g,N = goodGroupParameters[bitsIndex] salt = bytesToString(getRandomBytes(16)) x = makeX(salt, username, password) verifier = powMod(g, x, N) return N, g, salt, verifier def PAD(n, x): nLength = len(numberToString(n)) s = numberToString(x) if len(s) < nLength: s = ("\0" * (nLength-len(s))) + s return s def makeU(N, A, B): return stringToNumber(sha.sha(PAD(N, A) + PAD(N, B)).digest()) def makeK(N, g): return stringToNumber(sha.sha(numberToString(N) + PAD(N, g)).digest()) """ MAC_SSL Modified from Python HMAC by Trevor """ class MAC_SSL: """MAC_SSL class. This supports the API for Cryptographic Hash Functions (PEP 247). """ def __init__(self, key, msg = None, digestmod = None): """Create a new MAC_SSL object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. Defaults to the md5 module. """ if digestmod is None: import md5 digestmod = md5 if key == None: #TREVNEW - for faster copying return #TREVNEW self.digestmod = digestmod self.outer = digestmod.new() self.inner = digestmod.new() self.digest_size = digestmod.digest_size ipad = "\x36" * 40 opad = "\x5C" * 40 self.inner.update(key) self.inner.update(ipad) self.outer.update(key) self.outer.update(opad) if msg is not None: self.update(msg) def update(self, msg): """Update this hashing object with the string msg. """ self.inner.update(msg) def copy(self): """Return a separate copy of this hashing object. An update to this copy won't affect the original object. """ other = MAC_SSL(None) #TREVNEW - for faster copying other.digest_size = self.digest_size #TREVNEW other.digestmod = self.digestmod other.inner = self.inner.copy() other.outer = self.outer.copy() return other def digest(self): """Return the hash value of this hashing object. This returns a string containing 8-bit data. The object is not altered in any way by this function; you can continue updating the object after calling this function. """ h = self.outer.copy() h.update(self.inner.digest()) return h.digest() def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead. """ return "".join([hex(ord(x))[2:].zfill(2) for x in tuple(self.digest())])
Python
""" A helper class for using TLS Lite with stdlib clients (httplib, xmlrpclib, imaplib, poplib). """ from gdata.tlslite.Checker import Checker class ClientHelper: """This is a helper class used to integrate TLS Lite with various TLS clients (e.g. poplib, smtplib, httplib, etc.)""" def __init__(self, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings = None): """ For client authentication, use one of these argument combinations: - username, password (SRP) - username, sharedKey (shared-key) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP or shared-keys, or you can do certificate-based server authentication with one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) Certificate-based server authentication is compatible with SRP or certificate-based client authentication. It is not compatible with shared-keys. The constructor does not perform the TLS handshake itself, but simply stores these arguments for later. The handshake is performed only when this class needs to connect with the server. Then you should be prepared to handle TLS-specific exceptions. See the client handshake functions in L{tlslite.TLSConnection.TLSConnection} for details on which exceptions might be raised. @type username: str @param username: SRP or shared-key username. Requires the 'password' or 'sharedKey' argument. @type password: str @param password: SRP password for mutual authentication. Requires the 'username' argument. @type sharedKey: str @param sharedKey: Shared key for mutual authentication. Requires the 'username' argument. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes the SRP or shared-key related arguments. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: Private key for client authentication. Requires the 'certChain' argument. Excludes the SRP or shared-key related arguments. @type cryptoID: str @param cryptoID: cryptoID for server authentication. Mutually exclusive with the 'x509...' arguments. @type protocol: str @param protocol: cryptoID protocol URI for server authentication. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: Hex-encoded X.509 fingerprint for server authentication. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed to use this parameter. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. """ self.username = None self.password = None self.sharedKey = None self.certChain = None self.privateKey = None self.checker = None #SRP Authentication if username and password and not \ (sharedKey or certChain or privateKey): self.username = username self.password = password #Shared Key Authentication elif username and sharedKey and not \ (password or certChain or privateKey): self.username = username self.sharedKey = sharedKey #Certificate Chain Authentication elif certChain and privateKey and not \ (username or password or sharedKey): self.certChain = certChain self.privateKey = privateKey #No Authentication elif not password and not username and not \ sharedKey and not certChain and not privateKey: pass else: raise ValueError("Bad parameters") #Authenticate the server based on its cryptoID or fingerprint if sharedKey and (cryptoID or protocol or x509Fingerprint): raise ValueError("Can't use shared keys with other forms of"\ "authentication") self.checker = Checker(cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName) self.settings = settings self.tlsSession = None def _handshake(self, tlsConnection): if self.username and self.password: tlsConnection.handshakeClientSRP(username=self.username, password=self.password, checker=self.checker, settings=self.settings, session=self.tlsSession) elif self.username and self.sharedKey: tlsConnection.handshakeClientSharedKey(username=self.username, sharedKey=self.sharedKey, settings=self.settings) else: tlsConnection.handshakeClientCert(certChain=self.certChain, privateKey=self.privateKey, checker=self.checker, settings=self.settings, session=self.tlsSession) self.tlsSession = tlsConnection.session
Python
"""TLS Lite + imaplib.""" import socket from imaplib import IMAP4 from gdata.tlslite.TLSConnection import TLSConnection from gdata.tlslite.integration.ClientHelper import ClientHelper # IMAP TLS PORT IMAP4_TLS_PORT = 993 class IMAP4_TLS(IMAP4, ClientHelper): """This class extends L{imaplib.IMAP4} with TLS support.""" def __init__(self, host = '', port = IMAP4_TLS_PORT, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings=None): """Create a new IMAP4_TLS. For client authentication, use one of these argument combinations: - username, password (SRP) - username, sharedKey (shared-key) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP or shared-keys, or you can do certificate-based server authentication with one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) Certificate-based server authentication is compatible with SRP or certificate-based client authentication. It is not compatible with shared-keys. The caller should be prepared to handle TLS-specific exceptions. See the client handshake functions in L{tlslite.TLSConnection.TLSConnection} for details on which exceptions might be raised. @type host: str @param host: Server to connect to. @type port: int @param port: Port to connect to. @type username: str @param username: SRP or shared-key username. Requires the 'password' or 'sharedKey' argument. @type password: str @param password: SRP password for mutual authentication. Requires the 'username' argument. @type sharedKey: str @param sharedKey: Shared key for mutual authentication. Requires the 'username' argument. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes the SRP or shared-key related arguments. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: Private key for client authentication. Requires the 'certChain' argument. Excludes the SRP or shared-key related arguments. @type cryptoID: str @param cryptoID: cryptoID for server authentication. Mutually exclusive with the 'x509...' arguments. @type protocol: str @param protocol: cryptoID protocol URI for server authentication. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: Hex-encoded X.509 fingerprint for server authentication. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed to use this parameter. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. """ ClientHelper.__init__(self, username, password, sharedKey, certChain, privateKey, cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName, settings) IMAP4.__init__(self, host, port) def open(self, host = '', port = IMAP4_TLS_PORT): """Setup connection to remote server on "host:port". This connection will be used by the routines: read, readline, send, shutdown. """ self.host = host self.port = port self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sock.connect((host, port)) self.sock = TLSConnection(self.sock) self.sock.closeSocket = True ClientHelper._handshake(self, self.sock) self.file = self.sock.makefile('rb')
Python
"""TLS Lite + poplib.""" import socket from poplib import POP3 from gdata.tlslite.TLSConnection import TLSConnection from gdata.tlslite.integration.ClientHelper import ClientHelper # POP TLS PORT POP3_TLS_PORT = 995 class POP3_TLS(POP3, ClientHelper): """This class extends L{poplib.POP3} with TLS support.""" def __init__(self, host, port = POP3_TLS_PORT, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings=None): """Create a new POP3_TLS. For client authentication, use one of these argument combinations: - username, password (SRP) - username, sharedKey (shared-key) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP or shared-keys, or you can do certificate-based server authentication with one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) Certificate-based server authentication is compatible with SRP or certificate-based client authentication. It is not compatible with shared-keys. The caller should be prepared to handle TLS-specific exceptions. See the client handshake functions in L{tlslite.TLSConnection.TLSConnection} for details on which exceptions might be raised. @type host: str @param host: Server to connect to. @type port: int @param port: Port to connect to. @type username: str @param username: SRP or shared-key username. Requires the 'password' or 'sharedKey' argument. @type password: str @param password: SRP password for mutual authentication. Requires the 'username' argument. @type sharedKey: str @param sharedKey: Shared key for mutual authentication. Requires the 'username' argument. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes the SRP or shared-key related arguments. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: Private key for client authentication. Requires the 'certChain' argument. Excludes the SRP or shared-key related arguments. @type cryptoID: str @param cryptoID: cryptoID for server authentication. Mutually exclusive with the 'x509...' arguments. @type protocol: str @param protocol: cryptoID protocol URI for server authentication. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: Hex-encoded X.509 fingerprint for server authentication. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed to use this parameter. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. """ self.host = host self.port = port msg = "getaddrinfo returns an empty list" self.sock = None for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res try: self.sock = socket.socket(af, socktype, proto) self.sock.connect(sa) except socket.error, msg: if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error, msg ### New code below (all else copied from poplib) ClientHelper.__init__(self, username, password, sharedKey, certChain, privateKey, cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName, settings) self.sock = TLSConnection(self.sock) self.sock.closeSocket = True ClientHelper._handshake(self, self.sock) ### self.file = self.sock.makefile('rb') self._debugging = 0 self.welcome = self._getresp()
Python
"""TLS Lite + Twisted.""" from twisted.protocols.policies import ProtocolWrapper, WrappingFactory from twisted.python.failure import Failure from AsyncStateMachine import AsyncStateMachine from gdata.tlslite.TLSConnection import TLSConnection from gdata.tlslite.errors import * import socket import errno #The TLSConnection is created around a "fake socket" that #plugs it into the underlying Twisted transport class _FakeSocket: def __init__(self, wrapper): self.wrapper = wrapper self.data = "" def send(self, data): ProtocolWrapper.write(self.wrapper, data) return len(data) def recv(self, numBytes): if self.data == "": raise socket.error, (errno.EWOULDBLOCK, "") returnData = self.data[:numBytes] self.data = self.data[numBytes:] return returnData class TLSTwistedProtocolWrapper(ProtocolWrapper, AsyncStateMachine): """This class can wrap Twisted protocols to add TLS support. Below is a complete example of using TLS Lite with a Twisted echo server. There are two server implementations below. Echo is the original protocol, which is oblivious to TLS. Echo1 subclasses Echo and negotiates TLS when the client connects. Echo2 subclasses Echo and negotiates TLS when the client sends "STARTTLS":: from twisted.internet.protocol import Protocol, Factory from twisted.internet import reactor from twisted.protocols.policies import WrappingFactory from twisted.protocols.basic import LineReceiver from twisted.python import log from twisted.python.failure import Failure import sys from tlslite.api import * s = open("./serverX509Cert.pem").read() x509 = X509() x509.parse(s) certChain = X509CertChain([x509]) s = open("./serverX509Key.pem").read() privateKey = parsePEMKey(s, private=True) verifierDB = VerifierDB("verifierDB") verifierDB.open() class Echo(LineReceiver): def connectionMade(self): self.transport.write("Welcome to the echo server!\\r\\n") def lineReceived(self, line): self.transport.write(line + "\\r\\n") class Echo1(Echo): def connectionMade(self): if not self.transport.tlsStarted: self.transport.setServerHandshakeOp(certChain=certChain, privateKey=privateKey, verifierDB=verifierDB) else: Echo.connectionMade(self) def connectionLost(self, reason): pass #Handle any TLS exceptions here class Echo2(Echo): def lineReceived(self, data): if data == "STARTTLS": self.transport.setServerHandshakeOp(certChain=certChain, privateKey=privateKey, verifierDB=verifierDB) else: Echo.lineReceived(self, data) def connectionLost(self, reason): pass #Handle any TLS exceptions here factory = Factory() factory.protocol = Echo1 #factory.protocol = Echo2 wrappingFactory = WrappingFactory(factory) wrappingFactory.protocol = TLSTwistedProtocolWrapper log.startLogging(sys.stdout) reactor.listenTCP(1079, wrappingFactory) reactor.run() This class works as follows: Data comes in and is given to the AsyncStateMachine for handling. AsyncStateMachine will forward events to this class, and we'll pass them on to the ProtocolHandler, which will proxy them to the wrapped protocol. The wrapped protocol may then call back into this class, and these calls will be proxied into the AsyncStateMachine. The call graph looks like this: - self.dataReceived - AsyncStateMachine.inReadEvent - self.out(Connect|Close|Read)Event - ProtocolWrapper.(connectionMade|loseConnection|dataReceived) - self.(loseConnection|write|writeSequence) - AsyncStateMachine.(setCloseOp|setWriteOp) """ #WARNING: IF YOU COPY-AND-PASTE THE ABOVE CODE, BE SURE TO REMOVE #THE EXTRA ESCAPING AROUND "\\r\\n" def __init__(self, factory, wrappedProtocol): ProtocolWrapper.__init__(self, factory, wrappedProtocol) AsyncStateMachine.__init__(self) self.fakeSocket = _FakeSocket(self) self.tlsConnection = TLSConnection(self.fakeSocket) self.tlsStarted = False self.connectionLostCalled = False def connectionMade(self): try: ProtocolWrapper.connectionMade(self) except TLSError, e: self.connectionLost(Failure(e)) ProtocolWrapper.loseConnection(self) def dataReceived(self, data): try: if not self.tlsStarted: ProtocolWrapper.dataReceived(self, data) else: self.fakeSocket.data += data while self.fakeSocket.data: AsyncStateMachine.inReadEvent(self) except TLSError, e: self.connectionLost(Failure(e)) ProtocolWrapper.loseConnection(self) def connectionLost(self, reason): if not self.connectionLostCalled: ProtocolWrapper.connectionLost(self, reason) self.connectionLostCalled = True def outConnectEvent(self): ProtocolWrapper.connectionMade(self) def outCloseEvent(self): ProtocolWrapper.loseConnection(self) def outReadEvent(self, data): if data == "": ProtocolWrapper.loseConnection(self) else: ProtocolWrapper.dataReceived(self, data) def setServerHandshakeOp(self, **args): self.tlsStarted = True AsyncStateMachine.setServerHandshakeOp(self, **args) def loseConnection(self): if not self.tlsStarted: ProtocolWrapper.loseConnection(self) else: AsyncStateMachine.setCloseOp(self) def write(self, data): if not self.tlsStarted: ProtocolWrapper.write(self, data) else: #Because of the FakeSocket, write operations are guaranteed to #terminate immediately. AsyncStateMachine.setWriteOp(self, data) def writeSequence(self, seq): if not self.tlsStarted: ProtocolWrapper.writeSequence(self, seq) else: #Because of the FakeSocket, write operations are guaranteed to #terminate immediately. AsyncStateMachine.setWriteOp(self, "".join(seq))
Python
"""TLS Lite + SocketServer.""" from gdata.tlslite.TLSConnection import TLSConnection class TLSSocketServerMixIn: """ This class can be mixed in with any L{SocketServer.TCPServer} to add TLS support. To use this class, define a new class that inherits from it and some L{SocketServer.TCPServer} (with the mix-in first). Then implement the handshake() method, doing some sort of server handshake on the connection argument. If the handshake method returns True, the RequestHandler will be triggered. Below is a complete example of a threaded HTTPS server:: from SocketServer import * from BaseHTTPServer import * from SimpleHTTPServer import * from tlslite.api import * s = open("./serverX509Cert.pem").read() x509 = X509() x509.parse(s) certChain = X509CertChain([x509]) s = open("./serverX509Key.pem").read() privateKey = parsePEMKey(s, private=True) sessionCache = SessionCache() class MyHTTPServer(ThreadingMixIn, TLSSocketServerMixIn, HTTPServer): def handshake(self, tlsConnection): try: tlsConnection.handshakeServer(certChain=certChain, privateKey=privateKey, sessionCache=sessionCache) tlsConnection.ignoreAbruptClose = True return True except TLSError, error: print "Handshake failure:", str(error) return False httpd = MyHTTPServer(('localhost', 443), SimpleHTTPRequestHandler) httpd.serve_forever() """ def finish_request(self, sock, client_address): tlsConnection = TLSConnection(sock) if self.handshake(tlsConnection) == True: self.RequestHandlerClass(tlsConnection, client_address, self) tlsConnection.close() #Implement this method to do some form of handshaking. Return True #if the handshake finishes properly and the request is authorized. def handshake(self, tlsConnection): raise NotImplementedError()
Python
"""TLS Lite + httplib.""" import socket import httplib from gdata.tlslite.TLSConnection import TLSConnection from gdata.tlslite.integration.ClientHelper import ClientHelper class HTTPBaseTLSConnection(httplib.HTTPConnection): """This abstract class provides a framework for adding TLS support to httplib.""" default_port = 443 def __init__(self, host, port=None, strict=None): if strict == None: #Python 2.2 doesn't support strict httplib.HTTPConnection.__init__(self, host, port) else: httplib.HTTPConnection.__init__(self, host, port, strict) def connect(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if hasattr(sock, 'settimeout'): sock.settimeout(10) sock.connect((self.host, self.port)) #Use a TLSConnection to emulate a socket self.sock = TLSConnection(sock) #When httplib closes this, close the socket self.sock.closeSocket = True self._handshake(self.sock) def _handshake(self, tlsConnection): """Called to perform some sort of handshake. This method must be overridden in a subclass to do some type of handshake. This method will be called after the socket has been connected but before any data has been sent. If this method does not raise an exception, the TLS connection will be considered valid. This method may (or may not) be called every time an HTTP request is performed, depending on whether the underlying HTTP connection is persistent. @type tlsConnection: L{tlslite.TLSConnection.TLSConnection} @param tlsConnection: The connection to perform the handshake on. """ raise NotImplementedError() class HTTPTLSConnection(HTTPBaseTLSConnection, ClientHelper): """This class extends L{HTTPBaseTLSConnection} to support the common types of handshaking.""" def __init__(self, host, port=None, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings = None): """Create a new HTTPTLSConnection. For client authentication, use one of these argument combinations: - username, password (SRP) - username, sharedKey (shared-key) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP or shared-keys, or you can do certificate-based server authentication with one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) Certificate-based server authentication is compatible with SRP or certificate-based client authentication. It is not compatible with shared-keys. The constructor does not perform the TLS handshake itself, but simply stores these arguments for later. The handshake is performed only when this class needs to connect with the server. Thus you should be prepared to handle TLS-specific exceptions when calling methods inherited from L{httplib.HTTPConnection} such as request(), connect(), and send(). See the client handshake functions in L{tlslite.TLSConnection.TLSConnection} for details on which exceptions might be raised. @type host: str @param host: Server to connect to. @type port: int @param port: Port to connect to. @type username: str @param username: SRP or shared-key username. Requires the 'password' or 'sharedKey' argument. @type password: str @param password: SRP password for mutual authentication. Requires the 'username' argument. @type sharedKey: str @param sharedKey: Shared key for mutual authentication. Requires the 'username' argument. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes the SRP or shared-key related arguments. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: Private key for client authentication. Requires the 'certChain' argument. Excludes the SRP or shared-key related arguments. @type cryptoID: str @param cryptoID: cryptoID for server authentication. Mutually exclusive with the 'x509...' arguments. @type protocol: str @param protocol: cryptoID protocol URI for server authentication. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: Hex-encoded X.509 fingerprint for server authentication. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed to use this parameter. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. """ HTTPBaseTLSConnection.__init__(self, host, port) ClientHelper.__init__(self, username, password, sharedKey, certChain, privateKey, cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName, settings) def _handshake(self, tlsConnection): ClientHelper._handshake(self, tlsConnection)
Python
"""TLS Lite + smtplib.""" from smtplib import SMTP from gdata.tlslite.TLSConnection import TLSConnection from gdata.tlslite.integration.ClientHelper import ClientHelper class SMTP_TLS(SMTP): """This class extends L{smtplib.SMTP} with TLS support.""" def starttls(self, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings=None): """Puts the connection to the SMTP server into TLS mode. If the server supports TLS, this will encrypt the rest of the SMTP session. For client authentication, use one of these argument combinations: - username, password (SRP) - username, sharedKey (shared-key) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP or shared-keys, or you can do certificate-based server authentication with one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) Certificate-based server authentication is compatible with SRP or certificate-based client authentication. It is not compatible with shared-keys. The caller should be prepared to handle TLS-specific exceptions. See the client handshake functions in L{tlslite.TLSConnection.TLSConnection} for details on which exceptions might be raised. @type username: str @param username: SRP or shared-key username. Requires the 'password' or 'sharedKey' argument. @type password: str @param password: SRP password for mutual authentication. Requires the 'username' argument. @type sharedKey: str @param sharedKey: Shared key for mutual authentication. Requires the 'username' argument. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes the SRP or shared-key related arguments. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: Private key for client authentication. Requires the 'certChain' argument. Excludes the SRP or shared-key related arguments. @type cryptoID: str @param cryptoID: cryptoID for server authentication. Mutually exclusive with the 'x509...' arguments. @type protocol: str @param protocol: cryptoID protocol URI for server authentication. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: Hex-encoded X.509 fingerprint for server authentication. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed to use this parameter. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. """ (resp, reply) = self.docmd("STARTTLS") if resp == 220: helper = ClientHelper( username, password, sharedKey, certChain, privateKey, cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName, settings) conn = TLSConnection(self.sock) conn.closeSocket = True helper._handshake(conn) self.sock = conn self.file = conn.makefile('rb') return (resp, reply)
Python
"""TLS Lite + asyncore.""" import asyncore from gdata.tlslite.TLSConnection import TLSConnection from AsyncStateMachine import AsyncStateMachine class TLSAsyncDispatcherMixIn(AsyncStateMachine): """This class can be "mixed in" with an L{asyncore.dispatcher} to add TLS support. This class essentially sits between the dispatcher and the select loop, intercepting events and only calling the dispatcher when applicable. In the case of handle_read(), a read operation will be activated, and when it completes, the bytes will be placed in a buffer where the dispatcher can retrieve them by calling recv(), and the dispatcher's handle_read() will be called. In the case of handle_write(), the dispatcher's handle_write() will be called, and when it calls send(), a write operation will be activated. To use this class, you must combine it with an asyncore.dispatcher, and pass in a handshake operation with setServerHandshakeOp(). Below is an example of using this class with medusa. This class is mixed in with http_channel to create http_tls_channel. Note: 1. the mix-in is listed first in the inheritance list 2. the input buffer size must be at least 16K, otherwise the dispatcher might not read all the bytes from the TLS layer, leaving some bytes in limbo. 3. IE seems to have a problem receiving a whole HTTP response in a single TLS record, so HTML pages containing '\\r\\n\\r\\n' won't be displayed on IE. Add the following text into 'start_medusa.py', in the 'HTTP Server' section:: from tlslite.api import * s = open("./serverX509Cert.pem").read() x509 = X509() x509.parse(s) certChain = X509CertChain([x509]) s = open("./serverX509Key.pem").read() privateKey = parsePEMKey(s, private=True) class http_tls_channel(TLSAsyncDispatcherMixIn, http_server.http_channel): ac_in_buffer_size = 16384 def __init__ (self, server, conn, addr): http_server.http_channel.__init__(self, server, conn, addr) TLSAsyncDispatcherMixIn.__init__(self, conn) self.tlsConnection.ignoreAbruptClose = True self.setServerHandshakeOp(certChain=certChain, privateKey=privateKey) hs.channel_class = http_tls_channel If the TLS layer raises an exception, the exception will be caught in asyncore.dispatcher, which will call close() on this class. The TLS layer always closes the TLS connection before raising an exception, so the close operation will complete right away, causing asyncore.dispatcher.close() to be called, which closes the socket and removes this instance from the asyncore loop. """ def __init__(self, sock=None): AsyncStateMachine.__init__(self) if sock: self.tlsConnection = TLSConnection(sock) #Calculate the sibling I'm being mixed in with. #This is necessary since we override functions #like readable(), handle_read(), etc., but we #also want to call the sibling's versions. for cl in self.__class__.__bases__: if cl != TLSAsyncDispatcherMixIn and cl != AsyncStateMachine: self.siblingClass = cl break else: raise AssertionError() def readable(self): result = self.wantsReadEvent() if result != None: return result return self.siblingClass.readable(self) def writable(self): result = self.wantsWriteEvent() if result != None: return result return self.siblingClass.writable(self) def handle_read(self): self.inReadEvent() def handle_write(self): self.inWriteEvent() def outConnectEvent(self): self.siblingClass.handle_connect(self) def outCloseEvent(self): asyncore.dispatcher.close(self) def outReadEvent(self, readBuffer): self.readBuffer = readBuffer self.siblingClass.handle_read(self) def outWriteEvent(self): self.siblingClass.handle_write(self) def recv(self, bufferSize=16384): if bufferSize < 16384 or self.readBuffer == None: raise AssertionError() returnValue = self.readBuffer self.readBuffer = None return returnValue def send(self, writeBuffer): self.setWriteOp(writeBuffer) return len(writeBuffer) def close(self): if hasattr(self, "tlsConnection"): self.setCloseOp() else: asyncore.dispatcher.close(self)
Python
class IntegrationHelper: def __init__(self, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings = None): self.username = None self.password = None self.sharedKey = None self.certChain = None self.privateKey = None self.checker = None #SRP Authentication if username and password and not \ (sharedKey or certChain or privateKey): self.username = username self.password = password #Shared Key Authentication elif username and sharedKey and not \ (password or certChain or privateKey): self.username = username self.sharedKey = sharedKey #Certificate Chain Authentication elif certChain and privateKey and not \ (username or password or sharedKey): self.certChain = certChain self.privateKey = privateKey #No Authentication elif not password and not username and not \ sharedKey and not certChain and not privateKey: pass else: raise ValueError("Bad parameters") #Authenticate the server based on its cryptoID or fingerprint if sharedKey and (cryptoID or protocol or x509Fingerprint): raise ValueError("Can't use shared keys with other forms of"\ "authentication") self.checker = Checker(cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName) self.settings = settings
Python
"""Classes for integrating TLS Lite with other packages.""" __all__ = ["AsyncStateMachine", "HTTPTLSConnection", "POP3_TLS", "IMAP4_TLS", "SMTP_TLS", "XMLRPCTransport", "TLSSocketServerMixIn", "TLSAsyncDispatcherMixIn", "TLSTwistedProtocolWrapper"] try: import twisted del twisted except ImportError: del __all__[__all__.index("TLSTwistedProtocolWrapper")]
Python
"""TLS Lite + xmlrpclib.""" import xmlrpclib import httplib from gdata.tlslite.integration.HTTPTLSConnection import HTTPTLSConnection from gdata.tlslite.integration.ClientHelper import ClientHelper class XMLRPCTransport(xmlrpclib.Transport, ClientHelper): """Handles an HTTPS transaction to an XML-RPC server.""" def __init__(self, username=None, password=None, sharedKey=None, certChain=None, privateKey=None, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, settings=None): """Create a new XMLRPCTransport. An instance of this class can be passed to L{xmlrpclib.ServerProxy} to use TLS with XML-RPC calls:: from tlslite.api import XMLRPCTransport from xmlrpclib import ServerProxy transport = XMLRPCTransport(user="alice", password="abra123") server = ServerProxy("https://localhost", transport) For client authentication, use one of these argument combinations: - username, password (SRP) - username, sharedKey (shared-key) - certChain, privateKey (certificate) For server authentication, you can either rely on the implicit mutual authentication performed by SRP or shared-keys, or you can do certificate-based server authentication with one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) Certificate-based server authentication is compatible with SRP or certificate-based client authentication. It is not compatible with shared-keys. The constructor does not perform the TLS handshake itself, but simply stores these arguments for later. The handshake is performed only when this class needs to connect with the server. Thus you should be prepared to handle TLS-specific exceptions when calling methods of L{xmlrpclib.ServerProxy}. See the client handshake functions in L{tlslite.TLSConnection.TLSConnection} for details on which exceptions might be raised. @type username: str @param username: SRP or shared-key username. Requires the 'password' or 'sharedKey' argument. @type password: str @param password: SRP password for mutual authentication. Requires the 'username' argument. @type sharedKey: str @param sharedKey: Shared key for mutual authentication. Requires the 'username' argument. @type certChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @param certChain: Certificate chain for client authentication. Requires the 'privateKey' argument. Excludes the SRP or shared-key related arguments. @type privateKey: L{tlslite.utils.RSAKey.RSAKey} @param privateKey: Private key for client authentication. Requires the 'certChain' argument. Excludes the SRP or shared-key related arguments. @type cryptoID: str @param cryptoID: cryptoID for server authentication. Mutually exclusive with the 'x509...' arguments. @type protocol: str @param protocol: cryptoID protocol URI for server authentication. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: Hex-encoded X.509 fingerprint for server authentication. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed to use this parameter. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type settings: L{tlslite.HandshakeSettings.HandshakeSettings} @param settings: Various settings which can be used to control the ciphersuites, certificate types, and SSL/TLS versions offered by the client. """ ClientHelper.__init__(self, username, password, sharedKey, certChain, privateKey, cryptoID, protocol, x509Fingerprint, x509TrustList, x509CommonName, settings) def make_connection(self, host): # create a HTTPS connection object from a host descriptor host, extra_headers, x509 = self.get_host_info(host) http = HTTPTLSConnection(host, None, self.username, self.password, self.sharedKey, self.certChain, self.privateKey, self.checker.cryptoID, self.checker.protocol, self.checker.x509Fingerprint, self.checker.x509TrustList, self.checker.x509CommonName, self.settings) http2 = httplib.HTTP() http2._setup(http) return http2
Python
""" A state machine for using TLS Lite with asynchronous I/O. """ class AsyncStateMachine: """ This is an abstract class that's used to integrate TLS Lite with asyncore and Twisted. This class signals wantsReadsEvent() and wantsWriteEvent(). When the underlying socket has become readable or writeable, the event should be passed to this class by calling inReadEvent() or inWriteEvent(). This class will then try to read or write through the socket, and will update its state appropriately. This class will forward higher-level events to its subclass. For example, when a complete TLS record has been received, outReadEvent() will be called with the decrypted data. """ def __init__(self): self._clear() def _clear(self): #These store the various asynchronous operations (i.e. #generators). Only one of them, at most, is ever active at a #time. self.handshaker = None self.closer = None self.reader = None self.writer = None #This stores the result from the last call to the #currently active operation. If 0 it indicates that the #operation wants to read, if 1 it indicates that the #operation wants to write. If None, there is no active #operation. self.result = None def _checkAssert(self, maxActive=1): #This checks that only one operation, at most, is #active, and that self.result is set appropriately. activeOps = 0 if self.handshaker: activeOps += 1 if self.closer: activeOps += 1 if self.reader: activeOps += 1 if self.writer: activeOps += 1 if self.result == None: if activeOps != 0: raise AssertionError() elif self.result in (0,1): if activeOps != 1: raise AssertionError() else: raise AssertionError() if activeOps > maxActive: raise AssertionError() def wantsReadEvent(self): """If the state machine wants to read. If an operation is active, this returns whether or not the operation wants to read from the socket. If an operation is not active, this returns None. @rtype: bool or None @return: If the state machine wants to read. """ if self.result != None: return self.result == 0 return None def wantsWriteEvent(self): """If the state machine wants to write. If an operation is active, this returns whether or not the operation wants to write to the socket. If an operation is not active, this returns None. @rtype: bool or None @return: If the state machine wants to write. """ if self.result != None: return self.result == 1 return None def outConnectEvent(self): """Called when a handshake operation completes. May be overridden in subclass. """ pass def outCloseEvent(self): """Called when a close operation completes. May be overridden in subclass. """ pass def outReadEvent(self, readBuffer): """Called when a read operation completes. May be overridden in subclass.""" pass def outWriteEvent(self): """Called when a write operation completes. May be overridden in subclass.""" pass def inReadEvent(self): """Tell the state machine it can read from the socket.""" try: self._checkAssert() if self.handshaker: self._doHandshakeOp() elif self.closer: self._doCloseOp() elif self.reader: self._doReadOp() elif self.writer: self._doWriteOp() else: self.reader = self.tlsConnection.readAsync(16384) self._doReadOp() except: self._clear() raise def inWriteEvent(self): """Tell the state machine it can write to the socket.""" try: self._checkAssert() if self.handshaker: self._doHandshakeOp() elif self.closer: self._doCloseOp() elif self.reader: self._doReadOp() elif self.writer: self._doWriteOp() else: self.outWriteEvent() except: self._clear() raise def _doHandshakeOp(self): try: self.result = self.handshaker.next() except StopIteration: self.handshaker = None self.result = None self.outConnectEvent() def _doCloseOp(self): try: self.result = self.closer.next() except StopIteration: self.closer = None self.result = None self.outCloseEvent() def _doReadOp(self): self.result = self.reader.next() if not self.result in (0,1): readBuffer = self.result self.reader = None self.result = None self.outReadEvent(readBuffer) def _doWriteOp(self): try: self.result = self.writer.next() except StopIteration: self.writer = None self.result = None def setHandshakeOp(self, handshaker): """Start a handshake operation. @type handshaker: generator @param handshaker: A generator created by using one of the asynchronous handshake functions (i.e. handshakeServerAsync, or handshakeClientxxx(..., async=True). """ try: self._checkAssert(0) self.handshaker = handshaker self._doHandshakeOp() except: self._clear() raise def setServerHandshakeOp(self, **args): """Start a handshake operation. The arguments passed to this function will be forwarded to L{tlslite.TLSConnection.TLSConnection.handshakeServerAsync}. """ handshaker = self.tlsConnection.handshakeServerAsync(**args) self.setHandshakeOp(handshaker) def setCloseOp(self): """Start a close operation. """ try: self._checkAssert(0) self.closer = self.tlsConnection.closeAsync() self._doCloseOp() except: self._clear() raise def setWriteOp(self, writeBuffer): """Start a write operation. @type writeBuffer: str @param writeBuffer: The string to transmit. """ try: self._checkAssert(0) self.writer = self.tlsConnection.writeAsync(writeBuffer) self._doWriteOp() except: self._clear() raise
Python
"""Class for post-handshake certificate checking.""" from utils.cryptomath import hashAndBase64 from X509 import X509 from X509CertChain import X509CertChain from errors import * class Checker: """This class is passed to a handshake function to check the other party's certificate chain. If a handshake function completes successfully, but the Checker judges the other party's certificate chain to be missing or inadequate, a subclass of L{tlslite.errors.TLSAuthenticationError} will be raised. Currently, the Checker can check either an X.509 or a cryptoID chain (for the latter, cryptoIDlib must be installed). """ def __init__(self, cryptoID=None, protocol=None, x509Fingerprint=None, x509TrustList=None, x509CommonName=None, checkResumedSession=False): """Create a new Checker instance. You must pass in one of these argument combinations: - cryptoID[, protocol] (requires cryptoIDlib) - x509Fingerprint - x509TrustList[, x509CommonName] (requires cryptlib_py) @type cryptoID: str @param cryptoID: A cryptoID which the other party's certificate chain must match. The cryptoIDlib module must be installed. Mutually exclusive with all of the 'x509...' arguments. @type protocol: str @param protocol: A cryptoID protocol URI which the other party's certificate chain must match. Requires the 'cryptoID' argument. @type x509Fingerprint: str @param x509Fingerprint: A hex-encoded X.509 end-entity fingerprint which the other party's end-entity certificate must match. Mutually exclusive with the 'cryptoID' and 'x509TrustList' arguments. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The other party must present a certificate chain which extends to one of these root certificates. The cryptlib_py module must be installed. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. @type x509CommonName: str @param x509CommonName: The end-entity certificate's 'CN' field must match this value. For a web server, this is typically a server name such as 'www.amazon.com'. Mutually exclusive with the 'cryptoID' and 'x509Fingerprint' arguments. Requires the 'x509TrustList' argument. @type checkResumedSession: bool @param checkResumedSession: If resumed sessions should be checked. This defaults to False, on the theory that if the session was checked once, we don't need to bother re-checking it. """ if cryptoID and (x509Fingerprint or x509TrustList): raise ValueError() if x509Fingerprint and x509TrustList: raise ValueError() if x509CommonName and not x509TrustList: raise ValueError() if protocol and not cryptoID: raise ValueError() if cryptoID: import cryptoIDlib #So we raise an error here if x509TrustList: import cryptlib_py #So we raise an error here self.cryptoID = cryptoID self.protocol = protocol self.x509Fingerprint = x509Fingerprint self.x509TrustList = x509TrustList self.x509CommonName = x509CommonName self.checkResumedSession = checkResumedSession def __call__(self, connection): """Check a TLSConnection. When a Checker is passed to a handshake function, this will be called at the end of the function. @type connection: L{tlslite.TLSConnection.TLSConnection} @param connection: The TLSConnection to examine. @raise tlslite.errors.TLSAuthenticationError: If the other party's certificate chain is missing or bad. """ if not self.checkResumedSession and connection.resumed: return if self.cryptoID or self.x509Fingerprint or self.x509TrustList: if connection._client: chain = connection.session.serverCertChain else: chain = connection.session.clientCertChain if self.x509Fingerprint or self.x509TrustList: if isinstance(chain, X509CertChain): if self.x509Fingerprint: if chain.getFingerprint() != self.x509Fingerprint: raise TLSFingerprintError(\ "X.509 fingerprint mismatch: %s, %s" % \ (chain.getFingerprint(), self.x509Fingerprint)) else: #self.x509TrustList if not chain.validate(self.x509TrustList): raise TLSValidationError("X.509 validation failure") if self.x509CommonName and \ (chain.getCommonName() != self.x509CommonName): raise TLSAuthorizationError(\ "X.509 Common Name mismatch: %s, %s" % \ (chain.getCommonName(), self.x509CommonName)) elif chain: raise TLSAuthenticationTypeError() else: raise TLSNoAuthenticationError() elif self.cryptoID: import cryptoIDlib.CertChain if isinstance(chain, cryptoIDlib.CertChain.CertChain): if chain.cryptoID != self.cryptoID: raise TLSFingerprintError(\ "cryptoID mismatch: %s, %s" % \ (chain.cryptoID, self.cryptoID)) if self.protocol: if not chain.checkProtocol(self.protocol): raise TLSAuthorizationError(\ "cryptoID protocol mismatch") if not chain.validate(): raise TLSValidationError("cryptoID validation failure") elif chain: raise TLSAuthenticationTypeError() else: raise TLSNoAuthenticationError()
Python
"""Class for storing SRP password verifiers.""" from utils.cryptomath import * from utils.compat import * import mathtls from BaseDB import BaseDB class VerifierDB(BaseDB): """This class represent an in-memory or on-disk database of SRP password verifiers. A VerifierDB can be passed to a server handshake to authenticate a client based on one of the verifiers. This class is thread-safe. """ def __init__(self, filename=None): """Create a new VerifierDB instance. @type filename: str @param filename: Filename for an on-disk database, or None for an in-memory database. If the filename already exists, follow this with a call to open(). To create a new on-disk database, follow this with a call to create(). """ BaseDB.__init__(self, filename, "verifier") def _getItem(self, username, valueStr): (N, g, salt, verifier) = valueStr.split(" ") N = base64ToNumber(N) g = base64ToNumber(g) salt = base64ToString(salt) verifier = base64ToNumber(verifier) return (N, g, salt, verifier) def __setitem__(self, username, verifierEntry): """Add a verifier entry to the database. @type username: str @param username: The username to associate the verifier with. Must be less than 256 characters in length. Must not already be in the database. @type verifierEntry: tuple @param verifierEntry: The verifier entry to add. Use L{tlslite.VerifierDB.VerifierDB.makeVerifier} to create a verifier entry. """ BaseDB.__setitem__(self, username, verifierEntry) def _setItem(self, username, value): if len(username)>=256: raise ValueError("username too long") N, g, salt, verifier = value N = numberToBase64(N) g = numberToBase64(g) salt = stringToBase64(salt) verifier = numberToBase64(verifier) valueStr = " ".join( (N, g, salt, verifier) ) return valueStr def _checkItem(self, value, username, param): (N, g, salt, verifier) = value x = mathtls.makeX(salt, username, param) v = powMod(g, x, N) return (verifier == v) def makeVerifier(username, password, bits): """Create a verifier entry which can be stored in a VerifierDB. @type username: str @param username: The username for this verifier. Must be less than 256 characters in length. @type password: str @param password: The password for this verifier. @type bits: int @param bits: This values specifies which SRP group parameters to use. It must be one of (1024, 1536, 2048, 3072, 4096, 6144, 8192). Larger values are more secure but slower. 2048 is a good compromise between safety and speed. @rtype: tuple @return: A tuple which may be stored in a VerifierDB. """ return mathtls.makeVerifier(username, password, bits) makeVerifier = staticmethod(makeVerifier)
Python
"""OpenSSL/M2Crypto 3DES implementation.""" from cryptomath import * from TripleDES import * if m2cryptoLoaded: def new(key, mode, IV): return OpenSSL_TripleDES(key, mode, IV) class OpenSSL_TripleDES(TripleDES): def __init__(self, key, mode, IV): TripleDES.__init__(self, key, mode, IV, "openssl") self.key = key self.IV = IV def _createContext(self, encrypt): context = m2.cipher_ctx_new() cipherType = m2.des_ede3_cbc() m2.cipher_init(context, cipherType, self.key, self.IV, encrypt) return context def encrypt(self, plaintext): TripleDES.encrypt(self, plaintext) context = self._createContext(1) ciphertext = m2.cipher_update(context, plaintext) m2.cipher_ctx_free(context) self.IV = ciphertext[-self.block_size:] return ciphertext def decrypt(self, ciphertext): TripleDES.decrypt(self, ciphertext) context = self._createContext(0) #I think M2Crypto has a bug - it fails to decrypt and return the last block passed in. #To work around this, we append sixteen zeros to the string, below: plaintext = m2.cipher_update(context, ciphertext+('\0'*16)) #If this bug is ever fixed, then plaintext will end up having a garbage #plaintext block on the end. That's okay - the below code will ignore it. plaintext = plaintext[:len(ciphertext)] m2.cipher_ctx_free(context) self.IV = ciphertext[-self.block_size:] return plaintext
Python
"""PyCrypto RC4 implementation.""" from cryptomath import * from RC4 import * if pycryptoLoaded: import Crypto.Cipher.ARC4 def new(key): return PyCrypto_RC4(key) class PyCrypto_RC4(RC4): def __init__(self, key): RC4.__init__(self, key, "pycrypto") self.context = Crypto.Cipher.ARC4.new(key) def encrypt(self, plaintext): return self.context.encrypt(plaintext) def decrypt(self, ciphertext): return self.context.decrypt(ciphertext)
Python
"""OpenSSL/M2Crypto RSA implementation.""" from cryptomath import * from RSAKey import * from Python_RSAKey import Python_RSAKey #copied from M2Crypto.util.py, so when we load the local copy of m2 #we can still use it def password_callback(v, prompt1='Enter private key passphrase:', prompt2='Verify passphrase:'): from getpass import getpass while 1: try: p1=getpass(prompt1) if v: p2=getpass(prompt2) if p1==p2: break else: break except KeyboardInterrupt: return None return p1 if m2cryptoLoaded: class OpenSSL_RSAKey(RSAKey): def __init__(self, n=0, e=0): self.rsa = None self._hasPrivateKey = False if (n and not e) or (e and not n): raise AssertionError() if n and e: self.rsa = m2.rsa_new() m2.rsa_set_n(self.rsa, numberToMPI(n)) m2.rsa_set_e(self.rsa, numberToMPI(e)) def __del__(self): if self.rsa: m2.rsa_free(self.rsa) def __getattr__(self, name): if name == 'e': if not self.rsa: return 0 return mpiToNumber(m2.rsa_get_e(self.rsa)) elif name == 'n': if not self.rsa: return 0 return mpiToNumber(m2.rsa_get_n(self.rsa)) else: raise AttributeError def hasPrivateKey(self): return self._hasPrivateKey def hash(self): return Python_RSAKey(self.n, self.e).hash() def _rawPrivateKeyOp(self, m): s = numberToString(m) byteLength = numBytes(self.n) if len(s)== byteLength: pass elif len(s) == byteLength-1: s = '\0' + s else: raise AssertionError() c = stringToNumber(m2.rsa_private_encrypt(self.rsa, s, m2.no_padding)) return c def _rawPublicKeyOp(self, c): s = numberToString(c) byteLength = numBytes(self.n) if len(s)== byteLength: pass elif len(s) == byteLength-1: s = '\0' + s else: raise AssertionError() m = stringToNumber(m2.rsa_public_decrypt(self.rsa, s, m2.no_padding)) return m def acceptsPassword(self): return True def write(self, password=None): bio = m2.bio_new(m2.bio_s_mem()) if self._hasPrivateKey: if password: def f(v): return password m2.rsa_write_key(self.rsa, bio, m2.des_ede_cbc(), f) else: def f(): pass m2.rsa_write_key_no_cipher(self.rsa, bio, f) else: if password: raise AssertionError() m2.rsa_write_pub_key(self.rsa, bio) s = m2.bio_read(bio, m2.bio_ctrl_pending(bio)) m2.bio_free(bio) return s def writeXMLPublicKey(self, indent=''): return Python_RSAKey(self.n, self.e).write(indent) def generate(bits): key = OpenSSL_RSAKey() def f():pass key.rsa = m2.rsa_generate_key(bits, 3, f) key._hasPrivateKey = True return key generate = staticmethod(generate) def parse(s, passwordCallback=None): if s.startswith("-----BEGIN "): if passwordCallback==None: callback = password_callback else: def f(v, prompt1=None, prompt2=None): return passwordCallback() callback = f bio = m2.bio_new(m2.bio_s_mem()) try: m2.bio_write(bio, s) key = OpenSSL_RSAKey() if s.startswith("-----BEGIN RSA PRIVATE KEY-----"): def f():pass key.rsa = m2.rsa_read_key(bio, callback) if key.rsa == None: raise SyntaxError() key._hasPrivateKey = True elif s.startswith("-----BEGIN PUBLIC KEY-----"): key.rsa = m2.rsa_read_pub_key(bio) if key.rsa == None: raise SyntaxError() key._hasPrivateKey = False else: raise SyntaxError() return key finally: m2.bio_free(bio) else: raise SyntaxError() parse = staticmethod(parse)
Python
"""Helper functions for XML. This module has misc. helper functions for working with XML DOM nodes.""" from compat import * import os import re if os.name == "java": # Only for Jython from javax.xml.parsers import * import java builder = DocumentBuilderFactory.newInstance().newDocumentBuilder() def parseDocument(s): stream = java.io.ByteArrayInputStream(java.lang.String(s).getBytes()) return builder.parse(stream) else: from xml.dom import minidom from xml.sax import saxutils def parseDocument(s): return minidom.parseString(s) def parseAndStripWhitespace(s): try: element = parseDocument(s).documentElement except BaseException, e: raise SyntaxError(str(e)) stripWhitespace(element) return element #Goes through a DOM tree and removes whitespace besides child elements, #as long as this whitespace is correctly tab-ified def stripWhitespace(element, tab=0): element.normalize() lastSpacer = "\n" + ("\t"*tab) spacer = lastSpacer + "\t" #Zero children aren't allowed (i.e. <empty/>) #This makes writing output simpler, and matches Canonical XML if element.childNodes.length==0: #DON'T DO len(element.childNodes) - doesn't work in Jython raise SyntaxError("Empty XML elements not allowed") #If there's a single child, it must be text context if element.childNodes.length==1: if element.firstChild.nodeType == element.firstChild.TEXT_NODE: #If it's an empty element, remove if element.firstChild.data == lastSpacer: element.removeChild(element.firstChild) return #If not text content, give an error elif element.firstChild.nodeType == element.firstChild.ELEMENT_NODE: raise SyntaxError("Bad whitespace under '%s'" % element.tagName) else: raise SyntaxError("Unexpected node type in XML document") #Otherwise there's multiple child element child = element.firstChild while child: if child.nodeType == child.ELEMENT_NODE: stripWhitespace(child, tab+1) child = child.nextSibling elif child.nodeType == child.TEXT_NODE: if child == element.lastChild: if child.data != lastSpacer: raise SyntaxError("Bad whitespace under '%s'" % element.tagName) elif child.data != spacer: raise SyntaxError("Bad whitespace under '%s'" % element.tagName) next = child.nextSibling element.removeChild(child) child = next else: raise SyntaxError("Unexpected node type in XML document") def checkName(element, name): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Missing element: '%s'" % name) if name == None: return if element.tagName != name: raise SyntaxError("Wrong element name: should be '%s', is '%s'" % (name, element.tagName)) def getChild(element, index, name=None): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Wrong node type in getChild()") child = element.childNodes.item(index) if child == None: raise SyntaxError("Missing child: '%s'" % name) checkName(child, name) return child def getChildIter(element, index): class ChildIter: def __init__(self, element, index): self.element = element self.index = index def next(self): if self.index < len(self.element.childNodes): retVal = self.element.childNodes.item(self.index) self.index += 1 else: retVal = None return retVal def checkEnd(self): if self.index != len(self.element.childNodes): raise SyntaxError("Too many elements under: '%s'" % self.element.tagName) return ChildIter(element, index) def getChildOrNone(element, index): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Wrong node type in getChild()") child = element.childNodes.item(index) return child def getLastChild(element, index, name=None): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Wrong node type in getLastChild()") child = element.childNodes.item(index) if child == None: raise SyntaxError("Missing child: '%s'" % name) if child != element.lastChild: raise SyntaxError("Too many elements under: '%s'" % element.tagName) checkName(child, name) return child #Regular expressions for syntax-checking attribute and element content nsRegEx = "http://trevp.net/cryptoID\Z" cryptoIDRegEx = "([a-km-z3-9]{5}\.){3}[a-km-z3-9]{5}\Z" urlRegEx = "http(s)?://.{1,100}\Z" sha1Base64RegEx = "[A-Za-z0-9+/]{27}=\Z" base64RegEx = "[A-Za-z0-9+/]+={0,4}\Z" certsListRegEx = "(0)?(1)?(2)?(3)?(4)?(5)?(6)?(7)?(8)?(9)?\Z" keyRegEx = "[A-Z]\Z" keysListRegEx = "(A)?(B)?(C)?(D)?(E)?(F)?(G)?(H)?(I)?(J)?(K)?(L)?(M)?(N)?(O)?(P)?(Q)?(R)?(S)?(T)?(U)?(V)?(W)?(X)?(Y)?(Z)?\Z" dateTimeRegEx = "\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ\Z" shortStringRegEx = ".{1,100}\Z" exprRegEx = "[a-zA-Z0-9 ,()]{1,200}\Z" notAfterDeltaRegEx = "0|([1-9][0-9]{0,8})\Z" #A number from 0 to (1 billion)-1 booleanRegEx = "(true)|(false)" def getReqAttribute(element, attrName, regEx=""): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Wrong node type in getReqAttribute()") value = element.getAttribute(attrName) if not value: raise SyntaxError("Missing Attribute: " + attrName) if not re.match(regEx, value): raise SyntaxError("Bad Attribute Value for '%s': '%s' " % (attrName, value)) element.removeAttribute(attrName) return str(value) #de-unicode it; this is needed for bsddb, for example def getAttribute(element, attrName, regEx=""): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Wrong node type in getAttribute()") value = element.getAttribute(attrName) if value: if not re.match(regEx, value): raise SyntaxError("Bad Attribute Value for '%s': '%s' " % (attrName, value)) element.removeAttribute(attrName) return str(value) #de-unicode it; this is needed for bsddb, for example def checkNoMoreAttributes(element): if element.nodeType != element.ELEMENT_NODE: raise SyntaxError("Wrong node type in checkNoMoreAttributes()") if element.attributes.length!=0: raise SyntaxError("Extra attributes on '%s'" % element.tagName) def getText(element, regEx=""): textNode = element.firstChild if textNode == None: raise SyntaxError("Empty element '%s'" % element.tagName) if textNode.nodeType != textNode.TEXT_NODE: raise SyntaxError("Non-text node: '%s'" % element.tagName) if not re.match(regEx, textNode.data): raise SyntaxError("Bad Text Value for '%s': '%s' " % (element.tagName, textNode.data)) return str(textNode.data) #de-unicode it; this is needed for bsddb, for example #Function for adding tabs to a string def indent(s, steps, ch="\t"): tabs = ch*steps if s[-1] != "\n": s = tabs + s.replace("\n", "\n"+tabs) else: s = tabs + s.replace("\n", "\n"+tabs) s = s[ : -len(tabs)] return s def escape(s): return saxutils.escape(s)
Python
"""Factory functions for asymmetric cryptography. @sort: generateRSAKey, parseXMLKey, parsePEMKey, parseAsPublicKey, parseAsPrivateKey """ from compat import * from RSAKey import RSAKey from Python_RSAKey import Python_RSAKey import cryptomath if cryptomath.m2cryptoLoaded: from OpenSSL_RSAKey import OpenSSL_RSAKey if cryptomath.pycryptoLoaded: from PyCrypto_RSAKey import PyCrypto_RSAKey # ************************************************************************** # Factory Functions for RSA Keys # ************************************************************************** def generateRSAKey(bits, implementations=["openssl", "python"]): """Generate an RSA key with the specified bit length. @type bits: int @param bits: Desired bit length of the new key's modulus. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: A new RSA private key. """ for implementation in implementations: if implementation == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_RSAKey.generate(bits) elif implementation == "python": return Python_RSAKey.generate(bits) raise ValueError("No acceptable implementations") def parseXMLKey(s, private=False, public=False, implementations=["python"]): """Parse an XML-format key. The XML format used here is specific to tlslite and cryptoIDlib. The format can store the public component of a key, or the public and private components. For example:: <publicKey xmlns="http://trevp.net/rsa"> <n>4a5yzB8oGNlHo866CAspAC47M4Fvx58zwK8pou... <e>Aw==</e> </publicKey> <privateKey xmlns="http://trevp.net/rsa"> <n>4a5yzB8oGNlHo866CAspAC47M4Fvx58zwK8pou... <e>Aw==</e> <d>JZ0TIgUxWXmL8KJ0VqyG1V0J3ern9pqIoB0xmy... <p>5PreIj6z6ldIGL1V4+1C36dQFHNCQHJvW52GXc... <q>/E/wDit8YXPCxx126zTq2ilQ3IcW54NJYyNjiZ... <dP>mKc+wX8inDowEH45Qp4slRo1YveBgExKPROu6... <dQ>qDVKtBz9lk0shL5PR3ickXDgkwS576zbl2ztB... <qInv>j6E8EA7dNsTImaXexAmLA1DoeArsYeFAInr... </privateKey> @type s: str @param s: A string containing an XML public or private key. @type private: bool @param private: If True, a L{SyntaxError} will be raised if the private key component is not present. @type public: bool @param public: If True, the private key component (if present) will be discarded, so this function will always return a public key. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: An RSA key. @raise SyntaxError: If the key is not properly formatted. """ for implementation in implementations: if implementation == "python": key = Python_RSAKey.parseXML(s) break else: raise ValueError("No acceptable implementations") return _parseKeyHelper(key, private, public) #Parse as an OpenSSL or Python key def parsePEMKey(s, private=False, public=False, passwordCallback=None, implementations=["openssl", "python"]): """Parse a PEM-format key. The PEM format is used by OpenSSL and other tools. The format is typically used to store both the public and private components of a key. For example:: -----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDYscuoMzsGmW0pAYsmyHltxB2TdwHS0dImfjCMfaSDkfLdZY5+ dOWORVns9etWnr194mSGA1F0Pls/VJW8+cX9+3vtJV8zSdANPYUoQf0TP7VlJxkH dSRkUbEoz5bAAs/+970uos7n7iXQIni+3erUTdYEk2iWnMBjTljfgbK/dQIDAQAB AoGAJHoJZk75aKr7DSQNYIHuruOMdv5ZeDuJvKERWxTrVJqE32/xBKh42/IgqRrc esBN9ZregRCd7YtxoL+EVUNWaJNVx2mNmezEznrc9zhcYUrgeaVdFO2yBF1889zO gCOVwrO8uDgeyj6IKa25H6c1N13ih/o7ZzEgWbGG+ylU1yECQQDv4ZSJ4EjSh/Fl aHdz3wbBa/HKGTjC8iRy476Cyg2Fm8MZUe9Yy3udOrb5ZnS2MTpIXt5AF3h2TfYV VoFXIorjAkEA50FcJmzT8sNMrPaV8vn+9W2Lu4U7C+K/O2g1iXMaZms5PC5zV5aV CKXZWUX1fq2RaOzlbQrpgiolhXpeh8FjxwJBAOFHzSQfSsTNfttp3KUpU0LbiVvv i+spVSnA0O4rq79KpVNmK44Mq67hsW1P11QzrzTAQ6GVaUBRv0YS061td1kCQHnP wtN2tboFR6lABkJDjxoGRvlSt4SOPr7zKGgrWjeiuTZLHXSAnCY+/hr5L9Q3ZwXG 6x6iBdgLjVIe4BZQNtcCQQDXGv/gWinCNTN3MPWfTW/RGzuMYVmyBFais0/VrgdH h1dLpztmpQqfyH/zrBXQ9qL/zR4ojS6XYneO/U18WpEe -----END RSA PRIVATE KEY----- To generate a key like this with OpenSSL, run:: openssl genrsa 2048 > key.pem This format also supports password-encrypted private keys. TLS Lite can only handle password-encrypted private keys when OpenSSL and M2Crypto are installed. In this case, passwordCallback will be invoked to query the user for the password. @type s: str @param s: A string containing a PEM-encoded public or private key. @type private: bool @param private: If True, a L{SyntaxError} will be raised if the private key component is not present. @type public: bool @param public: If True, the private key component (if present) will be discarded, so this function will always return a public key. @type passwordCallback: callable @param passwordCallback: This function will be called, with no arguments, if the PEM-encoded private key is password-encrypted. The callback should return the password string. If the password is incorrect, SyntaxError will be raised. If no callback is passed and the key is password-encrypted, a prompt will be displayed at the console. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: An RSA key. @raise SyntaxError: If the key is not properly formatted. """ for implementation in implementations: if implementation == "openssl" and cryptomath.m2cryptoLoaded: key = OpenSSL_RSAKey.parse(s, passwordCallback) break elif implementation == "python": key = Python_RSAKey.parsePEM(s) break else: raise ValueError("No acceptable implementations") return _parseKeyHelper(key, private, public) def _parseKeyHelper(key, private, public): if private: if not key.hasPrivateKey(): raise SyntaxError("Not a private key!") if public: return _createPublicKey(key) if private: if hasattr(key, "d"): return _createPrivateKey(key) else: return key return key def parseAsPublicKey(s): """Parse an XML or PEM-formatted public key. @type s: str @param s: A string containing an XML or PEM-encoded public or private key. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: An RSA public key. @raise SyntaxError: If the key is not properly formatted. """ try: return parsePEMKey(s, public=True) except: return parseXMLKey(s, public=True) def parsePrivateKey(s): """Parse an XML or PEM-formatted private key. @type s: str @param s: A string containing an XML or PEM-encoded private key. @rtype: L{tlslite.utils.RSAKey.RSAKey} @return: An RSA private key. @raise SyntaxError: If the key is not properly formatted. """ try: return parsePEMKey(s, private=True) except: return parseXMLKey(s, private=True) def _createPublicKey(key): """ Create a new public key. Discard any private component, and return the most efficient key possible. """ if not isinstance(key, RSAKey): raise AssertionError() return _createPublicRSAKey(key.n, key.e) def _createPrivateKey(key): """ Create a new private key. Return the most efficient key possible. """ if not isinstance(key, RSAKey): raise AssertionError() if not key.hasPrivateKey(): raise AssertionError() return _createPrivateRSAKey(key.n, key.e, key.d, key.p, key.q, key.dP, key.dQ, key.qInv) def _createPublicRSAKey(n, e, implementations = ["openssl", "pycrypto", "python"]): for implementation in implementations: if implementation == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_RSAKey(n, e) elif implementation == "pycrypto" and cryptomath.pycryptoLoaded: return PyCrypto_RSAKey(n, e) elif implementation == "python": return Python_RSAKey(n, e) raise ValueError("No acceptable implementations") def _createPrivateRSAKey(n, e, d, p, q, dP, dQ, qInv, implementations = ["pycrypto", "python"]): for implementation in implementations: if implementation == "pycrypto" and cryptomath.pycryptoLoaded: return PyCrypto_RSAKey(n, e, d, p, q, dP, dQ, qInv) elif implementation == "python": return Python_RSAKey(n, e, d, p, q, dP, dQ, qInv) raise ValueError("No acceptable implementations")
Python
import os #Functions for manipulating datetime objects #CCYY-MM-DDThh:mm:ssZ def parseDateClass(s): year, month, day = s.split("-") day, tail = day[:2], day[2:] hour, minute, second = tail[1:].split(":") second = second[:2] year, month, day = int(year), int(month), int(day) hour, minute, second = int(hour), int(minute), int(second) return createDateClass(year, month, day, hour, minute, second) if os.name != "java": from datetime import datetime, timedelta #Helper functions for working with a date/time class def createDateClass(year, month, day, hour, minute, second): return datetime(year, month, day, hour, minute, second) def printDateClass(d): #Split off fractional seconds, append 'Z' return d.isoformat().split(".")[0]+"Z" def getNow(): return datetime.utcnow() def getHoursFromNow(hours): return datetime.utcnow() + timedelta(hours=hours) def getMinutesFromNow(minutes): return datetime.utcnow() + timedelta(minutes=minutes) def isDateClassExpired(d): return d < datetime.utcnow() def isDateClassBefore(d1, d2): return d1 < d2 else: #Jython 2.1 is missing lots of python 2.3 stuff, #which we have to emulate here: import java import jarray def createDateClass(year, month, day, hour, minute, second): c = java.util.Calendar.getInstance() c.setTimeZone(java.util.TimeZone.getTimeZone("UTC")) c.set(year, month-1, day, hour, minute, second) return c def printDateClass(d): return "%04d-%02d-%02dT%02d:%02d:%02dZ" % \ (d.get(d.YEAR), d.get(d.MONTH)+1, d.get(d.DATE), \ d.get(d.HOUR_OF_DAY), d.get(d.MINUTE), d.get(d.SECOND)) def getNow(): c = java.util.Calendar.getInstance() c.setTimeZone(java.util.TimeZone.getTimeZone("UTC")) c.get(c.HOUR) #force refresh? return c def getHoursFromNow(hours): d = getNow() d.add(d.HOUR, hours) return d def isDateClassExpired(d): n = getNow() return d.before(n) def isDateClassBefore(d1, d2): return d1.before(d2)
Python
"""Miscellaneous functions to mask Python version differences.""" import sys import os if sys.version_info < (2,2): raise AssertionError("Python 2.2 or later required") if sys.version_info < (2,3): def enumerate(collection): return zip(range(len(collection)), collection) class Set: def __init__(self, seq=None): self.values = {} if seq: for e in seq: self.values[e] = None def add(self, e): self.values[e] = None def discard(self, e): if e in self.values.keys(): del(self.values[e]) def union(self, s): ret = Set() for e in self.values.keys(): ret.values[e] = None for e in s.values.keys(): ret.values[e] = None return ret def issubset(self, other): for e in self.values.keys(): if e not in other.values.keys(): return False return True def __nonzero__( self): return len(self.values.keys()) def __contains__(self, e): return e in self.values.keys() def __iter__(self): return iter(set.values.keys()) if os.name != "java": import array def createByteArraySequence(seq): return array.array('B', seq) def createByteArrayZeros(howMany): return array.array('B', [0] * howMany) def concatArrays(a1, a2): return a1+a2 def bytesToString(bytes): return bytes.tostring() def stringToBytes(s): bytes = createByteArrayZeros(0) bytes.fromstring(s) return bytes import math def numBits(n): if n==0: return 0 s = "%x" % n return ((len(s)-1)*4) + \ {'0':0, '1':1, '2':2, '3':2, '4':3, '5':3, '6':3, '7':3, '8':4, '9':4, 'a':4, 'b':4, 'c':4, 'd':4, 'e':4, 'f':4, }[s[0]] return int(math.floor(math.log(n, 2))+1) BaseException = Exception import sys import traceback def formatExceptionTrace(e): newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) return newStr else: #Jython 2.1 is missing lots of python 2.3 stuff, #which we have to emulate here: #NOTE: JYTHON SUPPORT NO LONGER WORKS, DUE TO USE OF GENERATORS. #THIS CODE IS LEFT IN SO THAT ONE JYTHON UPDATES TO 2.2, IT HAS A #CHANCE OF WORKING AGAIN. import java import jarray def createByteArraySequence(seq): if isinstance(seq, type("")): #If it's a string, convert seq = [ord(c) for c in seq] return jarray.array(seq, 'h') #use short instead of bytes, cause bytes are signed def createByteArrayZeros(howMany): return jarray.zeros(howMany, 'h') #use short instead of bytes, cause bytes are signed def concatArrays(a1, a2): l = list(a1)+list(a2) return createByteArraySequence(l) #WAY TOO SLOW - MUST BE REPLACED------------ def bytesToString(bytes): return "".join([chr(b) for b in bytes]) def stringToBytes(s): bytes = createByteArrayZeros(len(s)) for count, c in enumerate(s): bytes[count] = ord(c) return bytes #WAY TOO SLOW - MUST BE REPLACED------------ def numBits(n): if n==0: return 0 n= 1L * n; #convert to long, if it isn't already return n.__tojava__(java.math.BigInteger).bitLength() #Adjust the string to an array of bytes def stringToJavaByteArray(s): bytes = jarray.zeros(len(s), 'b') for count, c in enumerate(s): x = ord(c) if x >= 128: x -= 256 bytes[count] = x return bytes BaseException = java.lang.Exception import sys import traceback def formatExceptionTrace(e): newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) return newStr
Python
"""Pure-Python RC4 implementation.""" from RC4 import RC4 from cryptomath import * def new(key): return Python_RC4(key) class Python_RC4(RC4): def __init__(self, key): RC4.__init__(self, key, "python") keyBytes = stringToBytes(key) S = [i for i in range(256)] j = 0 for i in range(256): j = (j + S[i] + keyBytes[i % len(keyBytes)]) % 256 S[i], S[j] = S[j], S[i] self.S = S self.i = 0 self.j = 0 def encrypt(self, plaintext): plaintextBytes = stringToBytes(plaintext) S = self.S i = self.i j = self.j for x in range(len(plaintextBytes)): i = (i + 1) % 256 j = (j + S[i]) % 256 S[i], S[j] = S[j], S[i] t = (S[i] + S[j]) % 256 plaintextBytes[x] ^= S[t] self.i = i self.j = j return bytesToString(plaintextBytes) def decrypt(self, ciphertext): return self.encrypt(ciphertext)
Python
"""OpenSSL/M2Crypto RC4 implementation.""" from cryptomath import * from RC4 import RC4 if m2cryptoLoaded: def new(key): return OpenSSL_RC4(key) class OpenSSL_RC4(RC4): def __init__(self, key): RC4.__init__(self, key, "openssl") self.rc4 = m2.rc4_new() m2.rc4_set_key(self.rc4, key) def __del__(self): m2.rc4_free(self.rc4) def encrypt(self, plaintext): return m2.rc4_update(self.rc4, plaintext) def decrypt(self, ciphertext): return self.encrypt(ciphertext)
Python
"""Class for parsing ASN.1""" from compat import * from codec import * #Takes a byte array which has a DER TLV field at its head class ASN1Parser: def __init__(self, bytes): p = Parser(bytes) p.get(1) #skip Type #Get Length self.length = self._getASN1Length(p) #Get Value self.value = p.getFixBytes(self.length) #Assuming this is a sequence... def getChild(self, which): p = Parser(self.value) for x in range(which+1): markIndex = p.index p.get(1) #skip Type length = self._getASN1Length(p) p.getFixBytes(length) return ASN1Parser(p.bytes[markIndex : p.index]) #Decode the ASN.1 DER length field def _getASN1Length(self, p): firstLength = p.get(1) if firstLength<=127: return firstLength else: lengthLength = firstLength & 0x7F return p.get(lengthLength)
Python
"""HMAC (Keyed-Hashing for Message Authentication) Python module. Implements the HMAC algorithm as described by RFC 2104. (This file is modified from the standard library version to do faster copying) """ def _strxor(s1, s2): """Utility method. XOR the two strings s1 and s2 (must have same length). """ return "".join(map(lambda x, y: chr(ord(x) ^ ord(y)), s1, s2)) # The size of the digests returned by HMAC depends on the underlying # hashing module used. digest_size = None class HMAC: """RFC2104 HMAC class. This supports the API for Cryptographic Hash Functions (PEP 247). """ def __init__(self, key, msg = None, digestmod = None): """Create a new HMAC object. key: key for the keyed hash object. msg: Initial input for the hash, if provided. digestmod: A module supporting PEP 247. Defaults to the md5 module. """ if digestmod is None: import md5 digestmod = md5 if key == None: #TREVNEW - for faster copying return #TREVNEW self.digestmod = digestmod self.outer = digestmod.new() self.inner = digestmod.new() self.digest_size = digestmod.digest_size blocksize = 64 ipad = "\x36" * blocksize opad = "\x5C" * blocksize if len(key) > blocksize: key = digestmod.new(key).digest() key = key + chr(0) * (blocksize - len(key)) self.outer.update(_strxor(key, opad)) self.inner.update(_strxor(key, ipad)) if msg is not None: self.update(msg) ## def clear(self): ## raise NotImplementedError, "clear() method not available in HMAC." def update(self, msg): """Update this hashing object with the string msg. """ self.inner.update(msg) def copy(self): """Return a separate copy of this hashing object. An update to this copy won't affect the original object. """ other = HMAC(None) #TREVNEW - for faster copying other.digest_size = self.digest_size #TREVNEW other.digestmod = self.digestmod other.inner = self.inner.copy() other.outer = self.outer.copy() return other def digest(self): """Return the hash value of this hashing object. This returns a string containing 8-bit data. The object is not altered in any way by this function; you can continue updating the object after calling this function. """ h = self.outer.copy() h.update(self.inner.digest()) return h.digest() def hexdigest(self): """Like digest(), but returns a string of hexadecimal digits instead. """ return "".join([hex(ord(x))[2:].zfill(2) for x in tuple(self.digest())]) def new(key, msg = None, digestmod = None): """Create a new hashing object and return it. key: The starting key for the hash. msg: if available, will immediately be hashed into the object's starting state. You can now feed arbitrary strings into the object using its update() method, and can ask for the hash value at any time by calling its digest() method. """ return HMAC(key, msg, digestmod)
Python
"""OpenSSL/M2Crypto AES implementation.""" from cryptomath import * from AES import * if m2cryptoLoaded: def new(key, mode, IV): return OpenSSL_AES(key, mode, IV) class OpenSSL_AES(AES): def __init__(self, key, mode, IV): AES.__init__(self, key, mode, IV, "openssl") self.key = key self.IV = IV def _createContext(self, encrypt): context = m2.cipher_ctx_new() if len(self.key)==16: cipherType = m2.aes_128_cbc() if len(self.key)==24: cipherType = m2.aes_192_cbc() if len(self.key)==32: cipherType = m2.aes_256_cbc() m2.cipher_init(context, cipherType, self.key, self.IV, encrypt) return context def encrypt(self, plaintext): AES.encrypt(self, plaintext) context = self._createContext(1) ciphertext = m2.cipher_update(context, plaintext) m2.cipher_ctx_free(context) self.IV = ciphertext[-self.block_size:] return ciphertext def decrypt(self, ciphertext): AES.decrypt(self, ciphertext) context = self._createContext(0) #I think M2Crypto has a bug - it fails to decrypt and return the last block passed in. #To work around this, we append sixteen zeros to the string, below: plaintext = m2.cipher_update(context, ciphertext+('\0'*16)) #If this bug is ever fixed, then plaintext will end up having a garbage #plaintext block on the end. That's okay - the below code will discard it. plaintext = plaintext[:len(ciphertext)] m2.cipher_ctx_free(context) self.IV = ciphertext[-self.block_size:] return plaintext
Python
"""cryptomath module This module has basic math/crypto code.""" import os import sys import math import base64 import binascii if sys.version_info[:2] <= (2, 4): from sha import sha as sha1 else: from hashlib import sha1 from compat import * # ************************************************************************** # Load Optional Modules # ************************************************************************** # Try to load M2Crypto/OpenSSL try: from M2Crypto import m2 m2cryptoLoaded = True except ImportError: m2cryptoLoaded = False # Try to load cryptlib try: import cryptlib_py try: cryptlib_py.cryptInit() except cryptlib_py.CryptException, e: #If tlslite and cryptoIDlib are both present, #they might each try to re-initialize this, #so we're tolerant of that. if e[0] != cryptlib_py.CRYPT_ERROR_INITED: raise cryptlibpyLoaded = True except ImportError: cryptlibpyLoaded = False #Try to load GMPY try: import gmpy gmpyLoaded = True except ImportError: gmpyLoaded = False #Try to load pycrypto try: import Crypto.Cipher.AES pycryptoLoaded = True except ImportError: pycryptoLoaded = False # ************************************************************************** # PRNG Functions # ************************************************************************** # Get os.urandom PRNG try: os.urandom(1) def getRandomBytes(howMany): return stringToBytes(os.urandom(howMany)) prngName = "os.urandom" except: # Else get cryptlib PRNG if cryptlibpyLoaded: def getRandomBytes(howMany): randomKey = cryptlib_py.cryptCreateContext(cryptlib_py.CRYPT_UNUSED, cryptlib_py.CRYPT_ALGO_AES) cryptlib_py.cryptSetAttribute(randomKey, cryptlib_py.CRYPT_CTXINFO_MODE, cryptlib_py.CRYPT_MODE_OFB) cryptlib_py.cryptGenerateKey(randomKey) bytes = createByteArrayZeros(howMany) cryptlib_py.cryptEncrypt(randomKey, bytes) return bytes prngName = "cryptlib" else: #Else get UNIX /dev/urandom PRNG try: devRandomFile = open("/dev/urandom", "rb") def getRandomBytes(howMany): return stringToBytes(devRandomFile.read(howMany)) prngName = "/dev/urandom" except IOError: #Else get Win32 CryptoAPI PRNG try: import win32prng def getRandomBytes(howMany): s = win32prng.getRandomBytes(howMany) if len(s) != howMany: raise AssertionError() return stringToBytes(s) prngName ="CryptoAPI" except ImportError: #Else no PRNG :-( def getRandomBytes(howMany): raise NotImplementedError("No Random Number Generator "\ "available.") prngName = "None" # ************************************************************************** # Converter Functions # ************************************************************************** def bytesToNumber(bytes): total = 0L multiplier = 1L for count in range(len(bytes)-1, -1, -1): byte = bytes[count] total += multiplier * byte multiplier *= 256 return total def numberToBytes(n): howManyBytes = numBytes(n) bytes = createByteArrayZeros(howManyBytes) for count in range(howManyBytes-1, -1, -1): bytes[count] = int(n % 256) n >>= 8 return bytes def bytesToBase64(bytes): s = bytesToString(bytes) return stringToBase64(s) def base64ToBytes(s): s = base64ToString(s) return stringToBytes(s) def numberToBase64(n): bytes = numberToBytes(n) return bytesToBase64(bytes) def base64ToNumber(s): bytes = base64ToBytes(s) return bytesToNumber(bytes) def stringToNumber(s): bytes = stringToBytes(s) return bytesToNumber(bytes) def numberToString(s): bytes = numberToBytes(s) return bytesToString(bytes) def base64ToString(s): try: return base64.decodestring(s) except binascii.Error, e: raise SyntaxError(e) except binascii.Incomplete, e: raise SyntaxError(e) def stringToBase64(s): return base64.encodestring(s).replace("\n", "") def mpiToNumber(mpi): #mpi is an openssl-format bignum string if (ord(mpi[4]) & 0x80) !=0: #Make sure this is a positive number raise AssertionError() bytes = stringToBytes(mpi[4:]) return bytesToNumber(bytes) def numberToMPI(n): bytes = numberToBytes(n) ext = 0 #If the high-order bit is going to be set, #add an extra byte of zeros if (numBits(n) & 0x7)==0: ext = 1 length = numBytes(n) + ext bytes = concatArrays(createByteArrayZeros(4+ext), bytes) bytes[0] = (length >> 24) & 0xFF bytes[1] = (length >> 16) & 0xFF bytes[2] = (length >> 8) & 0xFF bytes[3] = length & 0xFF return bytesToString(bytes) # ************************************************************************** # Misc. Utility Functions # ************************************************************************** def numBytes(n): if n==0: return 0 bits = numBits(n) return int(math.ceil(bits / 8.0)) def hashAndBase64(s): return stringToBase64(sha1(s).digest()) def getBase64Nonce(numChars=22): #defaults to an 132 bit nonce bytes = getRandomBytes(numChars) bytesStr = "".join([chr(b) for b in bytes]) return stringToBase64(bytesStr)[:numChars] # ************************************************************************** # Big Number Math # ************************************************************************** def getRandomNumber(low, high): if low >= high: raise AssertionError() howManyBits = numBits(high) howManyBytes = numBytes(high) lastBits = howManyBits % 8 while 1: bytes = getRandomBytes(howManyBytes) if lastBits: bytes[0] = bytes[0] % (1 << lastBits) n = bytesToNumber(bytes) if n >= low and n < high: return n def gcd(a,b): a, b = max(a,b), min(a,b) while b: a, b = b, a % b return a def lcm(a, b): #This will break when python division changes, but we can't use // cause #of Jython return (a * b) / gcd(a, b) #Returns inverse of a mod b, zero if none #Uses Extended Euclidean Algorithm def invMod(a, b): c, d = a, b uc, ud = 1, 0 while c != 0: #This will break when python division changes, but we can't use // #cause of Jython q = d / c c, d = d-(q*c), c uc, ud = ud - (q * uc), uc if d == 1: return ud % b return 0 if gmpyLoaded: def powMod(base, power, modulus): base = gmpy.mpz(base) power = gmpy.mpz(power) modulus = gmpy.mpz(modulus) result = pow(base, power, modulus) return long(result) else: #Copied from Bryan G. Olson's post to comp.lang.python #Does left-to-right instead of pow()'s right-to-left, #thus about 30% faster than the python built-in with small bases def powMod(base, power, modulus): nBitScan = 5 """ Return base**power mod modulus, using multi bit scanning with nBitScan bits at a time.""" #TREV - Added support for negative exponents negativeResult = False if (power < 0): power *= -1 negativeResult = True exp2 = 2**nBitScan mask = exp2 - 1 # Break power into a list of digits of nBitScan bits. # The list is recursive so easy to read in reverse direction. nibbles = None while power: nibbles = int(power & mask), nibbles power = power >> nBitScan # Make a table of powers of base up to 2**nBitScan - 1 lowPowers = [1] for i in xrange(1, exp2): lowPowers.append((lowPowers[i-1] * base) % modulus) # To exponentiate by the first nibble, look it up in the table nib, nibbles = nibbles prod = lowPowers[nib] # For the rest, square nBitScan times, then multiply by # base^nibble while nibbles: nib, nibbles = nibbles for i in xrange(nBitScan): prod = (prod * prod) % modulus if nib: prod = (prod * lowPowers[nib]) % modulus #TREV - Added support for negative exponents if negativeResult: prodInv = invMod(prod, modulus) #Check to make sure the inverse is correct if (prod * prodInv) % modulus != 1: raise AssertionError() return prodInv return prod #Pre-calculate a sieve of the ~100 primes < 1000: def makeSieve(n): sieve = range(n) for count in range(2, int(math.sqrt(n))): if sieve[count] == 0: continue x = sieve[count] * 2 while x < len(sieve): sieve[x] = 0 x += sieve[count] sieve = [x for x in sieve[2:] if x] return sieve sieve = makeSieve(1000) def isPrime(n, iterations=5, display=False): #Trial division with sieve for x in sieve: if x >= n: return True if n % x == 0: return False #Passed trial division, proceed to Rabin-Miller #Rabin-Miller implemented per Ferguson & Schneier #Compute s, t for Rabin-Miller if display: print "*", s, t = n-1, 0 while s % 2 == 0: s, t = s/2, t+1 #Repeat Rabin-Miller x times a = 2 #Use 2 as a base for first iteration speedup, per HAC for count in range(iterations): v = powMod(a, s, n) if v==1: continue i = 0 while v != n-1: if i == t-1: return False else: v, i = powMod(v, 2, n), i+1 a = getRandomNumber(2, n) return True def getRandomPrime(bits, display=False): if bits < 10: raise AssertionError() #The 1.5 ensures the 2 MSBs are set #Thus, when used for p,q in RSA, n will have its MSB set # #Since 30 is lcm(2,3,5), we'll set our test numbers to #29 % 30 and keep them there low = (2L ** (bits-1)) * 3/2 high = 2L ** bits - 30 p = getRandomNumber(low, high) p += 29 - (p % 30) while 1: if display: print ".", p += 30 if p >= high: p = getRandomNumber(low, high) p += 29 - (p % 30) if isPrime(p, display=display): return p #Unused at the moment... def getRandomSafePrime(bits, display=False): if bits < 10: raise AssertionError() #The 1.5 ensures the 2 MSBs are set #Thus, when used for p,q in RSA, n will have its MSB set # #Since 30 is lcm(2,3,5), we'll set our test numbers to #29 % 30 and keep them there low = (2 ** (bits-2)) * 3/2 high = (2 ** (bits-1)) - 30 q = getRandomNumber(low, high) q += 29 - (q % 30) while 1: if display: print ".", q += 30 if (q >= high): q = getRandomNumber(low, high) q += 29 - (q % 30) #Ideas from Tom Wu's SRP code #Do trial division on p and q before Rabin-Miller if isPrime(q, 0, display=display): p = (2 * q) + 1 if isPrime(p, display=display): if isPrime(q, display=display): return p
Python