code
stringlengths
1
1.72M
language
stringclasses
1 value
"""Abstract class for AES.""" class AES: def __init__(self, key, mode, IV, implementation): if len(key) not in (16, 24, 32): raise AssertionError() if mode != 2: raise AssertionError() if len(IV) != 16: raise AssertionError() self.isBlockCipher = True self.block_size = 16 self.implementation = implementation if len(key)==16: self.name = "aes128" elif len(key)==24: self.name = "aes192" elif len(key)==32: self.name = "aes256" else: raise AssertionError() #CBC-Mode encryption, returns ciphertext #WARNING: *MAY* modify the input as well def encrypt(self, plaintext): assert(len(plaintext) % 16 == 0) #CBC-Mode decryption, returns plaintext #WARNING: *MAY* modify the input as well def decrypt(self, ciphertext): assert(len(ciphertext) % 16 == 0)
Python
""" A pure python (slow) implementation of rijndael with a decent interface To include - from rijndael import rijndael To do a key setup - r = rijndael(key, block_size = 16) key must be a string of length 16, 24, or 32 blocksize must be 16, 24, or 32. Default is 16 To use - ciphertext = r.encrypt(plaintext) plaintext = r.decrypt(ciphertext) If any strings are of the wrong length a ValueError is thrown """ # ported from the Java reference code by Bram Cohen, bram@gawth.com, April 2001 # this code is public domain, unless someone makes # an intellectual property claim against the reference # code, in which case it can be made public domain by # deleting all the comments and renaming all the variables import copy import string #----------------------- #TREV - ADDED BECAUSE THERE'S WARNINGS ABOUT INT OVERFLOW BEHAVIOR CHANGING IN #2.4..... import os if os.name != "java": import exceptions if hasattr(exceptions, "FutureWarning"): import warnings warnings.filterwarnings("ignore", category=FutureWarning, append=1) #----------------------- shifts = [[[0, 0], [1, 3], [2, 2], [3, 1]], [[0, 0], [1, 5], [2, 4], [3, 3]], [[0, 0], [1, 7], [3, 5], [4, 4]]] # [keysize][block_size] num_rounds = {16: {16: 10, 24: 12, 32: 14}, 24: {16: 12, 24: 12, 32: 14}, 32: {16: 14, 24: 14, 32: 14}} A = [[1, 1, 1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 1], [1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 1, 1], [1, 1, 1, 1, 0, 0, 0, 1]] # produce log and alog tables, needed for multiplying in the # field GF(2^m) (generator = 3) alog = [1] for i in xrange(255): j = (alog[-1] << 1) ^ alog[-1] if j & 0x100 != 0: j ^= 0x11B alog.append(j) log = [0] * 256 for i in xrange(1, 255): log[alog[i]] = i # multiply two elements of GF(2^m) def mul(a, b): if a == 0 or b == 0: return 0 return alog[(log[a & 0xFF] + log[b & 0xFF]) % 255] # substitution box based on F^{-1}(x) box = [[0] * 8 for i in xrange(256)] box[1][7] = 1 for i in xrange(2, 256): j = alog[255 - log[i]] for t in xrange(8): box[i][t] = (j >> (7 - t)) & 0x01 B = [0, 1, 1, 0, 0, 0, 1, 1] # affine transform: box[i] <- B + A*box[i] cox = [[0] * 8 for i in xrange(256)] for i in xrange(256): for t in xrange(8): cox[i][t] = B[t] for j in xrange(8): cox[i][t] ^= A[t][j] * box[i][j] # S-boxes and inverse S-boxes S = [0] * 256 Si = [0] * 256 for i in xrange(256): S[i] = cox[i][0] << 7 for t in xrange(1, 8): S[i] ^= cox[i][t] << (7-t) Si[S[i] & 0xFF] = i # T-boxes G = [[2, 1, 1, 3], [3, 2, 1, 1], [1, 3, 2, 1], [1, 1, 3, 2]] AA = [[0] * 8 for i in xrange(4)] for i in xrange(4): for j in xrange(4): AA[i][j] = G[i][j] AA[i][i+4] = 1 for i in xrange(4): pivot = AA[i][i] if pivot == 0: t = i + 1 while AA[t][i] == 0 and t < 4: t += 1 assert t != 4, 'G matrix must be invertible' for j in xrange(8): AA[i][j], AA[t][j] = AA[t][j], AA[i][j] pivot = AA[i][i] for j in xrange(8): if AA[i][j] != 0: AA[i][j] = alog[(255 + log[AA[i][j] & 0xFF] - log[pivot & 0xFF]) % 255] for t in xrange(4): if i != t: for j in xrange(i+1, 8): AA[t][j] ^= mul(AA[i][j], AA[t][i]) AA[t][i] = 0 iG = [[0] * 4 for i in xrange(4)] for i in xrange(4): for j in xrange(4): iG[i][j] = AA[i][j + 4] def mul4(a, bs): if a == 0: return 0 r = 0 for b in bs: r <<= 8 if b != 0: r = r | mul(a, b) return r T1 = [] T2 = [] T3 = [] T4 = [] T5 = [] T6 = [] T7 = [] T8 = [] U1 = [] U2 = [] U3 = [] U4 = [] for t in xrange(256): s = S[t] T1.append(mul4(s, G[0])) T2.append(mul4(s, G[1])) T3.append(mul4(s, G[2])) T4.append(mul4(s, G[3])) s = Si[t] T5.append(mul4(s, iG[0])) T6.append(mul4(s, iG[1])) T7.append(mul4(s, iG[2])) T8.append(mul4(s, iG[3])) U1.append(mul4(t, iG[0])) U2.append(mul4(t, iG[1])) U3.append(mul4(t, iG[2])) U4.append(mul4(t, iG[3])) # round constants rcon = [1] r = 1 for t in xrange(1, 30): r = mul(2, r) rcon.append(r) del A del AA del pivot del B del G del box del log del alog del i del j del r del s del t del mul del mul4 del cox del iG class rijndael: def __init__(self, key, block_size = 16): if block_size != 16 and block_size != 24 and block_size != 32: raise ValueError('Invalid block size: ' + str(block_size)) if len(key) != 16 and len(key) != 24 and len(key) != 32: raise ValueError('Invalid key size: ' + str(len(key))) self.block_size = block_size ROUNDS = num_rounds[len(key)][block_size] BC = block_size / 4 # encryption round keys Ke = [[0] * BC for i in xrange(ROUNDS + 1)] # decryption round keys Kd = [[0] * BC for i in xrange(ROUNDS + 1)] ROUND_KEY_COUNT = (ROUNDS + 1) * BC KC = len(key) / 4 # copy user material bytes into temporary ints tk = [] for i in xrange(0, KC): tk.append((ord(key[i * 4]) << 24) | (ord(key[i * 4 + 1]) << 16) | (ord(key[i * 4 + 2]) << 8) | ord(key[i * 4 + 3])) # copy values into round key arrays t = 0 j = 0 while j < KC and t < ROUND_KEY_COUNT: Ke[t / BC][t % BC] = tk[j] Kd[ROUNDS - (t / BC)][t % BC] = tk[j] j += 1 t += 1 tt = 0 rconpointer = 0 while t < ROUND_KEY_COUNT: # extrapolate using phi (the round key evolution function) tt = tk[KC - 1] tk[0] ^= (S[(tt >> 16) & 0xFF] & 0xFF) << 24 ^ \ (S[(tt >> 8) & 0xFF] & 0xFF) << 16 ^ \ (S[ tt & 0xFF] & 0xFF) << 8 ^ \ (S[(tt >> 24) & 0xFF] & 0xFF) ^ \ (rcon[rconpointer] & 0xFF) << 24 rconpointer += 1 if KC != 8: for i in xrange(1, KC): tk[i] ^= tk[i-1] else: for i in xrange(1, KC / 2): tk[i] ^= tk[i-1] tt = tk[KC / 2 - 1] tk[KC / 2] ^= (S[ tt & 0xFF] & 0xFF) ^ \ (S[(tt >> 8) & 0xFF] & 0xFF) << 8 ^ \ (S[(tt >> 16) & 0xFF] & 0xFF) << 16 ^ \ (S[(tt >> 24) & 0xFF] & 0xFF) << 24 for i in xrange(KC / 2 + 1, KC): tk[i] ^= tk[i-1] # copy values into round key arrays j = 0 while j < KC and t < ROUND_KEY_COUNT: Ke[t / BC][t % BC] = tk[j] Kd[ROUNDS - (t / BC)][t % BC] = tk[j] j += 1 t += 1 # inverse MixColumn where needed for r in xrange(1, ROUNDS): for j in xrange(BC): tt = Kd[r][j] Kd[r][j] = U1[(tt >> 24) & 0xFF] ^ \ U2[(tt >> 16) & 0xFF] ^ \ U3[(tt >> 8) & 0xFF] ^ \ U4[ tt & 0xFF] self.Ke = Ke self.Kd = Kd def encrypt(self, plaintext): if len(plaintext) != self.block_size: raise ValueError('wrong block length, expected ' + str(self.block_size) + ' got ' + str(len(plaintext))) Ke = self.Ke BC = self.block_size / 4 ROUNDS = len(Ke) - 1 if BC == 4: SC = 0 elif BC == 6: SC = 1 else: SC = 2 s1 = shifts[SC][1][0] s2 = shifts[SC][2][0] s3 = shifts[SC][3][0] a = [0] * BC # temporary work array t = [] # plaintext to ints + key for i in xrange(BC): t.append((ord(plaintext[i * 4 ]) << 24 | ord(plaintext[i * 4 + 1]) << 16 | ord(plaintext[i * 4 + 2]) << 8 | ord(plaintext[i * 4 + 3]) ) ^ Ke[0][i]) # apply round transforms for r in xrange(1, ROUNDS): for i in xrange(BC): a[i] = (T1[(t[ i ] >> 24) & 0xFF] ^ T2[(t[(i + s1) % BC] >> 16) & 0xFF] ^ T3[(t[(i + s2) % BC] >> 8) & 0xFF] ^ T4[ t[(i + s3) % BC] & 0xFF] ) ^ Ke[r][i] t = copy.copy(a) # last round is special result = [] for i in xrange(BC): tt = Ke[ROUNDS][i] result.append((S[(t[ i ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF) result.append((S[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF) result.append((S[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8)) & 0xFF) result.append((S[ t[(i + s3) % BC] & 0xFF] ^ tt ) & 0xFF) return string.join(map(chr, result), '') def decrypt(self, ciphertext): if len(ciphertext) != self.block_size: raise ValueError('wrong block length, expected ' + str(self.block_size) + ' got ' + str(len(plaintext))) Kd = self.Kd BC = self.block_size / 4 ROUNDS = len(Kd) - 1 if BC == 4: SC = 0 elif BC == 6: SC = 1 else: SC = 2 s1 = shifts[SC][1][1] s2 = shifts[SC][2][1] s3 = shifts[SC][3][1] a = [0] * BC # temporary work array t = [0] * BC # ciphertext to ints + key for i in xrange(BC): t[i] = (ord(ciphertext[i * 4 ]) << 24 | ord(ciphertext[i * 4 + 1]) << 16 | ord(ciphertext[i * 4 + 2]) << 8 | ord(ciphertext[i * 4 + 3]) ) ^ Kd[0][i] # apply round transforms for r in xrange(1, ROUNDS): for i in xrange(BC): a[i] = (T5[(t[ i ] >> 24) & 0xFF] ^ T6[(t[(i + s1) % BC] >> 16) & 0xFF] ^ T7[(t[(i + s2) % BC] >> 8) & 0xFF] ^ T8[ t[(i + s3) % BC] & 0xFF] ) ^ Kd[r][i] t = copy.copy(a) # last round is special result = [] for i in xrange(BC): tt = Kd[ROUNDS][i] result.append((Si[(t[ i ] >> 24) & 0xFF] ^ (tt >> 24)) & 0xFF) result.append((Si[(t[(i + s1) % BC] >> 16) & 0xFF] ^ (tt >> 16)) & 0xFF) result.append((Si[(t[(i + s2) % BC] >> 8) & 0xFF] ^ (tt >> 8)) & 0xFF) result.append((Si[ t[(i + s3) % BC] & 0xFF] ^ tt ) & 0xFF) return string.join(map(chr, result), '') def encrypt(key, block): return rijndael(key, len(block)).encrypt(block) def decrypt(key, block): return rijndael(key, len(block)).decrypt(block) def test(): def t(kl, bl): b = 'b' * bl r = rijndael('a' * kl, bl) assert r.decrypt(r.encrypt(b)) == b t(16, 16) t(16, 24) t(16, 32) t(24, 16) t(24, 24) t(24, 32) t(32, 16) t(32, 24) t(32, 32)
Python
"""Cryptlib 3DES implementation.""" from cryptomath import * from TripleDES import * if cryptlibpyLoaded: def new(key, mode, IV): return Cryptlib_TripleDES(key, mode, IV) class Cryptlib_TripleDES(TripleDES): def __init__(self, key, mode, IV): TripleDES.__init__(self, key, mode, IV, "cryptlib") self.context = cryptlib_py.cryptCreateContext(cryptlib_py.CRYPT_UNUSED, cryptlib_py.CRYPT_ALGO_3DES) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_MODE, cryptlib_py.CRYPT_MODE_CBC) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_KEYSIZE, len(key)) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_KEY, key) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_IV, IV) def __del__(self): cryptlib_py.cryptDestroyContext(self.context) def encrypt(self, plaintext): TripleDES.encrypt(self, plaintext) bytes = stringToBytes(plaintext) cryptlib_py.cryptEncrypt(self.context, bytes) return bytesToString(bytes) def decrypt(self, ciphertext): TripleDES.decrypt(self, ciphertext) bytes = stringToBytes(ciphertext) cryptlib_py.cryptDecrypt(self.context, bytes) return bytesToString(bytes)
Python
"""Abstract class for RC4.""" from compat import * #For False class RC4: def __init__(self, keyBytes, implementation): if len(keyBytes) < 16 or len(keyBytes) > 256: raise ValueError() self.isBlockCipher = False self.name = "rc4" self.implementation = implementation def encrypt(self, plaintext): raise NotImplementedError() def decrypt(self, ciphertext): raise NotImplementedError()
Python
"""PyCrypto RSA implementation.""" from cryptomath import * from RSAKey import * from Python_RSAKey import Python_RSAKey if pycryptoLoaded: from Crypto.PublicKey import RSA class PyCrypto_RSAKey(RSAKey): def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0): if not d: self.rsa = RSA.construct( (n, e) ) else: self.rsa = RSA.construct( (n, e, d, p, q) ) def __getattr__(self, name): return getattr(self.rsa, name) def hasPrivateKey(self): return self.rsa.has_private() 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(self.rsa.decrypt((s,))) 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(self.rsa.encrypt(s, None)[0]) return m def writeXMLPublicKey(self, indent=''): return Python_RSAKey(self.n, self.e).write(indent) def generate(bits): key = PyCrypto_RSAKey() def f(numBytes): return bytesToString(getRandomBytes(numBytes)) key.rsa = RSA.generate(bits, f) return key generate = staticmethod(generate)
Python
"""PyCrypto AES implementation.""" from cryptomath import * from AES import * if pycryptoLoaded: import Crypto.Cipher.AES def new(key, mode, IV): return PyCrypto_AES(key, mode, IV) class PyCrypto_AES(AES): def __init__(self, key, mode, IV): AES.__init__(self, key, mode, IV, "pycrypto") self.context = Crypto.Cipher.AES.new(key, mode, IV) def encrypt(self, plaintext): return self.context.encrypt(plaintext) def decrypt(self, ciphertext): return self.context.decrypt(ciphertext)
Python
"""Abstract class for 3DES.""" from compat import * #For True class TripleDES: def __init__(self, key, mode, IV, implementation): if len(key) != 24: raise ValueError() if mode != 2: raise ValueError() if len(IV) != 8: raise ValueError() self.isBlockCipher = True self.block_size = 8 self.implementation = implementation self.name = "3des" #CBC-Mode encryption, returns ciphertext #WARNING: *MAY* modify the input as well def encrypt(self, plaintext): assert(len(plaintext) % 8 == 0) #CBC-Mode decryption, returns plaintext #WARNING: *MAY* modify the input as well def decrypt(self, ciphertext): assert(len(ciphertext) % 8 == 0)
Python
"""Cryptlib RC4 implementation.""" from cryptomath import * from RC4 import RC4 if cryptlibpyLoaded: def new(key): return Cryptlib_RC4(key) class Cryptlib_RC4(RC4): def __init__(self, key): RC4.__init__(self, key, "cryptlib") self.context = cryptlib_py.cryptCreateContext(cryptlib_py.CRYPT_UNUSED, cryptlib_py.CRYPT_ALGO_RC4) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_KEYSIZE, len(key)) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_KEY, key) def __del__(self): cryptlib_py.cryptDestroyContext(self.context) def encrypt(self, plaintext): bytes = stringToBytes(plaintext) cryptlib_py.cryptEncrypt(self.context, bytes) return bytesToString(bytes) def decrypt(self, ciphertext): return self.encrypt(ciphertext)
Python
"""Abstract class for RSA.""" from cryptomath import * class RSAKey: """This is an abstract base class for RSA keys. Particular implementations of RSA keys, such as L{OpenSSL_RSAKey.OpenSSL_RSAKey}, L{Python_RSAKey.Python_RSAKey}, and L{PyCrypto_RSAKey.PyCrypto_RSAKey}, inherit from this. To create or parse an RSA key, don't use one of these classes directly. Instead, use the factory functions in L{tlslite.utils.keyfactory}. """ def __init__(self, n=0, e=0): """Create a new RSA key. If n and e are passed in, the new key will be initialized. @type n: int @param n: RSA modulus. @type e: int @param e: RSA public exponent. """ raise NotImplementedError() def __len__(self): """Return the length of this key in bits. @rtype: int """ return numBits(self.n) def hasPrivateKey(self): """Return whether or not this key has a private component. @rtype: bool """ raise NotImplementedError() def hash(self): """Return the cryptoID <keyHash> value corresponding to this key. @rtype: str """ raise NotImplementedError() def getSigningAlgorithm(self): """Return the cryptoID sigAlgo value corresponding to this key. @rtype: str """ return "pkcs1-sha1" def hashAndSign(self, bytes): """Hash and sign the passed-in bytes. This requires the key to have a private component. It performs a PKCS1-SHA1 signature on the passed-in data. @type bytes: str or L{array.array} of unsigned bytes @param bytes: The value which will be hashed and signed. @rtype: L{array.array} of unsigned bytes. @return: A PKCS1-SHA1 signature on the passed-in data. """ if not isinstance(bytes, type("")): bytes = bytesToString(bytes) hashBytes = stringToBytes(sha1(bytes).digest()) prefixedHashBytes = self._addPKCS1SHA1Prefix(hashBytes) sigBytes = self.sign(prefixedHashBytes) return sigBytes def hashAndVerify(self, sigBytes, bytes): """Hash and verify the passed-in bytes with the signature. This verifies a PKCS1-SHA1 signature on the passed-in data. @type sigBytes: L{array.array} of unsigned bytes @param sigBytes: A PKCS1-SHA1 signature. @type bytes: str or L{array.array} of unsigned bytes @param bytes: The value which will be hashed and verified. @rtype: bool @return: Whether the signature matches the passed-in data. """ if not isinstance(bytes, type("")): bytes = bytesToString(bytes) hashBytes = stringToBytes(sha1(bytes).digest()) prefixedHashBytes = self._addPKCS1SHA1Prefix(hashBytes) return self.verify(sigBytes, prefixedHashBytes) def sign(self, bytes): """Sign the passed-in bytes. This requires the key to have a private component. It performs a PKCS1 signature on the passed-in data. @type bytes: L{array.array} of unsigned bytes @param bytes: The value which will be signed. @rtype: L{array.array} of unsigned bytes. @return: A PKCS1 signature on the passed-in data. """ if not self.hasPrivateKey(): raise AssertionError() paddedBytes = self._addPKCS1Padding(bytes, 1) m = bytesToNumber(paddedBytes) if m >= self.n: raise ValueError() c = self._rawPrivateKeyOp(m) sigBytes = numberToBytes(c) return sigBytes def verify(self, sigBytes, bytes): """Verify the passed-in bytes with the signature. This verifies a PKCS1 signature on the passed-in data. @type sigBytes: L{array.array} of unsigned bytes @param sigBytes: A PKCS1 signature. @type bytes: L{array.array} of unsigned bytes @param bytes: The value which will be verified. @rtype: bool @return: Whether the signature matches the passed-in data. """ paddedBytes = self._addPKCS1Padding(bytes, 1) c = bytesToNumber(sigBytes) if c >= self.n: return False m = self._rawPublicKeyOp(c) checkBytes = numberToBytes(m) return checkBytes == paddedBytes def encrypt(self, bytes): """Encrypt the passed-in bytes. This performs PKCS1 encryption of the passed-in data. @type bytes: L{array.array} of unsigned bytes @param bytes: The value which will be encrypted. @rtype: L{array.array} of unsigned bytes. @return: A PKCS1 encryption of the passed-in data. """ paddedBytes = self._addPKCS1Padding(bytes, 2) m = bytesToNumber(paddedBytes) if m >= self.n: raise ValueError() c = self._rawPublicKeyOp(m) encBytes = numberToBytes(c) return encBytes def decrypt(self, encBytes): """Decrypt the passed-in bytes. This requires the key to have a private component. It performs PKCS1 decryption of the passed-in data. @type encBytes: L{array.array} of unsigned bytes @param encBytes: The value which will be decrypted. @rtype: L{array.array} of unsigned bytes or None. @return: A PKCS1 decryption of the passed-in data or None if the data is not properly formatted. """ if not self.hasPrivateKey(): raise AssertionError() c = bytesToNumber(encBytes) if c >= self.n: return None m = self._rawPrivateKeyOp(c) decBytes = numberToBytes(m) if (len(decBytes) != numBytes(self.n)-1): #Check first byte return None if decBytes[0] != 2: #Check second byte return None for x in range(len(decBytes)-1): #Scan through for zero separator if decBytes[x]== 0: break else: return None return decBytes[x+1:] #Return everything after the separator def _rawPrivateKeyOp(self, m): raise NotImplementedError() def _rawPublicKeyOp(self, c): raise NotImplementedError() def acceptsPassword(self): """Return True if the write() method accepts a password for use in encrypting the private key. @rtype: bool """ raise NotImplementedError() def write(self, password=None): """Return a string containing the key. @rtype: str @return: A string describing the key, in whichever format (PEM or XML) is native to the implementation. """ raise NotImplementedError() def writeXMLPublicKey(self, indent=''): """Return a string containing the key. @rtype: str @return: A string describing the public key, in XML format. """ return Python_RSAKey(self.n, self.e).write(indent) def generate(bits): """Generate a new key with the specified bit length. @rtype: L{tlslite.utils.RSAKey.RSAKey} """ raise NotImplementedError() generate = staticmethod(generate) # ************************************************************************** # Helper Functions for RSA Keys # ************************************************************************** def _addPKCS1SHA1Prefix(self, bytes): prefixBytes = createByteArraySequence(\ [48,33,48,9,6,5,43,14,3,2,26,5,0,4,20]) prefixedBytes = prefixBytes + bytes return prefixedBytes def _addPKCS1Padding(self, bytes, blockType): padLength = (numBytes(self.n) - (len(bytes)+3)) if blockType == 1: #Signature padding pad = [0xFF] * padLength elif blockType == 2: #Encryption padding pad = createByteArraySequence([]) while len(pad) < padLength: padBytes = getRandomBytes(padLength * 2) pad = [b for b in padBytes if b != 0] pad = pad[:padLength] else: raise AssertionError() #NOTE: To be proper, we should add [0,blockType]. However, #the zero is lost when the returned padding is converted #to a number, so we don't even bother with it. Also, #adding it would cause a misalignment in verify() padding = createByteArraySequence([blockType] + pad + [0]) paddedBytes = padding + bytes return paddedBytes
Python
"""Miscellaneous functions to mask Python/Jython differences.""" import os import sha if os.name != "java": BaseException = Exception from sets import Set import array import math 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 def numBits(n): if n==0: return 0 return int(math.floor(math.log(n, 2))+1) class CertChainBase: pass class SelfTestBase: pass class ReportFuncBase: pass #Helper functions for working with sets (from Python 2.3) def iterSet(set): return iter(set) def getListFromSet(set): return list(set) #Factory function for getting a SHA1 object def getSHA1(s): return sha.sha(s) 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: import java import jarray BaseException = java.lang.Exception 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() #This properly creates static methods for Jython class staticmethod: def __init__(self, anycallable): self.__call__ = anycallable #Properties are not supported for Jython class property: def __init__(self, anycallable): pass #True and False have to be specially defined False = 0 True = 1 class StopIteration(Exception): pass 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 iterSet(set): return set.values.keys() def getListFromSet(set): return set.values.keys() """ class JCE_SHA1: def __init__(self, s=None): self.md = java.security.MessageDigest.getInstance("SHA1") if s: self.update(s) def update(self, s): self.md.update(s) def copy(self): sha1 = JCE_SHA1() sha1.md = self.md.clone() return sha1 def digest(self): digest = self.md.digest() bytes = jarray.zeros(20, 'h') for count in xrange(20): x = digest[count] if x < 0: x += 256 bytes[count] = x return bytes """ #Factory function for getting a SHA1 object #The JCE_SHA1 class is way too slow... #the sha.sha object we use instead is broken in the jython 2.1 #release, and needs to be patched def getSHA1(s): #return JCE_SHA1(s) return sha.sha(s) #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 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 AES implementation.""" from cryptomath import * from AES import * from rijndael import rijndael def new(key, mode, IV): return Python_AES(key, mode, IV) class Python_AES(AES): def __init__(self, key, mode, IV): AES.__init__(self, key, mode, IV, "python") self.rijndael = rijndael(key, 16) self.IV = IV def encrypt(self, plaintext): AES.encrypt(self, plaintext) plaintextBytes = stringToBytes(plaintext) chainBytes = stringToBytes(self.IV) #CBC Mode: For each block... for x in range(len(plaintextBytes)/16): #XOR with the chaining block blockBytes = plaintextBytes[x*16 : (x*16)+16] for y in range(16): blockBytes[y] ^= chainBytes[y] blockString = bytesToString(blockBytes) #Encrypt it encryptedBytes = stringToBytes(self.rijndael.encrypt(blockString)) #Overwrite the input with the output for y in range(16): plaintextBytes[(x*16)+y] = encryptedBytes[y] #Set the next chaining block chainBytes = encryptedBytes self.IV = bytesToString(chainBytes) return bytesToString(plaintextBytes) def decrypt(self, ciphertext): AES.decrypt(self, ciphertext) ciphertextBytes = stringToBytes(ciphertext) chainBytes = stringToBytes(self.IV) #CBC Mode: For each block... for x in range(len(ciphertextBytes)/16): #Decrypt it blockBytes = ciphertextBytes[x*16 : (x*16)+16] blockString = bytesToString(blockBytes) decryptedBytes = stringToBytes(self.rijndael.decrypt(blockString)) #XOR with the chaining block and overwrite the input with output for y in range(16): decryptedBytes[y] ^= chainBytes[y] ciphertextBytes[(x*16)+y] = decryptedBytes[y] #Set the next chaining block chainBytes = blockBytes self.IV = bytesToString(chainBytes) return bytesToString(ciphertextBytes)
Python
"""Toolkit for crypto and other stuff.""" __all__ = ["AES", "ASN1Parser", "cipherfactory", "codec", "Cryptlib_AES", "Cryptlib_RC4", "Cryptlib_TripleDES", "cryptomath: cryptomath module", "dateFuncs", "hmac", "JCE_RSAKey", "compat", "keyfactory", "OpenSSL_AES", "OpenSSL_RC4", "OpenSSL_RSAKey", "OpenSSL_TripleDES", "PyCrypto_AES", "PyCrypto_RC4", "PyCrypto_RSAKey", "PyCrypto_TripleDES", "Python_AES", "Python_RC4", "Python_RSAKey", "RC4", "rijndael", "RSAKey", "TripleDES", "xmltools"]
Python
"""Pure-Python RSA implementation.""" from cryptomath import * import xmltools from ASN1Parser import ASN1Parser from RSAKey import * class Python_RSAKey(RSAKey): def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0): if (n and not e) or (e and not n): raise AssertionError() self.n = n self.e = e self.d = d self.p = p self.q = q self.dP = dP self.dQ = dQ self.qInv = qInv self.blinder = 0 self.unblinder = 0 def hasPrivateKey(self): return self.d != 0 def hash(self): s = self.writeXMLPublicKey('\t\t') return hashAndBase64(s.strip()) def _rawPrivateKeyOp(self, m): #Create blinding values, on the first pass: if not self.blinder: self.unblinder = getRandomNumber(2, self.n) self.blinder = powMod(invMod(self.unblinder, self.n), self.e, self.n) #Blind the input m = (m * self.blinder) % self.n #Perform the RSA operation c = self._rawPrivateKeyOpHelper(m) #Unblind the output c = (c * self.unblinder) % self.n #Update blinding values self.blinder = (self.blinder * self.blinder) % self.n self.unblinder = (self.unblinder * self.unblinder) % self.n #Return the output return c def _rawPrivateKeyOpHelper(self, m): #Non-CRT version #c = powMod(m, self.d, self.n) #CRT version (~3x faster) s1 = powMod(m, self.dP, self.p) s2 = powMod(m, self.dQ, self.q) h = ((s1 - s2) * self.qInv) % self.p c = s2 + self.q * h return c def _rawPublicKeyOp(self, c): m = powMod(c, self.e, self.n) return m def acceptsPassword(self): return False def write(self, indent=''): if self.d: s = indent+'<privateKey xmlns="http://trevp.net/rsa">\n' else: s = indent+'<publicKey xmlns="http://trevp.net/rsa">\n' s += indent+'\t<n>%s</n>\n' % numberToBase64(self.n) s += indent+'\t<e>%s</e>\n' % numberToBase64(self.e) if self.d: s += indent+'\t<d>%s</d>\n' % numberToBase64(self.d) s += indent+'\t<p>%s</p>\n' % numberToBase64(self.p) s += indent+'\t<q>%s</q>\n' % numberToBase64(self.q) s += indent+'\t<dP>%s</dP>\n' % numberToBase64(self.dP) s += indent+'\t<dQ>%s</dQ>\n' % numberToBase64(self.dQ) s += indent+'\t<qInv>%s</qInv>\n' % numberToBase64(self.qInv) s += indent+'</privateKey>' else: s += indent+'</publicKey>' #Only add \n if part of a larger structure if indent != '': s += '\n' return s def writeXMLPublicKey(self, indent=''): return Python_RSAKey(self.n, self.e).write(indent) def generate(bits): key = Python_RSAKey() p = getRandomPrime(bits/2, False) q = getRandomPrime(bits/2, False) t = lcm(p-1, q-1) key.n = p * q key.e = 3L #Needed to be long, for Java key.d = invMod(key.e, t) key.p = p key.q = q key.dP = key.d % (p-1) key.dQ = key.d % (q-1) key.qInv = invMod(q, p) return key generate = staticmethod(generate) def parsePEM(s, passwordCallback=None): """Parse a string containing a <privateKey> or <publicKey>, or PEM-encoded key.""" start = s.find("-----BEGIN PRIVATE KEY-----") if start != -1: end = s.find("-----END PRIVATE KEY-----") if end == -1: raise SyntaxError("Missing PEM Postfix") s = s[start+len("-----BEGIN PRIVATE KEY -----") : end] bytes = base64ToBytes(s) return Python_RSAKey._parsePKCS8(bytes) else: start = s.find("-----BEGIN RSA PRIVATE KEY-----") if start != -1: end = s.find("-----END RSA PRIVATE KEY-----") if end == -1: raise SyntaxError("Missing PEM Postfix") s = s[start+len("-----BEGIN RSA PRIVATE KEY -----") : end] bytes = base64ToBytes(s) return Python_RSAKey._parseSSLeay(bytes) raise SyntaxError("Missing PEM Prefix") parsePEM = staticmethod(parsePEM) def parseXML(s): element = xmltools.parseAndStripWhitespace(s) return Python_RSAKey._parseXML(element) parseXML = staticmethod(parseXML) def _parsePKCS8(bytes): p = ASN1Parser(bytes) version = p.getChild(0).value[0] if version != 0: raise SyntaxError("Unrecognized PKCS8 version") rsaOID = p.getChild(1).value if list(rsaOID) != [6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0]: raise SyntaxError("Unrecognized AlgorithmIdentifier") #Get the privateKey privateKeyP = p.getChild(2) #Adjust for OCTET STRING encapsulation privateKeyP = ASN1Parser(privateKeyP.value) return Python_RSAKey._parseASN1PrivateKey(privateKeyP) _parsePKCS8 = staticmethod(_parsePKCS8) def _parseSSLeay(bytes): privateKeyP = ASN1Parser(bytes) return Python_RSAKey._parseASN1PrivateKey(privateKeyP) _parseSSLeay = staticmethod(_parseSSLeay) def _parseASN1PrivateKey(privateKeyP): version = privateKeyP.getChild(0).value[0] if version != 0: raise SyntaxError("Unrecognized RSAPrivateKey version") n = bytesToNumber(privateKeyP.getChild(1).value) e = bytesToNumber(privateKeyP.getChild(2).value) d = bytesToNumber(privateKeyP.getChild(3).value) p = bytesToNumber(privateKeyP.getChild(4).value) q = bytesToNumber(privateKeyP.getChild(5).value) dP = bytesToNumber(privateKeyP.getChild(6).value) dQ = bytesToNumber(privateKeyP.getChild(7).value) qInv = bytesToNumber(privateKeyP.getChild(8).value) return Python_RSAKey(n, e, d, p, q, dP, dQ, qInv) _parseASN1PrivateKey = staticmethod(_parseASN1PrivateKey) def _parseXML(element): try: xmltools.checkName(element, "privateKey") except SyntaxError: xmltools.checkName(element, "publicKey") #Parse attributes xmltools.getReqAttribute(element, "xmlns", "http://trevp.net/rsa\Z") xmltools.checkNoMoreAttributes(element) #Parse public values (<n> and <e>) n = base64ToNumber(xmltools.getText(xmltools.getChild(element, 0, "n"), xmltools.base64RegEx)) e = base64ToNumber(xmltools.getText(xmltools.getChild(element, 1, "e"), xmltools.base64RegEx)) d = 0 p = 0 q = 0 dP = 0 dQ = 0 qInv = 0 #Parse private values, if present if element.childNodes.length>=3: d = base64ToNumber(xmltools.getText(xmltools.getChild(element, 2, "d"), xmltools.base64RegEx)) p = base64ToNumber(xmltools.getText(xmltools.getChild(element, 3, "p"), xmltools.base64RegEx)) q = base64ToNumber(xmltools.getText(xmltools.getChild(element, 4, "q"), xmltools.base64RegEx)) dP = base64ToNumber(xmltools.getText(xmltools.getChild(element, 5, "dP"), xmltools.base64RegEx)) dQ = base64ToNumber(xmltools.getText(xmltools.getChild(element, 6, "dQ"), xmltools.base64RegEx)) qInv = base64ToNumber(xmltools.getText(xmltools.getLastChild(element, 7, "qInv"), xmltools.base64RegEx)) return Python_RSAKey(n, e, d, p, q, dP, dQ, qInv) _parseXML = staticmethod(_parseXML)
Python
"""Cryptlib AES implementation.""" from cryptomath import * from AES import * if cryptlibpyLoaded: def new(key, mode, IV): return Cryptlib_AES(key, mode, IV) class Cryptlib_AES(AES): def __init__(self, key, mode, IV): AES.__init__(self, key, mode, IV, "cryptlib") self.context = cryptlib_py.cryptCreateContext(cryptlib_py.CRYPT_UNUSED, cryptlib_py.CRYPT_ALGO_AES) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_MODE, cryptlib_py.CRYPT_MODE_CBC) cryptlib_py.cryptSetAttribute(self.context, cryptlib_py.CRYPT_CTXINFO_KEYSIZE, len(key)) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_KEY, key) cryptlib_py.cryptSetAttributeString(self.context, cryptlib_py.CRYPT_CTXINFO_IV, IV) def __del__(self): cryptlib_py.cryptDestroyContext(self.context) def encrypt(self, plaintext): AES.encrypt(self, plaintext) bytes = stringToBytes(plaintext) cryptlib_py.cryptEncrypt(self.context, bytes) return bytesToString(bytes) def decrypt(self, ciphertext): AES.decrypt(self, ciphertext) bytes = stringToBytes(ciphertext) cryptlib_py.cryptDecrypt(self.context, bytes) return bytesToString(bytes)
Python
"""Factory functions for symmetric cryptography.""" import os import Python_AES import Python_RC4 import cryptomath tripleDESPresent = False if cryptomath.m2cryptoLoaded: import OpenSSL_AES import OpenSSL_RC4 import OpenSSL_TripleDES tripleDESPresent = True if cryptomath.cryptlibpyLoaded: import Cryptlib_AES import Cryptlib_RC4 import Cryptlib_TripleDES tripleDESPresent = True if cryptomath.pycryptoLoaded: import PyCrypto_AES import PyCrypto_RC4 import PyCrypto_TripleDES tripleDESPresent = True # ************************************************************************** # Factory Functions for AES # ************************************************************************** def createAES(key, IV, implList=None): """Create a new AES object. @type key: str @param key: A 16, 24, or 32 byte string. @type IV: str @param IV: A 16 byte string @rtype: L{tlslite.utils.AES} @return: An AES object. """ if implList == None: implList = ["cryptlib", "openssl", "pycrypto", "python"] for impl in implList: if impl == "cryptlib" and cryptomath.cryptlibpyLoaded: return Cryptlib_AES.new(key, 2, IV) elif impl == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_AES.new(key, 2, IV) elif impl == "pycrypto" and cryptomath.pycryptoLoaded: return PyCrypto_AES.new(key, 2, IV) elif impl == "python": return Python_AES.new(key, 2, IV) raise NotImplementedError() def createRC4(key, IV, implList=None): """Create a new RC4 object. @type key: str @param key: A 16 to 32 byte string. @type IV: object @param IV: Ignored, whatever it is. @rtype: L{tlslite.utils.RC4} @return: An RC4 object. """ if implList == None: implList = ["cryptlib", "openssl", "pycrypto", "python"] if len(IV) != 0: raise AssertionError() for impl in implList: if impl == "cryptlib" and cryptomath.cryptlibpyLoaded: return Cryptlib_RC4.new(key) elif impl == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_RC4.new(key) elif impl == "pycrypto" and cryptomath.pycryptoLoaded: return PyCrypto_RC4.new(key) elif impl == "python": return Python_RC4.new(key) raise NotImplementedError() #Create a new TripleDES instance def createTripleDES(key, IV, implList=None): """Create a new 3DES object. @type key: str @param key: A 24 byte string. @type IV: str @param IV: An 8 byte string @rtype: L{tlslite.utils.TripleDES} @return: A 3DES object. """ if implList == None: implList = ["cryptlib", "openssl", "pycrypto"] for impl in implList: if impl == "cryptlib" and cryptomath.cryptlibpyLoaded: return Cryptlib_TripleDES.new(key, 2, IV) elif impl == "openssl" and cryptomath.m2cryptoLoaded: return OpenSSL_TripleDES.new(key, 2, IV) elif impl == "pycrypto" and cryptomath.pycryptoLoaded: return PyCrypto_TripleDES.new(key, 2, IV) raise NotImplementedError()
Python
"""PyCrypto 3DES implementation.""" from cryptomath import * from TripleDES import * if pycryptoLoaded: import Crypto.Cipher.DES3 def new(key, mode, IV): return PyCrypto_TripleDES(key, mode, IV) class PyCrypto_TripleDES(TripleDES): def __init__(self, key, mode, IV): TripleDES.__init__(self, key, mode, IV, "pycrypto") self.context = Crypto.Cipher.DES3.new(key, mode, IV) def encrypt(self, plaintext): return self.context.encrypt(plaintext) def decrypt(self, ciphertext): return self.context.decrypt(ciphertext)
Python
"""Classes for reading/writing binary data (such as TLS records).""" from compat import * class Writer: def __init__(self, length=0): #If length is zero, then this is just a "trial run" to determine length self.index = 0 self.bytes = createByteArrayZeros(length) def add(self, x, length): if self.bytes: newIndex = self.index+length-1 while newIndex >= self.index: self.bytes[newIndex] = x & 0xFF x >>= 8 newIndex -= 1 self.index += length def addFixSeq(self, seq, length): if self.bytes: for e in seq: self.add(e, length) else: self.index += len(seq)*length def addVarSeq(self, seq, length, lengthLength): if self.bytes: self.add(len(seq)*length, lengthLength) for e in seq: self.add(e, length) else: self.index += lengthLength + (len(seq)*length) class Parser: def __init__(self, bytes): self.bytes = bytes self.index = 0 def get(self, length): if self.index + length > len(self.bytes): raise SyntaxError() x = 0 for count in range(length): x <<= 8 x |= self.bytes[self.index] self.index += 1 return x def getFixBytes(self, lengthBytes): bytes = self.bytes[self.index : self.index+lengthBytes] self.index += lengthBytes return bytes def getVarBytes(self, lengthLength): lengthBytes = self.get(lengthLength) return self.getFixBytes(lengthBytes) def getFixList(self, length, lengthList): l = [0] * lengthList for x in range(lengthList): l[x] = self.get(length) return l def getVarList(self, length, lengthLength): lengthList = self.get(lengthLength) if lengthList % length != 0: raise SyntaxError() lengthList = int(lengthList/length) l = [0] * lengthList for x in range(lengthList): l[x] = self.get(length) return l def startLengthCheck(self, lengthLength): self.lengthCheck = self.get(lengthLength) self.indexCheck = self.index def setLengthCheck(self, length): self.lengthCheck = length self.indexCheck = self.index def stopLengthCheck(self): if (self.index - self.indexCheck) != self.lengthCheck: raise SyntaxError() def atLengthCheck(self): if (self.index - self.indexCheck) < self.lengthCheck: return False elif (self.index - self.indexCheck) == self.lengthCheck: return True else: raise SyntaxError()
Python
"""Classes representing TLS messages.""" from utils.compat import * from utils.cryptomath import * from errors import * from utils.codec import * from constants import * from X509 import X509 from X509CertChain import X509CertChain import sha import md5 class RecordHeader3: def __init__(self): self.type = 0 self.version = (0,0) self.length = 0 self.ssl2 = False def create(self, version, type, length): self.type = type self.version = version self.length = length return self def write(self): w = Writer(5) w.add(self.type, 1) w.add(self.version[0], 1) w.add(self.version[1], 1) w.add(self.length, 2) return w.bytes def parse(self, p): self.type = p.get(1) self.version = (p.get(1), p.get(1)) self.length = p.get(2) self.ssl2 = False return self class RecordHeader2: def __init__(self): self.type = 0 self.version = (0,0) self.length = 0 self.ssl2 = True def parse(self, p): if p.get(1)!=128: raise SyntaxError() self.type = ContentType.handshake self.version = (2,0) #We don't support 2-byte-length-headers; could be a problem self.length = p.get(1) return self class Msg: def preWrite(self, trial): if trial: w = Writer() else: length = self.write(True) w = Writer(length) return w def postWrite(self, w, trial): if trial: return w.index else: return w.bytes class Alert(Msg): def __init__(self): self.contentType = ContentType.alert self.level = 0 self.description = 0 def create(self, description, level=AlertLevel.fatal): self.level = level self.description = description return self def parse(self, p): p.setLengthCheck(2) self.level = p.get(1) self.description = p.get(1) p.stopLengthCheck() return self def write(self): w = Writer(2) w.add(self.level, 1) w.add(self.description, 1) return w.bytes class HandshakeMsg(Msg): def preWrite(self, handshakeType, trial): if trial: w = Writer() w.add(handshakeType, 1) w.add(0, 3) else: length = self.write(True) w = Writer(length) w.add(handshakeType, 1) w.add(length-4, 3) return w class ClientHello(HandshakeMsg): def __init__(self, ssl2=False): self.contentType = ContentType.handshake self.ssl2 = ssl2 self.client_version = (0,0) self.random = createByteArrayZeros(32) self.session_id = createByteArraySequence([]) self.cipher_suites = [] # a list of 16-bit values self.certificate_types = [CertificateType.x509] self.compression_methods = [] # a list of 8-bit values self.srp_username = None # a string def create(self, version, random, session_id, cipher_suites, certificate_types=None, srp_username=None): self.client_version = version self.random = random self.session_id = session_id self.cipher_suites = cipher_suites self.certificate_types = certificate_types self.compression_methods = [0] self.srp_username = srp_username return self def parse(self, p): if self.ssl2: self.client_version = (p.get(1), p.get(1)) cipherSpecsLength = p.get(2) sessionIDLength = p.get(2) randomLength = p.get(2) self.cipher_suites = p.getFixList(3, int(cipherSpecsLength/3)) self.session_id = p.getFixBytes(sessionIDLength) self.random = p.getFixBytes(randomLength) if len(self.random) < 32: zeroBytes = 32-len(self.random) self.random = createByteArrayZeros(zeroBytes) + self.random self.compression_methods = [0]#Fake this value #We're not doing a stopLengthCheck() for SSLv2, oh well.. else: p.startLengthCheck(3) self.client_version = (p.get(1), p.get(1)) self.random = p.getFixBytes(32) self.session_id = p.getVarBytes(1) self.cipher_suites = p.getVarList(2, 2) self.compression_methods = p.getVarList(1, 1) if not p.atLengthCheck(): totalExtLength = p.get(2) soFar = 0 while soFar != totalExtLength: extType = p.get(2) extLength = p.get(2) if extType == 6: self.srp_username = bytesToString(p.getVarBytes(1)) elif extType == 7: self.certificate_types = p.getVarList(1, 1) else: p.getFixBytes(extLength) soFar += 4 + extLength p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.client_hello, trial) w.add(self.client_version[0], 1) w.add(self.client_version[1], 1) w.addFixSeq(self.random, 1) w.addVarSeq(self.session_id, 1, 1) w.addVarSeq(self.cipher_suites, 2, 2) w.addVarSeq(self.compression_methods, 1, 1) extLength = 0 if self.certificate_types and self.certificate_types != \ [CertificateType.x509]: extLength += 5 + len(self.certificate_types) if self.srp_username: extLength += 5 + len(self.srp_username) if extLength > 0: w.add(extLength, 2) if self.certificate_types and self.certificate_types != \ [CertificateType.x509]: w.add(7, 2) w.add(len(self.certificate_types)+1, 2) w.addVarSeq(self.certificate_types, 1, 1) if self.srp_username: w.add(6, 2) w.add(len(self.srp_username)+1, 2) w.addVarSeq(stringToBytes(self.srp_username), 1, 1) return HandshakeMsg.postWrite(self, w, trial) class ServerHello(HandshakeMsg): def __init__(self): self.contentType = ContentType.handshake self.server_version = (0,0) self.random = createByteArrayZeros(32) self.session_id = createByteArraySequence([]) self.cipher_suite = 0 self.certificate_type = CertificateType.x509 self.compression_method = 0 def create(self, version, random, session_id, cipher_suite, certificate_type): self.server_version = version self.random = random self.session_id = session_id self.cipher_suite = cipher_suite self.certificate_type = certificate_type self.compression_method = 0 return self def parse(self, p): p.startLengthCheck(3) self.server_version = (p.get(1), p.get(1)) self.random = p.getFixBytes(32) self.session_id = p.getVarBytes(1) self.cipher_suite = p.get(2) self.compression_method = p.get(1) if not p.atLengthCheck(): totalExtLength = p.get(2) soFar = 0 while soFar != totalExtLength: extType = p.get(2) extLength = p.get(2) if extType == 7: self.certificate_type = p.get(1) else: p.getFixBytes(extLength) soFar += 4 + extLength p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.server_hello, trial) w.add(self.server_version[0], 1) w.add(self.server_version[1], 1) w.addFixSeq(self.random, 1) w.addVarSeq(self.session_id, 1, 1) w.add(self.cipher_suite, 2) w.add(self.compression_method, 1) extLength = 0 if self.certificate_type and self.certificate_type != \ CertificateType.x509: extLength += 5 if extLength != 0: w.add(extLength, 2) if self.certificate_type and self.certificate_type != \ CertificateType.x509: w.add(7, 2) w.add(1, 2) w.add(self.certificate_type, 1) return HandshakeMsg.postWrite(self, w, trial) class Certificate(HandshakeMsg): def __init__(self, certificateType): self.certificateType = certificateType self.contentType = ContentType.handshake self.certChain = None def create(self, certChain): self.certChain = certChain return self def parse(self, p): p.startLengthCheck(3) if self.certificateType == CertificateType.x509: chainLength = p.get(3) index = 0 certificate_list = [] while index != chainLength: certBytes = p.getVarBytes(3) x509 = X509() x509.parseBinary(certBytes) certificate_list.append(x509) index += len(certBytes)+3 if certificate_list: self.certChain = X509CertChain(certificate_list) elif self.certificateType == CertificateType.cryptoID: s = bytesToString(p.getVarBytes(2)) if s: try: import cryptoIDlib.CertChain except ImportError: raise SyntaxError(\ "cryptoID cert chain received, cryptoIDlib not present") self.certChain = cryptoIDlib.CertChain.CertChain().parse(s) else: raise AssertionError() p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.certificate, trial) if self.certificateType == CertificateType.x509: chainLength = 0 if self.certChain: certificate_list = self.certChain.x509List else: certificate_list = [] #determine length for cert in certificate_list: bytes = cert.writeBytes() chainLength += len(bytes)+3 #add bytes w.add(chainLength, 3) for cert in certificate_list: bytes = cert.writeBytes() w.addVarSeq(bytes, 1, 3) elif self.certificateType == CertificateType.cryptoID: if self.certChain: bytes = stringToBytes(self.certChain.write()) else: bytes = createByteArraySequence([]) w.addVarSeq(bytes, 1, 2) else: raise AssertionError() return HandshakeMsg.postWrite(self, w, trial) class CertificateRequest(HandshakeMsg): def __init__(self): self.contentType = ContentType.handshake self.certificate_types = [] #treat as opaque bytes for now self.certificate_authorities = createByteArraySequence([]) def create(self, certificate_types, certificate_authorities): self.certificate_types = certificate_types self.certificate_authorities = certificate_authorities return self def parse(self, p): p.startLengthCheck(3) self.certificate_types = p.getVarList(1, 1) self.certificate_authorities = p.getVarBytes(2) p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.certificate_request, trial) w.addVarSeq(self.certificate_types, 1, 1) w.addVarSeq(self.certificate_authorities, 1, 2) return HandshakeMsg.postWrite(self, w, trial) class ServerKeyExchange(HandshakeMsg): def __init__(self, cipherSuite): self.cipherSuite = cipherSuite self.contentType = ContentType.handshake self.srp_N = 0L self.srp_g = 0L self.srp_s = createByteArraySequence([]) self.srp_B = 0L self.signature = createByteArraySequence([]) def createSRP(self, srp_N, srp_g, srp_s, srp_B): self.srp_N = srp_N self.srp_g = srp_g self.srp_s = srp_s self.srp_B = srp_B return self def parse(self, p): p.startLengthCheck(3) self.srp_N = bytesToNumber(p.getVarBytes(2)) self.srp_g = bytesToNumber(p.getVarBytes(2)) self.srp_s = p.getVarBytes(1) self.srp_B = bytesToNumber(p.getVarBytes(2)) if self.cipherSuite in CipherSuite.srpRsaSuites: self.signature = p.getVarBytes(2) p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.server_key_exchange, trial) w.addVarSeq(numberToBytes(self.srp_N), 1, 2) w.addVarSeq(numberToBytes(self.srp_g), 1, 2) w.addVarSeq(self.srp_s, 1, 1) w.addVarSeq(numberToBytes(self.srp_B), 1, 2) if self.cipherSuite in CipherSuite.srpRsaSuites: w.addVarSeq(self.signature, 1, 2) return HandshakeMsg.postWrite(self, w, trial) def hash(self, clientRandom, serverRandom): oldCipherSuite = self.cipherSuite self.cipherSuite = None try: bytes = clientRandom + serverRandom + self.write()[4:] s = bytesToString(bytes) return stringToBytes(md5.md5(s).digest() + sha.sha(s).digest()) finally: self.cipherSuite = oldCipherSuite class ServerHelloDone(HandshakeMsg): def __init__(self): self.contentType = ContentType.handshake def create(self): return self def parse(self, p): p.startLengthCheck(3) p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.server_hello_done, trial) return HandshakeMsg.postWrite(self, w, trial) class ClientKeyExchange(HandshakeMsg): def __init__(self, cipherSuite, version=None): self.cipherSuite = cipherSuite self.version = version self.contentType = ContentType.handshake self.srp_A = 0 self.encryptedPreMasterSecret = createByteArraySequence([]) def createSRP(self, srp_A): self.srp_A = srp_A return self def createRSA(self, encryptedPreMasterSecret): self.encryptedPreMasterSecret = encryptedPreMasterSecret return self def parse(self, p): p.startLengthCheck(3) if self.cipherSuite in CipherSuite.srpSuites + \ CipherSuite.srpRsaSuites: self.srp_A = bytesToNumber(p.getVarBytes(2)) elif self.cipherSuite in CipherSuite.rsaSuites: if self.version in ((3,1), (3,2)): self.encryptedPreMasterSecret = p.getVarBytes(2) elif self.version == (3,0): self.encryptedPreMasterSecret = \ p.getFixBytes(len(p.bytes)-p.index) else: raise AssertionError() else: raise AssertionError() p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.client_key_exchange, trial) if self.cipherSuite in CipherSuite.srpSuites + \ CipherSuite.srpRsaSuites: w.addVarSeq(numberToBytes(self.srp_A), 1, 2) elif self.cipherSuite in CipherSuite.rsaSuites: if self.version in ((3,1), (3,2)): w.addVarSeq(self.encryptedPreMasterSecret, 1, 2) elif self.version == (3,0): w.addFixSeq(self.encryptedPreMasterSecret, 1) else: raise AssertionError() else: raise AssertionError() return HandshakeMsg.postWrite(self, w, trial) class CertificateVerify(HandshakeMsg): def __init__(self): self.contentType = ContentType.handshake self.signature = createByteArraySequence([]) def create(self, signature): self.signature = signature return self def parse(self, p): p.startLengthCheck(3) self.signature = p.getVarBytes(2) p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.certificate_verify, trial) w.addVarSeq(self.signature, 1, 2) return HandshakeMsg.postWrite(self, w, trial) class ChangeCipherSpec(Msg): def __init__(self): self.contentType = ContentType.change_cipher_spec self.type = 1 def create(self): self.type = 1 return self def parse(self, p): p.setLengthCheck(1) self.type = p.get(1) p.stopLengthCheck() return self def write(self, trial=False): w = Msg.preWrite(self, trial) w.add(self.type,1) return Msg.postWrite(self, w, trial) class Finished(HandshakeMsg): def __init__(self, version): self.contentType = ContentType.handshake self.version = version self.verify_data = createByteArraySequence([]) def create(self, verify_data): self.verify_data = verify_data return self def parse(self, p): p.startLengthCheck(3) if self.version == (3,0): self.verify_data = p.getFixBytes(36) elif self.version in ((3,1), (3,2)): self.verify_data = p.getFixBytes(12) else: raise AssertionError() p.stopLengthCheck() return self def write(self, trial=False): w = HandshakeMsg.preWrite(self, HandshakeType.finished, trial) w.addFixSeq(self.verify_data, 1) return HandshakeMsg.postWrite(self, w, trial) class ApplicationData(Msg): def __init__(self): self.contentType = ContentType.application_data self.bytes = createByteArraySequence([]) def create(self, bytes): self.bytes = bytes return self def parse(self, p): self.bytes = p.bytes return self def write(self): return self.bytes
Python
"""Constants used in various places.""" class CertificateType: x509 = 0 openpgp = 1 cryptoID = 2 class HandshakeType: hello_request = 0 client_hello = 1 server_hello = 2 certificate = 11 server_key_exchange = 12 certificate_request = 13 server_hello_done = 14 certificate_verify = 15 client_key_exchange = 16 finished = 20 class ContentType: change_cipher_spec = 20 alert = 21 handshake = 22 application_data = 23 all = (20,21,22,23) class AlertLevel: warning = 1 fatal = 2 class AlertDescription: """ @cvar bad_record_mac: A TLS record failed to decrypt properly. If this occurs during a shared-key or SRP handshake it most likely indicates a bad password. It may also indicate an implementation error, or some tampering with the data in transit. This alert will be signalled by the server if the SRP password is bad. It may also be signalled by the server if the SRP username is unknown to the server, but it doesn't wish to reveal that fact. This alert will be signalled by the client if the shared-key username is bad. @cvar handshake_failure: A problem occurred while handshaking. This typically indicates a lack of common ciphersuites between client and server, or some other disagreement (about SRP parameters or key sizes, for example). @cvar protocol_version: The other party's SSL/TLS version was unacceptable. This indicates that the client and server couldn't agree on which version of SSL or TLS to use. @cvar user_canceled: The handshake is being cancelled for some reason. """ close_notify = 0 unexpected_message = 10 bad_record_mac = 20 decryption_failed = 21 record_overflow = 22 decompression_failure = 30 handshake_failure = 40 no_certificate = 41 #SSLv3 bad_certificate = 42 unsupported_certificate = 43 certificate_revoked = 44 certificate_expired = 45 certificate_unknown = 46 illegal_parameter = 47 unknown_ca = 48 access_denied = 49 decode_error = 50 decrypt_error = 51 export_restriction = 60 protocol_version = 70 insufficient_security = 71 internal_error = 80 user_canceled = 90 no_renegotiation = 100 unknown_srp_username = 120 missing_srp_username = 121 untrusted_srp_parameters = 122 class CipherSuite: TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA = 0x0050 TLS_SRP_SHA_WITH_AES_128_CBC_SHA = 0x0053 TLS_SRP_SHA_WITH_AES_256_CBC_SHA = 0x0056 TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA = 0x0051 TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA = 0x0054 TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA = 0x0057 TLS_RSA_WITH_3DES_EDE_CBC_SHA = 0x000A TLS_RSA_WITH_AES_128_CBC_SHA = 0x002F TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035 TLS_RSA_WITH_RC4_128_SHA = 0x0005 srpSuites = [] srpSuites.append(TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA) srpSuites.append(TLS_SRP_SHA_WITH_AES_128_CBC_SHA) srpSuites.append(TLS_SRP_SHA_WITH_AES_256_CBC_SHA) def getSrpSuites(ciphers): suites = [] for cipher in ciphers: if cipher == "aes128": suites.append(CipherSuite.TLS_SRP_SHA_WITH_AES_128_CBC_SHA) elif cipher == "aes256": suites.append(CipherSuite.TLS_SRP_SHA_WITH_AES_256_CBC_SHA) elif cipher == "3des": suites.append(CipherSuite.TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA) return suites getSrpSuites = staticmethod(getSrpSuites) srpRsaSuites = [] srpRsaSuites.append(TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA) srpRsaSuites.append(TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA) srpRsaSuites.append(TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA) def getSrpRsaSuites(ciphers): suites = [] for cipher in ciphers: if cipher == "aes128": suites.append(CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA) elif cipher == "aes256": suites.append(CipherSuite.TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA) elif cipher == "3des": suites.append(CipherSuite.TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA) return suites getSrpRsaSuites = staticmethod(getSrpRsaSuites) rsaSuites = [] rsaSuites.append(TLS_RSA_WITH_3DES_EDE_CBC_SHA) rsaSuites.append(TLS_RSA_WITH_AES_128_CBC_SHA) rsaSuites.append(TLS_RSA_WITH_AES_256_CBC_SHA) rsaSuites.append(TLS_RSA_WITH_RC4_128_SHA) def getRsaSuites(ciphers): suites = [] for cipher in ciphers: if cipher == "aes128": suites.append(CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA) elif cipher == "aes256": suites.append(CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA) elif cipher == "rc4": suites.append(CipherSuite.TLS_RSA_WITH_RC4_128_SHA) elif cipher == "3des": suites.append(CipherSuite.TLS_RSA_WITH_3DES_EDE_CBC_SHA) return suites getRsaSuites = staticmethod(getRsaSuites) tripleDESSuites = [] tripleDESSuites.append(TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA) tripleDESSuites.append(TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA) tripleDESSuites.append(TLS_RSA_WITH_3DES_EDE_CBC_SHA) aes128Suites = [] aes128Suites.append(TLS_SRP_SHA_WITH_AES_128_CBC_SHA) aes128Suites.append(TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA) aes128Suites.append(TLS_RSA_WITH_AES_128_CBC_SHA) aes256Suites = [] aes256Suites.append(TLS_SRP_SHA_WITH_AES_256_CBC_SHA) aes256Suites.append(TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA) aes256Suites.append(TLS_RSA_WITH_AES_256_CBC_SHA) rc4Suites = [] rc4Suites.append(TLS_RSA_WITH_RC4_128_SHA) class Fault: badUsername = 101 badPassword = 102 badA = 103 clientSrpFaults = range(101,104) badVerifyMessage = 601 clientCertFaults = range(601,602) badPremasterPadding = 501 shortPremasterSecret = 502 clientNoAuthFaults = range(501,503) badIdentifier = 401 badSharedKey = 402 clientSharedKeyFaults = range(401,403) badB = 201 serverFaults = range(201,202) badFinished = 300 badMAC = 301 badPadding = 302 genericFaults = range(300,303) faultAlerts = {\ badUsername: (AlertDescription.unknown_srp_username, \ AlertDescription.bad_record_mac),\ badPassword: (AlertDescription.bad_record_mac,),\ badA: (AlertDescription.illegal_parameter,),\ badIdentifier: (AlertDescription.handshake_failure,),\ badSharedKey: (AlertDescription.bad_record_mac,),\ badPremasterPadding: (AlertDescription.bad_record_mac,),\ shortPremasterSecret: (AlertDescription.bad_record_mac,),\ badVerifyMessage: (AlertDescription.decrypt_error,),\ badFinished: (AlertDescription.decrypt_error,),\ badMAC: (AlertDescription.bad_record_mac,),\ badPadding: (AlertDescription.bad_record_mac,) } faultNames = {\ badUsername: "bad username",\ badPassword: "bad password",\ badA: "bad A",\ badIdentifier: "bad identifier",\ badSharedKey: "bad sharedkey",\ badPremasterPadding: "bad premaster padding",\ shortPremasterSecret: "short premaster secret",\ badVerifyMessage: "bad verify message",\ badFinished: "bad finished message",\ badMAC: "bad MAC",\ badPadding: "bad padding" }
Python
"""Class for storing shared keys.""" from utils.cryptomath import * from utils.compat import * from mathtls import * from Session import Session from BaseDB import BaseDB class SharedKeyDB(BaseDB): """This class represent an in-memory or on-disk database of shared keys. A SharedKeyDB can be passed to a server handshake function to authenticate a client based on one of the shared keys. This class is thread-safe. """ def __init__(self, filename=None): """Create a new SharedKeyDB. @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, "shared key") def _getItem(self, username, valueStr): session = Session() session._createSharedKey(username, valueStr) return session def __setitem__(self, username, sharedKey): """Add a shared key to the database. @type username: str @param username: The username to associate the shared key with. Must be less than or equal to 16 characters in length, and must not already be in the database. @type sharedKey: str @param sharedKey: The shared key to add. Must be less than 48 characters in length. """ BaseDB.__setitem__(self, username, sharedKey) def _setItem(self, username, value): if len(username)>16: raise ValueError("username too long") if len(value)>=48: raise ValueError("shared key too long") return value def _checkItem(self, value, username, param): newSession = self._getItem(username, param) return value.masterSecret == newSession.masterSecret
Python
"""Class for setting handshake parameters.""" from constants import CertificateType from utils import cryptomath from utils import cipherfactory class HandshakeSettings: """This class encapsulates various parameters that can be used with a TLS handshake. @sort: minKeySize, maxKeySize, cipherNames, certificateTypes, minVersion, maxVersion @type minKeySize: int @ivar minKeySize: The minimum bit length for asymmetric keys. If the other party tries to use SRP, RSA, or Diffie-Hellman parameters smaller than this length, an alert will be signalled. The default is 1023. @type maxKeySize: int @ivar maxKeySize: The maximum bit length for asymmetric keys. If the other party tries to use SRP, RSA, or Diffie-Hellman parameters larger than this length, an alert will be signalled. The default is 8193. @type cipherNames: list @ivar cipherNames: The allowed ciphers, in order of preference. The allowed values in this list are 'aes256', 'aes128', '3des', and 'rc4'. If these settings are used with a client handshake, they determine the order of the ciphersuites offered in the ClientHello message. If these settings are used with a server handshake, the server will choose whichever ciphersuite matches the earliest entry in this list. NOTE: If '3des' is used in this list, but TLS Lite can't find an add-on library that supports 3DES, then '3des' will be silently removed. The default value is ['aes256', 'aes128', '3des', 'rc4']. @type certificateTypes: list @ivar certificateTypes: The allowed certificate types, in order of preference. The allowed values in this list are 'x509' and 'cryptoID'. This list is only used with a client handshake. The client will advertise to the server which certificate types are supported, and will check that the server uses one of the appropriate types. NOTE: If 'cryptoID' is used in this list, but cryptoIDlib is not installed, then 'cryptoID' will be silently removed. @type minVersion: tuple @ivar minVersion: The minimum allowed SSL/TLS version. This variable can be set to (3,0) for SSL 3.0, (3,1) for TLS 1.0, or (3,2) for TLS 1.1. If the other party wishes to use a lower version, a protocol_version alert will be signalled. The default is (3,0). @type maxVersion: tuple @ivar maxVersion: The maximum allowed SSL/TLS version. This variable can be set to (3,0) for SSL 3.0, (3,1) for TLS 1.0, or (3,2) for TLS 1.1. If the other party wishes to use a higher version, a protocol_version alert will be signalled. The default is (3,2). (WARNING: Some servers may (improperly) reject clients which offer support for TLS 1.1. In this case, try lowering maxVersion to (3,1)). """ def __init__(self): self.minKeySize = 1023 self.maxKeySize = 8193 self.cipherNames = ["aes256", "aes128", "3des", "rc4"] self.cipherImplementations = ["cryptlib", "openssl", "pycrypto", "python"] self.certificateTypes = ["x509", "cryptoID"] self.minVersion = (3,0) self.maxVersion = (3,2) #Filters out options that are not supported def _filter(self): other = HandshakeSettings() other.minKeySize = self.minKeySize other.maxKeySize = self.maxKeySize other.cipherNames = self.cipherNames other.cipherImplementations = self.cipherImplementations other.certificateTypes = self.certificateTypes other.minVersion = self.minVersion other.maxVersion = self.maxVersion if not cipherfactory.tripleDESPresent: other.cipherNames = [e for e in self.cipherNames if e != "3des"] if len(other.cipherNames)==0: raise ValueError("No supported ciphers") try: import cryptoIDlib except ImportError: other.certificateTypes = [e for e in self.certificateTypes \ if e != "cryptoID"] if len(other.certificateTypes)==0: raise ValueError("No supported certificate types") if not cryptomath.cryptlibpyLoaded: other.cipherImplementations = [e for e in \ self.cipherImplementations if e != "cryptlib"] if not cryptomath.m2cryptoLoaded: other.cipherImplementations = [e for e in \ other.cipherImplementations if e != "openssl"] if not cryptomath.pycryptoLoaded: other.cipherImplementations = [e for e in \ other.cipherImplementations if e != "pycrypto"] if len(other.cipherImplementations)==0: raise ValueError("No supported cipher implementations") if other.minKeySize<512: raise ValueError("minKeySize too small") if other.minKeySize>16384: raise ValueError("minKeySize too large") if other.maxKeySize<512: raise ValueError("maxKeySize too small") if other.maxKeySize>16384: raise ValueError("maxKeySize too large") for s in other.cipherNames: if s not in ("aes256", "aes128", "rc4", "3des"): raise ValueError("Unknown cipher name: '%s'" % s) for s in other.cipherImplementations: if s not in ("cryptlib", "openssl", "python", "pycrypto"): raise ValueError("Unknown cipher implementation: '%s'" % s) for s in other.certificateTypes: if s not in ("x509", "cryptoID"): raise ValueError("Unknown certificate type: '%s'" % s) if other.minVersion > other.maxVersion: raise ValueError("Versions set incorrectly") if not other.minVersion in ((3,0), (3,1), (3,2)): raise ValueError("minVersion set incorrectly") if not other.maxVersion in ((3,0), (3,1), (3,2)): raise ValueError("maxVersion set incorrectly") return other def _getCertificateTypes(self): l = [] for ct in self.certificateTypes: if ct == "x509": l.append(CertificateType.x509) elif ct == "cryptoID": l.append(CertificateType.cryptoID) else: raise AssertionError() return l
Python
"""Class for caching TLS sessions.""" import thread import time class SessionCache: """This class is used by the server to cache TLS sessions. Caching sessions allows the client to use TLS session resumption and avoid the expense of a full handshake. To use this class, simply pass a SessionCache instance into the server handshake function. This class is thread-safe. """ #References to these instances #are also held by the caller, who may change the 'resumable' #flag, so the SessionCache must return the same instances #it was passed in. def __init__(self, maxEntries=10000, maxAge=14400): """Create a new SessionCache. @type maxEntries: int @param maxEntries: The maximum size of the cache. When this limit is reached, the oldest sessions will be deleted as necessary to make room for new ones. The default is 10000. @type maxAge: int @param maxAge: The number of seconds before a session expires from the cache. The default is 14400 (i.e. 4 hours).""" self.lock = thread.allocate_lock() # Maps sessionIDs to sessions self.entriesDict = {} #Circular list of (sessionID, timestamp) pairs self.entriesList = [(None,None)] * maxEntries self.firstIndex = 0 self.lastIndex = 0 self.maxAge = maxAge def __getitem__(self, sessionID): self.lock.acquire() try: self._purge() #Delete old items, so we're assured of a new one session = self.entriesDict[sessionID] #When we add sessions they're resumable, but it's possible #for the session to be invalidated later on (if a fatal alert #is returned), so we have to check for resumability before #returning the session. if session.valid(): return session else: raise KeyError() finally: self.lock.release() def __setitem__(self, sessionID, session): self.lock.acquire() try: #Add the new element self.entriesDict[sessionID] = session self.entriesList[self.lastIndex] = (sessionID, time.time()) self.lastIndex = (self.lastIndex+1) % len(self.entriesList) #If the cache is full, we delete the oldest element to make an #empty space if self.lastIndex == self.firstIndex: del(self.entriesDict[self.entriesList[self.firstIndex][0]]) self.firstIndex = (self.firstIndex+1) % len(self.entriesList) finally: self.lock.release() #Delete expired items def _purge(self): currentTime = time.time() #Search through the circular list, deleting expired elements until #we reach a non-expired element. Since elements in list are #ordered in time, we can break once we reach the first non-expired #element index = self.firstIndex while index != self.lastIndex: if currentTime - self.entriesList[index][1] > self.maxAge: del(self.entriesDict[self.entriesList[index][0]]) index = (index+1) % len(self.entriesList) else: break self.firstIndex = index def _test(): import doctest, SessionCache return doctest.testmod(SessionCache) if __name__ == "__main__": _test()
Python
"""Class representing a TLS session.""" from utils.compat import * from mathtls import * from constants import * class Session: """ This class represents a TLS session. TLS distinguishes between connections and sessions. A new handshake creates both a connection and a session. Data is transmitted over the connection. The session contains a more permanent record of the handshake. The session can be inspected to determine handshake results. The session can also be used to create a new connection through "session resumption". If the client and server both support this, they can create a new connection based on an old session without the overhead of a full handshake. The session for a L{tlslite.TLSConnection.TLSConnection} can be retrieved from the connection's 'session' attribute. @type srpUsername: str @ivar srpUsername: The client's SRP username (or None). @type sharedKeyUsername: str @ivar sharedKeyUsername: The client's shared-key username (or None). @type clientCertChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @ivar clientCertChain: The client's certificate chain (or None). @type serverCertChain: L{tlslite.X509CertChain.X509CertChain} or L{cryptoIDlib.CertChain.CertChain} @ivar serverCertChain: The server's certificate chain (or None). """ def __init__(self): self.masterSecret = createByteArraySequence([]) self.sessionID = createByteArraySequence([]) self.cipherSuite = 0 self.srpUsername = None self.sharedKeyUsername = None self.clientCertChain = None self.serverCertChain = None self.resumable = False self.sharedKey = False def _clone(self): other = Session() other.masterSecret = self.masterSecret other.sessionID = self.sessionID other.cipherSuite = self.cipherSuite other.srpUsername = self.srpUsername other.sharedKeyUsername = self.sharedKeyUsername other.clientCertChain = self.clientCertChain other.serverCertChain = self.serverCertChain other.resumable = self.resumable other.sharedKey = self.sharedKey return other def _calcMasterSecret(self, version, premasterSecret, clientRandom, serverRandom): if version == (3,0): self.masterSecret = PRF_SSL(premasterSecret, concatArrays(clientRandom, serverRandom), 48) elif version in ((3,1), (3,2)): self.masterSecret = PRF(premasterSecret, "master secret", concatArrays(clientRandom, serverRandom), 48) else: raise AssertionError() def valid(self): """If this session can be used for session resumption. @rtype: bool @return: If this session can be used for session resumption. """ return self.resumable or self.sharedKey def _setResumable(self, boolean): #Only let it be set if this isn't a shared key if not self.sharedKey: #Only let it be set to True if the sessionID is non-null if (not boolean) or (boolean and self.sessionID): self.resumable = boolean 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 self.cipherSuite in CipherSuite.aes128Suites: return "aes128" elif self.cipherSuite in CipherSuite.aes256Suites: return "aes256" elif self.cipherSuite in CipherSuite.rc4Suites: return "rc4" elif self.cipherSuite in CipherSuite.tripleDESSuites: return "3des" else: return None def _createSharedKey(self, sharedKeyUsername, sharedKey): if len(sharedKeyUsername)>16: raise ValueError() if len(sharedKey)>47: raise ValueError() self.sharedKeyUsername = sharedKeyUsername self.sessionID = createByteArrayZeros(16) for x in range(len(sharedKeyUsername)): self.sessionID[x] = ord(sharedKeyUsername[x]) premasterSecret = createByteArrayZeros(48) sharedKey = chr(len(sharedKey)) + sharedKey for x in range(48): premasterSecret[x] = ord(sharedKey[x % len(sharedKey)]) self.masterSecret = PRF(premasterSecret, "shared secret", createByteArraySequence([]), 48) self.sharedKey = True return self
Python
"""Base class for SharedKeyDB and VerifierDB.""" import anydbm import thread class BaseDB: def __init__(self, filename, type): self.type = type self.filename = filename if self.filename: self.db = None else: self.db = {} self.lock = thread.allocate_lock() def create(self): """Create a new on-disk database. @raise anydbm.error: If there's a problem creating the database. """ if self.filename: self.db = anydbm.open(self.filename, "n") #raises anydbm.error self.db["--Reserved--type"] = self.type self.db.sync() else: self.db = {} def open(self): """Open a pre-existing on-disk database. @raise anydbm.error: If there's a problem opening the database. @raise ValueError: If the database is not of the right type. """ if not self.filename: raise ValueError("Can only open on-disk databases") self.db = anydbm.open(self.filename, "w") #raises anydbm.error try: if self.db["--Reserved--type"] != self.type: raise ValueError("Not a %s database" % self.type) except KeyError: raise ValueError("Not a recognized database") def __getitem__(self, username): if self.db == None: raise AssertionError("DB not open") self.lock.acquire() try: valueStr = self.db[username] finally: self.lock.release() return self._getItem(username, valueStr) def __setitem__(self, username, value): if self.db == None: raise AssertionError("DB not open") valueStr = self._setItem(username, value) self.lock.acquire() try: self.db[username] = valueStr if self.filename: self.db.sync() finally: self.lock.release() def __delitem__(self, username): if self.db == None: raise AssertionError("DB not open") self.lock.acquire() try: del(self.db[username]) if self.filename: self.db.sync() finally: self.lock.release() def __contains__(self, username): """Check if the database contains the specified username. @type username: str @param username: The username to check for. @rtype: bool @return: True if the database contains the username, False otherwise. """ if self.db == None: raise AssertionError("DB not open") self.lock.acquire() try: return self.db.has_key(username) finally: self.lock.release() def check(self, username, param): value = self.__getitem__(username) return self._checkItem(value, username, param) def keys(self): """Return a list of usernames in the database. @rtype: list @return: The usernames in the database. """ if self.db == None: raise AssertionError("DB not open") self.lock.acquire() try: usernames = self.db.keys() finally: self.lock.release() usernames = [u for u in usernames if not u.startswith("--Reserved--")] return usernames
Python
"""Exception classes. @sort: TLSError, TLSAbruptCloseError, TLSAlert, TLSLocalAlert, TLSRemoteAlert, TLSAuthenticationError, TLSNoAuthenticationError, TLSAuthenticationTypeError, TLSFingerprintError, TLSAuthorizationError, TLSValidationError, TLSFaultError """ from constants import AlertDescription, AlertLevel class TLSError(Exception): """Base class for all TLS Lite exceptions.""" pass class TLSAbruptCloseError(TLSError): """The socket was closed without a proper TLS shutdown. The TLS specification mandates that an alert of some sort must be sent before the underlying socket is closed. If the socket is closed without this, it could signify that an attacker is trying to truncate the connection. It could also signify a misbehaving TLS implementation, or a random network failure. """ pass class TLSAlert(TLSError): """A TLS alert has been signalled.""" pass _descriptionStr = {\ AlertDescription.close_notify: "close_notify",\ AlertDescription.unexpected_message: "unexpected_message",\ AlertDescription.bad_record_mac: "bad_record_mac",\ AlertDescription.decryption_failed: "decryption_failed",\ AlertDescription.record_overflow: "record_overflow",\ AlertDescription.decompression_failure: "decompression_failure",\ AlertDescription.handshake_failure: "handshake_failure",\ AlertDescription.no_certificate: "no certificate",\ AlertDescription.bad_certificate: "bad_certificate",\ AlertDescription.unsupported_certificate: "unsupported_certificate",\ AlertDescription.certificate_revoked: "certificate_revoked",\ AlertDescription.certificate_expired: "certificate_expired",\ AlertDescription.certificate_unknown: "certificate_unknown",\ AlertDescription.illegal_parameter: "illegal_parameter",\ AlertDescription.unknown_ca: "unknown_ca",\ AlertDescription.access_denied: "access_denied",\ AlertDescription.decode_error: "decode_error",\ AlertDescription.decrypt_error: "decrypt_error",\ AlertDescription.export_restriction: "export_restriction",\ AlertDescription.protocol_version: "protocol_version",\ AlertDescription.insufficient_security: "insufficient_security",\ AlertDescription.internal_error: "internal_error",\ AlertDescription.user_canceled: "user_canceled",\ AlertDescription.no_renegotiation: "no_renegotiation",\ AlertDescription.unknown_srp_username: "unknown_srp_username",\ AlertDescription.missing_srp_username: "missing_srp_username"} class TLSLocalAlert(TLSAlert): """A TLS alert has been signalled by the local implementation. @type description: int @ivar description: Set to one of the constants in L{tlslite.constants.AlertDescription} @type level: int @ivar level: Set to one of the constants in L{tlslite.constants.AlertLevel} @type message: str @ivar message: Description of what went wrong. """ def __init__(self, alert, message=None): self.description = alert.description self.level = alert.level self.message = message def __str__(self): alertStr = TLSAlert._descriptionStr.get(self.description) if alertStr == None: alertStr = str(self.description) if self.message: return alertStr + ": " + self.message else: return alertStr class TLSRemoteAlert(TLSAlert): """A TLS alert has been signalled by the remote implementation. @type description: int @ivar description: Set to one of the constants in L{tlslite.constants.AlertDescription} @type level: int @ivar level: Set to one of the constants in L{tlslite.constants.AlertLevel} """ def __init__(self, alert): self.description = alert.description self.level = alert.level def __str__(self): alertStr = TLSAlert._descriptionStr.get(self.description) if alertStr == None: alertStr = str(self.description) return alertStr class TLSAuthenticationError(TLSError): """The handshake succeeded, but the other party's authentication was inadequate. This exception will only be raised when a L{tlslite.Checker.Checker} has been passed to a handshake function. The Checker will be invoked once the handshake completes, and if the Checker objects to how the other party authenticated, a subclass of this exception will be raised. """ pass class TLSNoAuthenticationError(TLSAuthenticationError): """The Checker was expecting the other party to authenticate with a certificate chain, but this did not occur.""" pass class TLSAuthenticationTypeError(TLSAuthenticationError): """The Checker was expecting the other party to authenticate with a different type of certificate chain.""" pass class TLSFingerprintError(TLSAuthenticationError): """The Checker was expecting the other party to authenticate with a certificate chain that matches a different fingerprint.""" pass class TLSAuthorizationError(TLSAuthenticationError): """The Checker was expecting the other party to authenticate with a certificate chain that has a different authorization.""" pass class TLSValidationError(TLSAuthenticationError): """The Checker has determined that the other party's certificate chain is invalid.""" pass class TLSFaultError(TLSError): """The other party responded incorrectly to an induced fault. This exception will only occur during fault testing, when a TLSConnection's fault variable is set to induce some sort of faulty behavior, and the other party doesn't respond appropriately. """ pass
Python
""" TLS Lite is a free python library that implements SSL v3, TLS v1, and TLS v1.1. TLS Lite supports non-traditional authentication methods such as SRP, shared keys, and cryptoIDs, in addition to X.509 certificates. TLS Lite is pure python, however it can access OpenSSL, cryptlib, pycrypto, and GMPY for faster crypto operations. TLS Lite integrates with httplib, xmlrpclib, poplib, imaplib, smtplib, SocketServer, asyncore, and Twisted. To use, do:: from tlslite.api import * Then use the L{tlslite.TLSConnection.TLSConnection} class with a socket, or use one of the integration classes in L{tlslite.integration}. @version: 0.3.8 """ __version__ = "0.3.8" __all__ = ["api", "BaseDB", "Checker", "constants", "errors", "FileObject", "HandshakeSettings", "mathtls", "messages", "Session", "SessionCache", "SharedKeyDB", "TLSConnection", "TLSRecordLayer", "VerifierDB", "X509", "X509CertChain", "integration", "utils"]
Python
"""Class representing an X.509 certificate chain.""" from utils import cryptomath class X509CertChain: """This class represents a chain of X.509 certificates. @type x509List: list @ivar x509List: A list of L{tlslite.X509.X509} instances, starting with the end-entity certificate and with every subsequent certificate certifying the previous. """ def __init__(self, x509List=None): """Create a new X509CertChain. @type x509List: list @param x509List: A list of L{tlslite.X509.X509} instances, starting with the end-entity certificate and with every subsequent certificate certifying the previous. """ if x509List: self.x509List = x509List else: self.x509List = [] def getNumCerts(self): """Get the number of certificates in this chain. @rtype: int """ return len(self.x509List) def getEndEntityPublicKey(self): """Get the public key from the end-entity certificate. @rtype: L{tlslite.utils.RSAKey.RSAKey} """ if self.getNumCerts() == 0: raise AssertionError() return self.x509List[0].publicKey def getFingerprint(self): """Get the hex-encoded fingerprint of the end-entity certificate. @rtype: str @return: A hex-encoded fingerprint. """ if self.getNumCerts() == 0: raise AssertionError() return self.x509List[0].getFingerprint() def getCommonName(self): """Get the Subject's Common Name from the end-entity 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. """ if self.getNumCerts() == 0: raise AssertionError() return self.x509List[0].getCommonName() def validate(self, x509TrustList): """Check the validity of the certificate chain. This checks that every certificate in the chain validates with the subsequent one, until some certificate validates with (or is identical to) one of the passed-in root certificates. The cryptlib_py module must be installed in order to use this function. @type x509TrustList: list of L{tlslite.X509.X509} @param x509TrustList: A list of trusted root certificates. The certificate chain must extend to one of these certificates to be considered valid. """ import cryptlib_py c1 = None c2 = None lastC = None rootC = None try: rootFingerprints = [c.getFingerprint() for c in x509TrustList] #Check that every certificate in the chain validates with the #next one for cert1, cert2 in zip(self.x509List, self.x509List[1:]): #If we come upon a root certificate, we're done. if cert1.getFingerprint() in rootFingerprints: return True c1 = cryptlib_py.cryptImportCert(cert1.writeBytes(), cryptlib_py.CRYPT_UNUSED) c2 = cryptlib_py.cryptImportCert(cert2.writeBytes(), cryptlib_py.CRYPT_UNUSED) try: cryptlib_py.cryptCheckCert(c1, c2) except: return False cryptlib_py.cryptDestroyCert(c1) c1 = None cryptlib_py.cryptDestroyCert(c2) c2 = None #If the last certificate is one of the root certificates, we're #done. if self.x509List[-1].getFingerprint() in rootFingerprints: return True #Otherwise, find a root certificate that the last certificate #chains to, and validate them. lastC = cryptlib_py.cryptImportCert(self.x509List[-1].writeBytes(), cryptlib_py.CRYPT_UNUSED) for rootCert in x509TrustList: rootC = cryptlib_py.cryptImportCert(rootCert.writeBytes(), cryptlib_py.CRYPT_UNUSED) if self._checkChaining(lastC, rootC): try: cryptlib_py.cryptCheckCert(lastC, rootC) return True except: return False return False finally: if not (c1 is None): cryptlib_py.cryptDestroyCert(c1) if not (c2 is None): cryptlib_py.cryptDestroyCert(c2) if not (lastC is None): cryptlib_py.cryptDestroyCert(lastC) if not (rootC is None): cryptlib_py.cryptDestroyCert(rootC) def _checkChaining(self, lastC, rootC): import cryptlib_py import array def compareNames(name): try: length = cryptlib_py.cryptGetAttributeString(lastC, name, None) lastName = array.array('B', [0] * length) cryptlib_py.cryptGetAttributeString(lastC, name, lastName) lastName = lastName.tostring() except cryptlib_py.CryptException, e: if e[0] == cryptlib_py.CRYPT_ERROR_NOTFOUND: lastName = None try: length = cryptlib_py.cryptGetAttributeString(rootC, name, None) rootName = array.array('B', [0] * length) cryptlib_py.cryptGetAttributeString(rootC, name, rootName) rootName = rootName.tostring() except cryptlib_py.CryptException, e: if e[0] == cryptlib_py.CRYPT_ERROR_NOTFOUND: rootName = None return lastName == rootName cryptlib_py.cryptSetAttribute(lastC, cryptlib_py.CRYPT_CERTINFO_ISSUERNAME, cryptlib_py.CRYPT_UNUSED) if not compareNames(cryptlib_py.CRYPT_CERTINFO_COUNTRYNAME): return False if not compareNames(cryptlib_py.CRYPT_CERTINFO_LOCALITYNAME): return False if not compareNames(cryptlib_py.CRYPT_CERTINFO_ORGANIZATIONNAME): return False if not compareNames(cryptlib_py.CRYPT_CERTINFO_ORGANIZATIONALUNITNAME): return False if not compareNames(cryptlib_py.CRYPT_CERTINFO_COMMONNAME): return False return True
Python
"""Import this module for easy access to TLS Lite objects. The TLS Lite API consists of classes, functions, and variables spread throughout this package. Instead of importing them individually with:: from tlslite.TLSConnection import TLSConnection from tlslite.HandshakeSettings import HandshakeSettings from tlslite.errors import * . . It's easier to do:: from tlslite.api import * This imports all the important objects (TLSConnection, Checker, HandshakeSettings, etc.) into the global namespace. In particular, it imports:: from constants import AlertLevel, AlertDescription, Fault from errors import * from Checker import Checker from HandshakeSettings import HandshakeSettings from Session import Session from SessionCache import SessionCache from SharedKeyDB import SharedKeyDB from TLSConnection import TLSConnection from VerifierDB import VerifierDB from X509 import X509 from X509CertChain import X509CertChain from integration.HTTPTLSConnection import HTTPTLSConnection from integration.POP3_TLS import POP3_TLS from integration.IMAP4_TLS import IMAP4_TLS from integration.SMTP_TLS import SMTP_TLS from integration.XMLRPCTransport import XMLRPCTransport from integration.TLSSocketServerMixIn import TLSSocketServerMixIn from integration.TLSAsyncDispatcherMixIn import TLSAsyncDispatcherMixIn from integration.TLSTwistedProtocolWrapper import TLSTwistedProtocolWrapper from utils.cryptomath import cryptlibpyLoaded, m2cryptoLoaded, gmpyLoaded, pycryptoLoaded, prngName from utils.keyfactory import generateRSAKey, parsePEMKey, parseXMLKey, parseAsPublicKey, parsePrivateKey """ from constants import AlertLevel, AlertDescription, Fault from errors import * from Checker import Checker from HandshakeSettings import HandshakeSettings from Session import Session from SessionCache import SessionCache from SharedKeyDB import SharedKeyDB from TLSConnection import TLSConnection from VerifierDB import VerifierDB from X509 import X509 from X509CertChain import X509CertChain from integration.HTTPTLSConnection import HTTPTLSConnection from integration.TLSSocketServerMixIn import TLSSocketServerMixIn from integration.TLSAsyncDispatcherMixIn import TLSAsyncDispatcherMixIn from integration.POP3_TLS import POP3_TLS from integration.IMAP4_TLS import IMAP4_TLS from integration.SMTP_TLS import SMTP_TLS from integration.XMLRPCTransport import XMLRPCTransport try: import twisted del(twisted) from integration.TLSTwistedProtocolWrapper import TLSTwistedProtocolWrapper except ImportError: pass from utils.cryptomath import cryptlibpyLoaded, m2cryptoLoaded, gmpyLoaded, \ pycryptoLoaded, prngName from utils.keyfactory import generateRSAKey, parsePEMKey, parseXMLKey, \ parseAsPublicKey, parsePrivateKey
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.laurabeth@gmail.com (Laura Beth Lincoln)' try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import gdata.spreadsheet.service import gdata.service import atom.service import gdata.spreadsheet import atom import getopt import sys import string class SimpleCRUD: def __init__(self, email, password): self.gd_client = gdata.spreadsheet.service.SpreadsheetsService() self.gd_client.email = email self.gd_client.password = password self.gd_client.source = 'Spreadsheets GData Sample' self.gd_client.ProgrammaticLogin() self.curr_key = '' self.curr_wksht_id = '' self.list_feed = None def _PromptForSpreadsheet(self): # Get the list of spreadsheets feed = self.gd_client.GetSpreadsheetsFeed() self._PrintFeed(feed) input = raw_input('\nSelection: ') id_parts = feed.entry[string.atoi(input)].id.text.split('/') self.curr_key = id_parts[len(id_parts) - 1] def _PromptForWorksheet(self): # Get the list of worksheets feed = self.gd_client.GetWorksheetsFeed(self.curr_key) self._PrintFeed(feed) input = raw_input('\nSelection: ') id_parts = feed.entry[string.atoi(input)].id.text.split('/') self.curr_wksht_id = id_parts[len(id_parts) - 1] def _PromptForCellsAction(self): print ('dump\n' 'update {row} {col} {input_value}\n' '\n') input = raw_input('Command: ') command = input.split(' ', 1) if command[0] == 'dump': self._CellsGetAction() elif command[0] == 'update': parsed = command[1].split(' ', 2) if len(parsed) == 3: self._CellsUpdateAction(parsed[0], parsed[1], parsed[2]) else: self._CellsUpdateAction(parsed[0], parsed[1], '') else: self._InvalidCommandError(input) def _PromptForListAction(self): print ('dump\n' 'insert {row_data} (example: insert label=content)\n' 'update {row_index} {row_data}\n' 'delete {row_index}\n' 'Note: No uppercase letters in column names!\n' '\n') input = raw_input('Command: ') command = input.split(' ' , 1) if command[0] == 'dump': self._ListGetAction() elif command[0] == 'insert': self._ListInsertAction(command[1]) elif command[0] == 'update': parsed = command[1].split(' ', 1) self._ListUpdateAction(parsed[0], parsed[1]) elif command[0] == 'delete': self._ListDeleteAction(command[1]) else: self._InvalidCommandError(input) def _CellsGetAction(self): # Get the feed of cells feed = self.gd_client.GetCellsFeed(self.curr_key, self.curr_wksht_id) self._PrintFeed(feed) def _CellsUpdateAction(self, row, col, inputValue): entry = self.gd_client.UpdateCell(row=row, col=col, inputValue=inputValue, key=self.curr_key, wksht_id=self.curr_wksht_id) if isinstance(entry, gdata.spreadsheet.SpreadsheetsCell): print 'Updated!' def _ListGetAction(self): # Get the list feed self.list_feed = self.gd_client.GetListFeed(self.curr_key, self.curr_wksht_id) self._PrintFeed(self.list_feed) def _ListInsertAction(self, row_data): entry = self.gd_client.InsertRow(self._StringToDictionary(row_data), self.curr_key, self.curr_wksht_id) if isinstance(entry, gdata.spreadsheet.SpreadsheetsList): print 'Inserted!' def _ListUpdateAction(self, index, row_data): self.list_feed = self.gd_client.GetListFeed(self.curr_key, self.curr_wksht_id) entry = self.gd_client.UpdateRow( self.list_feed.entry[string.atoi(index)], self._StringToDictionary(row_data)) if isinstance(entry, gdata.spreadsheet.SpreadsheetsList): print 'Updated!' def _ListDeleteAction(self, index): self.list_feed = self.gd_client.GetListFeed(self.curr_key, self.curr_wksht_id) self.gd_client.DeleteRow(self.list_feed.entry[string.atoi(index)]) print 'Deleted!' def _StringToDictionary(self, row_data): dict = {} for param in row_data.split(): temp = param.split('=') dict[temp[0]] = temp[1] return dict def _PrintFeed(self, feed): for i, entry in enumerate(feed.entry): if isinstance(feed, gdata.spreadsheet.SpreadsheetsCellsFeed): print '%s %s\n' % (entry.title.text, entry.content.text) elif isinstance(feed, gdata.spreadsheet.SpreadsheetsListFeed): print '%s %s %s' % (i, entry.title.text, entry.content.text) # Print this row's value for each column (the custom dictionary is # built using the gsx: elements in the entry.) print 'Contents:' for key in entry.custom: print ' %s: %s' % (key, entry.custom[key].text) print '\n', else: print '%s %s\n' % (i, entry.title.text) def _InvalidCommandError(self, input): print 'Invalid input: %s\n' % (input) def Run(self): self._PromptForSpreadsheet() self._PromptForWorksheet() input = raw_input('cells or list? ') if input == 'cells': while True: self._PromptForCellsAction() elif input == 'list': while True: self._PromptForListAction() def main(): # parse command line options try: opts, args = getopt.getopt(sys.argv[1:], "", ["user=", "pw="]) except getopt.error, msg: print 'python spreadsheetExample.py --user [username] --pw [password] ' sys.exit(2) user = '' pw = '' key = '' # Process options for o, a in opts: if o == "--user": user = a elif o == "--pw": pw = a if user == '' or pw == '': print 'python spreadsheetExample.py --user [username] --pw [password] ' sys.exit(2) sample = SimpleCRUD(user, pw) sample.Run() if __name__ == '__main__': main()
Python
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sample app for Google Apps Calendar Resource features. CalendarResourceSample: Demonstrates the use of the Calendar Resource API """ __author__ = 'pti@google.com (Prashant Tiwari)' import getpass from gdata.calendar_resource.client import CalendarResourceClient class CalendarResourceSample(object): def __init__(self, domain, email, password): """Constructor for the CalendarResourceSample object. Construct a CalendarResourceSample with the given args. Args: domain: The domain name ("domain.com") email: The email account of the user or the admin ("john@domain.com") password: The domain admin's password """ self.client = CalendarResourceClient(domain=domain) self.client.ClientLogin(email=email, password=password, source='googlecode-calendarresourcesample-v1') def create(self, resource_properties): """Creates a calendar resource with the given resource_properties Args: resource_properties: A dictionary of calendar resource properties """ print 'Creating a new calendar resource with id %s...' % ( resource_properties['resource_id']) print self.client.CreateResource( resource_id=resource_properties['resource_id'], resource_common_name=resource_properties['resource_name'], resource_description=resource_properties['resource_description'], resource_type=resource_properties['resource_type']) def get(self, resource_id=None): """Retrieves the calendar resource with the given resource_id Args: resource_id: The optional calendar resource identifier """ if resource_id: print 'Retrieving the calendar resource with id %s...' % (resource_id) print self.client.GetResource(resource_id=resource_id) else: print 'Retrieving all calendar resources...' print self.client.GetResourceFeed() def update(self, resource_properties): """Updates the calendar resource with the given resource_properties Args: resource_properties: A dictionary of calendar resource properties """ print 'Updating the calendar resource with id %s...' % ( resource_properties['resource_id']) print self.client.UpdateResource( resource_id=resource_properties['resource_id'], resource_common_name=resource_properties['resource_name'], resource_description=resource_properties['resource_description'], resource_type=resource_properties['resource_type']) def delete(self, resource_id): """Deletes the calendar resource with the given resource_id Args: resource_id: The unique calendar resource identifier """ print 'Deleting the calendar resource with id %s...' % (resource_id) self.client.DeleteResource(resource_id) print 'Calendar resource successfully deleted.' def main(): """Demonstrates the Calendar Resource API using CalendarResourceSample.""" domain = None admin_email = None admin_password = None do_continue = 'y' print("Google Apps Calendar Resource API Sample\n\n") while not domain: domain = raw_input('Google Apps domain: ') while not admin_email: admin_email = '%s@%s' % (raw_input('Administrator username: '), domain) while not admin_password: admin_password = getpass.getpass('Administrator password: ') sample = CalendarResourceSample(domain=domain, email=admin_email, password=admin_password) while do_continue.lower() != 'n': do_continue = call_service(sample) def call_service(sample): """Calls the service methods on the user input""" operation = None while operation not in ['c', 'C', 'g', 'G', 'u', 'U', 'd', 'D', 'q', 'Q']: operation = raw_input('Do [c=create|g=get|u=update|d=delete|q=quit]: ') operation = operation.lower() if operation == 'q': return 'n' resource_properties = get_input(operation) if operation == 'c': sample.create(resource_properties) elif operation == 'g': sample.get(resource_properties['resource_id']) elif operation == 'u': sample.update(resource_properties) elif operation == 'd': sample.delete(resource_properties['resource_id']) do_continue = None while do_continue not in ['', 'y', 'Y', 'n', 'N']: do_continue = raw_input('Want to continue (Y/n): ') if do_continue == '': do_continue = 'y' return do_continue.lower() def get_input(operation): """Gets user input from console""" resource_id = None resource_name = None resource_description = None resource_type = None if operation == 'g': resource_id = raw_input('Resource id (leave blank to get all resources): ') else: while not resource_id: resource_id = raw_input('Resource id: ') if operation == 'c': resource_name = raw_input('Resource common name (recommended): ') resource_description = raw_input('Resource description (recommended): ') resource_type = raw_input('Resource type (recommended): ') elif operation == 'u': resource_name = raw_input( 'New resource common name (leave blank if no change): ') resource_description = raw_input( 'New resource description (leave blank if no change): ') resource_type = raw_input('New resource type (leave blank if no change): ') resource_properties = {'resource_id': resource_id, 'resource_name': resource_name, 'resource_description': resource_description, 'resource_type': resource_type} return resource_properties if __name__ == '__main__': main()
Python
#!/usr/bin/env python # # Copyright 2009 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains a Sample for Google Profiles. ProfilesSample: demonstrates operations with the Profiles feed. """ __author__ = 'jtoledo (Julian Toledo)' import getopt import getpass import sys import gdata.contacts import gdata.contacts.service class ProfilesSample(object): """ProfilesSample object demonstrates operations with the Profiles feed.""" def __init__(self, email, password, domain): """Constructor for the ProfilesSample object. Takes an email and password corresponding to a gmail account to demonstrate the functionality of the Profiles feed. Args: email: [string] The e-mail address of the account to use for the sample. password: [string] The password corresponding to the account specified by the email parameter. domain: [string] The domain for the Profiles feed """ self.gd_client = gdata.contacts.service.ContactsService( contact_list=domain) self.gd_client.email = email self.gd_client.password = password self.gd_client.source = 'GoogleInc-ProfilesPythonSample-1' self.gd_client.ProgrammaticLogin() def PrintFeed(self, feed, ctr=0): """Prints out the contents of a feed to the console. Args: feed: A gdata.profiles.ProfilesFeed instance. ctr: [int] The number of entries in this feed previously printed. This allows continuous entry numbers when paging through a feed. Returns: The number of entries printed, including those previously printed as specified in ctr. This is for passing as an ar1gument to ctr on successive calls to this method. """ if not feed.entry: print '\nNo entries in feed.\n' return 0 for entry in feed.entry: self.PrintEntry(entry) return len(feed.entry) + ctr def PrintEntry(self, entry): """Prints out the contents of a single Entry to the console. Args: entry: A gdata.contacts.ProfilesEntry """ print '\n%s' % (entry.title.text) for email in entry.email: if email.primary == 'true': print 'Email: %s (primary)' % (email.address) else: print 'Email: %s' % (email.address) if entry.nickname: print 'Nickname: %s' % (entry.nickname.text) if entry.occupation: print 'Occupation: %s' % (entry.occupation.text) if entry.gender: print 'Gender: %s' % (entry.gender.value) if entry.birthday: print 'Birthday: %s' % (entry.birthday.when) for relation in entry.relation: print 'Relation: %s %s' % (relation.rel, relation.text) for user_defined_field in entry.user_defined_field: print 'UserDefinedField: %s %s' % (user_defined_field.key, user_defined_field.value) for website in entry.website: print 'Website: %s %s' % (website.href, website.rel) for phone_number in entry.phone_number: print 'Phone Number: %s' % phone_number.text for organization in entry.organization: print 'Organization:' if organization.org_name: print ' Name: %s' % (organization.org_name.text) if organization.org_title: print ' Title: %s' % (organization.org_title.text) if organization.org_department: print ' Department: %s' % (organization.org_department.text) if organization.org_job_description: print ' Job Desc: %s' % (organization.org_job_description.text) def PrintPaginatedFeed(self, feed, print_method): """Print all pages of a paginated feed. This will iterate through a paginated feed, requesting each page and printing the entries contained therein. Args: feed: A gdata.contacts.ProfilesFeed instance. print_method: The method which will be used to print each page of the """ ctr = 0 while feed: # Print contents of current feed ctr = print_method(feed=feed, ctr=ctr) # Prepare for next feed iteration next = feed.GetNextLink() feed = None if next: if self.PromptOperationShouldContinue(): # Another feed is available, and the user has given us permission # to fetch it feed = self.gd_client.GetProfilesFeed(next.href) else: # User has asked us to terminate feed = None def PromptOperationShouldContinue(self): """Display a "Continue" prompt. This give is used to give users a chance to break out of a loop, just in case they have too many profiles/groups. Returns: A boolean value, True if the current operation should continue, False if the current operation should terminate. """ while True: key_input = raw_input('Continue [Y/n]? ') if key_input is 'N' or key_input is 'n': return False elif key_input is 'Y' or key_input is 'y' or key_input is '': return True def ListAllProfiles(self): """Retrieves a list of profiles and displays name and primary email.""" feed = self.gd_client.GetProfilesFeed() self.PrintPaginatedFeed(feed, self.PrintFeed) def SelectProfile(self): username = raw_input('Please enter your username for the profile: ') entry_uri = self.gd_client.GetFeedUri('profiles')+'/'+username try: entry = self.gd_client.GetProfile(entry_uri) self.PrintEntry(entry) except gdata.service.RequestError: print 'Invalid username for the profile.' def PrintMenu(self): """Displays a menu of options for the user to choose from.""" print ('\nProfiles Sample\n' '1) List all of your Profiles.\n' '2) Get a single Profile.\n' '3) Exit.\n') def GetMenuChoice(self, maximum): """Retrieves the menu selection from the user. Args: maximum: [int] The maximum number of allowed choices (inclusive) Returns: The integer of the menu item chosen by the user. """ while True: key_input = raw_input('> ') try: num = int(key_input) except ValueError: print 'Invalid choice. Please choose a value between 1 and', maximum continue if num > maximum or num < 1: print 'Invalid choice. Please choose a value between 1 and', maximum else: return num def Run(self): """Prompts the user to choose funtionality to be demonstrated.""" try: while True: self.PrintMenu() choice = self.GetMenuChoice(3) if choice == 1: self.ListAllProfiles() elif choice == 2: self.SelectProfile() elif choice == 3: return except KeyboardInterrupt: print '\nGoodbye.' return def main(): """Demonstrates use of the Profiles using the ProfilesSample object.""" # Parse command line options try: opts, args = getopt.getopt(sys.argv[1:], '', ['user=', 'pw=', 'domain=']) except getopt.error, msg: print 'python profiles_example.py --user [username] --pw [password]' print ' --domain [domain]' sys.exit(2) user = '' pw = '' domain = '' # Process options for option, arg in opts: if option == '--user': user = arg elif option == '--pw': pw = arg elif option == '--domain': domain = arg while not user: print 'NOTE: Please run these tests only with a test account.' user = raw_input('Please enter your email: ') while not pw: pw = getpass.getpass('Please enter password: ') if not pw: print 'Password cannot be blank.' while not domain: domain = raw_input('Please enter your Apps domain: ') try: sample = ProfilesSample(user, pw, domain) except gdata.service.BadAuthentication: print 'Invalid user credentials given.' return sample.Run() if __name__ == '__main__': main()
Python
#!/usr/bin/env python # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unshare domain users contact information when contact sharing is enabled.""" __author__ = 'alainv@google.com (Alain Vongsouvanh)' import sys import gdata.contacts.client import gdata.contacts.data import gdata.gauth class BatchResult(object): """Hold batch processing results. Attributes: success_count: Number of successful operations. error_count: Number of failed operations. error_entries: List of failed entries. """ success_count = 0 error_count = 0 error_entries = [] class ProfilesManager(object): """ProfilesManager object used to unshare domain users contact information. Basic usage is: >>> manager = ProfilesManager(CONSUMER_KEY, CONSUMER_SECRET, ADMIN_EMAIL) >>> result = manager.UnshareProfiles() >>> print 'Success: %s - Error: %s' % (result.success, result.error_count) Attributes: profiles: List of ProfilesEntry. batch_size: Number of operations per batch request (default to 100). """ def __init__(self, consumer_key, consumer_secret, admin_email): domain = admin_email[admin_email.index('@') + 1:] self._gd_client = gdata.contacts.client.ContactsClient( source='GoogleInc-UnshareProfiles-1', domain=domain) self._gd_client.auth_token = gdata.gauth.TwoLeggedOAuthHmacToken( consumer_key, consumer_secret, admin_email) self._profiles = None self.batch_size = 100 @property def profiles(self): """Get the list of profiles for the domain. Returns: List of ProfilesEntry. """ if not self._profiles: self.GetAllProfiles() return self._profiles def GetAllProfiles(self): """Retrieve the list of user profiles for the domain.""" profiles = [] feed_uri = self._gd_client.GetFeedUri('profiles') while feed_uri: feed = self._gd_client.GetProfilesFeed(uri=feed_uri) profiles.extend(feed.entry) feed_uri = feed.FindNextLink() self._profiles = profiles def UnshareProfiles(self): """Unshare users' contact information. Uses batch request to optimize the resources. Returns: BatchResult object. """ if not self._profiles: self.GetAllProfiles() batch_size = max(self.batch_size, 100) index = 0 result = BatchResult() while index < len(self._profiles): request_feed = gdata.contacts.data.ProfilesFeed() for entry in self._profiles[index:index + batch_size]: entry.status = gdata.contacts.data.Status(indexed='false') request_feed.AddUpdate(entry=entry) result_feed = self._gd_client.ExecuteBatchProfiles(request_feed) for entry in result_feed.entry: if entry.batch_status.code == '200': self._profiles[index] = entry result.success_count += 1 else: result.error_entries.append(entry) result.error_count += 1 index += 1 return result def main(): """Demonstrates the use of the Profiles API to unshare profiles.""" if len(sys.argv) > 3: consumer_key = sys.argv[1] consumer_secret = sys.argv[2] admin_email = sys.argv[3] else: print ('python unshare_profiles.py [consumer_key] [consumer_secret]' ' [admin_email]') sys.exit(2) manager = ProfilesManager(consumer_key, consumer_secret, admin_email) result = manager.UnshareProfiles() print 'Success: %s - Error: %s' % (result.success_count, result.error_count) for entry in result.error_entries: print ' > Failed to update %s: (%s) %s' % ( entry.id.text, entry.batch_status.code, entry.batch_status.reason) sys.exit(result.error_count) if __name__ == '__main__': main()
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeffrey Scudder)' import sys import getopt import getpass import atom import gdata.contacts.data import gdata.contacts.client class ContactsSample(object): """ContactsSample object demonstrates operations with the Contacts feed.""" def __init__(self, email, password): """Constructor for the ContactsSample object. Takes an email and password corresponding to a gmail account to demonstrate the functionality of the Contacts feed. Args: email: [string] The e-mail address of the account to use for the sample. password: [string] The password corresponding to the account specified by the email parameter. Yields: A ContactsSample object used to run the sample demonstrating the functionality of the Contacts feed. """ self.gd_client = gdata.contacts.client.ContactsClient(source='GoogleInc-ContactsPythonSample-1') self.gd_client.ClientLogin(email, password, self.gd_client.source) def PrintFeed(self, feed, ctr=0): """Prints out the contents of a feed to the console. Args: feed: A gdata.contacts.ContactsFeed instance. ctr: [int] The number of entries in this feed previously printed. This allows continuous entry numbers when paging through a feed. Returns: The number of entries printed, including those previously printed as specified in ctr. This is for passing as an argument to ctr on successive calls to this method. """ if not feed.entry: print '\nNo entries in feed.\n' return 0 for i, entry in enumerate(feed.entry): print '\n%s %s' % (ctr+i+1, entry.title.text) if entry.content: print ' %s' % (entry.content.text) for email in entry.email: if email.primary and email.primary == 'true': print ' %s' % (email.address) # Show the contact groups that this contact is a member of. for group in entry.group_membership_info: print ' Member of group: %s' % (group.href) # Display extended properties. for extended_property in entry.extended_property: if extended_property.value: value = extended_property.value else: value = extended_property.GetXmlBlob() print ' Extended Property %s: %s' % (extended_property.name, value) return len(feed.entry) + ctr def PrintPaginatedFeed(self, feed, print_method): """ Print all pages of a paginated feed. This will iterate through a paginated feed, requesting each page and printing the entries contained therein. Args: feed: A gdata.contacts.ContactsFeed instance. print_method: The method which will be used to print each page of the feed. Must accept these two named arguments: feed: A gdata.contacts.ContactsFeed instance. ctr: [int] The number of entries in this feed previously printed. This allows continuous entry numbers when paging through a feed. """ ctr = 0 while feed: # Print contents of current feed ctr = print_method(feed=feed, ctr=ctr) # Prepare for next feed iteration next = feed.GetNextLink() feed = None if next: if self.PromptOperationShouldContinue(): # Another feed is available, and the user has given us permission # to fetch it feed = self.gd_client.GetContacts(uri=next.href) else: # User has asked us to terminate feed = None def PromptOperationShouldContinue(self): """ Display a "Continue" prompt. This give is used to give users a chance to break out of a loop, just in case they have too many contacts/groups. Returns: A boolean value, True if the current operation should continue, False if the current operation should terminate. """ while True: input = raw_input("Continue [Y/n]? ") if input is 'N' or input is 'n': return False elif input is 'Y' or input is 'y' or input is '': return True def ListAllContacts(self): """Retrieves a list of contacts and displays name and primary email.""" feed = self.gd_client.GetContacts() self.PrintPaginatedFeed(feed, self.PrintContactsFeed) def PrintGroupsFeed(self, feed, ctr): if not feed.entry: print '\nNo groups in feed.\n' return 0 for i, entry in enumerate(feed.entry): print '\n%s %s' % (ctr+i+1, entry.title.text) if entry.content: print ' %s' % (entry.content.text) # Display the group id which can be used to query the contacts feed. print ' Group ID: %s' % entry.id.text # Display extended properties. for extended_property in entry.extended_property: if extended_property.value: value = extended_property.value else: value = extended_property.GetXmlBlob() print ' Extended Property %s: %s' % (extended_property.name, value) return len(feed.entry) + ctr def PrintContactsFeed(self, feed, ctr): if not feed.entry: print '\nNo contacts in feed.\n' return 0 for i, entry in enumerate(feed.entry): if not entry.name is None: family_name = entry.name.family_name is None and " " or entry.name.family_name.text full_name = entry.name.full_name is None and " " or entry.name.full_name.text given_name = entry.name.given_name is None and " " or entry.name.given_name.text print '\n%s %s: %s - %s' % (ctr+i+1, full_name, given_name, family_name) else: print '\n%s %s (title)' % (ctr+i+1, entry.title.text) if entry.content: print ' %s' % (entry.content.text) for p in entry.structured_postal_address: print ' %s' % (p.formatted_address.text) # Display the group id which can be used to query the contacts feed. print ' Group ID: %s' % entry.id.text # Display extended properties. for extended_property in entry.extended_property: if extended_property.value: value = extended_property.value else: value = extended_property.GetXmlBlob() print ' Extended Property %s: %s' % (extended_property.name, value) for user_defined_field in entry.user_defined_field: print ' User Defined Field %s: %s' % (user_defined_field.key, user_defined_field.value) return len(feed.entry) + ctr def ListAllGroups(self): feed = self.gd_client.GetGroups() self.PrintPaginatedFeed(feed, self.PrintGroupsFeed) def CreateMenu(self): """Prompts that enable a user to create a contact.""" name = raw_input('Enter contact\'s name: ') notes = raw_input('Enter notes for contact: ') primary_email = raw_input('Enter primary email address: ') new_contact = gdata.contacts.data.ContactEntry(name=gdata.data.Name(full_name=gdata.data.FullName(text=name))) new_contact.content = atom.data.Content(text=notes) # Create a work email address for the contact and use as primary. new_contact.email.append(gdata.data.Email(address=primary_email, primary='true', rel=gdata.data.WORK_REL)) entry = self.gd_client.CreateContact(new_contact) if entry: print 'Creation successful!' print 'ID for the new contact:', entry.id.text else: print 'Upload error.' def QueryMenu(self): """Prompts for updated-min query parameters and displays results.""" updated_min = raw_input( 'Enter updated min (example: 2007-03-16T00:00:00): ') query = gdata.contacts.client.ContactsQuery() query.updated_min = updated_min feed = self.gd_client.GetContacts(q=query) self.PrintFeed(feed) def QueryGroupsMenu(self): """Prompts for updated-min query parameters and displays results.""" updated_min = raw_input( 'Enter updated min (example: 2007-03-16T00:00:00): ') query = gdata.contacts.client.ContactsQuery(feed='/m8/feeds/groups/default/full') query.updated_min = updated_min feed = self.gd_client.GetGroups(q=query) self.PrintGroupsFeed(feed, 0) def _SelectContact(self): feed = self.gd_client.GetContacts() self.PrintFeed(feed) selection = 5000 while selection > len(feed.entry)+1 or selection < 1: selection = int(raw_input( 'Enter the number for the contact you would like to modify: ')) return feed.entry[selection-1] def UpdateContactMenu(self): selected_entry = self._SelectContact() new_name = raw_input('Enter a new name for the contact: ') if not selected_entry.name: selected_entry.name = gdata.data.Name() selected_entry.name.full_name = gdata.data.FullName(text=new_name) self.gd_client.Update(selected_entry) def DeleteContactMenu(self): selected_entry = self._SelectContact() self.gd_client.Delete(selected_entry) def PrintMenu(self): """Displays a menu of options for the user to choose from.""" print ('\nContacts Sample\n' '1) List all of your contacts.\n' '2) Create a contact.\n' '3) Query contacts on updated time.\n' '4) Modify a contact.\n' '5) Delete a contact.\n' '6) List all of your contact groups.\n' '7) Query your groups on updated time.\n' '8) Exit.\n') def GetMenuChoice(self, max): """Retrieves the menu selection from the user. Args: max: [int] The maximum number of allowed choices (inclusive) Returns: The integer of the menu item chosen by the user. """ while True: input = raw_input('> ') try: num = int(input) except ValueError: print 'Invalid choice. Please choose a value between 1 and', max continue if num > max or num < 1: print 'Invalid choice. Please choose a value between 1 and', max else: return num def Run(self): """Prompts the user to choose funtionality to be demonstrated.""" try: while True: self.PrintMenu() choice = self.GetMenuChoice(8) if choice == 1: self.ListAllContacts() elif choice == 2: self.CreateMenu() elif choice == 3: self.QueryMenu() elif choice == 4: self.UpdateContactMenu() elif choice == 5: self.DeleteContactMenu() elif choice == 6: self.ListAllGroups() elif choice == 7: self.QueryGroupsMenu() elif choice == 8: return except KeyboardInterrupt: print '\nGoodbye.' return def main(): """Demonstrates use of the Contacts extension using the ContactsSample object.""" # Parse command line options try: opts, args = getopt.getopt(sys.argv[1:], '', ['user=', 'pw=']) except getopt.error, msg: print 'python contacts_example.py --user [username] --pw [password]' sys.exit(2) user = '' pw = '' # Process options for option, arg in opts: if option == '--user': user = arg elif option == '--pw': pw = arg while not user: print 'NOTE: Please run these tests only with a test account.' user = raw_input('Please enter your username: ') while not pw: pw = getpass.getpass() if not pw: print 'Password cannot be blank.' try: sample = ContactsSample(user, pw) except gdata.client.BadAuthentication: print 'Invalid user credentials given.' return sample.Run() if __name__ == '__main__': main()
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. """Sample running boilerplate.""" __author__ = 'afshar@google.com (Ali Afshar)' def Run(source_file): """Load a source file and run a sample from it.""" source = open(source_file).read() global_dict = {'__file__': source_file} exec source in global_dict samples = [global_dict[k] for k in global_dict if k.endswith('Sample')] lines = source.splitlines() for i, sample in enumerate(samples): print str(i).rjust(2), sample.__name__, '-', sample.__doc__ try: i = int(raw_input('Select sample: ').strip()) sample = samples[i] print '-' * 80 print 'def', '%s():' % sample.__name__ # print each line until a blank one (or eof). for line in lines[sample.func_code.co_firstlineno:]: if not line: break print line print '-' * 80 sample() except (ValueError, IndexError): print 'Bad selection.'
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. """Samples for the Documents List API v3.""" __author__ = 'afshar@google.com (Ali Afshar)' import os.path import gdata.data import gdata.acl.data import gdata.docs.client import gdata.docs.data import gdata.sample_util class SampleConfig(object): APP_NAME = 'GDataDocumentsListAPISample-v1.0' DEBUG = False def CreateClient(): """Create a Documents List Client.""" client = gdata.docs.client.DocsClient(source=SampleConfig.APP_NAME) client.http_client.debug = SampleConfig.DEBUG # Authenticate the user with CLientLogin, OAuth, or AuthSub. try: gdata.sample_util.authorize_client( client, service=client.auth_service, source=client.source, scopes=client.auth_scopes ) except gdata.client.BadAuthentication: exit('Invalid user credentials given.') except gdata.client.Error: exit('Login Error') return client def PrintResource(resource): """Display a resource to Standard Out.""" print resource.resource_id.text, resource.GetResourceType() def PrintFeed(feed): """Display a feed to Standard Out.""" for entry in feed.entry: PrintResource(entry) def _GetDataFilePath(name): return os.path.join( os.path.dirname( os.path.dirname( os.path.dirname(__file__))), 'tests', 'gdata_tests', 'docs', 'data', name) def GetResourcesSample(): """Get and display first page of resources.""" client = CreateClient() # Get a feed and print it feed = client.GetResources() PrintFeed(feed) def GetAllResourcesSample(): """Get and display all resources, using pagination.""" client = CreateClient() # Unlike client.GetResources, this returns a list of resources for resource in client.GetAllResources(): PrintResource(resource) def GetResourceSample(): """Fetch 5 resources from a feed, then again individually.""" client = CreateClient() for e1 in client.GetResources(limit=5).entry: e2 = client.GetResource(e1) print 'Refetched: ', e2.title.text, e2.resource_id.text def GetMetadataSample(): """Get and display the Metadata for the current user.""" client = CreateClient() # Fetch the metadata entry and display bits of it metadata = client.GetMetadata() print 'Quota' print ' Total:', metadata.quota_bytes_total.text print ' Used:', metadata.quota_bytes_used.text print ' Trashed:', metadata.quota_bytes_used_in_trash.text print 'Import / Export' for input_format in metadata.import_formats: print ' Import:', input_format.source, 'to', input_format.target for export_format in metadata.export_formats: print ' Export:', export_format.source, 'to', export_format.target print 'Features' for feature in metadata.features: print ' Feature:', feature.name.text print 'Upload Sizes' for upload_size in metadata.max_upload_sizes: print ' Kind:', upload_size.kind, upload_size.text def GetChangesSample(): """Get and display the Changes for the user.""" client = CreateClient() changes = client.GetChanges() for change in changes.entry: print change.title.text, change.changestamp.value def GetResourceAclSample(): """Get and display the ACL for a resource.""" client = CreateClient() for resource in client.GetResources(limit=5).entry: acl_feed = client.GetResourceAcl(resource) for acl in acl_feed.entry: print acl.role.value, acl.scope.type, acl.scope.value def CreateEmptyResourceSample(): """Create an empty resource of type document.""" client = CreateClient() document = gdata.docs.data.Resource(type='document', title='My Sample Doc') document = client.CreateResource(document) print 'Created:', document.title.text, document.resource_id.text def CreateCollectionSample(): """Create an empty collection.""" client = CreateClient() col = gdata.docs.data.Resource(type='folder', title='My Sample Folder') col = client.CreateResource(col) print 'Created collection:', col.title.text, col.resource_id.text def CreateResourceInCollectionSample(): """Create a collection, then create a document in it.""" client = CreateClient() col = gdata.docs.data.Resource(type='folder', title='My Sample Folder') col = client.CreateResource(col) print 'Created collection:', col.title.text, col.resource_id.text doc = gdata.docs.data.Resource(type='document', title='My Sample Doc') doc = client.CreateResource(doc, collection=col) print 'Created:', doc.title.text, doc.resource_id.text def UploadResourceSample(): """Upload a document, and convert to Google Docs.""" client = CreateClient() doc = gdata.docs.data.Resource(type='document', title='My Sample Doc') # This is a convenient MS Word doc that we know exists path = _GetDataFilePath('test.0.doc') print 'Selected file at: %s' % path # Create a MediaSource, pointing to the file media = gdata.data.MediaSource() media.SetFileHandle(path, 'application/msword') # Pass the MediaSource when creating the new Resource doc = client.CreateResource(doc, media=media) print 'Created, and uploaded:', doc.title.text, doc.resource_id.text def UploadUnconvertedFileSample(): """Upload a document, unconverted.""" client = CreateClient() doc = gdata.docs.data.Resource(type='document', title='My Sample Raw Doc') path = _GetDataFilePath('test.0.doc') media = gdata.data.MediaSource() media.SetFileHandle(path, 'application/msword') # Pass the convert=false parameter create_uri = gdata.docs.client.RESOURCE_UPLOAD_URI + '?convert=false' doc = client.CreateResource(doc, create_uri=create_uri, media=media) print 'Created, and uploaded:', doc.title.text, doc.resource_id.text def DeleteResourceSample(): """Delete a resource (after creating it).""" client = CreateClient() doc = gdata.docs.data.Resource(type='document', title='My Sample Doc') doc = client.CreateResource(doc) # Delete the resource we just created. client.DeleteResource(doc) def AddAclSample(): """Create a resource and an ACL.""" client = CreateClient() doc = gdata.docs.data.Resource(type='document', title='My Sample Doc') doc = client.CreateResource(doc) acl_entry = gdata.docs.data.AclEntry( scope=gdata.acl.data.AclScope(value='user@example.com', type='user'), role=gdata.acl.data.AclRole(value='reader'), ) client.AddAclEntry(doc, acl_entry, send_notifications=False) def DeleteAclSample(): """Create an ACL entry, and delete it.""" client = CreateClient() doc = gdata.docs.data.Resource(type='document', title='My Sample Doc') doc = client.CreateResource(doc) acl_entry = gdata.docs.data.AclEntry( scope=gdata.acl.data.AclScope(value='user@example.com', type='user'), role=gdata.acl.data.AclRole(value='reader'), ) acl_entry = client.AddAclEntry(doc, acl_entry) client.DeleteAclEntry(acl_entry) def AddAclBatchSample(): """Add a list of ACLs as a batch.""" client = CreateClient() doc = gdata.docs.data.Resource(type='document', title='My Sample Doc') doc = client.CreateResource(doc) acl1 = gdata.docs.data.AclEntry( scope=gdata.acl.data.AclScope(value='user1@example.com', type='user'), role=gdata.acl.data.AclRole(value='reader'), batch_operation=gdata.data.BatchOperation(type='insert'), ) acl2 = gdata.docs.data.AclEntry( scope=gdata.acl.data.AclScope(value='user2@example.com', type='user'), role=gdata.acl.data.AclRole(value='reader'), batch_operation=gdata.data.BatchOperation(type='insert'), ) # Create a list of operations to perform together. acl_operations = [acl1, acl2] # Perform the operations. client.BatchProcessAclEntries(doc, acl_operations) def GetRevisionsSample(): """Get the revision history for resources.""" client = CreateClient() for entry in client.GetResources(limit=55).entry: revisions = client.GetRevisions(entry) for revision in revisions.entry: print revision.publish, revision.GetPublishLink() if __name__ == '__main__': import samplerunner samplerunner.Run(__file__)
Python
#!/usr/bin/python # # Copyright (C) 2007, 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = ('api.jfisher (Jeff Fisher), ' 'e.bidelman (Eric Bidelman)') import sys import re import os.path import getopt import getpass import gdata.docs.service import gdata.spreadsheet.service def truncate(content, length=15, suffix='...'): if len(content) <= length: return content else: return content[:length] + suffix class DocsSample(object): """A DocsSample object demonstrates the Document List feed.""" def __init__(self, email, password): """Constructor for the DocsSample object. Takes an email and password corresponding to a gmail account to demonstrate the functionality of the Document List feed. Args: email: [string] The e-mail address of the account to use for the sample. password: [string] The password corresponding to the account specified by the email parameter. Returns: A DocsSample object used to run the sample demonstrating the functionality of the Document List feed. """ source = 'Document List Python Sample' self.gd_client = gdata.docs.service.DocsService() self.gd_client.ClientLogin(email, password, source=source) # Setup a spreadsheets service for downloading spreadsheets self.gs_client = gdata.spreadsheet.service.SpreadsheetsService() self.gs_client.ClientLogin(email, password, source=source) def _PrintFeed(self, feed): """Prints out the contents of a feed to the console. Args: feed: A gdata.docs.DocumentListFeed instance. """ print '\n' if not feed.entry: print 'No entries in feed.\n' print '%-18s %-12s %s' % ('TITLE', 'TYPE', 'RESOURCE ID') for entry in feed.entry: print '%-18s %-12s %s' % (truncate(entry.title.text.encode('UTF-8')), entry.GetDocumentType(), entry.resourceId.text) def _GetFileExtension(self, file_name): """Returns the uppercase file extension for a file. Args: file_name: [string] The basename of a filename. Returns: A string containing the file extension of the file. """ match = re.search('.*\.([a-zA-Z]{3,}$)', file_name) if match: return match.group(1).upper() return False def _UploadMenu(self): """Prompts that enable a user to upload a file to the Document List feed.""" file_path = '' file_path = raw_input('Enter path to file: ') if not file_path: return elif not os.path.isfile(file_path): print 'Not a valid file.' return file_name = os.path.basename(file_path) ext = self._GetFileExtension(file_name) if not ext or ext not in gdata.docs.service.SUPPORTED_FILETYPES: print 'File type not supported. Check the file extension.' return else: content_type = gdata.docs.service.SUPPORTED_FILETYPES[ext] title = '' while not title: title = raw_input('Enter name for document: ') try: ms = gdata.MediaSource(file_path=file_path, content_type=content_type) except IOError: print 'Problems reading file. Check permissions.' return if ext in ['CSV', 'ODS', 'XLS', 'XLSX']: print 'Uploading spreadsheet...' elif ext in ['PPT', 'PPS']: print 'Uploading presentation...' else: print 'Uploading word processor document...' entry = self.gd_client.Upload(ms, title) if entry: print 'Upload successful!' print 'Document now accessible at:', entry.GetAlternateLink().href else: print 'Upload error.' def _DownloadMenu(self): """Prompts that enable a user to download a local copy of a document.""" resource_id = '' resource_id = raw_input('Enter an resource id: ') file_path = '' file_path = raw_input('Save file to: ') if not file_path or not resource_id: return file_name = os.path.basename(file_path) ext = self._GetFileExtension(file_name) if not ext or ext not in gdata.docs.service.SUPPORTED_FILETYPES: print 'File type not supported. Check the file extension.' return else: content_type = gdata.docs.service.SUPPORTED_FILETYPES[ext] doc_type = resource_id[:resource_id.find(':')] # When downloading a spreadsheet, the authenticated request needs to be # sent with the spreadsheet service's auth token. if doc_type == 'spreadsheet': print 'Downloading spreadsheet to %s...' % (file_path,) docs_token = self.gd_client.GetClientLoginToken() self.gd_client.SetClientLoginToken(self.gs_client.GetClientLoginToken()) self.gd_client.Export(resource_id, file_path, gid=0) self.gd_client.SetClientLoginToken(docs_token) else: print 'Downloading document to %s...' % (file_path,) self.gd_client.Export(resource_id, file_path) def _ListDocuments(self): """Retrieves and displays a list of documents based on the user's choice.""" print 'Retrieve (all/document/folder/presentation/spreadsheet/pdf): ' category = raw_input('Enter a category: ') if category == 'all': feed = self.gd_client.GetDocumentListFeed() elif category == 'folder': query = gdata.docs.service.DocumentQuery(categories=['folder'], params={'showfolders': 'true'}) feed = self.gd_client.Query(query.ToUri()) else: query = gdata.docs.service.DocumentQuery(categories=[category]) feed = self.gd_client.Query(query.ToUri()) self._PrintFeed(feed) def _ListAclPermissions(self): """Retrieves a list of a user's folders and displays them.""" resource_id = raw_input('Enter an resource id: ') query = gdata.docs.service.DocumentAclQuery(resource_id) print '\nListing document permissions:' feed = self.gd_client.GetDocumentListAclFeed(query.ToUri()) for acl_entry in feed.entry: print '%s - %s (%s)' % (acl_entry.role.value, acl_entry.scope.value, acl_entry.scope.type) def _ModifyAclPermissions(self): """Create or updates the ACL entry on an existing document.""" resource_id = raw_input('Enter an resource id: ') email = raw_input('Enter an email address: ') role_value = raw_input('Enter a permission (reader/writer/owner/remove): ') uri = gdata.docs.service.DocumentAclQuery(resource_id).ToUri() acl_feed = self.gd_client.GetDocumentListAclFeed(uri) found_acl_entry = None for acl_entry in acl_feed.entry: if acl_entry.scope.value == email: found_acl_entry = acl_entry break if found_acl_entry: if role_value == 'remove': # delete ACL entry self.gd_client.Delete(found_acl_entry.GetEditLink().href) else: # update ACL entry found_acl_entry.role.value = role_value updated_entry = self.gd_client.Put( found_acl_entry, found_acl_entry.GetEditLink().href, converter=gdata.docs.DocumentListAclEntryFromString) else: scope = gdata.docs.Scope(value=email, type='user') role = gdata.docs.Role(value=role_value) acl_entry = gdata.docs.DocumentListAclEntry(scope=scope, role=role) inserted_entry = self.gd_client.Post( acl_entry, uri, converter=gdata.docs.DocumentListAclEntryFromString) print '\nListing document permissions:' acl_feed = self.gd_client.GetDocumentListAclFeed(uri) for acl_entry in acl_feed.entry: print '%s - %s (%s)' % (acl_entry.role.value, acl_entry.scope.value, acl_entry.scope.type) def _FullTextSearch(self): """Searches a user's documents for a text string. Provides prompts to search a user's documents and displays the results of such a search. The text_query parameter of the DocumentListQuery object corresponds to the contents of the q parameter in the feed. Note that this parameter searches the content of documents, not just their titles. """ input = raw_input('Enter search term: ') query = gdata.docs.service.DocumentQuery(text_query=input) feed = self.gd_client.Query(query.ToUri()) self._PrintFeed(feed) def _PrintMenu(self): """Displays a menu of options for the user to choose from.""" print ('\nDocument List Sample\n' '1) List your documents.\n' '2) Search your documents.\n' '3) Upload a document.\n' '4) Download a document.\n' "5) List a document's permissions.\n" "6) Add/change a document's permissions.\n" '7) Exit.\n') def _GetMenuChoice(self, max): """Retrieves the menu selection from the user. Args: max: [int] The maximum number of allowed choices (inclusive) Returns: The integer of the menu item chosen by the user. """ while True: input = raw_input('> ') try: num = int(input) except ValueError: print 'Invalid choice. Please choose a value between 1 and', max continue if num > max or num < 1: print 'Invalid choice. Please choose a value between 1 and', max else: return num def Run(self): """Prompts the user to choose funtionality to be demonstrated.""" try: while True: self._PrintMenu() choice = self._GetMenuChoice(7) if choice == 1: self._ListDocuments() elif choice == 2: self._FullTextSearch() elif choice == 3: self._UploadMenu() elif choice == 4: self._DownloadMenu() elif choice == 5: self._ListAclPermissions() elif choice == 6: self._ModifyAclPermissions() elif choice == 7: print '\nGoodbye.' return except KeyboardInterrupt: print '\nGoodbye.' return def main(): """Demonstrates use of the Docs extension using the DocsSample object.""" # Parse command line options try: opts, args = getopt.getopt(sys.argv[1:], '', ['user=', 'pw=']) except getopt.error, msg: print 'python docs_example.py --user [username] --pw [password] ' sys.exit(2) user = '' pw = '' key = '' # Process options for option, arg in opts: if option == '--user': user = arg elif option == '--pw': pw = arg while not user: print 'NOTE: Please run these tests only with a test account.' user = raw_input('Please enter your username: ') while not pw: pw = getpass.getpass() if not pw: print 'Password cannot be blank.' try: sample = DocsSample(user, pw) except gdata.service.BadAuthentication: print 'Invalid user credentials given.' return sample.Run() if __name__ == '__main__': main()
Python
#!/usr/bin/python # # Copyright (C) 2008 Yu-Jie Lin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import gdata.webmastertools.service import gdata.service try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import getpass username = '' password = '' username = raw_input('Please enter your username: ') password = getpass.getpass() client = gdata.webmastertools.service.GWebmasterToolsService( email=username, password=password, source='PythonWebmasterToolsSample-1') print 'Logging in' client.ProgrammaticLogin() print 'Retrieving Sites feed' feed = client.GetSitesFeed() # Format the feed print print 'You have %d site(s), last updated at %s' % ( len(feed.entry), feed.updated.text) print print "%-25s %25s %25s" % ('Site', 'Last Updated', 'Last Crawled') print '='*80 def safeElementText(element): if hasattr(element, 'text'): return element.text return '' # Format each site for entry in feed.entry: print "%-25s %25s %25s" % ( entry.title.text.replace('http://', '')[:25], entry.updated.text[:25], safeElementText(entry.crawled)[:25]) print " Preferred: %-23s Indexed: %5s GeoLoc: %10s" % ( safeElementText(entry.preferred_domain)[:30], entry.indexed.text[:5], safeElementText(entry.geolocation)[:10]) print " Crawl rate: %-10s Verified: %5s" % ( safeElementText(entry.crawl_rate)[:10], entry.verified.text[:5]) print
Python
#!/usr/bin/python # # Copyright (C) 2008 Yu-Jie Lin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import gdata.webmastertools.service import gdata.service try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import getpass username = '' password = '' site_uri = '' username = raw_input('Please enter your username: ') password = getpass.getpass() site_uri = raw_input('Please enter your site url: ') client = gdata.webmastertools.service.GWebmasterToolsService( email=username, password=password, source='PythonWebmasterToolsSample-1') print 'Logging in' client.ProgrammaticLogin() print 'Retrieving Sitemaps feed' feed = client.GetSitemapsFeed(site_uri) # Format the feed print print 'You have %d sitemap(s), last updated at %s' % ( len(feed.entry), feed.updated.text) print print '='*80 def safeElementText(element): if hasattr(element, 'text'): return element.text return '' # Format each site for entry in feed.entry: print entry.title.text.replace('http://', '')[:80] print " Last Updated : %29s Status: %10s" % ( entry.updated.text[:29], entry.sitemap_status.text[:10]) print " Last Downloaded: %29s URL Count: %10s" % ( safeElementText(entry.sitemap_last_downloaded)[:29], safeElementText(entry.sitemap_url_count)[:10]) print
Python
#!/usr/bin/python # # Copyright (C) 2008 Yu-Jie Lin # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import urllib import gdata.webmastertools.service import gdata.service try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import getpass username = '' password = '' username = raw_input('Please enter your username: ') password = getpass.getpass() client = gdata.webmastertools.service.GWebmasterToolsService( email=username, password=password, source='PythonWebmasterToolsSample-1') EXAMPLE_SITE = 'http://www.example.com/' EXAMPLE_SITEMAP = 'http://www.example.com/sitemap-index.xml' def safeElementText(element): if hasattr(element, 'text'): return element.text return '' print 'Logging in' client.ProgrammaticLogin() print print 'Adding site: %s' % EXAMPLE_SITE entry = client.AddSite(EXAMPLE_SITE) print print "%-25s %25s %25s" % ('Site', 'Last Updated', 'Last Crawled') print '='*80 print "%-25s %25s %25s" % ( entry.title.text.replace('http://', '')[:25], entry.updated.text[:25], safeElementText(entry.crawled)[:25]) print " Preferred: %-23s Indexed: %5s GeoLoc: %10s" % ( safeElementText(entry.preferred_domain)[:30], entry.indexed.text[:5], safeElementText(entry.geolocation)[:10]) print " Crawl rate: %-10s Verified: %5s" % ( safeElementText(entry.crawl_rate)[:10], entry.verified.text[:5]) # Verifying a site. This sample won't do this since we don't own example.com #client.VerifySite(EXAMPLE_SITE, 'htmlpage') # The following needs the ownership of the site #client.UpdateGeoLocation(EXAMPLE_SITE, 'US') #client.UpdateCrawlRate(EXAMPLE_SITE, 'normal') #client.UpdatePreferredDomain(EXAMPLE_SITE, 'preferwww') #client.UpdateEnhancedImageSearch(EXAMPLE_SITE, 'true') print print 'Adding sitemap: %s' % EXAMPLE_SITEMAP entry = client.AddSitemap(EXAMPLE_SITE, EXAMPLE_SITEMAP) print entry.title.text.replace('http://', '')[:80] print " Last Updated : %29s Status: %10s" % ( entry.updated.text[:29], entry.sitemap_status.text[:10]) print " Last Downloaded: %29s URL Count: %10s" % ( safeElementText(entry.sitemap_last_downloaded)[:29], safeElementText(entry.sitemap_url_count)[:10]) # Add a mobile sitemap #entry = client.AddMobileSitemap(EXAMPLE_SITE, 'http://.../sitemap-mobile-example.xml', 'XHTML') # Add a news sitemap, your site must be included in Google News. # See also http://google.com/support/webmasters/bin/answer.py?answer=42738 #entry = client.AddNewsSitemap(EXAMPLE_SITE, 'http://.../sitemap-news-example.xml', 'Label') print print 'Deleting sitemap: %s' % EXAMPLE_SITEMAP client.DeleteSitemap(EXAMPLE_SITE, EXAMPLE_SITEMAP) print print 'Deleting site: %s' % EXAMPLE_SITE client.DeleteSite(EXAMPLE_SITE) print
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. # This file demonstrates how to use the Google Data API's Python client library # to interface with the Codesearch service. __author__ = 'vbarathan@gmail.com (Prakash Barathan)' from gdata import service import gdata.codesearch.service import gdata import atom import getopt import sys class CodesearchExample: def __init__(self): """Creates a GData service instance to talk to Codesearch service.""" self.service = gdata.codesearch.service.CodesearchService( source='Codesearch_Python_Sample-1.0') def PrintCodeSnippets(self, query): """Prints the codesearch results for given query.""" feed = self.service.GetSnippetsFeed(query) print feed.title.text + " Results for '" + query + "'" print '============================================' for entry in feed.entry: print "" + entry.title.text for match in entry.match: print "\tline#" + match.line_number + ":" + match.text.replace('\n', '') print def main(): """The main function runs the CodesearchExample application with user specified query.""" # parse command line options try: opts, args = getopt.getopt(sys.argv[1:], "", ["query="]) except getopt.error, msg: print ('python CodesearchExample.py --query [query_text]') sys.exit(2) query = '' # Process options for o, a in opts: if o == "--query": query = a if query == '': print ('python CodesearchExample.py --query [query]') sys.exit(2) sample = CodesearchExample() sample.PrintCodeSnippets(query) if __name__ == '__main__': main()
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. """Sample Google Analytics Data Export API Data Feed application. This sample demonstrates how to make requests and retrieve the important information from the Google Analytics Data Export API Data Feed. This sample requires a Google Analytics username and password and uses the Client Login authorization routine. Class DataFeedDemo: Prints all the important Data Feed informantion. """ __author__ = 'api.nickm@google.com (Nick Mihailovski)' import gdata.analytics.client import gdata.sample_util def main(): """Main function for the sample.""" demo = DataFeedDemo() demo.PrintFeedDetails() demo.PrintDataSources() demo.PrintFeedAggregates() demo.PrintSegmentInfo() demo.PrintOneEntry() demo.PrintFeedTable() class DataFeedDemo(object): """Gets data from the Data Feed. Attributes: data_feed: Google Analytics AccountList returned form the API. """ def __init__(self): """Inits DataFeedDemo.""" SOURCE_APP_NAME = 'Google-dataFeedDemoPython-v2' my_client = gdata.analytics.client.AnalyticsClient(source=SOURCE_APP_NAME) try: gdata.sample_util.authorize_client( my_client, service=my_client.auth_service, source=SOURCE_APP_NAME, scopes=['https://www.google.com/analytics/feeds/']) except gdata.client.BadAuthentication: exit('Invalid user credentials given.') except gdata.client.Error: exit('Login Error') table_id = gdata.sample_util.get_param( name='table_id', prompt='Please enter your Google Analytics Table id (format ga:xxxx)') # DataFeedQuery simplifies constructing API queries and uri encodes params. data_query = gdata.analytics.client.DataFeedQuery({ 'ids': table_id, 'start-date': '2008-10-01', 'end-date': '2008-10-30', 'dimensions': 'ga:source,ga:medium', 'metrics': 'ga:visits', 'sort': '-ga:visits', 'filters': 'ga:medium==referral', 'max-results': '50'}) self.feed = my_client.GetDataFeed(data_query) def PrintFeedDetails(self): """Prints important Analytics related data found at the top of the feed.""" print '\n-------- Feed Data --------' print 'Feed Title = ' + self.feed.title.text print 'Feed Id = ' + self.feed.id.text print 'Total Results Found = ' + self.feed.total_results.text print 'Start Index = ' + self.feed.start_index.text print 'Results Returned = ' + self.feed.items_per_page.text print 'Start Date = ' + self.feed.start_date.text print 'End Date = ' + self.feed.end_date.text print 'Has Sampled Data = ' + str(self.feed.HasSampledData()) def PrintDataSources(self): """Prints data found in the data source elements. This data has information about the Google Analytics account the referenced table ID belongs to. Note there is currently exactly one data source in the data feed. """ data_source = self.feed.data_source[0] print '\n-------- Data Source Data --------' print 'Table ID = ' + data_source.table_id.text print 'Table Name = ' + data_source.table_name.text print 'Web Property Id = ' + data_source.GetProperty('ga:webPropertyId').value print 'Profile Id = ' + data_source.GetProperty('ga:profileId').value print 'Account Name = ' + data_source.GetProperty('ga:accountName').value def PrintFeedAggregates(self): """Prints data found in the aggregates elements. This contains the sum of all the metrics defined in the query across. This sum spans all the rows matched in the feed.total_results property and not just the rows returned by the response. """ aggregates = self.feed.aggregates print '\n-------- Metric Aggregates --------' for met in aggregates.metric: print '' print 'Metric Name = ' + met.name print 'Metric Value = ' + met.value print 'Metric Type = ' + met.type print 'Metric CI = ' + met.confidence_interval def PrintSegmentInfo(self): """Prints segment information if the query has advanced segments defined.""" print '-------- Advanced Segments Information --------' if self.feed.segment: if segment.name: print 'Segment Name = ' + str(segment.name) if segment.id: print 'Segment Id = ' + str(segment.id) print 'Segment Definition = ' + segment.definition.text else: print 'No segments defined' def PrintOneEntry(self): """Prints all the important Google Analytics data found in an entry""" print '\n-------- One Entry --------' if len(self.feed.entry) == 0: print 'No entries found' return entry = self.feed.entry[0] print 'ID = ' + entry.id.text for dim in entry.dimension: print 'Dimension Name = ' + dim.name print 'Dimension Value = ' + dim.value for met in entry.metric: print 'Metric Name = ' + met.name print 'Metric Value = ' + met.value print 'Metric Type = ' + met.type print 'Metric CI = ' + met.confidence_interval def PrintFeedTable(self): """Prints all the entries as a table.""" print '\n-------- All Entries In a Table --------' for entry in self.feed.entry: for dim in entry.dimension: print ('Dimension Name = %s \t Dimension Value = %s' % (dim.name, dim.value)) for met in entry.metric: print ('Metric Name = %s \t Metric Value = %s' % (met.name, met.value)) print '---' if __name__ == '__main__': main()
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. """Sample Google Analytics Data Export API Account Feed application. This sample demonstrates how to retrieve the important data from the Google Analytics Data Export API Account feed using the Python Client library. This requires a Google Analytics username and password and uses the Client Login authorization routine. Class AccountFeedDemo: Prints all the import Account Feed data. """ __author__ = 'api.nickm@google.com (Nick Mihailovski)' import gdata.analytics.client import gdata.sample_util def main(): """Main fucntion for the sample.""" demo = AccountFeedDemo() demo.PrintFeedDetails() demo.PrintAdvancedSegments() demo.PrintCustomVarForOneEntry() demo.PrintGoalsForOneEntry() demo.PrintAccountEntries() class AccountFeedDemo(object): """Prints the Google Analytics account feed Attributes: account_feed: Google Analytics AccountList returned form the API. """ def __init__(self): """Inits AccountFeedDemo.""" SOURCE_APP_NAME = 'Google-accountFeedDemoPython-v1' my_client = gdata.analytics.client.AnalyticsClient(source=SOURCE_APP_NAME) try: gdata.sample_util.authorize_client( my_client, service=my_client.auth_service, source=SOURCE_APP_NAME, scopes=['https://www.google.com/analytics/feeds/']) except gdata.client.BadAuthentication: exit('Invalid user credentials given.') except gdata.client.Error: exit('Login Error') account_query = gdata.analytics.client.AccountFeedQuery() self.feed = my_client.GetAccountFeed(account_query) def PrintFeedDetails(self): """Prints important Analytics related data found at the top of the feed.""" print '-------- Important Feed Data --------' print 'Feed Title = ' + self.feed.title.text print 'Feed Id = ' + self.feed.id.text print 'Total Results Found = ' + self.feed.total_results.text print 'Start Index = ' + self.feed.start_index.text print 'Results Returned = ' + self.feed.items_per_page.text def PrintAdvancedSegments(self): """Prints the advanced segments for this user.""" print '-------- Advances Segments --------' if not self.feed.segment: print 'No advanced segments found' else: for segment in self.feed.segment: print 'Segment Name = ' + segment.name print 'Segment Id = ' + segment.id print 'Segment Definition = ' + segment.definition.text def PrintCustomVarForOneEntry(self): """Prints custom variable information for the first profile that has custom variable configured.""" print '-------- Custom Variables --------' if not self.feed.entry: print 'No entries found' else: for entry in self.feed.entry: if entry.custom_variable: for custom_variable in entry.custom_variable: print 'Custom Variable Index = ' + custom_variable.index print 'Custom Variable Name = ' + custom_variable.name print 'Custom Variable Scope = ' + custom_variable.scope return print 'No custom variables defined for this user' def PrintGoalsForOneEntry(self): """Prints All the goal information for one profile.""" print '-------- Goal Configuration --------' if not self.feed.entry: print 'No entries found' else: for entry in self.feed.entry: if entry.goal: for goal in entry.goal: print 'Goal Number = ' + goal.number print 'Goal Name = ' + goal.name print 'Goal Value = ' + goal.value print 'Goal Active = ' + goal.active if goal.destination: self.PrintDestinationGoal(goal.destination) elif goal.engagement: self.PrintEngagementGoal(goal.engagement) return def PrintDestinationGoal(self, destination): """Prints the important information for destination goals including all the configured steps if they exist. Args: destination: gdata.data.Destination The destination goal configuration. """ print '----- Destination Goal -----' print 'Expression = ' + destination.expression print 'Match Type = ' + destination.match_type print 'Step 1 Required = ' + destination.step1_required print 'Case Sensitive = ' + destination.case_sensitive # Print goal steps. if destination.step: print '----- Destination Goal Steps -----' for step in destination.step: print 'Step Number = ' + step.number print 'Step Name = ' + step.name print 'Step Path = ' + step.path def PrintEngagementGoal(self, engagement): """Prints the important information for engagement goals. Args: engagement: gdata.data.Engagement The engagement goal configuration. """ print '----- Engagement Goal -----' print 'Goal Type = ' + engagement.type print 'Goal Engagement = ' + engagement.comparison print 'Goal Threshold = ' + engagement.threshold_value def PrintAccountEntries(self): """Prints important Analytics data found in each account entry""" print '-------- First 1000 Profiles in Account Feed --------' if not self.feed.entry: print 'No entries found' else: for entry in self.feed.entry: print 'Web Property ID = ' + entry.GetProperty('ga:webPropertyId').value print 'Account Name = ' + entry.GetProperty('ga:accountName').value print 'Account Id = ' + entry.GetProperty('ga:accountId').value print 'Profile Name = ' + entry.title.text print 'Profile ID = ' + entry.GetProperty('ga:profileId').value print 'Table ID = ' + entry.table_id.text print 'Currency = ' + entry.GetProperty('ga:currency').value print 'TimeZone = ' + entry.GetProperty('ga:timezone').value if entry.custom_variable: print 'This profile has custom variables' if entry.goal: print 'This profile has goals' if __name__ == '__main__': main()
Python
#!/usr/bin/python # # Copyright 2010 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Google Analytics Management API Demo. This script demonstrates how to retrieve the important data from the Google Analytics Data Management API using the Python Client library. This example requires a Google Analytics account with data and a username and password. Each feed in the Management API is retrieved and printed using the respective print method in ManagementFeedDemo. To simplify setting filters and query parameters, each feed has it's own query class. Check the <code>gdata.analytics.client</code> module for more details on usage. main: The main method of this example. GetAnalyticsClient: Returns an authorized AnalyticsClient object. Class ManagementFeedDemo: Prints all the import Account Feed data. """ __author__ = 'api.nickm@google.com (Nick Mihailovski)' import gdata.analytics.client import gdata.sample_util ACCOUNT_ID = '~all' WEB_PROPERTY_ID = '~all' PROFILE_ID = '~all' def main(): """Main example script. Un-comment each method to print the feed.""" demo = ManagementFeedDemo(GetAnalyticsClient()) demo.PrintAccountFeed() # demo.PrintWebPropertyFeed() # demo.PrintProfileFeed() # demo.PrintGoalFeed() # demo.PrintSegmentFeed() def GetAnalyticsClient(): """Returns an authorized GoogleAnalayticsClient object. Uses the Google Data python samples wrapper to prompt the user for credentials then tries to authorize the client object with the Google Analytics API. Returns: An authorized GoogleAnalyticsClient object. """ SOURCE_APP_NAME = 'Analytics-ManagementAPI-Demo-v1' my_client = gdata.analytics.client.AnalyticsClient(source=SOURCE_APP_NAME) try: gdata.sample_util.authorize_client( my_client, service=my_client.auth_service, source=SOURCE_APP_NAME, scopes=['https://www.google.com/analytics/feeds/']) except gdata.client.BadAuthentication: exit('Invalid user credentials given.') except gdata.client.Error: exit('Login Error') return my_client class ManagementFeedDemo(object): """The main demo for the management feed. Attributes: my_client: gdata.analytics.client The AnalyticsClient object for this demo. """ def __init__(self, my_client): """Initializes the ManagementFeedDemo class. Args: my_client: gdata.analytics.client An authorized GoogleAnalyticsClient object. """ self.my_client = my_client def PrintAccountFeed(self): """Requests and prints the important data in the Account Feed. Note: AccountQuery is used for the ManagementAPI. AccountFeedQuery is used for the Data Export API. """ account_query = gdata.analytics.client.AccountQuery() results = self.my_client.GetManagementFeed(account_query) print '-------- Account Feed Data --------' if not results.entry: print 'no entries found' else: for entry in results.entry: print 'Account Name = ' + entry.GetProperty('ga:accountName').value print 'Account ID = ' + entry.GetProperty('ga:accountId').value print 'Child Feed Link = ' + entry.GetChildLink('analytics#webproperties').href print def PrintWebPropertyFeed(self): """Requests and prints the important data in the Web Property Feed.""" web_property_query = gdata.analytics.client.WebPropertyQuery( acct_id=ACCOUNT_ID) results = self.my_client.GetManagementFeed(web_property_query) print '-------- Web Property Feed Data --------' if not results.entry: print 'no entries found' else: for entry in results.entry: print 'Account ID = ' + entry.GetProperty('ga:accountId').value print 'Web Property ID = ' + entry.GetProperty('ga:webPropertyId').value print 'Child Feed Link = ' + entry.GetChildLink('analytics#profiles').href print def PrintProfileFeed(self): """Requests and prints the important data in the Profile Feed. Note: TableId has a different namespace (dxp:) than all the other properties (ga:). """ profile_query = gdata.analytics.client.ProfileQuery( acct_id=ACCOUNT_ID, web_prop_id=WEB_PROPERTY_ID) results = self.my_client.GetManagementFeed(profile_query) print '-------- Profile Feed Data --------' if not results.entry: print 'no entries found' else: for entry in results.entry: print 'Account ID = ' + entry.GetProperty('ga:accountId').value print 'Web Property ID = ' + entry.GetProperty('ga:webPropertyId').value print 'Profile ID = ' + entry.GetProperty('ga:profileId').value print 'Currency = ' + entry.GetProperty('ga:currency').value print 'Timezone = ' + entry.GetProperty('ga:timezone').value print 'TableId = ' + entry.GetProperty('dxp:tableId').value print 'Child Feed Link = ' + entry.GetChildLink('analytics#goals').href print def PrintGoalFeed(self): """Requests and prints the important data in the Goal Feed. Note: There are two types of goals, destination and engagement which need to be handled differently. """ goal_query = gdata.analytics.client.GoalQuery( acct_id=ACCOUNT_ID, web_prop_id=WEB_PROPERTY_ID, profile_id=PROFILE_ID) results = self.my_client.GetManagementFeed(goal_query) print '-------- Goal Feed Data --------' if not results.entry: print 'no entries found' else: for entry in results.entry: print 'Goal Number = ' + entry.goal.number print 'Goal Name = ' + entry.goal.name print 'Goal Value = ' + entry.goal.value print 'Goal Active = ' + entry.goal.active if entry.goal.destination: self.PrintDestinationGoal(entry.goal.destination) elif entry.goal.engagement: self.PrintEngagementGoal(entry.goal.engagement) def PrintDestinationGoal(self, destination): """Prints the important information for destination goals including all the configured steps if they exist. Args: destination: gdata.data.Destination The destination goal configuration. """ print '\t----- Destination Goal -----' print '\tExpression = ' + destination.expression print '\tMatch Type = ' + destination.match_type print '\tStep 1 Required = ' + destination.step1_required print '\tCase Sensitive = ' + destination.case_sensitive if destination.step: print '\t\t----- Destination Goal Steps -----' for step in destination.step: print '\t\tStep Number = ' + step.number print '\t\tStep Name = ' + step.name print '\t\tStep Path = ' + step.path print def PrintEngagementGoal(self, engagement): """Prints the important information for engagement goals. Args: engagement: gdata.data.Engagement The engagement goal configuration. """ print '\t----- Engagement Goal -----' print '\tGoal Type = ' + engagement.type print '\tGoal Engagement = ' + engagement.comparison print '\tGoal Threshold = ' + engagement.threshold_value print def PrintSegmentFeed(self): """Requests and prints the important data in the Profile Feed.""" adv_seg_query = gdata.analytics.client.AdvSegQuery() results = self.my_client.GetManagementFeed(adv_seg_query) print '-------- Advanced Segment Feed Data --------' if not results.entry: print 'no entries found' else: for entry in results.entry: print 'Segment ID = ' + entry.segment.id print 'Segment Name = ' + entry.segment.name print 'Segment Definition = ' + entry.segment.definition.text print if __name__ == '__main__': main()
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. __author__ = 'api.rboyd@gmail.com (Ryan Boyd)' try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import gdata.calendar.data import gdata.calendar.client import gdata.acl.data import atom import getopt import sys import string import time class CalendarExample: def __init__(self, email, password): """Creates a CalendarService and provides ClientLogin auth details to it. The email and password are required arguments for ClientLogin. The CalendarService automatically sets the service to be 'cl', as is appropriate for calendar. The 'source' defined below is an arbitrary string, but should be used to reference your name or the name of your organization, the app name and version, with '-' between each of the three values. The account_type is specified to authenticate either Google Accounts or Google Apps accounts. See gdata.service or http://code.google.com/apis/accounts/AuthForInstalledApps.html for more info on ClientLogin. NOTE: ClientLogin should only be used for installed applications and not for multi-user web applications.""" self.cal_client = gdata.calendar.client.CalendarClient(source='Google-Calendar_Python_Sample-1.0') self.cal_client.ClientLogin(email, password, self.cal_client.source); def _PrintUserCalendars(self): """Retrieves the list of calendars to which the authenticated user either owns or subscribes to. This is the same list as is represented in the Google Calendar GUI. Although we are only printing the title of the calendar in this case, other information, including the color of the calendar, the timezone, and more. See CalendarListEntry for more details on available attributes.""" feed = self.cal_client.GetAllCalendarsFeed() print 'Printing allcalendars: %s' % feed.title.text for i, a_calendar in zip(xrange(len(feed.entry)), feed.entry): print '\t%s. %s' % (i, a_calendar.title.text,) def _PrintOwnCalendars(self): """Retrieves the list of calendars to which the authenticated user owns -- Although we are only printing the title of the calendar in this case, other information, including the color of the calendar, the timezone, and more. See CalendarListEntry for more details on available attributes.""" feed = self.cal_client.GetOwnCalendarsFeed() print 'Printing owncalendars: %s' % feed.title.text for i, a_calendar in zip(xrange(len(feed.entry)), feed.entry): print '\t%s. %s' % (i, a_calendar.title.text,) def _PrintAllEventsOnDefaultCalendar(self): """Retrieves all events on the primary calendar for the authenticated user. In reality, the server limits the result set intially returned. You can use the max_results query parameter to allow the server to send additional results back (see query parameter use in DateRangeQuery for more info). Additionally, you can page through the results returned by using the feed.GetNextLink().href value to get the location of the next set of results.""" feed = self.cal_client.GetCalendarEventFeed() print 'Events on Primary Calendar: %s' % (feed.title.text,) for i, an_event in zip(xrange(len(feed.entry)), feed.entry): print '\t%s. %s' % (i, an_event.title.text,) for p, a_participant in zip(xrange(len(an_event.who)), an_event.who): print '\t\t%s. %s' % (p, a_participant.email,) print '\t\t\t%s' % (a_participant.value,) if a_participant.attendee_status: print '\t\t\t%s' % (a_participant.attendee_status.value,) def _FullTextQuery(self, text_query='Tennis'): """Retrieves events from the calendar which match the specified full-text query. The full-text query searches the title and content of an event, but it does not search the value of extended properties at the time of this writing. It uses the default (primary) calendar of the authenticated user and uses the private visibility/full projection feed. Please see: http://code.google.com/apis/calendar/reference.html#Feeds for more information on the feed types. Note: as we're not specifying any query parameters other than the full-text query, recurring events returned will not have gd:when elements in the response. Please see the Google Calendar API query paramters reference for more info: http://code.google.com/apis/calendar/reference.html#Parameters""" print 'Full text query for events on Primary Calendar: \'%s\'' % ( text_query,) query = gdata.calendar.client.CalendarEventQuery(text_query=text_query) feed = self.cal_client.GetCalendarEventFeed(q=query) for i, an_event in zip(xrange(len(feed.entry)), feed.entry): print '\t%s. %s' % (i, an_event.title.text,) print '\t\t%s. %s' % (i, an_event.content.text,) for a_when in an_event.when: print '\t\tStart time: %s' % (a_when.start,) print '\t\tEnd time: %s' % (a_when.end,) def _DateRangeQuery(self, start_date='2007-01-01', end_date='2007-07-01'): """Retrieves events from the server which occur during the specified date range. This uses the CalendarEventQuery class to generate the URL which is used to retrieve the feed. For more information on valid query parameters, see: http://code.google.com/apis/calendar/reference.html#Parameters""" print 'Date range query for events on Primary Calendar: %s to %s' % ( start_date, end_date,) query = gdata.calendar.client.CalendarEventQuery(start_min=start_date, start_max=end_date) feed = self.cal_client.GetCalendarEventFeed(q=query) for i, an_event in zip(xrange(len(feed.entry)), feed.entry): print '\t%s. %s' % (i, an_event.title.text,) for a_when in an_event.when: print '\t\tStart time: %s' % (a_when.start,) print '\t\tEnd time: %s' % (a_when.end,) def _InsertCalendar(self, title='Little League Schedule', description='This calendar contains practice and game times', time_zone='America/Los_Angeles', hidden=False, location='Oakland', color='#2952A3'): """Creates a new calendar using the specified data.""" print 'Creating new calendar with title "%s"' % title calendar = gdata.calendar.data.CalendarEntry() calendar.title = atom.data.Title(text=title) calendar.summary = atom.data.Summary(text=description) calendar.where.append(gdata.calendar.data.CalendarWhere(value=location)) calendar.color = gdata.calendar.data.ColorProperty(value=color) calendar.timezone = gdata.calendar.data.TimeZoneProperty(value=time_zone) if hidden: calendar.hidden = gdata.calendar.data.HiddenProperty(value='true') else: calendar.hidden = gdata.calendar.data.HiddenProperty(value='false') new_calendar = self.cal_client.InsertCalendar(new_calendar=calendar) return new_calendar def _UpdateCalendar(self, calendar, title='New Title', color=None): """Updates the title and, optionally, the color of the supplied calendar""" print 'Updating the calendar titled "%s" with the title "%s"' % ( calendar.title.text, title) calendar.title = atom.data.Title(text=title) if color is not None: calendar.color = gdata.calendar.data.ColorProperty(value=color) updated_calendar = self.cal_client.Update(calendar) return updated_calendar def _DeleteAllCalendars(self): """Deletes all calendars. Note: the primary calendar cannot be deleted""" feed = self.cal_client.GetOwnCalendarsFeed() for entry in feed.entry: print 'Deleting calendar: %s' % entry.title.text try: self.cal_client.Delete(entry.GetEditLink().href) except gdata.client.RequestError, msg: if msg.body.startswith('Cannot remove primary calendar'): print '\t%s' % msg.body else: print '\tUnexpected Error: %s' % msg.body def _InsertSubscription(self, id='python.gcal.test%40gmail.com'): """Subscribes to the calendar with the specified ID.""" print 'Subscribing to the calendar with ID: %s' % id calendar = gdata.calendar.data.CalendarEntry() calendar.id = atom.data.Id(text=id) returned_calendar = self.cal_client.InsertCalendarSubscription(calendar) return returned_calendar def _UpdateCalendarSubscription(self, id='python.gcal.test%40gmail.com', color=None, hidden=None, selected=None): """Updates the subscription to the calendar with the specified ID.""" print 'Updating the calendar subscription with ID: %s' % id calendar_url = ( 'http://www.google.com/calendar/feeds/default/allcalendars/full/%s' % id) calendar_entry = self.cal_client.GetCalendarEntry(calendar_url) if color is not None: calendar_entry.color = gdata.calendar.data.ColorProperty(value=color) if hidden is not None: if hidden: calendar_entry.hidden = gdata.calendar.data.HiddenProperty(value='true') else: calendar_entry.hidden = gdata.calendar.data.HiddenProperty(value='false') if selected is not None: if selected: calendar_entry.selected = gdata.calendar.data.SelectedProperty(value='true') else: calendar_entry.selected = gdata.calendar.data.SelectedProperty(value='false') updated_calendar = self.cal_client.Update(calendar_entry) return updated_calendar def _DeleteCalendarSubscription(self, id='python.gcal.test%40gmail.com'): """Deletes the subscription to the calendar with the specified ID.""" print 'Deleting the calendar subscription with ID: %s' % id calendar_url = ( 'http://www.google.com/calendar/feeds/default/allcalendars/full/%s' % id) calendar_entry = self.cal_client.GetCalendarEntry(calendar_url) self.cal_client.Delete(calendar_entry.GetEditLink().href) def _InsertEvent(self, title='Tennis with Beth', content='Meet for a quick lesson', where='On the courts', start_time=None, end_time=None, recurrence_data=None): """Inserts a basic event using either start_time/end_time definitions or gd:recurrence RFC2445 icalendar syntax. Specifying both types of dates is not valid. Note how some members of the CalendarEventEntry class use arrays and others do not. Members which are allowed to occur more than once in the calendar or GData "kinds" specifications are stored as arrays. Even for these elements, Google Calendar may limit the number stored to 1. The general motto to use when working with the Calendar data API is that functionality not available through the GUI will not be available through the API. Please see the GData Event "kind" document: http://code.google.com/apis/gdata/elements.html#gdEventKind for more information""" event = gdata.calendar.data.CalendarEventEntry() event.title = atom.data.Title(text=title) event.content = atom.data.Content(text=content) event.where.append(gdata.data.Where(value=where)) if recurrence_data is not None: # Set a recurring event event.recurrence = gdata.data.Recurrence(text=recurrence_data) else: if start_time is None: # Use current time for the start_time and have the event last 1 hour start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime()) end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + 3600)) event.when.append(gdata.data.When(start=start_time, end=end_time)) new_event = self.cal_client.InsertEvent(event) return new_event def _InsertSingleEvent(self, title='One-time Tennis with Beth', content='Meet for a quick lesson', where='On the courts', start_time=None, end_time=None): """Uses the _InsertEvent helper method to insert a single event which does not have any recurrence syntax specified.""" new_event = self._InsertEvent(title, content, where, start_time, end_time, recurrence_data=None) print 'New single event inserted: %s' % (new_event.id.text,) print '\tEvent edit URL: %s' % (new_event.GetEditLink().href,) print '\tEvent HTML URL: %s' % (new_event.GetHtmlLink().href,) return new_event def _InsertRecurringEvent(self, title='Weekly Tennis with Beth', content='Meet for a quick lesson', where='On the courts', recurrence_data=None): """Uses the _InsertEvent helper method to insert a recurring event which has only RFC2445 icalendar recurrence syntax specified. Note the use of carriage return/newline pairs at the end of each line in the syntax. Even when specifying times (as opposed to only dates), VTIMEZONE syntax is not required if you use a standard Java timezone ID. Please see the docs for more information on gd:recurrence syntax: http://code.google.com/apis/gdata/elements.html#gdRecurrence """ if recurrence_data is None: recurrence_data = ('DTSTART;VALUE=DATE:20070501\r\n' + 'DTEND;VALUE=DATE:20070502\r\n' + 'RRULE:FREQ=WEEKLY;BYDAY=Tu;UNTIL=20070904\r\n') new_event = self._InsertEvent(title, content, where, recurrence_data=recurrence_data, start_time=None, end_time=None) print 'New recurring event inserted: %s' % (new_event.id.text,) print '\tEvent edit URL: %s' % (new_event.GetEditLink().href,) print '\tEvent HTML URL: %s' % (new_event.GetHtmlLink().href,) return new_event def _InsertQuickAddEvent(self, content="Tennis with John today 3pm-3:30pm"): """Creates an event with the quick_add property set to true so the content is processed as quick add content instead of as an event description.""" event = gdata.calendar.data.CalendarEventEntry() event.content = atom.data.Content(text=content) event.quick_add = gdata.calendar.data.QuickAddProperty(value='true') new_event = self.cal_client.InsertEvent(event) return new_event def _InsertSimpleWebContentEvent(self): """Creates a WebContent object and embeds it in a WebContentLink. The WebContentLink is appended to the existing list of links in the event entry. Finally, the calendar client inserts the event.""" # Create a WebContent object url = 'http://www.google.com/logos/worldcup06.gif' web_content = gdata.calendar.data.WebContent(url=url, width='276', height='120') # Create a WebContentLink object that contains the WebContent object title = 'World Cup' href = 'http://www.google.com/calendar/images/google-holiday.gif' type = 'image/gif' web_content_link = gdata.calendar.data.WebContentLink(title=title, href=href, link_type=type, web_content=web_content) # Create an event that contains this web content event = gdata.calendar.data.CalendarEventEntry() event.link.append(web_content_link) print 'Inserting Simple Web Content Event' new_event = self.cal_client.InsertEvent(event) return new_event def _InsertWebContentGadgetEvent(self): """Creates a WebContent object and embeds it in a WebContentLink. The WebContentLink is appended to the existing list of links in the event entry. Finally, the calendar client inserts the event. Web content gadget events display Calendar Gadgets inside Google Calendar.""" # Create a WebContent object url = 'http://google.com/ig/modules/datetime.xml' web_content = gdata.calendar.data.WebContent(url=url, width='300', height='136') web_content.web_content_gadget_pref.append( gdata.calendar.data.WebContentGadgetPref(name='color', value='green')) # Create a WebContentLink object that contains the WebContent object title = 'Date and Time Gadget' href = 'http://gdata.ops.demo.googlepages.com/birthdayicon.gif' type = 'application/x-google-gadgets+xml' web_content_link = gdata.calendar.data.WebContentLink(title=title, href=href, link_type=type, web_content=web_content) # Create an event that contains this web content event = gdata.calendar.data.CalendarEventEntry() event.link.append(web_content_link) print 'Inserting Web Content Gadget Event' new_event = self.cal_client.InsertEvent(event) return new_event def _UpdateTitle(self, event, new_title='Updated event title'): """Updates the title of the specified event with the specified new_title. Note that the UpdateEvent method (like InsertEvent) returns the CalendarEventEntry object based upon the data returned from the server after the event is inserted. This represents the 'official' state of the event on the server. The 'edit' link returned in this event can be used for future updates. Due to the use of the 'optimistic concurrency' method of version control, most GData services do not allow you to send multiple update requests using the same edit URL. Please see the docs: http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency """ previous_title = event.title.text event.title.text = new_title print 'Updating title of event from:\'%s\' to:\'%s\'' % ( previous_title, event.title.text,) return self.cal_client.Update(event) def _AddReminder(self, event, minutes=10): """Adds a reminder to the event. This uses the default reminder settings for the user to determine what type of notifications are sent (email, sms, popup, etc.) and sets the reminder for 'minutes' number of minutes before the event. Note: you can only use values for minutes as specified in the Calendar GUI.""" for a_when in event.when: if len(a_when.reminder) > 0: a_when.reminder[0].minutes = minutes else: a_when.reminder.append(gdata.data.Reminder(minutes=str(minutes))) print 'Adding %d minute reminder to event' % (minutes,) return self.cal_client.Update(event) def _AddExtendedProperty(self, event, name='http://www.example.com/schemas/2005#mycal.id', value='1234'): """Adds an arbitrary name/value pair to the event. This value is only exposed through the API. Extended properties can be used to store extra information needed by your application. The recommended format is used as the default arguments above. The use of the URL format is to specify a namespace prefix to avoid collisions between different applications.""" event.extended_property.append( gdata.calendar.data.CalendarExtendedProperty(name=name, value=value)) print 'Adding extended property to event: \'%s\'=\'%s\'' % (name, value,) return self.cal_client.Update(event) def _DeleteEvent(self, event): """Given an event object returned for the calendar server, this method deletes the event. The edit link present in the event is the URL used in the HTTP DELETE request.""" self.cal_client.Delete(event.GetEditLink().href) def _PrintAclFeed(self): """Sends a HTTP GET to the default ACL URL (http://www.google.com/calendar/feeds/default/acl/full) and displays the feed returned in the response.""" feed = self.cal_client.GetCalendarAclFeed() print feed.title.text for i, a_rule in zip(xrange(len(feed.entry)), feed.entry): print '\t%s. %s' % (i, a_rule.title.text,) print '\t\t Role: %s' % (a_rule.role.value,) print '\t\t Scope %s - %s' % (a_rule.scope.type, a_rule.scope.value) def _CreateAclRule(self, username): """Creates a ACL rule that grants the given user permission to view free/busy information on the default calendar. Note: It is not necessary to specify a title for the ACL entry. The server will set this to be the value of the role specified (in this case "freebusy").""" print 'Creating Acl rule for user: %s' % username rule = gdata.calendar.data.CalendarAclEntry() rule.scope = gdata.acl.data.AclScope(value=username, type="user") roleValue = "http://schemas.google.com/gCal/2005#%s" % ("freebusy") rule.role = gdata.acl.data.AclRole(value=roleValue) aclUrl = "https://www.google.com/calendar/feeds/default/acl/full" returned_rule = self.cal_client.InsertAclEntry(rule, aclUrl) def _RetrieveAclRule(self, username): """Builds the aclEntryUri or the entry created in the previous example. The sends a HTTP GET message and displays the entry returned in the response.""" aclEntryUri = "http://www.google.com/calendar/feeds/" aclEntryUri += "default/acl/full/user:%s" % (username) entry = self.cal_client.GetCalendarAclEntry(aclEntryUri) print '\t%s' % (entry.title.text,) print '\t\t Role: %s' % (entry.role.value,) print '\t\t Scope %s - %s' % (entry.scope.type, entry.scope.value) return entry def _UpdateAclRule(self, entry): """Modifies the value of the role in the given entry and POSTs the updated entry. Note that while the role of an ACL entry can be updated, the scope can not be modified.""" print 'Update Acl rule: %s' % (entry.GetEditLink().href) roleValue = "http://schemas.google.com/gCal/2005#%s" % ("read") entry.role = gdata.acl.data.AclRole(value=roleValue) returned_rule = self.cal_client.Update(entry) def _DeleteAclRule(self, entry): """Given an ACL entry returned for the calendar server, this method deletes the entry. The edit link present in the entry is the URL used in the HTTP DELETE request.""" self.cal_client.Delete(entry.GetEditLink().href) def _batchRequest(self, updateEntry, deleteEntry): """Execute a batch request to create, update and delete an entry.""" print 'Executing batch request to insert, update and delete entries.' # feed that holds all the batch rquest entries request_feed = gdata.calendar.data.CalendarEventFeed() # creating an event entry to insert insertEntry = gdata.calendar.data.CalendarEventEntry() insertEntry.title = atom.data.Title(text='Python: batch insert') insertEntry.content = atom.data.Content(text='my content') start_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime()) end_time = time.strftime('%Y-%m-%dT%H:%M:%S.000Z', time.gmtime(time.time() + 3600)) insertEntry.when.append(gdata.calendar.data.When(start=start_time, end=end_time)) insertEntry.batch_id = gdata.data.BatchId(text='insert-request') # add the insert entry to the batch feed request_feed.AddInsert(entry=insertEntry) if updateEntry: updateEntry.batch_id = gdata.data.BatchId(text='update-request') updateEntry.title = atom.data.Title(text='Python: batch update') # add the update entry to the batch feed request_feed.AddUpdate(entry=updateEntry) if deleteEntry: deleteEntry.batch_id = gdata.data.BatchId(text='delete-request') # add the delete entry to the batch feed request_feed.AddDelete(entry=deleteEntry) # submit the batch request to the server response_feed = self.cal_client.ExecuteBatch(request_feed, gdata.calendar.client.DEFAULT_BATCH_URL) # iterate the response feed to get the operation status for entry in response_feed.entry: print '\tbatch id: %s' % (entry.batch_id.text,) print '\tstatus: %s' % (entry.batch_status.code,) print '\treason: %s' % (entry.batch_status.reason,) if entry.batch_id.text == 'insert-request': insertEntry = entry elif entry.batch_id.text == 'update-request': updateEntry = entry return (insertEntry, updateEntry) def Run(self, delete='false'): """Runs each of the example methods defined above. Note how the result of the _InsertSingleEvent call is used for updating the title and the result of updating the title is used for inserting the reminder and again with the insertion of the extended property. This is due to the Calendar's use of GData's optimistic concurrency versioning control system: http://code.google.com/apis/gdata/reference.html#Optimistic-concurrency """ # Getting feeds and query results self._PrintUserCalendars() self._PrintOwnCalendars() self._PrintAllEventsOnDefaultCalendar() self._FullTextQuery() self._DateRangeQuery() # Inserting and updating events see = self._InsertSingleEvent() see_u_title = self._UpdateTitle(see, 'New title for single event') see_u_reminder = self._AddReminder(see_u_title, minutes=30) see_u_ext_prop = self._AddExtendedProperty(see_u_reminder, name='propname', value='propvalue') ree = self._InsertRecurringEvent() simple_web_content_event = self._InsertSimpleWebContentEvent() web_content_gadget_event = self._InsertWebContentGadgetEvent() quick_add_event = self._InsertQuickAddEvent() # Access Control List examples self._PrintAclFeed() self._CreateAclRule("user@gmail.com") entry = self._RetrieveAclRule("user@gmail.com") self._UpdateAclRule(entry) self._DeleteAclRule(entry) # Creating, updating and deleting calendars inserted_calendar = self._InsertCalendar() updated_calendar = self._UpdateCalendar(calendar=inserted_calendar) # Insert Subscription inserted_subscription = self._InsertSubscription() updated_subscription = self._UpdateCalendarSubscription(selected=False) # Execute a batch request (quick_add_event, see_u_ext_prop) = self._batchRequest(see_u_ext_prop, quick_add_event) # Delete entries if delete argument='true' if delete == 'true': print 'Deleting created events' self.cal_client.Delete(see_u_ext_prop) self.cal_client.Delete(ree) self.cal_client.Delete(simple_web_content_event) self.cal_client.Delete(web_content_gadget_event) self.cal_client.Delete(quick_add_event) print 'Deleting subscriptions' self._DeleteCalendarSubscription() print 'Deleting all calendars' self._DeleteAllCalendars() def main(): """Runs the CalendarExample application with the provided username and and password values. Authentication credentials are required. NOTE: It is recommended that you run this sample using a test account.""" # parse command line options try: opts, args = getopt.getopt(sys.argv[1:], "", ["user=", "pw=", "delete="]) except getopt.error, msg: print ('python calendarExample.py --user [username] --pw [password] ' + '--delete [true|false] ') sys.exit(2) user = '' pw = '' delete = 'false' # Process options for o, a in opts: if o == "--user": user = a elif o == "--pw": pw = a elif o == "--delete": delete = a if user == '' or pw == '': print ('python calendarExample.py --user [username] --pw [password] ' + '--delete [true|false] ') sys.exit(2) sample = CalendarExample(user, pw) sample.Run(delete) if __name__ == '__main__': main()
Python
#!/usr/bin/python # # 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. """Sample to demonstrate using secure AuthSub in the Google Data Python client. This sample focuses on the Google Health Data API because it requires the use of secure tokens. This samples makes queries against the H9 Developer's Sandbox (https://www.google.com/h9). To run this sample: 1.) Use Apache's mod_python 2.) Run from your local webserver (e.g. http://localhost/...) 3.) You need to have entered medication data into H9 HealthAubSubHelper: Class to handle secure AuthSub tokens. GetMedicationHTML: Returns the user's medication formatted in HTML. index: Main entry point for the web app. """ __author__ = 'e.bidelman@google.com (Eric Bidelman)' import os import sys import urllib import gdata.auth import gdata.service H9_PROFILE_FEED_URL = 'https://www.google.com/h9/feeds/profile/default' class HealthAuthSubHelper(object): """A secure AuthSub helper to interact with the Google Health Data API""" H9_AUTHSUB_HANDLER = 'https://www.google.com/h9/authsub' H9_SCOPE = 'https://www.google.com/h9/feeds/' def GetNextUrl(self, req): """Computes the current URL the web app is running from. Args: req: mod_python mp_request instance to build the URL from. Returns: A string representing the web app's URL. """ if req.is_https(): next_url = 'https://' else: next_url = 'http://' next_url += req.hostname + req.unparsed_uri return next_url def GenerateAuthSubRequestUrl(self, next, scopes=[H9_SCOPE], secure=True, session=True, extra_params=None, include_scopes_in_next=True): """Constructs the URL to the AuthSub token handler. Args: next: string The URL AuthSub will redirect back to. Use self.GetNextUrl() to return that URL. scopes: (optional) string or list of scopes the token will be valid for. secure: (optional) boolean True if the token should be a secure one session: (optional) boolean True if the token will be exchanged for a session token. extra_params: (optional) dict of additional parameters to pass to AuthSub. include_scopes_in_next: (optional) boolean True if the scopes in the scopes should be passed to AuthSub. Returns: A string (as a URL) to use for the AuthSubRequest endpoint. """ auth_sub_url = gdata.service.GenerateAuthSubRequestUrl( next, scopes, hd='default', secure=secure, session=session, request_url=self.H9_AUTHSUB_HANDLER, include_scopes_in_next=include_scopes_in_next) if extra_params: auth_sub_url = '%s&%s' % (auth_sub_url, urllib.urlencode(extra_params)) return auth_sub_url def SetPrivateKey(self, filename): """Reads the private key from the specified file. See http://code.google.com/apis/gdata/authsub.html#Registered for\ information on how to create a RSA private key/public cert pair. Args: filename: string .pem file the key is stored in. Returns: The private key as a string. Raises: IOError: The file could not be read or does not exist. """ try: f = open(filename) rsa_private_key = f.read() f.close() except IOError, (errno, strerror): raise 'I/O error(%s): %s' % (errno, strerror) self.rsa_key = rsa_private_key return rsa_private_key def GetMedicationHTML(feed): """Prints out the user's medication to the console. Args: feed: A gdata.GDataFeed instance. Returns: An HTML formatted string containing the user's medication data. """ if not feed.entry: return '<b>No entries in feed</b><br>' html = [] for entry in feed.entry: try: ccr = entry.FindExtensions('ContinuityOfCareRecord')[0] body = ccr.FindChildren('Body')[0] meds = body.FindChildren('Medications')[0].FindChildren('Medication') for med in meds: name = med.FindChildren('Product')[0].FindChildren('ProductName')[0] html.append('<li>%s</li>' % name.FindChildren('Text')[0].text) except: html.append('<b>No medication data in this profile</b><br>') return '<ul>%s</ul>' % ''.join(html) def index(req): req.content_type = 'text/html' authsub = HealthAuthSubHelper() client = gdata.service.GDataService(service='weaver') current_url = authsub.GetNextUrl(req) rsa_key = authsub.SetPrivateKey('/path/to/yourRSAPrivateKey.pem') # Strip token query parameter's value from URL if it exists token = gdata.auth.extract_auth_sub_token_from_url(current_url, rsa_key=rsa_key) if not token: """STEP 1: No single use token in the URL or a saved session token. Generate the AuthSub URL to fetch a single use token.""" params = {'permission': 1} authsub_url = authsub.GenerateAuthSubRequestUrl(current_url, extra_params=params) req.write('<a href="%s">Link your Google Health Profile</a>' % authsub_url) else: """STEP 2: A single use token was extracted from the URL. Upgrade the one time token to a session token.""" req.write('<b>Single use token</b>: %s<br>' % str(token)) client.UpgradeToSessionToken(token) # calls gdata.service.SetAuthSubToken() """STEP 3: Done with AuthSub :) Save the token for subsequent requests. Query the Health Data API""" req.write('<b>Token info</b>: %s<br>' % client.AuthSubTokenInfo()) req.write('<b>Session token</b>: %s<br>' % client.GetAuthSubToken()) # Query the Health Data API params = {'digest': 'true', 'strict': 'true'} uri = '%s?%s' % (H9_PROFILE_FEED_URL, urllib.urlencode(params)) feed = client.GetFeed(uri) req.write('<h4>Listing medications</h4>') req.write(GetMedicationHTML(feed)) """STEP 4: Revoke the session token.""" req.write('Revoked session token') client.RevokeAuthSubToken()
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. __author__ = 'j.s@google.com (Jeff Scudder)' import os import wsgiref.handlers from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp import template from google.appengine.ext.webapp.util import run_wsgi_app import gdata.gauth import gdata.data import gdata.blogger.client def get_auth_token(request): """Retrieves the AuthSub token for the current user. Will first check the request URL for a token request parameter indicating that the user has been sent to this page after authorizing the app. Auto-upgrades to a session token. If the token was not in the URL, which will usually be the case, looks for the token in the datastore. Returns: The token object if one was found for the current user. If there is no current user, it returns False, if there is a current user but no AuthSub token, it returns None. """ current_user = users.get_current_user() if current_user is None or current_user.user_id() is None: return False # Look for the token string in the current page's URL. token_string, token_scopes = gdata.gauth.auth_sub_string_from_url( request.url) if token_string is None: # Try to find a previously obtained session token. return gdata.gauth.ae_load('blogger' + current_user.user_id()) # If there was a new token in the current page's URL, convert it to # to a long lived session token and persist it to be used in future # requests. single_use_token = gdata.gauth.AuthSubToken(token_string, token_scopes) # Create a client to make the HTTP request to upgrade the single use token # to a long lived session token. client = gdata.client.GDClient() session_token = client.upgrade_token(single_use_token) gdata.gauth.ae_save(session_token, 'blogger' + current_user.user_id()) return session_token class ListBlogs(webapp.RequestHandler): """Requests the list of the user's blogs from the Blogger API.""" def get(self): template_values = { 'sign_out': users.create_logout_url('/') } # See if we have an auth token for this user. token = get_auth_token(self.request) if token is None: template_values['auth_url'] = gdata.gauth.generate_auth_sub_url( self.request.url, ['http://www.blogger.com/feeds/']) path = os.path.join(os.path.dirname(__file__), 'auth_required.html') self.response.out.write(template.render(path, template_values)) return elif token == False: self.response.out.write( '<html><body><a href="%s">You must sign in first</a>' '</body></html>' % users.create_login_url('/blogs')) return client = gdata.blogger.client.BloggerClient() feed = client.get_blogs(auth_token=token) template_values['feed'] = feed path = os.path.join(os.path.dirname(__file__), 'list_blogs.html') self.response.out.write(template.render(path, template_values)) class WritePost(webapp.RequestHandler): def get(self): template_values = { 'sign_out': users.create_logout_url('/'), 'blog_id': self.request.get('id') } # We should have an auth token for this user. token = get_auth_token(self.request) if not token: self.redirect('/blogs') return path = os.path.join(os.path.dirname(__file__), 'post_editor.html') self.response.out.write(template.render(path, template_values)) def post(self): token = get_auth_token(self.request) if not token: self.redirect('/blogs') return draft = False if self.request.get('draft') == 'true': draft = True client = gdata.blogger.client.BloggerClient() new_post = client.add_post( self.request.get('blog_id'), self.request.get('title'), self.request.get('body'), draft=draft, auth_token=token) if not draft: self.response.out.write( 'See your new post <a href="%s">here</a>.' % ( new_post.find_alternate_link())) else: self.response.out.write( 'This was a draft blog post, visit ' '<a href="http://blogger.com/">blogger.com</a> to publish') def main(): application = webapp.WSGIApplication([('/blogs', ListBlogs), ('/write_post', WritePost)], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main()
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. # This file demonstrates how to use the Google Data API's Python client library # to interface with the Blogger service. There are examples for the following # operations: # # * Retrieving the list of all the user's blogs # * Retrieving all posts on a single blog # * Performing a date-range query for posts on a blog # * Creating draft posts and publishing posts # * Updating posts # * Retrieving comments # * Creating comments # * Deleting comments # * Deleting posts __author__ = 'lkeppler@google.com (Luke Keppler)' import gdata.blogger.client import gdata.client import gdata.sample_util import gdata.data import atom.data class BloggerExample: def __init__(self): """Creates a GDataService and provides ClientLogin auth details to it. The email and password are required arguments for ClientLogin. The 'source' defined below is an arbitrary string, but should be used to reference your name or the name of your organization, the app name and version, with '-' between each of the three values.""" # Authenticate using ClientLogin, AuthSub, or OAuth. self.client = gdata.blogger.client.BloggerClient() gdata.sample_util.authorize_client( self.client, service='blogger', source='Blogger_Python_Sample-2.0', scopes=['http://www.blogger.com/feeds/']) # Get the blog ID for the first blog. feed = self.client.get_blogs() self.blog_id = feed.entry[0].get_blog_id() def PrintUserBlogTitles(self): """Prints a list of all the user's blogs.""" # Request the feed. feed = self.client.get_blogs() # Print the results. print feed.title.text for entry in feed.entry: print "\t" + entry.title.text print def CreatePost(self, title, content, is_draft): """This method creates a new post on a blog. The new post can be stored as a draft or published based on the value of the is_draft parameter. The method creates an GDataEntry for the new post using the title, content, author_name and is_draft parameters. With is_draft, True saves the post as a draft, while False publishes the post. Then it uses the given GDataService to insert the new post. If the insertion is successful, the added post (GDataEntry) will be returned. """ return self.client.add_post(self.blog_id, title, content, draft=is_draft) def PrintAllPosts(self): """This method displays the titles of all the posts in a blog. First it requests the posts feed for the blogs and then it prints the results. """ # Request the feed. feed = self.client.get_posts(self.blog_id) # Print the results. print feed.title.text for entry in feed.entry: if not entry.title.text: print "\tNo Title" else: print "\t" + entry.title.text.encode('utf-8') print def PrintPostsInDateRange(self, start_time, end_time): """This method displays the title and modification time for any posts that have been created or updated in the period between the start_time and end_time parameters. The method creates the query, submits it to the GDataService, and then displays the results. Note that while the start_time is inclusive, the end_time is exclusive, so specifying an end_time of '2007-07-01' will include those posts up until 2007-6-30 11:59:59PM. The start_time specifies the beginning of the search period (inclusive), while end_time specifies the end of the search period (exclusive). """ # Create query and submit a request. query = gdata.blogger.client.Query(updated_min=start_time, updated_max=end_time, order_by='updated') print query.updated_min print query.order_by feed = self.client.get_posts(self.blog_id, query=query) # Print the results. print feed.title.text + " posts between " + start_time + " and " + end_time print feed.title.text for entry in feed.entry: if not entry.title.text: print "\tNo Title" else: print "\t" + entry.title.text print def UpdatePostTitle(self, entry_to_update, new_title): """This method updates the title of the given post. The GDataEntry object is updated with the new title, then a request is sent to the GDataService. If the insertion is successful, the updated post will be returned. Note that other characteristics of the post can also be modified by updating the values of the entry object before submitting the request. The entry_to_update is a GDatEntry containing the post to update. The new_title is the text to use for the post's new title. Returns: a GDataEntry containing the newly-updated post. """ # Set the new title in the Entry object entry_to_update.title = atom.data.Title(type='xhtml', text=new_title) return self.client.update(entry_to_update) def CreateComment(self, post_id, comment_text): """This method adds a comment to the specified post. First the comment feed's URI is built using the given post ID. Then a GDataEntry is created for the comment and submitted to the GDataService. The post_id is the ID of the post on which to post comments. The comment_text is the text of the comment to store. Returns: an entry containing the newly-created comment NOTE: This functionality is not officially supported yet. """ return self.client.add_comment(self.blog_id, post_id, comment_text) def PrintAllComments(self, post_id): """This method displays all the comments for the given post. First the comment feed's URI is built using the given post ID. Then the method requests the comments feed and displays the results. Takes the post_id of the post on which to view comments. """ feed = self.client.get_post_comments(self.blog_id, post_id) # Display the results print feed.title.text for entry in feed.entry: print "\t" + entry.title.text print "\t" + entry.updated.text print def DeleteComment(self, comment_entry): """This method removes the comment specified by the given edit_link_href, the URI for editing the comment. """ self.client.delete(comment_entry) def DeletePost(self, post_entry): """This method removes the post specified by the given edit_link_href, the URI for editing the post. """ self.client.delete(post_entry) def run(self): """Runs each of the example methods defined above, demonstrating how to interface with the Blogger service. """ # Demonstrate retrieving a list of the user's blogs. self.PrintUserBlogTitles() # Demonstrate how to create a draft post. draft_post = self.CreatePost('Snorkling in Aruba', '<p>We had <b>so</b> much fun snorkling in Aruba<p>', True) print 'Successfully created draft post: "' + draft_post.title.text + '".\n' # Delete the draft blog post. self.client.delete(draft_post) # Demonstrate how to publish a public post. public_post = self.CreatePost("Back from vacation", "<p>I didn't want to leave Aruba, but I ran out of money :(<p>", False) print "Successfully created public post: \"" + public_post.title.text + "\".\n" # Demonstrate various feed queries. print "Now listing all posts." self.PrintAllPosts() print "Now listing all posts between 2007-04-04 and 2007-04-23." self.PrintPostsInDateRange("2007-04-04", "2007-04-23") # Demonstrate updating a post's title. print "Now updating the title of the post we just created:" public_post = self.UpdatePostTitle(public_post, "The party's over") print "Successfully changed the post's title to \"" + public_post.title.text + "\".\n" # Demonstrate how to retrieve the comments for a post. # Get the post ID and build the comments feed URI for the specified post post_id = public_post.get_post_id() print "Now posting a comment on the post titled: \"" + public_post.title.text + "\"." comment = self.CreateComment(post_id, "Did you see any sharks?") print "Successfully posted \"" + comment.content.text + "\" on the post titled: \"" + public_post.title.text + "\".\n" comment_id = comment.GetCommentId() print "Now printing all comments" self.PrintAllComments(post_id) # Delete the comment we just posted print "Now deleting the comment we just posted" self.DeleteComment(comment) print "Successfully deleted comment." self.PrintAllComments(post_id) # Demonstrate deleting posts. print "Now deleting the post titled: \"" + public_post.title.text + "\"." self.DeletePost(public_post) print "Successfully deleted post." self.PrintAllPosts() def main(): """The main function runs the BloggerExample application. NOTE: It is recommended that you run this sample using a test account. """ sample = BloggerExample() sample.run() if __name__ == '__main__': main()
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This file demonstrates how to use the Google Data API's Python client library # to interface with the Blogger service. There are examples for the following # operations: # # * Retrieving the list of all the user's blogs # * Retrieving all posts on a single blog # * Performing a date-range query for posts on a blog # * Creating draft posts and publishing posts # * Updating posts # * Retrieving comments # * Creating comments # * Deleting comments # * Deleting posts __author__ = 'lkeppler@google.com (Luke Keppler)' from gdata import service import gdata import atom import getopt import sys class BloggerExample: def __init__(self, email, password): """Creates a GDataService and provides ClientLogin auth details to it. The email and password are required arguments for ClientLogin. The 'source' defined below is an arbitrary string, but should be used to reference your name or the name of your organization, the app name and version, with '-' between each of the three values.""" # Authenticate using ClientLogin. self.service = service.GDataService(email, password) self.service.source = 'Blogger_Python_Sample-1.0' self.service.service = 'blogger' self.service.server = 'www.blogger.com' self.service.ProgrammaticLogin() # Get the blog ID for the first blog. feed = self.service.Get('/feeds/default/blogs') self_link = feed.entry[0].GetSelfLink() if self_link: self.blog_id = self_link.href.split('/')[-1] def PrintUserBlogTitles(self): """Prints a list of all the user's blogs.""" # Request the feed. query = service.Query() query.feed = '/feeds/default/blogs' feed = self.service.Get(query.ToUri()) # Print the results. print feed.title.text for entry in feed.entry: print "\t" + entry.title.text print def CreatePost(self, title, content, author_name, is_draft): """This method creates a new post on a blog. The new post can be stored as a draft or published based on the value of the is_draft parameter. The method creates an GDataEntry for the new post using the title, content, author_name and is_draft parameters. With is_draft, True saves the post as a draft, while False publishes the post. Then it uses the given GDataService to insert the new post. If the insertion is successful, the added post (GDataEntry) will be returned. """ # Create the entry to insert. entry = gdata.GDataEntry() entry.author.append(atom.Author(atom.Name(text=author_name))) entry.title = atom.Title(title_type='xhtml', text=title) entry.content = atom.Content(content_type='html', text=content) if is_draft: control = atom.Control() control.draft = atom.Draft(text='yes') entry.control = control # Ask the service to insert the new entry. return self.service.Post(entry, '/feeds/' + self.blog_id + '/posts/default') def PrintAllPosts(self): """This method displays the titles of all the posts in a blog. First it requests the posts feed for the blogs and then it prints the results. """ # Request the feed. feed = self.service.GetFeed('/feeds/' + self.blog_id + '/posts/default') # Print the results. print feed.title.text for entry in feed.entry: if not entry.title.text: print "\tNo Title" else: print "\t" + entry.title.text print def PrintPostsInDateRange(self, start_time, end_time): """This method displays the title and modification time for any posts that have been created or updated in the period between the start_time and end_time parameters. The method creates the query, submits it to the GDataService, and then displays the results. Note that while the start_time is inclusive, the end_time is exclusive, so specifying an end_time of '2007-07-01' will include those posts up until 2007-6-30 11:59:59PM. The start_time specifies the beginning of the search period (inclusive), while end_time specifies the end of the search period (exclusive). """ # Create query and submit a request. query = service.Query() query.feed = '/feeds/' + self.blog_id + '/posts/default' query.updated_min = start_time query.updated_max = end_time query.orderby = 'updated' feed = self.service.Get(query.ToUri()) # Print the results. print feed.title.text + " posts between " + start_time + " and " + end_time print feed.title.text for entry in feed.entry: if not entry.title.text: print "\tNo Title" else: print "\t" + entry.title.text print def UpdatePostTitle(self, entry_to_update, new_title): """This method updates the title of the given post. The GDataEntry object is updated with the new title, then a request is sent to the GDataService. If the insertion is successful, the updated post will be returned. Note that other characteristics of the post can also be modified by updating the values of the entry object before submitting the request. The entry_to_update is a GDatEntry containing the post to update. The new_title is the text to use for the post's new title. Returns: a GDataEntry containing the newly-updated post. """ # Set the new title in the Entry object entry_to_update.title = atom.Title('xhtml', new_title) # Grab the edit URI edit_uri = entry_to_update.GetEditLink().href return self.service.Put(entry_to_update, edit_uri) def CreateComment(self, post_id, comment_text): """This method adds a comment to the specified post. First the comment feed's URI is built using the given post ID. Then a GDataEntry is created for the comment and submitted to the GDataService. The post_id is the ID of the post on which to post comments. The comment_text is the text of the comment to store. Returns: an entry containing the newly-created comment NOTE: This functionality is not officially supported yet. """ # Build the comment feed URI feed_uri = '/feeds/' + self.blog_id + '/' + post_id + '/comments/default' # Create a new entry for the comment and submit it to the GDataService entry = gdata.GDataEntry() entry.content = atom.Content(content_type='xhtml', text=comment_text) return self.service.Post(entry, feed_uri) def PrintAllComments(self, post_id): """This method displays all the comments for the given post. First the comment feed's URI is built using the given post ID. Then the method requests the comments feed and displays the results. Takes the post_id of the post on which to view comments. """ # Build comment feed URI and request comments on the specified post feed_url = '/feeds/' + self.blog_id + '/comments/default' feed = self.service.Get(feed_url) # Display the results print feed.title.text for entry in feed.entry: print "\t" + entry.title.text print "\t" + entry.updated.text print def DeleteComment(self, post_id, comment_id): """This method removes the comment specified by the given edit_link_href, the URI for editing the comment. """ feed_uri = '/feeds/' + self.blog_id + '/' + post_id + '/comments/default/' + comment_id self.service.Delete(feed_uri) def DeletePost(self, edit_link_href): """This method removes the post specified by the given edit_link_href, the URI for editing the post. """ self.service.Delete(edit_link_href) def run(self): """Runs each of the example methods defined above, demonstrating how to interface with the Blogger service. """ # Demonstrate retrieving a list of the user's blogs. self.PrintUserBlogTitles() # Demonstrate how to create a draft post. draft_post = self.CreatePost("Snorkling in Aruba", "<p>We had <b>so</b> much fun snorkling in Aruba<p>", "Post author", True) print "Successfully created draft post: \"" + draft_post.title.text + "\".\n" # Demonstrate how to publish a public post. public_post = self.CreatePost("Back from vacation", "<p>I didn't want to leave Aruba, but I ran out of money :(<p>", "Post author", False) print "Successfully created public post: \"" + public_post.title.text + "\".\n" # Demonstrate various feed queries. print "Now listing all posts." self.PrintAllPosts() print "Now listing all posts between 2007-04-04 and 2007-04-23." self.PrintPostsInDateRange("2007-04-04", "2007-04-23") # Demonstrate updating a post's title. print "Now updating the title of the post we just created:" public_post = self.UpdatePostTitle(public_post, "The party's over") print "Successfully changed the post's title to \"" + public_post.title.text + "\".\n" # Demonstrate how to retrieve the comments for a post. # Get the post ID and build the comments feed URI for the specified post self_id = public_post.id.text tokens = self_id.split("-") post_id = tokens[-1] print "Now posting a comment on the post titled: \"" + public_post.title.text + "\"." comment = self.CreateComment(post_id, "Did you see any sharks?") print "Successfully posted \"" + comment.content.text + "\" on the post titled: \"" + public_post.title.text + "\".\n" comment_id = comment.GetEditLink().href.split("/")[-1] print "Now printing all comments" self.PrintAllComments(post_id) # Delete the comment we just posted print "Now deleting the comment we just posted" self.DeleteComment(post_id, comment_id) print "Successfully deleted comment." self.PrintAllComments(post_id) # Get the post's edit URI edit_uri = public_post.GetEditLink().href # Demonstrate deleting posts. print "Now deleting the post titled: \"" + public_post.title.text + "\"." self.DeletePost(edit_uri) print "Successfully deleted post." self.PrintAllPosts() def main(): """The main function runs the BloggerExample application with the provided username and password values. Authentication credentials are required. NOTE: It is recommended that you run this sample using a test account.""" # parse command line options try: opts, args = getopt.getopt(sys.argv[1:], "", ["email=", "password="]) except getopt.error, msg: print ('python BloggerExample.py --email [email] --password [password] ') sys.exit(2) email = '' password = '' # Process options for o, a in opts: if o == "--email": email = a elif o == "--password": password = a if email == '' or password == '': print ('python BloggerExample.py --email [email] --password [password]') sys.exit(2) sample = BloggerExample(email, password) sample.run() if __name__ == '__main__': main()
Python
__author__ = 'wiktorgworek@google.com (Wiktor Gworek)' import wsgiref.handlers import atom import os import cgi import gdata.blogger.service from oauth import OAuthDanceHandler, OAuthHandler, requiresOAuth from google.appengine.ext import webapp from google.appengine.ext.webapp import template class MainHandler(OAuthHandler): """Main handler. If user is not logged in via OAuth it will display welcome page. In other case user's blogs on Blogger will be displayed.""" def get(self): try: template_values = {'logged': self.client.has_access_token()} if template_values['logged']: feed = self.client.blogger.GetBlogFeed() blogs = [] for entry in feed.entry: blogs.append({ 'id': entry.GetBlogId(), 'title': entry.title.text, 'link': entry.GetHtmlLink().href, 'published': entry.published.text, 'updated': entry.updated.text }) template_values['blogs'] = blogs except gdata.service.RequestError, error: template_values['logged'] = False path = os.path.join(os.path.dirname(__file__), 'index.html') self.response.out.write(template.render(path, template_values)) class NewPostHandler(OAuthHandler): """Handles AJAX POST request to create a new post on a blog.""" @requiresOAuth def post(self): entry = atom.Entry(content=atom.Content(text=self.request.get('body'))) self.client.blogger.AddPost(entry, blog_id=self.request.get('id')) def main(): application = webapp.WSGIApplication([ (r'/oauth/(.*)', OAuthDanceHandler), ('/new_post', NewPostHandler), ('/', MainHandler), ], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main()
Python
"""Provides OAuth authorization. Main components are: * OAuthClient - provides logic for 3-legged OAuth protocol, * OAuthDanceHandler - wrapper for OAuthClient for handling OAuth requests, * OAuthHandler - from this handler should inherit all other handlers that want to be authenticated and have access to BloggerService. Be sure that you added @requiredOAuth on top of your request method (i.e. post, get). Request tokens are stored in OAuthRequestToken (explicite) and access tokens are stored in TokenCollection (implicit) provided by gdata.alt.appengine. Heavily used resources and ideas from: * http://github.com/tav/tweetapp, * Examples of OAuth from GData Python Client written by Eric Bidelman. """ __author__ = ('wiktorgworek (Wiktor Gworek), ' 'e.bidelman (Eric Bidelman)') import os import gdata.auth import gdata.client import gdata.alt.appengine import gdata.blogger.service from google.appengine.api import users from google.appengine.ext import db from google.appengine.ext import webapp from google.appengine.ext.webapp import template SETTINGS = { 'APP_NAME': 'YOUR_APPLICATION_NAME', 'CONSUMER_KEY': 'YOUR_CONSUMER_KEY', 'CONSUMER_SECRET': 'YOUR_CONSUMER_SECRET', 'SIG_METHOD': gdata.auth.OAuthSignatureMethod.HMAC_SHA1, 'SCOPES': gdata.service.CLIENT_LOGIN_SCOPES['blogger'] } # ------------------------------------------------------------------------------ # Data store models. # ------------------------------------------------------------------------------ class OAuthRequestToken(db.Model): """Stores OAuth request token.""" token_key = db.StringProperty(required=True) token_secret = db.StringProperty(required=True) created = db.DateTimeProperty(auto_now_add=True) # ------------------------------------------------------------------------------ # OAuth client. # ------------------------------------------------------------------------------ class OAuthClient(object): __public__ = ('request_token', 'callback', 'revoke_token') def __init__(self, handler): self.handler = handler self.blogger = gdata.blogger.service.BloggerService( source=SETTINGS['APP_NAME']) self.blogger.SetOAuthInputParameters(SETTINGS['SIG_METHOD'], SETTINGS['CONSUMER_KEY'], consumer_secret=SETTINGS['CONSUMER_SECRET']) gdata.alt.appengine.run_on_appengine(self.blogger) def has_access_token(self): """Checks if there is an access token in token store.""" access_token = self.blogger.token_store.find_token( '%20'.join(SETTINGS['SCOPES'])) return isinstance(access_token, gdata.auth.OAuthToken) def request_token(self): """Fetches a request token and redirects the user to the approval page.""" if users.get_current_user(): # 1.) REQUEST TOKEN STEP. Provide the data scope(s) and the page we'll # be redirected back to after the user grants access on the approval page. req_token = self.blogger.FetchOAuthRequestToken( scopes=SETTINGS['SCOPES'], oauth_callback=self.handler.request.uri.replace( 'request_token', 'callback')) # When using HMAC, persist the token secret in order to re-create an # OAuthToken object coming back from the approval page. db_token = OAuthRequestToken(token_key = req_token.key, token_secret=req_token.secret) db_token.put() # 2.) APPROVAL STEP. Redirect to user to Google's OAuth approval page. self.handler.redirect(self.blogger.GenerateOAuthAuthorizationURL()) def callback(self): """Invoked after we're redirected back from the approval page.""" oauth_token = gdata.auth.OAuthTokenFromUrl(self.handler.request.uri) if oauth_token: # Find request token saved by put() method. db_token = OAuthRequestToken.all().filter( 'token_key =', oauth_token.key).fetch(1)[0] oauth_token.secret = db_token.token_secret oauth_token.oauth_input_params = self.blogger.GetOAuthInputParameters() self.blogger.SetOAuthToken(oauth_token) # 3.) Exchange the authorized request token for an access token oauth_verifier = self.handler.request.get( 'oauth_verifier', default_value='') access_token = self.blogger.UpgradeToOAuthAccessToken( oauth_verifier=oauth_verifier) # Remember the access token in the current user's token store if access_token and users.get_current_user(): self.blogger.token_store.add_token(access_token) elif access_token: self.blogger.current_token = access_token self.blogger.SetOAuthToken(access_token) self.handler.redirect('/') def revoke_token(self): """Revokes the current user's OAuth access token.""" try: self.blogger.RevokeOAuthToken() except gdata.service.RevokingOAuthTokenFailed: pass except gdata.service.NonOAuthToken: pass self.blogger.token_store.remove_all_tokens() self.handler.redirect('/') # ------------------------------------------------------------------------------ # Request handlers. # ------------------------------------------------------------------------------ class OAuthDanceHandler(webapp.RequestHandler): """Handler for the 3 legged OAuth dance. This handler is responsible for fetching an initial OAuth request token, redirecting the user to the approval page. When the user grants access, they will be redirected back to this GET handler and their authorized request token will be exchanged for a long-lived access token.""" def __init__(self): super(OAuthDanceHandler, self).__init__() self.client = OAuthClient(self) def get(self, action=''): if action in self.client.__public__: self.response.out.write(getattr(self.client, action)()) else: self.response.out.write(self.client.request_token()) class OAuthHandler(webapp.RequestHandler): """All handlers requiring OAuth should inherit from this class.""" def __init__(self): super(OAuthHandler, self).__init__() self.client = OAuthClient(self) def requiresOAuth(fun): """Decorator for request handlers to gain authentication via OAuth. Must be used in a handler that inherits from OAuthHandler.""" def decorate(self, *args, **kwargs): if self.client.has_access_token(): try: fun(self, *args, **kwargs) except gdata.service.RequestError, error: if error.code in [401, 403]: self.redirect('/oauth/request_token') else: raise else: self.redirect('/oauth/request_token') return decorate
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. __author__ = 'e.bidelman (Eric Bidelman)' import getopt import mimetypes import os.path import sys import gdata.sample_util import gdata.sites.client import gdata.sites.data SOURCE_APP_NAME = 'googleInc-GoogleSitesAPIPythonLibSample-v1.1' MAIN_MENU = ['1) List site content', '2) List recent activity', '3) List revision history', '4) Create webpage', '5) Create web attachment', '6) Upload attachment', '7) Download attachment', '8) Delete item', '9) List sites', '10) Create a new site', "11) List site's sharing permissions", '12) Change settings', '13) Exit'] SETTINGS_MENU = ['1) Change current site.', '2) Change domain.'] class SitesExample(object): """Wrapper around the Sites API functionality.""" def __init__(self, site_name=None, site_domain=None, debug=False): if site_domain is None: site_domain = self.PromptDomain() if site_name is None: site_name = self.PromptSiteName() mimetypes.init() self.client = gdata.sites.client.SitesClient( source=SOURCE_APP_NAME, site=site_name, domain=site_domain) self.client.http_client.debug = debug try: gdata.sample_util.authorize_client( self.client, service=self.client.auth_service, source=SOURCE_APP_NAME, scopes=['http://sites.google.com/feeds/', 'https://sites.google.com/feeds/']) except gdata.client.BadAuthentication: exit('Invalid user credentials given.') except gdata.client.Error: exit('Login Error') def PrintMainMenu(self): """Displays a menu of options for the user to choose from.""" print '\nSites API Sample' print '================================' print '\n'.join(MAIN_MENU) print '================================\n' def PrintSettingsMenu(self): """Displays a menu of settings for the user change.""" print '\nSites API Sample > Settings' print '================================' print '\n'.join(SETTINGS_MENU) print '================================\n' def GetMenuChoice(self, menu): """Retrieves the menu selection from the user. Args: menu: list The menu to get a selection from. Returns: The integer of the menu item chosen by the user. """ max_choice = len(menu) while True: user_input = raw_input(': ') try: num = int(user_input) except ValueError: continue if num <= max_choice and num > 0: return num def PromptSiteName(self): site_name = '' while not site_name: site_name = raw_input('site name: ') if not site_name: print 'Please enter the name of your Google Site.' return site_name def PromptDomain(self): return raw_input(('If your Site is hosted on a Google Apps domain, ' 'enter it (e.g. example.com): ')) or 'site' def GetChoiceSelection(self, feed, message): for i, entry in enumerate(feed.entry): print '%d.) %s' % (i + 1, entry.title.text) choice = 0 while not choice or not 0 <= choice <= len(feed.entry): choice = int(raw_input(message)) print return choice def PrintEntry(self, entry): print '%s [%s]' % (entry.title.text, entry.Kind()) if entry.page_name: print ' page name:\t%s' % entry.page_name.text if entry.content: print ' content\t%s...' % str(entry.content.html)[0:100] def PrintListItem(self, entry): print '%s [%s]' % (entry.title.text, entry.Kind()) for col in entry.field: print ' %s %s\t%s' % (col.index, col.name, col.text) def PrintListPage(self, entry): print '%s [%s]' % (entry.title.text, entry.Kind()) for col in entry.data.column: print ' %s %s' % (col.index, col.name) def PrintFileCabinetPage(self, entry): print '%s [%s]' % (entry.title.text, entry.Kind()) print ' page name:\t%s' % entry.page_name.text print ' content\t%s...' % str(entry.content.html)[0:100] def PrintAttachment(self, entry): print '%s [%s]' % (entry.title.text, entry.Kind()) if entry.summary is not None: print ' description:\t%s' % entry.summary.text print ' content\t%s, %s' % (entry.content.type, entry.content.src) def PrintWebAttachment(self, entry): print '%s [%s]' % (entry.title.text, entry.Kind()) if entry.summary.text is not None: print ' description:\t%s' % entry.summary.text print ' content src\t%s' % entry.content.src def Run(self): """Executes the demo application.""" try: while True: self.PrintMainMenu() choice = self.GetMenuChoice(MAIN_MENU) if choice == 1: kind_choice = raw_input('What kind (all|%s)?: ' % '|'.join( gdata.sites.data.SUPPORT_KINDS)) if kind_choice in gdata.sites.data.SUPPORT_KINDS: uri = '%s?kind=%s' % (self.client.make_content_feed_uri(), kind_choice) feed = self.client.GetContentFeed(uri=uri) else: feed = self.client.GetContentFeed() print "\nFetching content feed of '%s'...\n" % self.client.site for entry in feed.entry: kind = entry.Kind() if kind == 'attachment': self.PrintAttachment(entry) elif kind == 'webattachment': self.PrintWebAttachment(entry) elif kind == 'filecabinet': self.PrintFileCabinetPage(entry) elif kind == 'listitem': self.PrintListItem(entry) elif kind == 'listpage': self.PrintListPage(entry) else: self.PrintEntry(entry) print ' revision:\t%s' % entry.revision.text print ' updated:\t%s' % entry.updated.text parent_link = entry.FindParentLink() if parent_link: print ' parent link:\t%s' % parent_link if entry.GetAlternateLink(): print ' view in Sites:\t%s' % entry.GetAlternateLink().href if entry.feed_link: print ' feed of items:\t%s' % entry.feed_link.href if entry.IsDeleted(): print ' deleted:\t%s' % entry.IsDeleted() if entry.in_reply_to: print ' in reply to:\t%s' % entry.in_reply_to.href print elif choice == 2: print "\nFetching activity feed of '%s'..." % self.client.site feed = self.client.GetActivityFeed() for entry in feed.entry: print ' %s [%s on %s]' % (entry.title.text, entry.Kind(), entry.updated.text) elif choice == 3: print "\nFetching content feed of '%s'...\n" % self.client.site feed = self.client.GetContentFeed() try: selection = self.GetChoiceSelection( feed, 'Select a page to fetch revisions for: ') except TypeError: continue except ValueError: continue feed = self.client.GetRevisionFeed( feed.entry[selection - 1].GetNodeId()) for entry in feed.entry: print entry.title.text print ' new version on:\t%s' % entry.updated.text print ' view changes:\t%s' % entry.GetAlternateLink().href print ' current version:\t%s...' % str(entry.content.html)[0:100] print elif choice == 4: print "\nFetching content feed of '%s'...\n" % self.client.site feed = self.client.GetContentFeed() try: selection = self.GetChoiceSelection( feed, 'Select a parent to upload to (or hit ENTER for none): ') except ValueError: selection = None page_title = raw_input('Enter a page title: ') parent = None if selection is not None: parent = feed.entry[selection - 1] new_entry = self.client.CreatePage( 'webpage', page_title, '<b>Your html content</b>', parent=parent) if new_entry.GetAlternateLink(): print 'Created. View it at: %s' % new_entry.GetAlternateLink().href elif choice == 5: print "\nFetching filecabinets on '%s'...\n" % self.client.site uri = '%s?kind=%s' % (self.client.make_content_feed_uri(), 'filecabinet') feed = self.client.GetContentFeed(uri=uri) selection = self.GetChoiceSelection( feed, 'Select a filecabinet to create the web attachment on: ') url = raw_input('Enter the URL of the attachment: ') content_type = raw_input("Enter the attachment's mime type: ") title = raw_input('Enter a title for the web attachment: ') description = raw_input('Enter a description: ') parent_entry = None if selection is not None: parent_entry = feed.entry[selection - 1] self.client.CreateWebAttachment(url, content_type, title, parent_entry, description=description) print 'Created!' elif choice == 6: print "\nFetching filecainets on '%s'...\n" % self.client.site uri = '%s?kind=%s' % (self.client.make_content_feed_uri(), 'filecabinet') feed = self.client.GetContentFeed(uri=uri) selection = self.GetChoiceSelection( feed, 'Select a filecabinet to upload to: ') filepath = raw_input('Enter a filename: ') page_title = raw_input('Enter a title for the file: ') description = raw_input('Enter a description: ') filename = os.path.basename(filepath) file_ex = filename[filename.rfind('.'):] if not file_ex in mimetypes.types_map: content_type = raw_input( 'Unrecognized file extension. Please enter the mime type: ') else: content_type = mimetypes.types_map[file_ex] entry = None if selection is not None: entry = feed.entry[selection - 1] new_entry = self.client.UploadAttachment( filepath, entry, content_type=content_type, title=page_title, description=description) print 'Uploaded. View it at: %s' % new_entry.GetAlternateLink().href elif choice == 7: print "\nFetching all attachments on '%s'...\n" % self.client.site uri = '%s?kind=%s' % (self.client.make_content_feed_uri(), 'attachment') feed = self.client.GetContentFeed(uri=uri) selection = self.GetChoiceSelection( feed, 'Select an attachment to download: ') filepath = raw_input('Save as: ') entry = None if selection is not None: entry = feed.entry[selection - 1] self.client.DownloadAttachment(entry, filepath) print 'Downloaded.' elif choice == 8: print "\nFetching content feed of '%s'...\n" % self.client.site feed = self.client.GetContentFeed() selection = self.GetChoiceSelection(feed, 'Select a page to delete: ') entry = None if selection is not None: entry = feed.entry[selection - 1] self.client.Delete(entry) print 'Removed!' elif choice == 9: print ('\nFetching your list of sites for domain: %s...\n' % self.client.domain) feed = self.client.GetSiteFeed() for entry in feed.entry: print entry.title.text print ' site name: ' + entry.site_name.text if entry.summary.text: print ' summary: ' + entry.summary.text if entry.FindSourceLink(): print ' copied from site: ' + entry.FindSourceLink() print ' acl feed: %s\n' % entry.FindAclLink() elif choice == 10: title = raw_input('Enter a title: ') summary = raw_input('Enter a description: ') theme = raw_input('Theme name (ex. "default"): ') new_entry = self.client.CreateSite( title, description=summary, theme=theme) print 'Site created! View it at: ' + new_entry.GetAlternateLink().href elif choice == 11: print "\nFetching acl permissions of '%s'...\n" % self.client.site feed = self.client.GetAclFeed() for entry in feed.entry: print '%s (%s) - %s' % (entry.scope.value, entry.scope.type, entry.role.value) elif choice == 12: self.PrintSettingsMenu() settings_choice = self.GetMenuChoice(SETTINGS_MENU) if settings_choice == 1: self.client.site = self.PromptSiteName() elif settings_choice == 2: self.client.domain = self.PromptDomain() elif choice == 13: print 'Later!\n' return except gdata.client.RequestError, error: print error except KeyboardInterrupt: return def main(): """The main function runs the SitesExample application.""" print 'NOTE: Please run these tests only with a test account.\n' try: opts, args = getopt.getopt(sys.argv[1:], '', ['site=', 'domain=', 'debug']) except getopt.error, msg: print """python sites_sample.py --site [sitename] --domain [domain or "site"] --debug [prints debug info if set]""" sys.exit(2) site = None domain = None debug = False for option, arg in opts: if option == '--site': site = arg elif option == '--domain': domain = arg elif option == '--debug': debug = True sample = SitesExample(site, domain, debug=debug) sample.Run() if __name__ == '__main__': main()
Python
#!/usr/bin/python # # Copyright (C) 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # This sample uses the Google Spreadsheets data API and the Google # Calendar data API. The script pulls a list of birthdays from a # Google Spreadsheet and inserts them as webContent events in the # user's Google Calendar. # # The script expects a certain format in the spreadsheet: Name, # Birthday, Photo URL, and Edit URL as headers. Expected format # of the birthday is: MM/DD. Edit URL is to be left blank by the # user - the script uses this column to determine whether to insert # a new event or to update an event at the URL. # # See the spreadsheet below for an example: # http://spreadsheets.google.com/pub?key=pfMX-JDVnx47J0DxqssIQHg # __author__ = 'api.stephaniel@google.com (Stephanie Liu)' try: from xml.etree import ElementTree # for Python 2.5 users except: from elementtree import ElementTree import gdata.spreadsheet.service import gdata.calendar.service import gdata.calendar import gdata.service import atom.service import gdata.spreadsheet import atom import string import time import datetime import getopt import getpass import sys class BirthdaySample: # CONSTANTS: Expected column headers: name, birthday, photourl, editurl & # default calendar reminder set to 2 days NAME = "name" BIRTHDAY = "birthday" PHOTO_URL = "photourl" EDIT_URL = "editurl" REMINDER = 60 * 24 * 2 # minutes def __init__(self, email, password): """ Initializes spreadsheet and calendar clients. Creates SpreadsheetsService and CalendarService objects and authenticates to each with ClientLogin. For more information about ClientLogin authentication: http://code.google.com/apis/accounts/AuthForInstalledApps.html Args: email: string password: string """ self.s_client = gdata.spreadsheet.service.SpreadsheetsService() self.s_client.email = email self.s_client.password = password self.s_client.source = 'exampleCo-birthdaySample-1' self.s_client.ProgrammaticLogin() self.c_client = gdata.calendar.service.CalendarService() self.c_client.email = email self.c_client.password = password self.c_client.source = 'exampleCo-birthdaySample-1' self.c_client.ProgrammaticLogin() def _PrintFeed(self, feed): """ Prints out Spreadsheet feeds in human readable format. Generic function taken from spreadsheetsExample.py. Args: feed: SpreadsheetsCellsFeed, SpreadsheetsListFeed, SpreadsheetsWorksheetsFeed, or SpreadsheetsSpreadsheetsFeed """ for i, entry in enumerate(feed.entry): if isinstance(feed, gdata.spreadsheet.SpreadsheetsCellsFeed): print '%s %s\n' % (entry.title.text, entry.content.text) elif isinstance(feed, gdata.spreadsheet.SpreadsheetsListFeed): print '%s %s %s\n' % (i, entry.title.text, entry.content.text) else: print '%s %s\n' % (i, entry.title.text) def _PromptForSpreadsheet(self): """ Prompts user to select spreadsheet. Gets and displays titles of all spreadsheets for user to select. Generic function taken from spreadsheetsExample.py. Args: none Returns: spreadsheet ID that the user selected: string """ feed = self.s_client.GetSpreadsheetsFeed() self._PrintFeed(feed) input = raw_input('\nSelection: ') # extract and return the spreadsheet ID return feed.entry[string.atoi(input)].id.text.rsplit('/', 1)[1] def _PromptForWorksheet(self, key): """ Prompts user to select desired worksheet. Gets and displays titles of all worksheets for user to select. Generic function taken from spreadsheetsExample.py. Args: key: string Returns: the worksheet ID that the user selected: string """ feed = self.s_client.GetWorksheetsFeed(key) self._PrintFeed(feed) input = raw_input('\nSelection: ') # extract and return the worksheet ID return feed.entry[string.atoi(input)].id.text.rsplit('/', 1)[1] def _AddReminder(self, event, minutes): """ Adds a reminder to a calendar event. This function sets the reminder attribute of the CalendarEventEntry. The script sets it to 2 days by default, and this value is not settable by the user. However, it can easily be changed to take this option. Args: event: CalendarEventEntry minutes: int Returns: the updated event: CalendarEventEntry """ for a_when in event.when: if len(a_when.reminder) > 0: a_when.reminder[0].minutes = minutes else: a_when.reminder.append(gdata.calendar.Reminder(minutes=minutes)) return self.c_client.UpdateEvent(event.GetEditLink().href, event) def _CreateBirthdayWebContentEvent(self, name, birthday, photo_url): """ Create the birthday web content event. This function creates and populates a CalendarEventEntry. webContent specific attributes are set. To learn more about the webContent format: http://www.google.com/support/calendar/bin/answer.py?answer=48528 Args: name: string birthday: string - expected format (MM/DD) photo_url: string Returns: the webContent CalendarEventEntry """ title = "%s's Birthday!" % name content = "It's %s's Birthday!" % name month = string.atoi(birthday.split("/")[0]) day = string.atoi(birthday.split("/")[1]) # Get current year year = time.ctime()[-4:] year = string.atoi(year) # Calculate the "end date" for the all day event start_time = datetime.date(year, month, day) one_day = datetime.timedelta(days=1) end_time = start_time + one_day start_time_str = start_time.strftime("%Y-%m-%d") end_time_str = end_time.strftime("%Y-%m-%d") # Create yearly recurrence rule recurrence_data = ("DTSTART;VALUE=DATE:%s\r\n" "DTEND;VALUE=DATE:%s\r\n" "RRULE:FREQ=YEARLY;WKST=SU\r\n" % (start_time.strftime("%Y%m%d"), end_time.strftime("%Y%m%d"))) web_rel = "http://schemas.google.com/gCal/2005/webContent" icon_href = "http://www.perstephanie.com/images/birthdayicon.gif" icon_type = "image/gif" extension_text = ( 'gCal:webContent xmlns:gCal="http://schemas.google.com/gCal/2005"' ' url="%s" width="300" height="225"' % (photo_url)) event = gdata.calendar.CalendarEventEntry() event.title = atom.Title(text=title) event.content = atom.Content(text=content) event.recurrence = gdata.calendar.Recurrence(text=recurrence_data) event.when.append(gdata.calendar.When(start_time=start_time_str, end_time=end_time_str)) # Adding the webContent specific XML event.link.append(atom.Link(rel=web_rel, title=title, href=icon_href, link_type=icon_type)) event.link[0].extension_elements.append( atom.ExtensionElement(extension_text)) return event def _InsertBirthdayWebContentEvent(self, event): """ Insert event into the authenticated user's calendar. Args: event: CalendarEventEntry Returns: the newly created CalendarEventEntry """ edit_uri = '/calendar/feeds/default/private/full' return self.c_client.InsertEvent(event, edit_uri) def Run(self): """ Run sample. TODO: add exception handling Args: none """ key_id = self._PromptForSpreadsheet() wksht_id = self._PromptForWorksheet(key_id) feed = self.s_client.GetListFeed(key_id, wksht_id) found_name = False found_birthday = False found_photourl = False found_editurl = False # Check to make sure all headers are present # Need to find at least one instance of name, birthday, photourl # editurl if len(feed.entry) > 0: for name, custom in feed.entry[0].custom.iteritems(): if custom.column == self.NAME: found_name = True elif custom.column == self.BIRTHDAY: found_birthday = True elif custom.column == self.PHOTO_URL: found_photourl = True elif custom.column == self.EDIT_URL: found_editurl = True if not found_name and found_birthday and found_photourl and found_editurl: print ("ERROR - Unexpected number of column headers. Should have: %s," " %s, %s, and %s." % (self.NAME, self.BIRTHDAY, self.PHOTO_URL, self.EDIT_URL)) sys.exit(1) # For every row in the spreadsheet, grab all the data and either insert # a new event into the calendar, or update the existing event # Create dict to represent the row data to update edit link back to # Spreadsheet for entry in feed.entry: d = {} input_valid = True for name, custom in entry.custom.iteritems(): d[custom.column] = custom.text month = int(d[self.BIRTHDAY].split("/")[0]) day = int(d[self.BIRTHDAY].split("/")[1]) # Some input checking. Script will allow the insert to continue with # a missing name value. if d[self.NAME] is None: d[self.NAME] = " " if d[self.PHOTO_URL] is None: input_valid = False if d[self.BIRTHDAY] is None: input_valid = False elif not 1 <= month <= 12 or not 1 <= day <= 31: input_valid = False if d[self.EDIT_URL] is None and input_valid: event = self._CreateBirthdayWebContentEvent(d[self.NAME], d[self.BIRTHDAY], d[self.PHOTO_URL]) event = self._InsertBirthdayWebContentEvent(event) event = self._AddReminder(event, self.REMINDER) print "Added %s's birthday!" % d[self.NAME] elif input_valid: # Event already exists edit_link = d[self.EDIT_URL] event = self._CreateBirthdayWebContentEvent(d[self.NAME], d[self.BIRTHDAY], d[self.PHOTO_URL]) event = self.c_client.UpdateEvent(edit_link, event) event = self._AddReminder(event, self.REMINDER) print "Updated %s's birthday!" % d[self.NAME] if input_valid: d[self.EDIT_URL] = event.GetEditLink().href self.s_client.UpdateRow(entry, d) else: print "Warning - Skipping row, missing valid input." def main(): email = raw_input("Please enter your email: ") password = getpass.getpass("Please enter your password: ") sample = BirthdaySample(email, password) sample.Run() if __name__ == '__main__': main()
Python
#!/usr/bin/python # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sample for the User Provisioning API to demonstrate all methods. Usage: $ python userprovisioning_quick_start_example.py You can also specify the user credentials from the command-line $ python userprovisioning_quick_start_example.py --client_id [client_id] --client_secret [client_scret] --domain [domain] You can get help for command-line arguments as $ python userprovisioning_quick_start_example.py --help """ __author__ = 'Shraddha Gupta <shraddhag@google.com>' import getopt import getpass import sys import gdata.apps.client SCOPE = 'https://apps-apis.google.com/a/feeds/user/' USER_AGENT = 'UserProvisioningQuickStartExample' class UserProvisioning(object): """Demonstrates all the functions of user provisioning.""" def __init__(self, client_id, client_secret, domain): """ Args: client_id: [string] The clientId of the developer. client_secret: [string] The clientSecret of the developer. domain: [string] The domain on which the functions are to be performed. """ self.client_id = client_id self.client_secret = client_secret self.domain = domain def _AuthorizeClient(self): """Authorize the client for making API requests.""" self.token = gdata.gauth.OAuth2Token( client_id=self.client_id, client_secret=self.client_secret, scope=SCOPE, user_agent=USER_AGENT) uri = self.token.generate_authorize_url() print 'Please visit this URL to authorize the application:' print uri # Get the verification code from the standard input. code = raw_input('What is the verification code? ').strip() self.token.get_access_token(code) self.client = gdata.apps.client.AppsClient( domain=self.domain, auth_token=self.token) def _PrintUserDetails(self, entry): """Prints the attributes for a user entry. Args: entry: [UserEntry] User entry corresponding to a user """ print '\nGiven Name: %s' % (entry.name.given_name) print 'Family Name: %s' % (entry.name.family_name) print 'Username: %s' % (entry.login.user_name) print 'Is Admin: %s' % (entry.login.admin) print 'Is Suspended: %s' % (entry.login.suspended) print 'Change password at next login: %s\n' % ( entry.login.change_password) def _PrintNicknameDetails(self, entry): """Prints the attributes for a user nickname entry. Args: entry: [NicknameEntry] """ print 'Username: %s' % (entry.login.user_name) print 'Nickname: %s\n' % (entry.nickname.name) def _GetChoice(self, for_value): choice = raw_input(('(Optional) Enter a choice for %s\n' '1-True 2-False ') % (for_value)) if choice == '1': return True return False def _CreateUser(self): """Creates a new user account.""" user_name = given_name = family_name = password = None confirm_password = '' while not user_name: user_name = raw_input('Enter a new username: ') while not given_name: given_name = raw_input('Enter given name for the user: ') while not family_name: family_name = raw_input('Enter family name for the user: ') while not password == confirm_password: password = '' while not password: sys.stdout.write('Enter password for the user: ') password = getpass.getpass() if password.__len__() == 0: break if password.__len__() < 8: print 'Password must be at least 8 characters long' password = '' sys.stdout.write('Confirm password: ') confirm_password = getpass.getpass() is_admin = self._GetChoice('is_admin ') hash_function = raw_input('(Optional) Enter a hash function ') suspended = self._GetChoice('suspended ') change_password = self._GetChoice('change_password ') quota = raw_input('(Optional) Enter a quota ') if quota == 'None' or not quota.isdigit(): quota = None user_entry = self.client.CreateUser( user_name=user_name, given_name=given_name, family_name=family_name, password=password, admin=is_admin, suspended=suspended, password_hash_function=hash_function, change_password=change_password) self._PrintUserDetails(user_entry) print 'User Created' def _UpdateUser(self): """Updates a user.""" user_name = raw_input('Enter the username ') if user_name is None: print 'Username missing\n' return user_entry = self.client.RetrieveUser(user_name=user_name) print self._PrintUserDetails(user_entry) attributes = {1: 'given_name', 2: 'family_name', 3: 'user_name', 4: 'suspended', 5: 'is_admin'} print attributes attr = int(raw_input('\nEnter number(1-5) of attribute to be updated ')) updated_val = raw_input('Enter updated value ') if attr == 1: user_entry.name.given_name = updated_val if attr == 2: user_entry.name.family_name = updated_val if attr == 3: user_entry.login.user_name = updated_val if attr == 4: user_entry.login.suspended = updated_val if attr == 5: user_entry.login.admin = updated_val updated = self.client.UpdateUser(user_entry.login.user_name, user_entry) self._PrintUserDetails(updated) def _RetrieveSingleUser(self): """Retrieves a single user.""" user_name = raw_input('Enter the username ') if user_name is None: print 'Username missing\n' return response = self.client.RetrieveUser(user_name=user_name) self._PrintUserDetails(response) def _RetrieveAllUsers(self): """Retrieves all users from all the domains.""" response = self.client.RetrieveAllUsers() for entry in response.entry: self._PrintUserDetails(entry) def _DeleteUser(self): """Deletes a user.""" user_name = raw_input('Enter the username ') if user_name is None: print 'Username missing\n' return self.client.DeleteUser(user_name=user_name) print 'User Deleted' def _CreateNickname(self): """Creates a user alias.""" user_name = raw_input('Enter the username ') nickname = raw_input('Enter a nickname for user ') if None in (user_name, nickname): print 'Username/Nickname missing\n' return nickname = self.client.CreateNickname( user_name=user_name, nickname=nickname) print nickname print 'Nickname Created' def _RetrieveNickname(self): """Retrieves a nickname entry.""" nickname = raw_input('Enter the username ') if nickname is None: print 'Nickname missing\n' return response = self.client.RetrieveNickname(nickname=nickname) self._PrintNicknameDetails(response) def _RetrieveUserNicknames(self): """Retrieves all nicknames of a user.""" user_name = raw_input('Enter the username ') if user_name is None: print 'Username missing\n' return response = self.client.RetrieveNicknames(user_name=user_name) for entry in response.entry: self._PrintNicknameDetails(entry) def _DeleteNickname(self): """Deletes a nickname.""" nickname = raw_input('Enter the username ') if nickname is None: print 'Nickname missing\n' return self.client.DeleteNickname(nickname=nickname) print 'Nickname deleted' def Run(self): """Runs the sample by getting user input and taking appropriate action.""" # List of all the functions and their descriptions functions_list = [ {'function': self._CreateUser, 'description': 'Create a user'}, {'function': self._UpdateUser, 'description': 'Update a user'}, {'function': self._RetrieveSingleUser, 'description': 'Retrieve a single user'}, {'function': self._RetrieveAllUsers, 'description': 'Retrieve all users'}, {'function': self._DeleteUser, 'description': 'Delete a user'}, {'function': self._CreateNickname, 'description': 'Create a nickname'}, {'function': self._RetrieveNickname, 'description': 'Retrieve a nickname'}, {'function': self._RetrieveUserNicknames, 'description': 'Retrieve all nicknames for a user'}, {'function': self._DeleteNickname, 'description': 'Delete a nickname'} ] self._AuthorizeClient() while True: print '\nChoose an option:\n0 - to exit' for i in range (0, len(functions_list)): print '%d - %s' % ((i+1), functions_list[i]['description']) choice = int(raw_input()) if choice == 0: break if choice < 0 or choice > 11: print 'Not a valid option!' continue functions_list[choice-1]['function']() def main(): """A menu driven application to demo all methods of user provisioning.""" usage = ('python userprovisioning_quick_start_example.py ' '--client_id [clientId] --client_secret [clientSecret] ' '--domain [domain]') # Parse command line options try: opts, args = getopt.getopt(sys.argv[1:], '', ['client_id=', 'client_secret=', 'domain=']) except getopt.error, msg: print 'Usage: %s' % usage return client_id = None client_secret = None domain = None # Parse options for option, arg in opts: if option == '--client_id': client_id = arg elif option == '--client_secret': client_secret = arg elif option == '--domain': domain = arg if None in (client_id, client_secret, domain): print 'Usage: %s' % usage return try: user_provisioning = UserProvisioning(client_id, client_secret, domain) except gdata.service.BadAuthentication: print 'Invalid user credentials given.' return user_provisioning.Run() if __name__ == '__main__': main()
Python
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'Gunjan Sharma <gunjansharma@google.com>' import getopt import getpass import sys import gdata.apps.multidomain.client SCOPE = 'https://apps-apis.google.com/a/feeds/user/' USER_AGENT = 'MultiDomainQuickStartExample' class UserData(object): """Data corresponding to a single user.""" def __init__(self): self.email = '' self.first_name = '' self.last_name = '' self.password = '' self.confirm_password = 'temp' self.is_admin = '' self.hash_function = '' self.suspended = '' self.change_password = '' self.ip_whitelisted = '' self.quota = '' class MultiDomainQuickStartExample(object): """Demonstrates all the functions of multidomain user provisioning.""" def __init__(self, client_id, client_secret, domain): """Constructor for the MultiDomainQuickStartExample object. Takes a client_id, client_secret and domain to create an object for multidomain user provisioning. Args: client_id: [string] The clientId of the developer. client_secret: [string] The clientSecret of the developer. domain: [string] The domain on which the functions are to be performed. """ self.client_id = client_id self.client_secret = client_secret self.domain = domain token = gdata.gauth.OAuth2Token( client_id=self.client_id, client_secret=self.client_secret, scope=SCOPE, user_agent=USER_AGENT) uri = token.generate_authorize_url() print 'Please visit this URL to authorize the application:' print uri # Get the verification code from the standard input. code = raw_input('What is the verification code? ').strip() token.get_access_token(code) self.multidomain_client = ( gdata.apps.multidomain.client.MultiDomainProvisioningClient( domain=self.domain, auth_token=token)) def _PrintUserDetails(self, entry): """Prints all the information for a user entry. Args: entry: [UserEntry] User entry corresponding to a user """ print 'First Name: %s' % (entry.first_name) print 'Last Name: %s' % (entry.last_name) print 'Email: %s' % (entry.email) print 'Is Admin: %s' % (entry.is_admin) print 'Is Suspended: %s' % (entry.suspended) print 'Change password at next login: %s' % ( entry.change_password_at_next_login) print '\n' def _PrintAliasDetails(self, entry): """Prints all the information for a user alias entry. Args: entry: [AliasEntry] Alias entry correspoding to an alias """ print 'User Email: %s' % (entry.user_email) print 'Alias Email: %s' % (entry.alias_email) print '\n' def _GetChoice(self, for_field): """Gets a choice for a field. Args: for_field: [string] The field for which input is to be taken. Return: True/False/None: Depending on the choice made by the user. """ choice = int(raw_input(('Enter a choice for %s\n' '1-True 2-False 3-Default/Skip: ') % (for_field))) if choice == 1: return True elif choice == 2: return False return None def _TakeUserData(self, function='create'): """Takes input data for _UpdateUser and _CreateUser functions. Args: function: [string] representing the kind of function (create/update) from where this function was called. Return: user_data: [UserData] All data for a user. """ extra_stmt = '' if function == 'update': extra_stmt = '. Press enter to not update the field' user_data = UserData() while not user_data.email: user_data.email = raw_input('Enter a valid email address' '(username@domain.com): ') while not user_data.first_name: user_data.first_name = raw_input(('Enter first name for the user%s: ') % (extra_stmt)) if function == 'update': break while not user_data.last_name: user_data.last_name = raw_input(('Enter last name for the user%s: ') % (extra_stmt)) if function == 'update': break while not user_data.password == user_data.confirm_password: user_data.password = '' while not user_data.password: sys.stdout.write(('Enter password for the user%s: ') % (extra_stmt)) user_data.password = getpass.getpass() if function == 'update' and user_data.password.__len__() == 0: break if user_data.password.__len__() < 8: print 'Password must be at least 8 characters long' user_data.password = '' if function == 'update' and user_data.password.__len__() == 0: break sys.stdout.write('Confirm password: ') user_data.confirm_password = getpass.getpass() user_data.is_admin = self._GetChoice('is_admin') user_data.hash_function = raw_input('Enter a hash function or None: ') user_data.suspended = self._GetChoice('suspended') user_data.change_password = self._GetChoice('change_password') user_data.ip_whitelisted = self._GetChoice('ip_whitelisted') user_data.quota = raw_input('Enter a quota or None: ') if user_data.quota == 'None' or not user_data.quota.isdigit(): user_data.quota = None if user_data.hash_function == 'None': user_data.hash_function = None return user_data def _CreateUser(self): """Creates a new user account.""" user_data = self._TakeUserData() self.multidomain_client.CreateUser( user_data.email, user_data.first_name, user_data.last_name, user_data.password, user_data.is_admin, hash_function=user_data.hash_function, suspended=user_data.suspended, change_password=user_data.change_password, ip_whitelisted=user_data.ip_whitelisted, quota=user_data.quota) def _UpdateUser(self): """Updates a user.""" user_data = self._TakeUserData('update') user_entry = self.multidomain_client.RetrieveUser(user_data.email) if user_data.first_name: user_entry.first_name = user_data.first_name if user_data.last_name: user_entry.last_name = user_data.last_name if user_data.password: user_entry.password = user_data.password if not user_data.hash_function is None: user_entry.hash_function = user_data.hash_function if not user_data.quota is None: user_entry.quota = user_entry.quota if not user_data.is_admin is None: user_entry.is_admin = (str(user_data.is_admin)).lower() if not user_data.suspended is None: user_entry.suspended = (str(user_data.suspended)).lower() if not user_data.change_password is None: user_entry.change_password = (str(user_data.change_password)).lower() if not user_data.ip_whitelisted is None: user_entry.ip_whitelisted = (str(user_data.ip_whitelisted)).lower() self.multidomain_client.UpdateUser(user_data.email, user_entry) def _RenameUser(self): """Renames username of a user.""" old_email = '' new_email = '' while not old_email: old_email = raw_input('Enter old email address(username@domain.com): ') while not new_email: new_email = raw_input('Enter new email address(username@domain.com): ') self.multidomain_client.RenameUser(old_email, new_email) def _RetrieveSingleUser(self): """Retrieves a single user.""" email = '' while not email: email = raw_input('Enter a valid email address(username@domain.com): ') response = self.multidomain_client.RetrieveUser(email) self._PrintUserDetails(response) def _RetrieveAllUsers(self): """Retrieves all users from all the domains.""" response = self.multidomain_client.RetrieveAllUsers() for entry in response.entry: self._PrintUserDetails(entry) def _DeleteUser(self): """Deletes a user.""" email = '' while not email: email = raw_input('Enter a valid email address(username@domain.com): ') self.multidomain_client.DeleteUser(email) def _CreateUserAlias(self): """Creates a user alias.""" email = '' alias = '' while not email: email = raw_input('Enter a valid email address(username@domain.com): ') while not alias: alias = raw_input('Enter a valid alias email address' '(username@domain.com): ') self.multidomain_client.CreateAlias(email, alias) def _RetrieveAlias(self): """Retrieves a user corresponding to an alias.""" alias = '' while not alias: alias = raw_input('Enter a valid alias email address' '(username@domain.com): ') response = self.multidomain_client.RetrieveAlias(alias) self._PrintAliasDetails(response) def _RetrieveAllAliases(self): """Retrieves all user aliases for all users.""" response = self.multidomain_client.RetrieveAllAliases() for entry in response.entry: self._PrintAliasDetails(entry) def _RetrieveAllUserAliases(self): """Retrieves all user aliases of a user.""" email = '' while not email: email = raw_input('Enter a valid email address(username@domain.com): ') response = self.multidomain_client.RetrieveAllUserAliases(email) for entry in response.entry: self._PrintAliasDetails(entry) def _DeleteAlias(self): """Deletes a user alias.""" alias = '' while not alias: alias = raw_input('Enter a valid alias email address' '(username@domain.com): ') self.multidomain_client.DeleteAlias(alias) def Run(self): """Runs the sample by getting user input and takin appropriate action.""" #List of all the function and there description functions_list = [ {'function': self._CreateUser, 'description': 'Create a user'}, {'function': self._UpdateUser, 'description': 'Updating a user'}, {'function': self._RenameUser, 'description': 'Renaming a user'}, {'function': self._RetrieveSingleUser, 'description': 'Retrieve a single user'}, {'function': self._RetrieveAllUsers, 'description': 'Retrieve all users in all domains'}, {'function': self._DeleteUser, 'description': 'Deleting a User from a domain'}, {'function': self._CreateUserAlias, 'description': 'Create a User Alias in a domain'}, {'function': self._RetrieveAlias, 'description': 'Retrieve a User Alias in a domain'}, {'function': self._RetrieveAllAliases, 'description': 'Retrieve all User Aliases in a Domain'}, {'function': self._RetrieveAllUserAliases, 'description': 'Retrieve all User Aliases for a User'}, {'function': self._DeleteAlias, 'description': 'Delete a user alias from a domain'} ] while True: print 'Choose an option:\n0 - to exit' for i in range (0, len(functions_list)): print '%d - %s' % ((i+1), functions_list[i]['description']) choice = int(raw_input()) if choice == 0: break if choice < 0 or choice > len(functions_list): print 'Not a valid option!' continue functions_list[choice-1]['function']() def main(): """Runs the sample using an instance of MultiDomainQuickStartExample.""" # Parse command line options try: opts, args = getopt.getopt(sys.argv[1:], '', ['client_id=', 'client_secret=', 'domain=']) except getopt.error, msg: print ('python multidomain_provisioning_quick_start_example.py' '--client_id [clientId] --client_secret [clientSecret]' '--domain [domain]') sys.exit(2) client_id = '' client_secret = '' domain = '' # Parse options for option, arg in opts: if option == '--client_id': client_id = arg elif option == '--client_secret': client_secret = arg elif option == '--domain': domain = arg while not client_id: client_id = raw_input('Please enter a clientId: ') while not client_secret: client_secret = raw_input('Please enter a clientSecret: ') while not domain: domain = raw_input('Please enter domain name (example.com): ') try: multidomain_quick_start_example = MultiDomainQuickStartExample( client_id, client_secret, domain) except gdata.service.BadAuthentication: print 'Invalid user credentials given.' return multidomain_quick_start_example.Run() if __name__ == '__main__': main()
Python
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Sample to demonstrate the Email Settings API's labels and filters creation. The sample creates labels and filters corresponding to festivals, which are some days ahead. """ __author__ = 'Gunjan Sharma <gunjansharma@google.com>' from datetime import date from datetime import datetime import getopt import random import sys import time import gdata.apps.client import gdata.apps.emailsettings.client SCOPES = ['https://apps-apis.google.com/a/feeds/emailsettings/2.0/', 'https://apps-apis.google.com/a/feeds/user/'] FESTIVALS_LIST = [ { 'name': 'Christmas', 'date': '25/12', 'tags': ['Merry Christmas', 'Happy Christmas', 'Happy X-mas', 'Merry X-mas'] }, { 'name': 'Halloween', 'date': '31/10', 'tags': ['Happy Halloween', 'Trick or Treat', 'Guise'] }, { 'name': 'Sankranti', 'date': '14/01', 'tags': ['Makar Sankranti', 'Happy Sankranti'] }, { 'name': 'New Year', 'date': '31/12', 'tags': ['Happy New Year', 'New Year Best Wishes'] }] # Number of days left before a festival should be less than MAX_DAY_LEFT # to be considered for filter creation. MAX_DAYS_LEFT = 15 # Maximum retries to be done for exponential back-off MAX_RETRIES = 6 class FestivalSettingsException(Exception): """Exception class for FestivalSettings to show appropriate error message.""" def __init__(self, message): """Create new FestivalSettingsException with appropriate error message.""" super(FestivalSettingsException, self).__init__(message) class FestivalSettings(object): """Sample demonstrating how to create filter and label for domain's user.""" def __init__(self, consumer_key, consumer_secret, domain): """Create a new FestivalSettings object configured for a domain. Args: consumer_key: [string] The consumerKey of the domain. consumer_secret: [string] The consumerSecret of the domain. domain: [string] The domain whose user's POP settings to be changed. """ self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.domain = domain def Authorize(self): """Asks the domain's admin to authorize. Access to the two APIs needs to be authorized, provisioning users and Gmail settings. The function creates clients for both APIs. """ self.email_settings_client = ( gdata.apps.emailsettings.client.EmailSettingsClient( domain=self.domain)) self.provisioning_client = gdata.apps.client.AppsClient(domain=self.domain) request_token = self.email_settings_client.GetOAuthToken( SCOPES, None, self.consumer_key, consumer_secret=self.consumer_secret) print request_token.GenerateAuthorizationUrl() raw_input('Manually go to the above URL and authenticate.' 'Press Return after authorization.') access_token = self.email_settings_client.GetAccessToken(request_token) self.email_settings_client.auth_token = access_token self.provisioning_client.auth_token = access_token def _CreateLabelsFiltersForUser(self, username): """Creates labels and filters for a domain's user. Args: username: [string] The user's username to create labels and filters for. """ today = date.today() for festival in FESTIVALS_LIST: d = datetime.strptime(festival['date'], '%d/%m').date() d = d.replace(year=today.year) days_left = (d - today).days d = d.replace(year=today.year+1) days_left_next_year = (d - today).days if ((0 <= days_left <= MAX_DAYS_LEFT) or (0 <= days_left_next_year <= MAX_DAYS_LEFT)): self._CreateFestivalSettingsForUser(username, festival, 1) def _CreateFestivalSettingsForUser(self, username, festival, tries): """Creates the festival wishes labels and filters for a domain's user. Args: username: [string] The user's username to create labels and filters for. festival: [dictionary] The details for the festival. tries: Number of times the operation has been retried. """ label_name = festival['name'] + ' Wishes' try: self.email_settings_client.CreateLabel(username=username, name=label_name) for tag in festival['tags']: self.email_settings_client.CreateFilter(username=username, has_the_word=tag, label=label_name) except gdata.client.RequestError, e: if e.status == 503 and tries < MAX_RETRIES: time.sleep(2 ^ tries + random.randint(0, 10)) self._CreateFestivalSettingsForUser(username, festival, tries+1) def Run(self): """Handles the flow of the sample. Asks application user for whom to create the festival wishes labels and filters. """ print 'Whom would you like to create labels for?' print ('1 - For all user in the domain.' '(WARNING: May take a long time depending on your domain size.)') print '2 - Single user' choice = raw_input('Enter your choice: ').strip() if choice.isdigit(): choice = int(choice) if choice == 1: users = self.provisioning_client.RetrieveAllUsers() for user in users.entry: self._CreateLabelsFiltersForUser(user.login.user_name) elif choice == 2: username = raw_input('Enter a valid username: ') self._CreateLabelsFiltersForUser(username) else: print 'Invalid choice' return print 'Labels and Filters created successfully' def PrintUsageString(): """Prints the correct call for running the sample.""" print ('python emailsettings_labels_filters.py' '--consumer_key [ConsumerKey] --consumer_secret [ConsumerSecret]' '--domain [domain]') def main(): """Runs the sample using an instance of FestivalSettings.""" try: opts, args = getopt.getopt(sys.argv[1:], '', ['consumer_key=', 'consumer_secret=', 'domain=']) except getopt.error, msg: PrintUsageString() sys.exit(1) consumer_key = '' consumer_secret = '' domain = '' for option, arg in opts: if option == '--consumer_key': consumer_key = arg elif option == '--consumer_secret': consumer_secret = arg elif option == '--domain': domain = arg if not (consumer_key and consumer_secret and domain): print 'Requires exactly three flags.' PrintUsageString() sys.exit(1) festival_wishes_labels = FestivalSettings( consumer_key, consumer_secret, domain) try: festival_wishes_labels.Authorize() except gdata.client.RequestError, e: if e.status == 400: raise FestivalSettingsException('Invalid consumer credentials') else: raise FestivalSettingsException('Unknown server error') sys.exit(1) try: festival_wishes_labels.Run() except gdata.client.RequestError, e: if e.status == 403: raise FestivalSettingsException('Invalid Domain') elif e.status == 400: raise FestivalSettingsException('Invalid username') else: print e.reason raise FestivalSettingsException('Unknown error') if __name__ == '__main__': main()
Python
#!/usr/bin/python2.4 # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'Gunjan Sharma <gunjansharma@google.com>' import getopt import sys import gdata.apps.groups.client import gdata.apps.groups.data SCOPE = 'https://apps-apis.google.com/a/feeds/groups/' USER_AGENT = 'GroupsQuickStartExample' class GroupsQuickStartExample(object): """Demonstrates all the functions of Groups provisioning.""" def __init__(self, client_id, client_secret, domain): """Constructor for the GroupsQuickStartExample object. Takes a client_id, client_secret and domain needed to create an object for groups provisioning. Args: client_id: [string] The clientId of the developer. client_secret: [string] The clientSecret of the developer. domain: [string] The domain on which the functions are to be performed. """ self.client_id = client_id self.client_secret = client_secret self.domain = domain def CreateGroupsClient(self): """Creates a groups provisioning client using OAuth2.0 flow.""" token = gdata.gauth.OAuth2Token( client_id=self.client_id, client_secret=self.client_secret, scope=SCOPE, user_agent=USER_AGENT) uri = token.generate_authorize_url() print 'Please visit this URL to authorize the application:' print uri # Get the verification code from the standard input. code = raw_input('What is the verification code? ').strip() token.get_access_token(code) self.groups_client = gdata.apps.groups.client.GroupsProvisioningClient( domain=self.domain, auth_token=token) def _GetValidGroupId(self): """Takes a valid group email address as input. Return: group_id: [string] a valid group email address """ group_id = '' while not group_id: group_id = raw_input('Enter a valid group email address' '(group@domain.com): ') return group_id def _GetValidMemberId(self): """Takes a valid member email address as input. Return: member_id: [string] a valid member email address """ member_id = '' while not member_id: member_id = raw_input('Enter a valid member email address' '(username@domain.com): ') return member_id def _PrintGroupDetails(self, group_entry): """Print all the details of a group. Args: group_entry: [GroupEntry] contains all the data about the group. """ print 'Group ID: ' + group_entry.group_id print 'Group Name: ' + group_entry.group_name print 'Description: ' + group_entry.description print 'Email Permissions: ' + group_entry.email_permission print '' def _PrintMemberDetails(self, member_entry): """Print all the details of a group member. Args: member_entry: [GroupMemberEntry] contains all the data about the group member. """ print 'Member ID: ' + member_entry.member_id print 'Member Type: ' + member_entry.member_type print 'Is Direct Member: ' + member_entry.direct_member print '' def _TakeGroupData(self, function='create'): """Takes input data for _UpdateGroup and _CreateGroup functions. Args: function: [string] representing the kind of function (create/update) from where this function was called. Return: group_data: [gdata.apps.groups.data.GroupEntry] All data for a group. """ email_permission_options = ['Owner', 'Member', 'Domain', 'Anyone'] extra_stmt = '' if function == 'update': extra_stmt = '. Press enter to not update the field' group_data = gdata.apps.groups.data.GroupEntry() group_data.group_id = self._GetValidGroupId() while not group_data.group_name: group_data.group_name = raw_input('Enter name for the group%s: ' % extra_stmt) if function == 'update': break group_data.description = raw_input('Enter description for the group%s: ' % extra_stmt) print ('Choose an option for email permission%s:' % extra_stmt) i = 1 for option in email_permission_options: print '%d - %s' % (i, option) i += 1 choice = (raw_input()) if not choice: choice = -1 choice = int(choice) if choice > 0 and choice <= len(email_permission_options): group_data.email_permission = email_permission_options[choice-1] return group_data def _CreateGroup(self): """Creates a new group.""" group_data = self._TakeGroupData() self.groups_client.CreateGroup(group_data.group_id, group_data.group_name, group_data.description, group_data.email_permission) def _UpdateGroup(self): """Updates an existing group.""" group_data = self._TakeGroupData(function='update') group_entry = self.groups_client.RetrieveGroup(group_data.group_id) if group_data.group_name: group_entry.group_name = group_data.group_name if group_data.description: group_entry.description = group_data.description if group_data.email_permission: group_entry.email_permission = group_data.email_permission self.groups_client.UpdateGroup(group_data.GetGroupId(), group_entry) def _RetrieveSingleGroup(self): """Retrieves a single group.""" group_id = self._GetValidGroupId() group_entry = self.groups_client.RetrieveGroup(group_id) self._PrintGroupDetails(group_entry) def _RetrieveAllGroupsForMember(self): """Retrieves all the groups the user is a member of.""" member_id = self._GetValidMemberId() direct_only = raw_input('Write true/false for direct_only: ') if direct_only == 'true': direct_only = True else: direct_only = False groups_feed = self.groups_client.RetrieveGroups(member_id, direct_only) for entry in groups_feed.entry: self._PrintGroupDetails(entry) def _RetrieveAllGroups(self): """Retrieves all the groups in a domain.""" groups_feed = self.groups_client.RetrieveAllGroups() for entry in groups_feed.entry: self._PrintGroupDetails(entry) def _DeleteGroup(self): """Delete a group.""" group_id = self._GetValidGroupId() self.groups_client.DeleteGroup(group_id) def _AddMemberToGroup(self): """Add a member to a particular group.""" group_id = self._GetValidGroupId() member_id = self._GetValidMemberId() self.groups_client.AddMemberToGroup(group_id, member_id) def _RetrieveSingleMember(self): """Retrieve a single member from a group.""" group_id = self._GetValidGroupId() member_id = self._GetValidMemberId() member_entry = self.groups_client.RetrieveGroupMember(group_id, member_id) self._PrintMemberDetails(member_entry) def _RetrieveAllMembersOfGroup(self): """Retrieve all the members of a group.""" group_id = self._GetValidGroupId() members_feed = self.groups_client.RetrieveAllMembers(group_id) for entry in members_feed.entry: self._PrintMemberDetails(entry) def _RemoveMemberFromGroup(self): """Remove a member from a group.""" group_id = self._GetValidGroupId() member_id = self._GetValidMemberId() self.groups_client.RemoveMemberFromGroup(group_id, member_id) def Run(self): """Runs the sample by getting user input and takin appropriate action.""" #List of all the function and there description functions_list = [ {'function': self._CreateGroup, 'description': 'Create a Group'}, {'function': self._UpdateGroup, 'description': 'Updating a Group'}, {'function': self._RetrieveSingleGroup, 'description': 'Retrieve a single Group'}, {'function': self._RetrieveAllGroupsForMember, 'description': 'Retrieve all Groups for a member'}, {'function': self._RetrieveAllGroups, 'description': 'Retrieve all Groups in a domain'}, {'function': self._DeleteGroup, 'description': 'Deleting a Group from a domain'}, {'function': self._AddMemberToGroup, 'description': 'Add a member to a Group'}, {'function': self._RetrieveSingleMember, 'description': 'Retrieve a member of a group'}, {'function': self._RetrieveAllMembersOfGroup, 'description': 'Retrieve all members of a group'}, {'function': self._RemoveMemberFromGroup, 'description': 'Delete a member from a Group'} ] while True: print 'Choose an option:\n0 - to exit' for i in range (0, len(functions_list)): print '%d - %s' % ((i+1), functions_list[i]['description']) choice = int(raw_input()) if choice == 0: break if choice < 0 or choice > len(functions_list): print 'Not a valid option!' continue functions_list[choice-1]['function']() def main(): """Runs the sample using an instance of GroupsQuickStartExample.""" # Parse command line options try: opts, args = getopt.getopt(sys.argv[1:], '', ['client_id=', 'client_secret=', 'domain=']) except getopt.error, msg: print ('python groups_provisioning_quick_start_example.py' ' --client_id [clientId] --client_secret [clientSecret]' ' --domain [domain]') sys.exit(2) client_id = '' client_secret = '' domain = '' # Parse options for option, arg in opts: if option == '--client_id': client_id = arg elif option == '--client_secret': client_secret = arg elif option == '--domain': domain = arg while not client_id: client_id = raw_input('Please enter a clientId: ') while not client_secret: client_secret = raw_input('Please enter a clientSecret: ') while not domain: domain = raw_input('Please enter domain name (example.com): ') try: groups_quick_start_example = GroupsQuickStartExample( client_id, client_secret, domain) except gdata.service.BadAuthentication: print 'Invalid user credentials given.' return groups_quick_start_example.CreateGroupsClient() groups_quick_start_example.Run() if __name__ == '__main__': main()
Python
#!/usr/bin/python2.4 # # Copyright 2012 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. """Sample to demonstrate the Email Audit API's email monitoring functions. The sample demonstrates the creating, updating, retrieving and deleting of email monitors. """ __author__ = 'Gunjan Sharma <gunjansharma@google.com>' from datetime import datetime import getopt import re import sys import gdata from gdata.apps.audit.service import AuditService class EmailMonitoringException(Exception): """Exception class for EmailMonitoring, shows appropriate error message.""" class EmailMonitoring(object): """Sample demonstrating how to perform CRUD operations on email monitor.""" def __init__(self, consumer_key, consumer_secret, domain): """Create a new EmailMonitoring object configured for a domain. Args: consumer_key: A string representing a consumerKey. consumer_secret: A string representing a consumerSecret. domain: A string representing the domain to work on in the sample. """ self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.domain = domain self._Authorize() def _Authorize(self): """Asks the domain's admin to authorize access to the apps Apis.""" self.service = AuditService(domain=self.domain, source='emailAuditSample') self.service.SetOAuthInputParameters( gdata.auth.OAuthSignatureMethod.HMAC_SHA1, self.consumer_key, self.consumer_secret) request_token = self.service.FetchOAuthRequestToken() self.service.SetOAuthToken(request_token) auth_url = self.service.GenerateOAuthAuthorizationURL() print auth_url raw_input('Manually go to the above URL and authenticate.' 'Press Return after authorization.') self.service.UpgradeToOAuthAccessToken() def _CheckUsername(self, username): """Checks if a given username is valid or not. Args: username: A string to check for validity. Returns: True if username is valid, False otherwise. """ if len(username) > 64: print 'Username length should be less than 64' return False pattern = re.compile('[^\w\.\+-_\']+') return not bool(pattern.search(username)) def _GetValidUsername(self, typeof): """Takes a valid username as input. Args: typeof: A string representing the type of user. Returns: A valid string corresponding to username. """ username = '' while not username: username = raw_input('Enter a valid %s username: ' % typeof) if not self._CheckUsername(username): print 'Invalid username' username = '' return username def _GetValidDate(self, is_neccessary): """Takes a valid date as input in 'yyyy-mm-dd HH:MM' format. Args: is_neccessary: A boolean denoting if a non empty value is needed. Returns: A valid string corresponding to date. """ date = '' extra_stmt = '' if not is_neccessary: extra_stmt = '. Press enter to skip.' while not date: date = raw_input( 'Enter a valid date as (yyyy-mm-dd HH:MM)%s:' % extra_stmt) if not (date and is_neccessary): return date try: datetime.strptime(date, '%Y-%m-%d %H:%M') return date except ValueError: print 'Not a valid date!' date = '' def _GetBool(self, name): """Takes a boolean value as input. Args: name: A string for which input is to be taken. Returns: A boolean for an entity represented by name. """ choice = raw_input( 'Enter your choice (t/f) for %s (defaults to False):' % name).strip() if choice == 't': return True return False def _CreateEmailMonitor(self): """Creates/Updates an email monitor.""" src_user = self._GetValidUsername('source') dest_user = self._GetValidUsername('destination') end_date = self._GetValidDate(True) start_date = self._GetValidDate(False) incoming_headers = self._GetBool('incoming headers') outgoing_headers = self._GetBool('outgoing headers') drafts = self._GetBool('drafts') drafts_headers = False if drafts: drafts_headers = self._GetBool('drafts headers') chats = self._GetBool('chats') chats_headers = False if chats: self._GetBool('chats headers') self.service.createEmailMonitor( src_user, dest_user, end_date, start_date, incoming_headers, outgoing_headers, drafts, drafts_headers, chats, chats_headers) print 'Email monitor created/updated successfully!\n' def _RetrieveEmailMonitor(self): """Retrieves all email monitors for a user.""" src_user = self._GetValidUsername('source') monitors = self.service.getEmailMonitors(src_user) for monitor in monitors: for key in monitor.keys(): print '%s ----------- %s' % (key, monitor.get(key)) print '' print 'Email monitors retrieved successfully!\n' def _DeleteEmailMonitor(self): """Deletes an email monitor.""" src_user = self._GetValidUsername('source') dest_user = self._GetValidUsername('destination') self.service.deleteEmailMonitor(src_user, dest_user) print 'Email monitor deleted successfully!\n' def Run(self): """Handles the flow of the sample.""" functions_list = [ { 'function': self._CreateEmailMonitor, 'description': 'Create a email monitor for a domain user' }, { 'function': self._CreateEmailMonitor, 'description': 'Update a email monitor for a domain user' }, { 'function': self._RetrieveEmailMonitor, 'description': 'Retrieve all email monitors for a domain user' }, { 'function': self._DeleteEmailMonitor, 'description': 'Delete a email monitor for a domain user' } ] while True: print 'What would you like to do? Choose an option:' print '0 - To exit' for i in range (0, len(functions_list)): print '%d - %s' % ((i + 1), functions_list[i].get('description')) choice = raw_input('Enter your choice: ').strip() if choice.isdigit(): choice = int(choice) if choice == 0: break if choice < 0 or choice > len(functions_list): print 'Not a valid option!' continue try: functions_list[choice - 1].get('function')() except gdata.apps.service.AppsForYourDomainException, e: if e.error_code == 1301: print '\nError: Invalid username!!\n' else: raise e def PrintUsageString(): """Prints the correct call for running the sample.""" print ('python email_audit_email_monitoring.py ' '--consumer_key [ConsumerKey] --consumer_secret [ConsumerSecret] ' '--domain [domain]') def main(): """Runs the sample using an instance of EmailMonitoring.""" try: opts, args = getopt.getopt(sys.argv[1:], '', ['consumer_key=', 'consumer_secret=', 'domain=']) except getopt.error, msg: PrintUsageString() sys.exit(1) consumer_key = '' consumer_secret = '' domain = '' for option, arg in opts: if option == '--consumer_key': consumer_key = arg elif option == '--consumer_secret': consumer_secret = arg elif option == '--domain': domain = arg if not (consumer_key and consumer_secret and domain): print 'Requires exactly three flags.' PrintUsageString() sys.exit(1) try: email_monitoring = EmailMonitoring( consumer_key, consumer_secret, domain) email_monitoring.Run() except gdata.apps.service.AppsForYourDomainException, e: raise EmailMonitoringException('Invalid Domain') except gdata.service.FetchingOAuthRequestTokenFailed, e: raise EmailMonitoringException('Invalid consumer credentials') except Exception, e: if e.args[0].get('status') == 503: raise EmailMonitoringException('Server busy') elif e.args[0].get('status') == 500: raise EmailMonitoringException('Internal server error') else: raise EmailMonitoringException('Unknown error') if __name__ == '__main__': main()
Python
#!/usr/bin/python # # Copyright 2011 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Search users with a given pattern and move to a new organization. Sample to move users to a new organization based on a pattern using the User Provisioning and Organization Provisioning APIs. Usage: $ python search_organize_users.py """ __author__ = 'Shraddha Gupta <shraddhag@google.com>' from optparse import OptionParser import re from gdata.apps.client import AppsClient from gdata.apps.organization.client import OrganizationUnitProvisioningClient import gdata.gauth BATCH_SIZE = 25 SCOPES = ('https://apps-apis.google.com/a/feeds/user/ ' 'https://apps-apis.google.com/a/feeds/policies/') USER_AGENT = 'SearchAndOrganizeUsers' class SearchAndOrganizeUsers(object): """Search users with a pattern and move them to organization.""" def __init__(self, client_id, client_secret, domain): """Create a new SearchAndOrganizeUsers object configured for a domain. Args: client_id: [string] The clientId of the developer. client_secret: [string] The clientSecret of the developer. domain: [string] The domain on which the functions are to be performed. """ self.client_id = client_id self.client_secret = client_secret self.domain = domain def AuthorizeClient(self): """Authorize the clients for making API requests.""" self.token = gdata.gauth.OAuth2Token( client_id=self.client_id, client_secret=self.client_secret, scope=SCOPES, user_agent=USER_AGENT) uri = self.token.generate_authorize_url() print 'Please visit this URL to authorize the application:' print uri # Get the verification code from the standard input. code = raw_input('What is the verification code? ').strip() self.token.get_access_token(code) self.user_client = AppsClient(domain=self.domain, auth_token=self.token) self.org_client = OrganizationUnitProvisioningClient( domain=self.domain, auth_token=self.token) def OrganizeUsers(self, customer_id, org_unit_path, pattern): """Find users with given pattern and move to an organization in batches. Args: customer_id: [string] customer_id to make calls to Organization API. org_unit_path: [string] path of organization unit where users are moved pattern: [regex object] regex to match with users """ users = self.user_client.RetrieveAllUsers() matched_users = [] # Search the users that match given pattern for user in users.entry: if (pattern.search(user.login.user_name) or pattern.search(user.name.given_name) or pattern.search(user.name.family_name)): user_email = '%s@%s' % (user.login.user_name, self.domain) matched_users.append(user_email) # Maximum BATCH_SIZE users can be moved at one time # Split users into batches of BATCH_SIZE and move in batches for i in xrange(0, len(matched_users), BATCH_SIZE): batch_to_move = matched_users[i: i + BATCH_SIZE] self.org_client.MoveUserToOrgUnit(customer_id, org_unit_path, batch_to_move) print 'Number of users moved = %d' % len(matched_users) def Run(self, org_unit_path, regex): self.AuthorizeClient() customer_id_entry = self.org_client.RetrieveCustomerId() customer_id = customer_id_entry.customer_id pattern = re.compile(regex) print 'Moving Users with the pattern %s' % regex self.OrganizeUsers(customer_id, org_unit_path, pattern) def main(): usage = 'Usage: %prog [options]' parser = OptionParser(usage=usage) parser.add_option('--DOMAIN', help='Google Apps Domain, e.g. "domain.com".') parser.add_option('--CLIENT_ID', help='Registered CLIENT_ID of Domain.') parser.add_option('--CLIENT_SECRET', help='Registered CLIENT_SECRET of Domain.') parser.add_option('--ORG_UNIT_PATH', help='Orgunit path of organization where to move users.') parser.add_option('--PATTERN', help='Pattern to search in users') (options, args) = parser.parse_args() if not (options.DOMAIN and options.CLIENT_ID and options.CLIENT_SECRET and options.ORG_UNIT_PATH and options.PATTERN): parser.print_help() return sample = SearchAndOrganizeUsers(options.CLIENT_ID, options.CLIENT_SECRET, options.DOMAIN) sample.Run(options.ORG_UNIT_PATH, options.PATTERN) if __name__ == '__main__': main()
Python
#!/usr/bin/python # # Copyright 2012 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. """Sample to list all the members of a group. The sample demonstrates how to get all members from a group (say Group1) including members from groups that are members of Group1. It recursively finds the members of groups that are the member of given group and lists them. """ __author__ = 'Shraddha Gupta <shraddhag@google.com>' from optparse import OptionParser import gdata.apps.groups.client SCOPE = 'https://apps-apis.google.com/a/feeds/groups/' USER_AGENT = 'ListUserMembersFromGroup' def GetAuthToken(client_id, client_secret): """Get an OAuth 2.0 access token using the given client_id and client_secret. Client_id and client_secret can be found on the API Access tab on the Google APIs Console <http://code.google.com/apis/console>. Args: client_id: String, client id of the developer. client_secret: String, client secret of the developer. Returns: token: String, authorized OAuth 2.0 token. """ token = gdata.gauth.OAuth2Token( client_id=client_id, client_secret=client_secret, scope=SCOPE, user_agent=USER_AGENT) uri = token.generate_authorize_url() print 'Please visit this URL to authorize the application:' print uri # Get the verification code from the standard input. code = raw_input('What is the verification code? ').strip() token.get_access_token(code) return token def ListAllMembers(group_client, group_id): """Lists all members including members of sub-groups. Args: group_client: gdata.apps.groups.client.GroupsProvisioningClient instance. group_id: String, identifier of the group from which members are listed. Returns: members_list: List containing the member_id of group members. """ members_list = [] try: group_members = group_client.RetrieveAllMembers(group_id) for member in group_members.entry: if member.member_type == 'Group': temp_list = ListAllMembers(group_client, member.member_id) members_list.extend(temp_list) else: members_list.append(member.member_id) except gdata.client.RequestError, e: print 'Request error: %s %s %s' % (e.status, e.reason, e.body) return members_list def main(): """Demonstrates retrieval of members of a group.""" usage = ('Usage: %prog --DOMAIN <domain> --CLIENT_ID <client_id> ' '--CLIENT_SECRET <client_secret> --GROUP_ID <group_id> ') parser = OptionParser(usage=usage) parser.add_option('--DOMAIN', help='Google Apps Domain, e.g. "domain.com".') parser.add_option('--CLIENT_ID', help='Registered CLIENT_ID of Domain.') parser.add_option('--CLIENT_SECRET', help='Registered CLIENT_SECRET of Domain.') parser.add_option('--GROUP_ID', help='Group identifier of the group to list members from.') (options, args) = parser.parse_args() if not (options.DOMAIN and options.CLIENT_ID and options.CLIENT_SECRET and options.GROUP_ID): parser.print_help() return group_client = gdata.apps.groups.client.GroupsProvisioningClient( domain=options.DOMAIN) token = GetAuthToken(options.CLIENT_ID, options.CLIENT_SECRET) token.authorize(group_client) members_list = ListAllMembers(group_client, options.GROUP_ID) no_duplicate_members_list = list(set(members_list)) print 'User members of the group %s are: ' % options.GROUP_ID print no_duplicate_members_list if __name__ == '__main__': main()
Python
#!/usr/bin/python # # Copyright 2012 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. """Sample to retrieve profile and contacts of a domain user. The sample uses 2-legged OAuth to authorize clients of User Provisioning and Contacts API and retrieves user's profile and contacts. """ __author__ = 'Shraddha Gupta <shraddhag@google.com>' from optparse import OptionParser import gdata.apps.client import gdata.contacts.client import gdata.gauth class UserProfileAndContactsSample(object): """Class to demonstrate retrieval of domain user's profile and contacts.""" def __init__(self, consumer_key, consumer_secret): """Creates a new UserProfileAndContactsSample object for a domain. Args: consumer_key: String, consumer key of the domain. consumer_secret: String, consumer secret of the domain. """ self.consumer_key = consumer_key self.consumer_secret = consumer_secret self.domain = consumer_key def TwoLOAuthorize(self, admin_id): """Authorize clients of User Provisioning and Contacts API using 2LO. Args: admin_id: String, admin username for 2LO with the Provisioning API. """ requestor_id = '%s@%s' % (admin_id, self.consumer_key) two_legged_oauth_token = gdata.gauth.TwoLeggedOAuthHmacToken( self.consumer_key, self.consumer_secret, requestor_id) self.apps_client = gdata.apps.client.AppsClient(domain=self.domain) self.apps_client.auth_token = two_legged_oauth_token self.contacts_client = gdata.contacts.client.ContactsClient( domain=self.domain) self.contacts_client.auth_token = two_legged_oauth_token def PrintProfile(self, profile): """Prints the contents of a profile entry. Args: profile: gdata.contacts.data.ProfileEntry. """ for email in profile.email: if email.primary == 'true': print 'Email: %s (primary)' % email.address else: print 'Email: %s' % email.address if profile.name: print 'Name: %s' % profile.name.full_name.text if profile.nickname: print 'Nickname: %s' % profile.nickname.text if profile.occupation: print 'Occupation: %s' % profile.occupation.text if profile.gender: print 'Gender: %s' % profile.gender.value if profile.birthday: print 'Birthday: %s' % profile.birthday.when for phone_number in profile.phone_number: print 'Phone Number: %s' % phone_number.text def GetProfile(self, admin_id, user_id): """Retrieves the profile of a user. Args: admin_id: String, admin username. user_id: String, user whose profile is retrieved. Returns: profile_entry: gdata.contacts.data.ProfileEntry. """ requestor_id = '%s@%s' % (admin_id, self.domain) self.contacts_client.auth_token.requestor_id = requestor_id entry_uri = '%s/%s' % (self.contacts_client.GetFeedUri('profiles'), user_id) profile_entry = self.contacts_client.GetProfile(entry_uri) return profile_entry def GetContacts(self, user_id): """Retrieves the contacts of a user. Args: user_id: String, user whose contacts are retrieved. Returns: contacts: List of strings containing user contacts. """ requestor_id = '%s@%s' % (user_id, self.domain) self.contacts_client.auth_token.requestor_id = requestor_id contacts = [] try: contact_feed = self.contacts_client.GetContacts() for contact_entry in contact_feed.entry: contacts.append(contact_entry.title.text) except gdata.client.Unauthorized, e: print 'Error: %s %s' % (e.status, e.reason) return contacts def Run(self, admin_id, user_id): """Retrieves profile and contacts of a user. Args: admin_id: String, admin username. user_id: String, user whose information is retrieved. """ self.TwoLOAuthorize(admin_id) print 'Profile of user: %s' % user_id profile = self.GetProfile(admin_id, user_id) self.PrintProfile(profile) user = self.apps_client.RetrieveUser(user_id) print 'Is admin: %s' % user.login.admin print 'Suspended: %s' % user.login.suspended contacts = self.GetContacts(user_id) print '\nContacts of user ' for contact in contacts: print contact def main(): """Demonstrates retrieval of domain user's profile and contacts using 2LO.""" usage = ('Usage: %prog --consumer_key <consumer_key> ' '--consumer_secret <consumer_secret> --admin_id <admin_id> ' '--user_id=<user_id> ') parser = OptionParser(usage=usage) parser.add_option('--consumer_key', help='Domain name is also consumer key.') parser.add_option('--consumer_secret', help='Consumer secret of the domain.') parser.add_option('--admin_id', help='Username of admin.') parser.add_option('--user_id', help='Username of domain user.') (options, args) = parser.parse_args() if (not options.consumer_key or not options.consumer_secret or not options.admin_id or not options.user_id): parser.print_help() return 1 sample = UserProfileAndContactsSample(options.consumer_key, options.consumer_secret) sample.Run(options.admin_id, options.user_id) if __name__ == '__main__': main()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import base64 class BasicAuth(object): """Sets the Authorization header as defined in RFC1945""" def __init__(self, user_id, password): self.basic_cookie = base64.encodestring( '%s:%s' % (user_id, password)).strip() def modify_request(self, http_request): http_request.headers['Authorization'] = 'Basic %s' % self.basic_cookie ModifyRequest = modify_request class NoAuth(object): def modify_request(self, http_request): pass
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeff Scudder)' import atom.http_interface import atom.url class Error(Exception): pass class NoRecordingFound(Error): pass class MockRequest(object): """Holds parameters of an HTTP request for matching against future requests. """ def __init__(self, operation, url, data=None, headers=None): self.operation = operation if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) self.url = url self.data = data self.headers = headers class MockResponse(atom.http_interface.HttpResponse): """Simulates an httplib.HTTPResponse object.""" def __init__(self, body=None, status=None, reason=None, headers=None): if body and hasattr(body, 'read'): self.body = body.read() else: self.body = body if status is not None: self.status = int(status) else: self.status = None self.reason = reason self._headers = headers or {} def read(self): return self.body class MockHttpClient(atom.http_interface.GenericHttpClient): def __init__(self, headers=None, recordings=None, real_client=None): """An HttpClient which responds to request with stored data. The request-response pairs are stored as tuples in a member list named recordings. The MockHttpClient can be switched from replay mode to record mode by setting the real_client member to an instance of an HttpClient which will make real HTTP requests and store the server's response in list of recordings. Args: headers: dict containing HTTP headers which should be included in all HTTP requests. recordings: The initial recordings to be used for responses. This list contains tuples in the form: (MockRequest, MockResponse) real_client: An HttpClient which will make a real HTTP request. The response will be converted into a MockResponse and stored in recordings. """ self.recordings = recordings or [] self.real_client = real_client self.headers = headers or {} def add_response(self, response, operation, url, data=None, headers=None): """Adds a request-response pair to the recordings list. After the recording is added, future matching requests will receive the response. Args: response: MockResponse operation: str url: str data: str, Currently the data is ignored when looking for matching requests. headers: dict of strings: Currently the headers are ignored when looking for matching requests. """ request = MockRequest(operation, url, data=data, headers=headers) self.recordings.append((request, response)) def request(self, operation, url, data=None, headers=None): """Returns a matching MockResponse from the recordings. If the real_client is set, the request will be passed along and the server's response will be added to the recordings and also returned. If there is no match, a NoRecordingFound error will be raised. """ if self.real_client is None: if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) for recording in self.recordings: if recording[0].operation == operation and recording[0].url == url: return recording[1] raise NoRecordingFound('No recodings found for %s %s' % ( operation, url)) else: # There is a real HTTP client, so make the request, and record the # response. response = self.real_client.request(operation, url, data=data, headers=headers) # TODO: copy the headers stored_response = MockResponse(body=response, status=response.status, reason=response.reason) self.add_response(stored_response, operation, url, data=data, headers=headers) return stored_response
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core XML_TEMPLATE = '{http://www.w3.org/XML/1998/namespace}%s' ATOM_TEMPLATE = '{http://www.w3.org/2005/Atom}%s' APP_TEMPLATE_V1 = '{http://purl.org/atom/app#}%s' APP_TEMPLATE_V2 = '{http://www.w3.org/2007/app}%s' class Name(atom.core.XmlElement): """The atom:name element.""" _qname = ATOM_TEMPLATE % 'name' class Email(atom.core.XmlElement): """The atom:email element.""" _qname = ATOM_TEMPLATE % 'email' class Uri(atom.core.XmlElement): """The atom:uri element.""" _qname = ATOM_TEMPLATE % 'uri' class Person(atom.core.XmlElement): """A foundation class which atom:author and atom:contributor extend. A person contains information like name, email address, and web page URI for an author or contributor to an Atom feed. """ name = Name email = Email uri = Uri class Author(Person): """The atom:author element. An author is a required element in Feed unless each Entry contains an Author. """ _qname = ATOM_TEMPLATE % 'author' class Contributor(Person): """The atom:contributor element.""" _qname = ATOM_TEMPLATE % 'contributor' class Link(atom.core.XmlElement): """The atom:link element.""" _qname = ATOM_TEMPLATE % 'link' href = 'href' rel = 'rel' type = 'type' hreflang = 'hreflang' title = 'title' length = 'length' class Generator(atom.core.XmlElement): """The atom:generator element.""" _qname = ATOM_TEMPLATE % 'generator' uri = 'uri' version = 'version' class Text(atom.core.XmlElement): """A foundation class from which atom:title, summary, etc. extend. This class should never be instantiated. """ type = 'type' class Title(Text): """The atom:title element.""" _qname = ATOM_TEMPLATE % 'title' class Subtitle(Text): """The atom:subtitle element.""" _qname = ATOM_TEMPLATE % 'subtitle' class Rights(Text): """The atom:rights element.""" _qname = ATOM_TEMPLATE % 'rights' class Summary(Text): """The atom:summary element.""" _qname = ATOM_TEMPLATE % 'summary' class Content(Text): """The atom:content element.""" _qname = ATOM_TEMPLATE % 'content' src = 'src' class Category(atom.core.XmlElement): """The atom:category element.""" _qname = ATOM_TEMPLATE % 'category' term = 'term' scheme = 'scheme' label = 'label' class Id(atom.core.XmlElement): """The atom:id element.""" _qname = ATOM_TEMPLATE % 'id' class Icon(atom.core.XmlElement): """The atom:icon element.""" _qname = ATOM_TEMPLATE % 'icon' class Logo(atom.core.XmlElement): """The atom:logo element.""" _qname = ATOM_TEMPLATE % 'logo' class Draft(atom.core.XmlElement): """The app:draft element which indicates if this entry should be public.""" _qname = (APP_TEMPLATE_V1 % 'draft', APP_TEMPLATE_V2 % 'draft') class Control(atom.core.XmlElement): """The app:control element indicating restrictions on publication. The APP control element may contain a draft element indicating whether or not this entry should be publicly available. """ _qname = (APP_TEMPLATE_V1 % 'control', APP_TEMPLATE_V2 % 'control') draft = Draft class Date(atom.core.XmlElement): """A parent class for atom:updated, published, etc.""" class Updated(Date): """The atom:updated element.""" _qname = ATOM_TEMPLATE % 'updated' class Published(Date): """The atom:published element.""" _qname = ATOM_TEMPLATE % 'published' class LinkFinder(object): """An "interface" providing methods to find link elements Entry elements often contain multiple links which differ in the rel attribute or content type. Often, developers are interested in a specific type of link so this class provides methods to find specific classes of links. This class is used as a mixin in Atom entries and feeds. """ def find_url(self, rel): """Returns the URL (as a string) in a link with the desired rel value.""" for link in self.link: if link.rel == rel and link.href: return link.href return None FindUrl = find_url def get_link(self, rel): """Returns a link object which has the desired rel value. If you are interested in the URL instead of the link object, consider using find_url instead. """ for link in self.link: if link.rel == rel and link.href: return link return None GetLink = get_link def find_self_link(self): """Find the first link with rel set to 'self' Returns: A str containing the link's href or None if none of the links had rel equal to 'self' """ return self.find_url('self') FindSelfLink = find_self_link def get_self_link(self): return self.get_link('self') GetSelfLink = get_self_link def find_edit_link(self): return self.find_url('edit') FindEditLink = find_edit_link def get_edit_link(self): return self.get_link('edit') GetEditLink = get_edit_link def find_edit_media_link(self): link = self.find_url('edit-media') # Search for media-edit as well since Picasa API used media-edit instead. if link is None: return self.find_url('media-edit') return link FindEditMediaLink = find_edit_media_link def get_edit_media_link(self): link = self.get_link('edit-media') if link is None: return self.get_link('media-edit') return link GetEditMediaLink = get_edit_media_link def find_next_link(self): return self.find_url('next') FindNextLink = find_next_link def get_next_link(self): return self.get_link('next') GetNextLink = get_next_link def find_license_link(self): return self.find_url('license') FindLicenseLink = find_license_link def get_license_link(self): return self.get_link('license') GetLicenseLink = get_license_link def find_alternate_link(self): return self.find_url('alternate') FindAlternateLink = find_alternate_link def get_alternate_link(self): return self.get_link('alternate') GetAlternateLink = get_alternate_link class FeedEntryParent(atom.core.XmlElement, LinkFinder): """A super class for atom:feed and entry, contains shared attributes""" author = [Author] category = [Category] contributor = [Contributor] id = Id link = [Link] rights = Rights title = Title updated = Updated def __init__(self, atom_id=None, text=None, *args, **kwargs): if atom_id is not None: self.id = atom_id atom.core.XmlElement.__init__(self, text=text, *args, **kwargs) class Source(FeedEntryParent): """The atom:source element.""" _qname = ATOM_TEMPLATE % 'source' generator = Generator icon = Icon logo = Logo subtitle = Subtitle class Entry(FeedEntryParent): """The atom:entry element.""" _qname = ATOM_TEMPLATE % 'entry' content = Content published = Published source = Source summary = Summary control = Control class Feed(Source): """The atom:feed element which contains entries.""" _qname = ATOM_TEMPLATE % 'feed' entry = [Entry] class ExtensionElement(atom.core.XmlElement): """Provided for backwards compatibility to the v1 atom.ExtensionElement.""" def __init__(self, tag=None, namespace=None, attributes=None, children=None, text=None, *args, **kwargs): if namespace: self._qname = '{%s}%s' % (namespace, tag) else: self._qname = tag self.children = children or [] self.attributes = attributes or {} self.text = text _BecomeChildElement = atom.core.XmlElement._become_child
Python
#!/usr/bin/env python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import inspect try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree try: from xml.dom.minidom import parseString as xmlString except ImportError: xmlString = None STRING_ENCODING = 'utf-8' class XmlElement(object): """Represents an element node in an XML document. The text member is a UTF-8 encoded str or unicode. """ _qname = None _other_elements = None _other_attributes = None # The rule set contains mappings for XML qnames to child members and the # appropriate member classes. _rule_set = None _members = None text = None def __init__(self, text=None, *args, **kwargs): if ('_members' not in self.__class__.__dict__ or self.__class__._members is None): self.__class__._members = tuple(self.__class__._list_xml_members()) for member_name, member_type in self.__class__._members: if member_name in kwargs: setattr(self, member_name, kwargs[member_name]) else: if isinstance(member_type, list): setattr(self, member_name, []) else: setattr(self, member_name, None) self._other_elements = [] self._other_attributes = {} if text is not None: self.text = text def _list_xml_members(cls): """Generator listing all members which are XML elements or attributes. The following members would be considered XML members: foo = 'abc' - indicates an XML attribute with the qname abc foo = SomeElement - indicates an XML child element foo = [AnElement] - indicates a repeating XML child element, each instance will be stored in a list in this member foo = ('att1', '{http://example.com/namespace}att2') - indicates an XML attribute which has different parsing rules in different versions of the protocol. Version 1 of the XML parsing rules will look for an attribute with the qname 'att1' but verion 2 of the parsing rules will look for a namespaced attribute with the local name of 'att2' and an XML namespace of 'http://example.com/namespace'. """ members = [] for pair in inspect.getmembers(cls): if not pair[0].startswith('_') and pair[0] != 'text': member_type = pair[1] if (isinstance(member_type, tuple) or isinstance(member_type, list) or isinstance(member_type, (str, unicode)) or (inspect.isclass(member_type) and issubclass(member_type, XmlElement))): members.append(pair) return members _list_xml_members = classmethod(_list_xml_members) def _get_rules(cls, version): """Initializes the _rule_set for the class which is used when parsing XML. This method is used internally for parsing and generating XML for an XmlElement. It is not recommended that you call this method directly. Returns: A tuple containing the XML parsing rules for the appropriate version. The tuple looks like: (qname, {sub_element_qname: (member_name, member_class, repeating), ..}, {attribute_qname: member_name}) To give a couple of concrete example, the atom.data.Control _get_rules with version of 2 will return: ('{http://www.w3.org/2007/app}control', {'{http://www.w3.org/2007/app}draft': ('draft', <class 'atom.data.Draft'>, False)}, {}) Calling _get_rules with version 1 on gdata.data.FeedLink will produce: ('{http://schemas.google.com/g/2005}feedLink', {'{http://www.w3.org/2005/Atom}feed': ('feed', <class 'gdata.data.GDFeed'>, False)}, {'href': 'href', 'readOnly': 'read_only', 'countHint': 'count_hint', 'rel': 'rel'}) """ # Initialize the _rule_set to make sure there is a slot available to store # the parsing rules for this version of the XML schema. # Look for rule set in the class __dict__ proxy so that only the # _rule_set for this class will be found. By using the dict proxy # we avoid finding rule_sets defined in superclasses. # The four lines below provide support for any number of versions, but it # runs a bit slower then hard coding slots for two versions, so I'm using # the below two lines. #if '_rule_set' not in cls.__dict__ or cls._rule_set is None: # cls._rule_set = [] #while len(cls.__dict__['_rule_set']) < version: # cls._rule_set.append(None) # If there is no rule set cache in the class, provide slots for two XML # versions. If and when there is a version 3, this list will need to be # expanded. if '_rule_set' not in cls.__dict__ or cls._rule_set is None: cls._rule_set = [None, None] # If a version higher than 2 is requested, fall back to version 2 because # 2 is currently the highest supported version. if version > 2: return cls._get_rules(2) # Check the dict proxy for the rule set to avoid finding any rule sets # which belong to the superclass. We only want rule sets for this class. if cls._rule_set[version-1] is None: # The rule set for each version consists of the qname for this element # ('{namespace}tag'), a dictionary (elements) for looking up the # corresponding class member when given a child element's qname, and a # dictionary (attributes) for looking up the corresponding class member # when given an XML attribute's qname. elements = {} attributes = {} if ('_members' not in cls.__dict__ or cls._members is None): cls._members = tuple(cls._list_xml_members()) for member_name, target in cls._members: if isinstance(target, list): # This member points to a repeating element. elements[_get_qname(target[0], version)] = (member_name, target[0], True) elif isinstance(target, tuple): # This member points to a versioned XML attribute. if version <= len(target): attributes[target[version-1]] = member_name else: attributes[target[-1]] = member_name elif isinstance(target, (str, unicode)): # This member points to an XML attribute. attributes[target] = member_name elif issubclass(target, XmlElement): # This member points to a single occurance element. elements[_get_qname(target, version)] = (member_name, target, False) version_rules = (_get_qname(cls, version), elements, attributes) cls._rule_set[version-1] = version_rules return version_rules else: return cls._rule_set[version-1] _get_rules = classmethod(_get_rules) def get_elements(self, tag=None, namespace=None, version=1): """Find all sub elements which match the tag and namespace. To find all elements in this object, call get_elements with the tag and namespace both set to None (the default). This method searches through the object's members and the elements stored in _other_elements which did not match any of the XML parsing rules for this class. Args: tag: str namespace: str version: int Specifies the version of the XML rules to be used when searching for matching elements. Returns: A list of the matching XmlElements. """ matches = [] ignored1, elements, ignored2 = self.__class__._get_rules(version) if elements: for qname, element_def in elements.iteritems(): member = getattr(self, element_def[0]) if member: if _qname_matches(tag, namespace, qname): if element_def[2]: # If this is a repeating element, copy all instances into the # result list. matches.extend(member) else: matches.append(member) for element in self._other_elements: if _qname_matches(tag, namespace, element._qname): matches.append(element) return matches GetElements = get_elements # FindExtensions and FindChildren are provided for backwards compatibility # to the atom.AtomBase class. # However, FindExtensions may return more results than the v1 atom.AtomBase # method does, because get_elements searches both the expected children # and the unexpected "other elements". The old AtomBase.FindExtensions # method searched only "other elements" AKA extension_elements. FindExtensions = get_elements FindChildren = get_elements def get_attributes(self, tag=None, namespace=None, version=1): """Find all attributes which match the tag and namespace. To find all attributes in this object, call get_attributes with the tag and namespace both set to None (the default). This method searches through the object's members and the attributes stored in _other_attributes which did not fit any of the XML parsing rules for this class. Args: tag: str namespace: str version: int Specifies the version of the XML rules to be used when searching for matching attributes. Returns: A list of XmlAttribute objects for the matching attributes. """ matches = [] ignored1, ignored2, attributes = self.__class__._get_rules(version) if attributes: for qname, attribute_def in attributes.iteritems(): if isinstance(attribute_def, (list, tuple)): attribute_def = attribute_def[0] member = getattr(self, attribute_def) # TODO: ensure this hasn't broken existing behavior. #member = getattr(self, attribute_def[0]) if member: if _qname_matches(tag, namespace, qname): matches.append(XmlAttribute(qname, member)) for qname, value in self._other_attributes.iteritems(): if _qname_matches(tag, namespace, qname): matches.append(XmlAttribute(qname, value)) return matches GetAttributes = get_attributes def _harvest_tree(self, tree, version=1): """Populates object members from the data in the tree Element.""" qname, elements, attributes = self.__class__._get_rules(version) for element in tree: if elements and element.tag in elements: definition = elements[element.tag] # If this is a repeating element, make sure the member is set to a # list. if definition[2]: if getattr(self, definition[0]) is None: setattr(self, definition[0], []) getattr(self, definition[0]).append(_xml_element_from_tree(element, definition[1], version)) else: setattr(self, definition[0], _xml_element_from_tree(element, definition[1], version)) else: self._other_elements.append(_xml_element_from_tree(element, XmlElement, version)) for attrib, value in tree.attrib.iteritems(): if attributes and attrib in attributes: setattr(self, attributes[attrib], value) else: self._other_attributes[attrib] = value if tree.text: self.text = tree.text def _to_tree(self, version=1, encoding=None): new_tree = ElementTree.Element(_get_qname(self, version)) self._attach_members(new_tree, version, encoding) return new_tree def _attach_members(self, tree, version=1, encoding=None): """Convert members to XML elements/attributes and add them to the tree. Args: tree: An ElementTree.Element which will be modified. The members of this object will be added as child elements or attributes according to the rules described in _expected_elements and _expected_attributes. The elements and attributes stored in other_attributes and other_elements are also added a children of this tree. version: int Ingnored in this method but used by VersionedElement. encoding: str (optional) """ qname, elements, attributes = self.__class__._get_rules(version) encoding = encoding or STRING_ENCODING # Add the expected elements and attributes to the tree. if elements: for tag, element_def in elements.iteritems(): member = getattr(self, element_def[0]) # If this is a repeating element and there are members in the list. if member and element_def[2]: for instance in member: instance._become_child(tree, version) elif member: member._become_child(tree, version) if attributes: for attribute_tag, member_name in attributes.iteritems(): value = getattr(self, member_name) if value: tree.attrib[attribute_tag] = value # Add the unexpected (other) elements and attributes to the tree. for element in self._other_elements: element._become_child(tree, version) for key, value in self._other_attributes.iteritems(): # I'm not sure if unicode can be used in the attribute name, so for now # we assume the encoding is correct for the attribute name. if not isinstance(value, unicode): value = value.decode(encoding) tree.attrib[key] = value if self.text: if isinstance(self.text, unicode): tree.text = self.text else: tree.text = self.text.decode(encoding) def to_string(self, version=1, encoding=None, pretty_print=None): """Converts this object to XML.""" tree_string = ElementTree.tostring(self._to_tree(version, encoding)) if pretty_print and xmlString is not None: return xmlString(tree_string).toprettyxml() return tree_string ToString = to_string def __str__(self): return self.to_string() def _become_child(self, tree, version=1): """Adds a child element to tree with the XML data in self.""" new_child = ElementTree.Element('') tree.append(new_child) new_child.tag = _get_qname(self, version) self._attach_members(new_child, version) def __get_extension_elements(self): return self._other_elements def __set_extension_elements(self, elements): self._other_elements = elements extension_elements = property(__get_extension_elements, __set_extension_elements, """Provides backwards compatibility for v1 atom.AtomBase classes.""") def __get_extension_attributes(self): return self._other_attributes def __set_extension_attributes(self, attributes): self._other_attributes = attributes extension_attributes = property(__get_extension_attributes, __set_extension_attributes, """Provides backwards compatibility for v1 atom.AtomBase classes.""") def _get_tag(self, version=1): qname = _get_qname(self, version) if qname: return qname[qname.find('}')+1:] return None def _get_namespace(self, version=1): qname = _get_qname(self, version) if qname.startswith('{'): return qname[1:qname.find('}')] else: return None def _set_tag(self, tag): if isinstance(self._qname, tuple): self._qname = self._qname.copy() if self._qname[0].startswith('{'): self._qname[0] = '{%s}%s' % (self._get_namespace(1), tag) else: self._qname[0] = tag else: if self._qname is not None and self._qname.startswith('{'): self._qname = '{%s}%s' % (self._get_namespace(), tag) else: self._qname = tag def _set_namespace(self, namespace): tag = self._get_tag(1) if tag is None: tag = '' if isinstance(self._qname, tuple): self._qname = self._qname.copy() if namespace: self._qname[0] = '{%s}%s' % (namespace, tag) else: self._qname[0] = tag else: if namespace: self._qname = '{%s}%s' % (namespace, tag) else: self._qname = tag tag = property(_get_tag, _set_tag, """Provides backwards compatibility for v1 atom.AtomBase classes.""") namespace = property(_get_namespace, _set_namespace, """Provides backwards compatibility for v1 atom.AtomBase classes.""") # Provided for backwards compatibility to atom.ExtensionElement children = extension_elements attributes = extension_attributes def _get_qname(element, version): if isinstance(element._qname, tuple): if version <= len(element._qname): return element._qname[version-1] else: return element._qname[-1] else: return element._qname def _qname_matches(tag, namespace, qname): """Logic determines if a QName matches the desired local tag and namespace. This is used in XmlElement.get_elements and XmlElement.get_attributes to find matches in the element's members (among all expected-and-unexpected elements-and-attributes). Args: expected_tag: string expected_namespace: string qname: string in the form '{xml_namespace}localtag' or 'tag' if there is no namespace. Returns: boolean True if the member's tag and namespace fit the expected tag and namespace. """ # If there is no expected namespace or tag, then everything will match. if qname is None: member_tag = None member_namespace = None else: if qname.startswith('{'): member_namespace = qname[1:qname.index('}')] member_tag = qname[qname.index('}') + 1:] else: member_namespace = None member_tag = qname return ((tag is None and namespace is None) # If there is a tag, but no namespace, see if the local tag matches. or (namespace is None and member_tag == tag) # There was no tag, but there was a namespace so see if the namespaces # match. or (tag is None and member_namespace == namespace) # There was no tag, and the desired elements have no namespace, so check # to see that the member's namespace is None. or (tag is None and namespace == '' and member_namespace is None) # The tag and the namespace both match. or (tag == member_tag and namespace == member_namespace) # The tag matches, and the expected namespace is the empty namespace, # check to make sure the member's namespace is None. or (tag == member_tag and namespace == '' and member_namespace is None)) def parse(xml_string, target_class=None, version=1, encoding=None): """Parses the XML string according to the rules for the target_class. Args: xml_string: str or unicode target_class: XmlElement or a subclass. If None is specified, the XmlElement class is used. version: int (optional) The version of the schema which should be used when converting the XML into an object. The default is 1. encoding: str (optional) The character encoding of the bytes in the xml_string. Default is 'UTF-8'. """ if target_class is None: target_class = XmlElement if isinstance(xml_string, unicode): if encoding is None: xml_string = xml_string.encode(STRING_ENCODING) else: xml_string = xml_string.encode(encoding) tree = ElementTree.fromstring(xml_string) return _xml_element_from_tree(tree, target_class, version) Parse = parse xml_element_from_string = parse XmlElementFromString = xml_element_from_string def _xml_element_from_tree(tree, target_class, version=1): if target_class._qname is None: instance = target_class() instance._qname = tree.tag instance._harvest_tree(tree, version) return instance # TODO handle the namespace-only case # Namespace only will be used with Google Spreadsheets rows and # Google Base item attributes. elif tree.tag == _get_qname(target_class, version): instance = target_class() instance._harvest_tree(tree, version) return instance return None class XmlAttribute(object): def __init__(self, qname, value): self._qname = qname self.value = value
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """AtomPubClient provides CRUD ops. in line with the Atom Publishing Protocol. """ __author__ = 'j.s@google.com (Jeff Scudder)' import atom.http_core class Error(Exception): pass class MissingHost(Error): pass class AtomPubClient(object): host = None auth_token = None ssl = False # Whether to force all requests over https xoauth_requestor_id = None def __init__(self, http_client=None, host=None, auth_token=None, source=None, xoauth_requestor_id=None, **kwargs): """Creates a new AtomPubClient instance. Args: source: The name of your application. http_client: An object capable of performing HTTP requests through a request method. This object is used to perform the request when the AtomPubClient's request method is called. Used to allow HTTP requests to be directed to a mock server, or use an alternate library instead of the default of httplib to make HTTP requests. host: str The default host name to use if a host is not specified in the requested URI. auth_token: An object which sets the HTTP Authorization header when its modify_request method is called. """ self.http_client = http_client or atom.http_core.ProxiedHttpClient() if host is not None: self.host = host if auth_token is not None: self.auth_token = auth_token self.xoauth_requestor_id = xoauth_requestor_id self.source = source def request(self, method=None, uri=None, auth_token=None, http_request=None, **kwargs): """Performs an HTTP request to the server indicated. Uses the http_client instance to make the request. Args: method: The HTTP method as a string, usually one of 'GET', 'POST', 'PUT', or 'DELETE' uri: The URI desired as a string or atom.http_core.Uri. http_request: auth_token: An authorization token object whose modify_request method sets the HTTP Authorization header. Returns: The results of calling self.http_client.request. With the default http_client, this is an HTTP response object. """ # Modify the request based on the AtomPubClient settings and parameters # passed in to the request. http_request = self.modify_request(http_request) if isinstance(uri, (str, unicode)): uri = atom.http_core.Uri.parse_uri(uri) if uri is not None: uri.modify_request(http_request) if isinstance(method, (str, unicode)): http_request.method = method # Any unrecognized arguments are assumed to be capable of modifying the # HTTP request. for name, value in kwargs.iteritems(): if value is not None: value.modify_request(http_request) # Default to an http request if the protocol scheme is not set. if http_request.uri.scheme is None: http_request.uri.scheme = 'http' # Override scheme. Force requests over https. if self.ssl: http_request.uri.scheme = 'https' if http_request.uri.path is None: http_request.uri.path = '/' # Add the Authorization header at the very end. The Authorization header # value may need to be calculated using information in the request. if auth_token: auth_token.modify_request(http_request) elif self.auth_token: self.auth_token.modify_request(http_request) # Check to make sure there is a host in the http_request. if http_request.uri.host is None: raise MissingHost('No host provided in request %s %s' % ( http_request.method, str(http_request.uri))) # Perform the fully specified request using the http_client instance. # Sends the request to the server and returns the server's response. return self.http_client.request(http_request) Request = request def get(self, uri=None, auth_token=None, http_request=None, **kwargs): """Performs a request using the GET method, returns an HTTP response.""" return self.request(method='GET', uri=uri, auth_token=auth_token, http_request=http_request, **kwargs) Get = get def post(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs): """Sends data using the POST method, returns an HTTP response.""" return self.request(method='POST', uri=uri, auth_token=auth_token, http_request=http_request, data=data, **kwargs) Post = post def put(self, uri=None, data=None, auth_token=None, http_request=None, **kwargs): """Sends data using the PUT method, returns an HTTP response.""" return self.request(method='PUT', uri=uri, auth_token=auth_token, http_request=http_request, data=data, **kwargs) Put = put def delete(self, uri=None, auth_token=None, http_request=None, **kwargs): """Performs a request using the DELETE method, returns an HTTP response.""" return self.request(method='DELETE', uri=uri, auth_token=auth_token, http_request=http_request, **kwargs) Delete = delete def modify_request(self, http_request): """Changes the HTTP request before sending it to the server. Sets the User-Agent HTTP header and fills in the HTTP host portion of the URL if one was not included in the request (for this it uses the self.host member if one is set). This method is called in self.request. Args: http_request: An atom.http_core.HttpRequest() (optional) If one is not provided, a new HttpRequest is instantiated. Returns: An atom.http_core.HttpRequest() with the User-Agent header set and if this client has a value in its host member, the host in the request URL is set. """ if http_request is None: http_request = atom.http_core.HttpRequest() if self.host is not None and http_request.uri.host is None: http_request.uri.host = self.host if self.xoauth_requestor_id is not None: http_request.uri.query['xoauth_requestor_id'] = self.xoauth_requestor_id # Set the user agent header for logging purposes. if self.source: http_request.headers['User-Agent'] = '%s gdata-py/2.0.15' % self.source else: http_request.headers['User-Agent'] = 'gdata-py/2.0.15' return http_request ModifyRequest = modify_request class CustomHeaders(object): """Add custom headers to an http_request. Usage: >>> custom_headers = atom.client.CustomHeaders(header1='value1', header2='value2') >>> client.get(uri, custom_headers=custom_headers) """ def __init__(self, **kwargs): """Creates a CustomHeaders instance. Initialize the headers dictionary with the arguments list. """ self.headers = kwargs def modify_request(self, http_request): """Changes the HTTP request before sending it to the server. Adds the custom headers to the HTTP request. Args: http_request: An atom.http_core.HttpRequest(). Returns: An atom.http_core.HttpRequest() with the added custom headers. """ for name, value in self.headers.iteritems(): if value is not None: http_request.headers[name] = value return http_request
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """HttpClients in this module use httplib to make HTTP requests. This module make HTTP requests based on httplib, but there are environments in which an httplib based approach will not work (if running in Google App Engine for example). In those cases, higher level classes (like AtomService and GDataService) can swap out the HttpClient to transparently use a different mechanism for making HTTP requests. HttpClient: Contains a request method which performs an HTTP call to the server. ProxiedHttpClient: Contains a request method which connects to a proxy using settings stored in operating system environment variables then performs an HTTP call to the endpoint server. """ __author__ = 'api.jscudder (Jeff Scudder)' import types import os import httplib import atom.url import atom.http_interface import socket import base64 import atom.http_core ssl_imported = False ssl = None try: import ssl ssl_imported = True except ImportError: pass class ProxyError(atom.http_interface.Error): pass class TestConfigurationError(Exception): pass DEFAULT_CONTENT_TYPE = 'application/atom+xml' class HttpClient(atom.http_interface.GenericHttpClient): # Added to allow old v1 HttpClient objects to use the new # http_code.HttpClient. Used in unit tests to inject a mock client. v2_http_client = None def __init__(self, headers=None): self.debug = False self.headers = headers or {} def request(self, operation, url, data=None, headers=None): """Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE. Usage example, perform and HTTP GET on http://www.google.com/: import atom.http client = atom.http.HttpClient() http_response = client.request('GET', 'http://www.google.com/') Args: operation: str The HTTP operation to be performed. This is usually one of 'GET', 'POST', 'PUT', or 'DELETE' data: filestream, list of parts, or other object which can be converted to a string. Should be set to None when performing a GET or DELETE. If data is a file-like object which can be read, this method will read a chunk of 100K bytes at a time and send them. If the data is a list of parts to be sent, each part will be evaluated and sent. url: The full URL to which the request should be sent. Can be a string or atom.url.Url. headers: dict of strings. HTTP headers which should be sent in the request. """ all_headers = self.headers.copy() if headers: all_headers.update(headers) # If the list of headers does not include a Content-Length, attempt to # calculate it based on the data object. if data and 'Content-Length' not in all_headers: if isinstance(data, types.StringTypes): all_headers['Content-Length'] = str(len(data)) else: raise atom.http_interface.ContentLengthRequired('Unable to calculate ' 'the length of the data parameter. Specify a value for ' 'Content-Length') # Set the content type to the default value if none was set. if 'Content-Type' not in all_headers: all_headers['Content-Type'] = DEFAULT_CONTENT_TYPE if self.v2_http_client is not None: http_request = atom.http_core.HttpRequest(method=operation) atom.http_core.Uri.parse_uri(str(url)).modify_request(http_request) http_request.headers = all_headers if data: http_request._body_parts.append(data) return self.v2_http_client.request(http_request=http_request) if not isinstance(url, atom.url.Url): if isinstance(url, types.StringTypes): url = atom.url.parse_url(url) else: raise atom.http_interface.UnparsableUrlObject('Unable to parse url ' 'parameter because it was not a string or atom.url.Url') connection = self._prepare_connection(url, all_headers) if self.debug: connection.debuglevel = 1 connection.putrequest(operation, self._get_access_url(url), skip_host=True) if url.port is not None: connection.putheader('Host', '%s:%s' % (url.host, url.port)) else: connection.putheader('Host', url.host) # Overcome a bug in Python 2.4 and 2.5 # httplib.HTTPConnection.putrequest adding # HTTP request header 'Host: www.google.com:443' instead of # 'Host: www.google.com', and thus resulting the error message # 'Token invalid - AuthSub token has wrong scope' in the HTTP response. if (url.protocol == 'https' and int(url.port or 443) == 443 and hasattr(connection, '_buffer') and isinstance(connection._buffer, list)): header_line = 'Host: %s:443' % url.host replacement_header_line = 'Host: %s' % url.host try: connection._buffer[connection._buffer.index(header_line)] = ( replacement_header_line) except ValueError: # header_line missing from connection._buffer pass # Send the HTTP headers. for header_name in all_headers: connection.putheader(header_name, all_headers[header_name]) connection.endheaders() # If there is data, send it in the request. if data: if isinstance(data, list): for data_part in data: _send_data_part(data_part, connection) else: _send_data_part(data, connection) # Return the HTTP Response from the server. return connection.getresponse() def _prepare_connection(self, url, headers): if not isinstance(url, atom.url.Url): if isinstance(url, types.StringTypes): url = atom.url.parse_url(url) else: raise atom.http_interface.UnparsableUrlObject('Unable to parse url ' 'parameter because it was not a string or atom.url.Url') if url.protocol == 'https': if not url.port: return httplib.HTTPSConnection(url.host) return httplib.HTTPSConnection(url.host, int(url.port)) else: if not url.port: return httplib.HTTPConnection(url.host) return httplib.HTTPConnection(url.host, int(url.port)) def _get_access_url(self, url): return url.to_string() class ProxiedHttpClient(HttpClient): """Performs an HTTP request through a proxy. The proxy settings are obtained from enviroment variables. The URL of the proxy server is assumed to be stored in the environment variables 'https_proxy' and 'http_proxy' respectively. If the proxy server requires a Basic Auth authorization header, the username and password are expected to be in the 'proxy-username' or 'proxy_username' variable and the 'proxy-password' or 'proxy_password' variable, or in 'http_proxy' or 'https_proxy' as "protocol://[username:password@]host:port". After connecting to the proxy server, the request is completed as in HttpClient.request. """ def _prepare_connection(self, url, headers): proxy_settings = os.environ.get('%s_proxy' % url.protocol) if not proxy_settings: # The request was HTTP or HTTPS, but there was no appropriate proxy set. return HttpClient._prepare_connection(self, url, headers) else: proxy_auth = _get_proxy_auth(proxy_settings) proxy_netloc = _get_proxy_net_location(proxy_settings) if url.protocol == 'https': # Set any proxy auth headers if proxy_auth: proxy_auth = 'Proxy-authorization: %s' % proxy_auth # Construct the proxy connect command. port = url.port if not port: port = '443' proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (url.host, port) # Set the user agent to send to the proxy if headers and 'User-Agent' in headers: user_agent = 'User-Agent: %s\r\n' % (headers['User-Agent']) else: user_agent = 'User-Agent: python\r\n' proxy_pieces = '%s%s%s\r\n' % (proxy_connect, proxy_auth, user_agent) # Find the proxy host and port. proxy_url = atom.url.parse_url(proxy_netloc) if not proxy_url.port: proxy_url.port = '80' # Connect to the proxy server, very simple recv and error checking p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) p_sock.connect((proxy_url.host, int(proxy_url.port))) p_sock.sendall(proxy_pieces) response = '' # Wait for the full response. while response.find("\r\n\r\n") == -1: response += p_sock.recv(8192) p_status = response.split()[1] if p_status != str(200): raise ProxyError('Error status=%s' % str(p_status)) # Trivial setup for ssl socket. sslobj = None if ssl_imported: sslobj = ssl.wrap_socket(p_sock, None, None) else: sock_ssl = socket.ssl(p_sock, None, None) sslobj = httplib.FakeSocket(p_sock, sock_ssl) # Initalize httplib and replace with the proxy socket. connection = httplib.HTTPConnection(proxy_url.host) connection.sock = sslobj return connection else: # If protocol was not https. # Find the proxy host and port. proxy_url = atom.url.parse_url(proxy_netloc) if not proxy_url.port: proxy_url.port = '80' if proxy_auth: headers['Proxy-Authorization'] = proxy_auth.strip() return httplib.HTTPConnection(proxy_url.host, int(proxy_url.port)) def _get_access_url(self, url): return url.to_string() def _get_proxy_auth(proxy_settings): """Returns proxy authentication string for header. Will check environment variables for proxy authentication info, starting with proxy(_/-)username and proxy(_/-)password before checking the given proxy_settings for a [protocol://]username:password@host[:port] string. Args: proxy_settings: String from http_proxy or https_proxy environment variable. Returns: Authentication string for proxy, or empty string if no proxy username was found. """ proxy_username = None proxy_password = None proxy_username = os.environ.get('proxy-username') if not proxy_username: proxy_username = os.environ.get('proxy_username') proxy_password = os.environ.get('proxy-password') if not proxy_password: proxy_password = os.environ.get('proxy_password') if not proxy_username: if '@' in proxy_settings: protocol_and_proxy_auth = proxy_settings.split('@')[0].split(':') if len(protocol_and_proxy_auth) == 3: # 3 elements means we have [<protocol>, //<user>, <password>] proxy_username = protocol_and_proxy_auth[1].lstrip('/') proxy_password = protocol_and_proxy_auth[2] elif len(protocol_and_proxy_auth) == 2: # 2 elements means we have [<user>, <password>] proxy_username = protocol_and_proxy_auth[0] proxy_password = protocol_and_proxy_auth[1] if proxy_username: user_auth = base64.encodestring('%s:%s' % (proxy_username, proxy_password)) return 'Basic %s\r\n' % (user_auth.strip()) else: return '' def _get_proxy_net_location(proxy_settings): """Returns proxy host and port. Args: proxy_settings: String from http_proxy or https_proxy environment variable. Must be in the form of protocol://[username:password@]host:port Returns: String in the form of protocol://host:port """ if '@' in proxy_settings: protocol = proxy_settings.split(':')[0] netloc = proxy_settings.split('@')[1] return '%s://%s' % (protocol, netloc) else: return proxy_settings def _send_data_part(data, connection): if isinstance(data, types.StringTypes): connection.send(data) return # Check to see if data is a file-like object that has a read method. elif hasattr(data, 'read'): # Read the file and send it a chunk at a time. while 1: binarydata = data.read(100000) if binarydata == '': break connection.send(binarydata) return else: # The data object was not a file. # Try to convert to a string and send the data. connection.send(str(data)) return
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' import StringIO import pickle import os.path import tempfile import atom.http_core class Error(Exception): pass class NoRecordingFound(Error): pass class MockHttpClient(object): debug = None real_client = None last_request_was_live = False # The following members are used to construct the session cache temp file # name. # These are combined to form the file name # /tmp/cache_prefix.cache_case_name.cache_test_name cache_name_prefix = 'gdata_live_test' cache_case_name = '' cache_test_name = '' def __init__(self, recordings=None, real_client=None): self._recordings = recordings or [] if real_client is not None: self.real_client = real_client def add_response(self, http_request, status, reason, headers=None, body=None): response = MockHttpResponse(status, reason, headers, body) # TODO Scrub the request and the response. self._recordings.append((http_request._copy(), response)) AddResponse = add_response def request(self, http_request): """Provide a recorded response, or record a response for replay. If the real_client is set, the request will be made using the real_client, and the response from the server will be recorded. If the real_client is None (the default), this method will examine the recordings and find the first which matches. """ request = http_request._copy() _scrub_request(request) if self.real_client is None: self.last_request_was_live = False for recording in self._recordings: if _match_request(recording[0], request): return recording[1] else: # Pass along the debug settings to the real client. self.real_client.debug = self.debug # Make an actual request since we can use the real HTTP client. self.last_request_was_live = True response = self.real_client.request(http_request) scrubbed_response = _scrub_response(response) self.add_response(request, scrubbed_response.status, scrubbed_response.reason, dict(atom.http_core.get_headers(scrubbed_response)), scrubbed_response.read()) # Return the recording which we just added. return self._recordings[-1][1] raise NoRecordingFound('No recoding was found for request: %s %s' % ( request.method, str(request.uri))) Request = request def _save_recordings(self, filename): recording_file = open(os.path.join(tempfile.gettempdir(), filename), 'wb') pickle.dump(self._recordings, recording_file) recording_file.close() def _load_recordings(self, filename): recording_file = open(os.path.join(tempfile.gettempdir(), filename), 'rb') self._recordings = pickle.load(recording_file) recording_file.close() def _delete_recordings(self, filename): full_path = os.path.join(tempfile.gettempdir(), filename) if os.path.exists(full_path): os.remove(full_path) def _load_or_use_client(self, filename, http_client): if os.path.exists(os.path.join(tempfile.gettempdir(), filename)): self._load_recordings(filename) else: self.real_client = http_client def use_cached_session(self, name=None, real_http_client=None): """Attempts to load recordings from a previous live request. If a temp file with the recordings exists, then it is used to fulfill requests. If the file does not exist, then a real client is used to actually make the desired HTTP requests. Requests and responses are recorded and will be written to the desired temprary cache file when close_session is called. Args: name: str (optional) The file name of session file to be used. The file is loaded from the temporary directory of this machine. If no name is passed in, a default name will be constructed using the cache_name_prefix, cache_case_name, and cache_test_name of this object. real_http_client: atom.http_core.HttpClient the real client to be used if the cached recordings are not found. If the default value is used, this will be an atom.http_core.HttpClient. """ if real_http_client is None: real_http_client = atom.http_core.HttpClient() if name is None: self._recordings_cache_name = self.get_cache_file_name() else: self._recordings_cache_name = name self._load_or_use_client(self._recordings_cache_name, real_http_client) def close_session(self): """Saves recordings in the temporary file named in use_cached_session.""" if self.real_client is not None: self._save_recordings(self._recordings_cache_name) def delete_session(self, name=None): """Removes recordings from a previous live request.""" if name is None: self._delete_recordings(self._recordings_cache_name) else: self._delete_recordings(name) def get_cache_file_name(self): return '%s.%s.%s' % (self.cache_name_prefix, self.cache_case_name, self.cache_test_name) def _dump(self): """Provides debug information in a string.""" output = 'MockHttpClient\n real_client: %s\n cache file name: %s\n' % ( self.real_client, self.get_cache_file_name()) output += ' recordings:\n' i = 0 for recording in self._recordings: output += ' recording %i is for: %s %s\n' % ( i, recording[0].method, str(recording[0].uri)) i += 1 return output def _match_request(http_request, stored_request): """Determines whether a request is similar enough to a stored request to cause the stored response to be returned.""" # Check to see if the host names match. if (http_request.uri.host is not None and http_request.uri.host != stored_request.uri.host): return False # Check the request path in the URL (/feeds/private/full/x) elif http_request.uri.path != stored_request.uri.path: return False # Check the method used in the request (GET, POST, etc.) elif http_request.method != stored_request.method: return False # If there is a gsession ID in either request, make sure that it is matched # exactly. elif ('gsessionid' in http_request.uri.query or 'gsessionid' in stored_request.uri.query): if 'gsessionid' not in stored_request.uri.query: return False elif 'gsessionid' not in http_request.uri.query: return False elif (http_request.uri.query['gsessionid'] != stored_request.uri.query['gsessionid']): return False # Ignores differences in the query params (?start-index=5&max-results=20), # the body of the request, the port number, HTTP headers, just to name a # few. return True def _scrub_request(http_request): """ Removes email address and password from a client login request. Since the mock server saves the request and response in plantext, sensitive information like the password should be removed before saving the recordings. At the moment only requests sent to a ClientLogin url are scrubbed. """ if (http_request and http_request.uri and http_request.uri.path and http_request.uri.path.endswith('ClientLogin')): # Remove the email and password from a ClientLogin request. http_request._body_parts = [] http_request.add_form_inputs( {'form_data': 'client login request has been scrubbed'}) else: # We can remove the body of the post from the recorded request, since # the request body is not used when finding a matching recording. http_request._body_parts = [] return http_request def _scrub_response(http_response): return http_response class EchoHttpClient(object): """Sends the request data back in the response. Used to check the formatting of the request as it was sent. Always responds with a 200 OK, and some information from the HTTP request is returned in special Echo-X headers in the response. The following headers are added in the response: 'Echo-Host': The host name and port number to which the HTTP connection is made. If no port was passed in, the header will contain host:None. 'Echo-Uri': The path portion of the URL being requested. /example?x=1&y=2 'Echo-Scheme': The beginning of the URL, usually 'http' or 'https' 'Echo-Method': The HTTP method being used, 'GET', 'POST', 'PUT', etc. """ def request(self, http_request): return self._http_request(http_request.uri, http_request.method, http_request.headers, http_request._body_parts) def _http_request(self, uri, method, headers=None, body_parts=None): body = StringIO.StringIO() response = atom.http_core.HttpResponse(status=200, reason='OK', body=body) if headers is None: response._headers = {} else: # Copy headers from the request to the response but convert values to # strings. Server response headers always come in as strings, so an int # should be converted to a corresponding string when echoing. for header, value in headers.iteritems(): response._headers[header] = str(value) response._headers['Echo-Host'] = '%s:%s' % (uri.host, str(uri.port)) response._headers['Echo-Uri'] = uri._get_relative_path() response._headers['Echo-Scheme'] = uri.scheme response._headers['Echo-Method'] = method for part in body_parts: if isinstance(part, str): body.write(part) elif hasattr(part, 'read'): body.write(part.read()) body.seek(0) return response class SettableHttpClient(object): """An HTTP Client which responds with the data given in set_response.""" def __init__(self, status, reason, body, headers): """Configures the response for the server. See set_response for details on the arguments to the constructor. """ self.set_response(status, reason, body, headers) self.last_request = None def set_response(self, status, reason, body, headers): """Determines the response which will be sent for each request. Args: status: An int for the HTTP status code, example: 200, 404, etc. reason: String for the HTTP reason, example: OK, NOT FOUND, etc. body: The body of the HTTP response as a string or a file-like object (something with a read method). headers: dict of strings containing the HTTP headers in the response. """ self.response = atom.http_core.HttpResponse(status=status, reason=reason, body=body) self.response._headers = headers.copy() def request(self, http_request): self.last_request = http_request return self.response class MockHttpResponse(atom.http_core.HttpResponse): def __init__(self, status=None, reason=None, headers=None, body=None): self._headers = headers or {} if status is not None: self.status = status if reason is not None: self.reason = reason if body is not None: # Instead of using a file-like object for the body, store as a string # so that reads can be repeated. if hasattr(body, 'read'): self._body = body.read() else: self._body = body def read(self): return self._body
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """MockService provides CRUD ops. for mocking calls to AtomPub services. MockService: Exposes the publicly used methods of AtomService to provide a mock interface which can be used in unit tests. """ import atom.service import pickle __author__ = 'api.jscudder (Jeffrey Scudder)' # Recordings contains pairings of HTTP MockRequest objects with MockHttpResponse objects. recordings = [] # If set, the mock service HttpRequest are actually made through this object. real_request_handler = None def ConcealValueWithSha(source): import sha return sha.new(source[:-5]).hexdigest() def DumpRecordings(conceal_func=ConcealValueWithSha): if conceal_func: for recording_pair in recordings: recording_pair[0].ConcealSecrets(conceal_func) return pickle.dumps(recordings) def LoadRecordings(recordings_file_or_string): if isinstance(recordings_file_or_string, str): atom.mock_service.recordings = pickle.loads(recordings_file_or_string) elif hasattr(recordings_file_or_string, 'read'): atom.mock_service.recordings = pickle.loads( recordings_file_or_string.read()) def HttpRequest(service, operation, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Simulates an HTTP call to the server, makes an actual HTTP request if real_request_handler is set. This function operates in two different modes depending on if real_request_handler is set or not. If real_request_handler is not set, HttpRequest will look in this module's recordings list to find a response which matches the parameters in the function call. If real_request_handler is set, this function will call real_request_handler.HttpRequest, add the response to the recordings list, and respond with the actual response. Args: service: atom.AtomService object which contains some of the parameters needed to make the request. The following members are used to construct the HTTP call: server (str), additional_headers (dict), port (int), and ssl (bool). operation: str The HTTP operation to be performed. This is usually one of 'GET', 'POST', 'PUT', or 'DELETE' data: ElementTree, filestream, list of parts, or other object which can be converted to a string. Should be set to None when performing a GET or PUT. If data is a file-like object which can be read, this method will read a chunk of 100K bytes at a time and send them. If the data is a list of parts to be sent, each part will be evaluated and sent. uri: The beginning of the URL to which the request should be sent. Examples: '/', '/base/feeds/snippets', '/m8/feeds/contacts/default/base' extra_headers: dict of strings. HTTP headers which should be sent in the request. These headers are in addition to those stored in service.additional_headers. url_params: dict of strings. Key value pairs to be added to the URL as URL parameters. For example {'foo':'bar', 'test':'param'} will become ?foo=bar&test=param. escape_params: bool default True. If true, the keys and values in url_params will be URL escaped when the form is constructed (Special characters converted to %XX form.) content_type: str The MIME type for the data being sent. Defaults to 'application/atom+xml', this is only used if data is set. """ full_uri = atom.service.BuildUri(uri, url_params, escape_params) (server, port, ssl, uri) = atom.service.ProcessUrl(service, uri) current_request = MockRequest(operation, full_uri, host=server, ssl=ssl, data=data, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, content_type=content_type) # If the request handler is set, we should actually make the request using # the request handler and record the response to replay later. if real_request_handler: response = real_request_handler.HttpRequest(service, operation, data, uri, extra_headers=extra_headers, url_params=url_params, escape_params=escape_params, content_type=content_type) # TODO: need to copy the HTTP headers from the real response into the # recorded_response. recorded_response = MockHttpResponse(body=response.read(), status=response.status, reason=response.reason) # Insert a tuple which maps the request to the response object returned # when making an HTTP call using the real_request_handler. recordings.append((current_request, recorded_response)) return recorded_response else: # Look through available recordings to see if one matches the current # request. for request_response_pair in recordings: if request_response_pair[0].IsMatch(current_request): return request_response_pair[1] return None class MockRequest(object): """Represents a request made to an AtomPub server. These objects are used to determine if a client request matches a recorded HTTP request to determine what the mock server's response will be. """ def __init__(self, operation, uri, host=None, ssl=False, port=None, data=None, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Constructor for a MockRequest Args: operation: str One of 'GET', 'POST', 'PUT', or 'DELETE' this is the HTTP operation requested on the resource. uri: str The URL describing the resource to be modified or feed to be retrieved. This should include the protocol (http/https) and the host (aka domain). For example, these are some valud full_uris: 'http://example.com', 'https://www.google.com/accounts/ClientLogin' host: str (optional) The server name which will be placed at the beginning of the URL if the uri parameter does not begin with 'http'. Examples include 'example.com', 'www.google.com', 'www.blogger.com'. ssl: boolean (optional) If true, the request URL will begin with https instead of http. data: ElementTree, filestream, list of parts, or other object which can be converted to a string. (optional) Should be set to None when performing a GET or PUT. If data is a file-like object which can be read, the constructor will read the entire file into memory. If the data is a list of parts to be sent, each part will be evaluated and stored. extra_headers: dict (optional) HTTP headers included in the request. url_params: dict (optional) Key value pairs which should be added to the URL as URL parameters in the request. For example uri='/', url_parameters={'foo':'1','bar':'2'} could become '/?foo=1&bar=2'. escape_params: boolean (optional) Perform URL escaping on the keys and values specified in url_params. Defaults to True. content_type: str (optional) Provides the MIME type of the data being sent. """ self.operation = operation self.uri = _ConstructFullUrlBase(uri, host=host, ssl=ssl) self.data = data self.extra_headers = extra_headers self.url_params = url_params or {} self.escape_params = escape_params self.content_type = content_type def ConcealSecrets(self, conceal_func): """Conceal secret data in this request.""" if self.extra_headers.has_key('Authorization'): self.extra_headers['Authorization'] = conceal_func( self.extra_headers['Authorization']) def IsMatch(self, other_request): """Check to see if the other_request is equivalent to this request. Used to determine if a recording matches an incoming request so that a recorded response should be sent to the client. The matching is not exact, only the operation and URL are examined currently. Args: other_request: MockRequest The request which we want to check this (self) MockRequest against to see if they are equivalent. """ # More accurate matching logic will likely be required. return (self.operation == other_request.operation and self.uri == other_request.uri) def _ConstructFullUrlBase(uri, host=None, ssl=False): """Puts URL components into the form http(s)://full.host.strinf/uri/path Used to construct a roughly canonical URL so that URLs which begin with 'http://example.com/' can be compared to a uri of '/' when the host is set to 'example.com' If the uri contains 'http://host' already, the host and ssl parameters are ignored. Args: uri: str The path component of the URL, examples include '/' host: str (optional) The host name which should prepend the URL. Example: 'example.com' ssl: boolean (optional) If true, the returned URL will begin with https instead of http. Returns: String which has the form http(s)://example.com/uri/string/contents """ if uri.startswith('http'): return uri if ssl: return 'https://%s%s' % (host, uri) else: return 'http://%s%s' % (host, uri) class MockHttpResponse(object): """Returned from MockService crud methods as the server's response.""" def __init__(self, body=None, status=None, reason=None, headers=None): """Construct a mock HTTPResponse and set members. Args: body: str (optional) The HTTP body of the server's response. status: int (optional) reason: str (optional) headers: dict (optional) """ self.body = body self.status = status self.reason = reason self.headers = headers or {} def read(self): return self.body def getheader(self, header_name): return self.headers[header_name]
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module provides a TokenStore class which is designed to manage auth tokens required for different services. Each token is valid for a set of scopes which is the start of a URL. An HTTP client will use a token store to find a valid Authorization header to send in requests to the specified URL. If the HTTP client determines that a token has expired or been revoked, it can remove the token from the store so that it will not be used in future requests. """ __author__ = 'api.jscudder (Jeff Scudder)' import atom.http_interface import atom.url SCOPE_ALL = 'http' class TokenStore(object): """Manages Authorization tokens which will be sent in HTTP headers.""" def __init__(self, scoped_tokens=None): self._tokens = scoped_tokens or {} def add_token(self, token): """Adds a new token to the store (replaces tokens with the same scope). Args: token: A subclass of http_interface.GenericToken. The token object is responsible for adding the Authorization header to the HTTP request. The scopes defined in the token are used to determine if the token is valid for a requested scope when find_token is called. Returns: True if the token was added, False if the token was not added becase no scopes were provided. """ if not hasattr(token, 'scopes') or not token.scopes: return False for scope in token.scopes: self._tokens[str(scope)] = token return True def find_token(self, url): """Selects an Authorization header token which can be used for the URL. Args: url: str or atom.url.Url or a list containing the same. The URL which is going to be requested. All tokens are examined to see if any scopes begin match the beginning of the URL. The first match found is returned. Returns: The token object which should execute the HTTP request. If there was no token for the url (the url did not begin with any of the token scopes available), then the atom.http_interface.GenericToken will be returned because the GenericToken calls through to the http client without adding an Authorization header. """ if url is None: return None if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) if url in self._tokens: token = self._tokens[url] if token.valid_for_scope(url): return token else: del self._tokens[url] for scope, token in self._tokens.iteritems(): if token.valid_for_scope(url): return token return atom.http_interface.GenericToken() def remove_token(self, token): """Removes the token from the token_store. This method is used when a token is determined to be invalid. If the token was found by find_token, but resulted in a 401 or 403 error stating that the token was invlid, then the token should be removed to prevent future use. Returns: True if a token was found and then removed from the token store. False if the token was not in the TokenStore. """ token_found = False scopes_to_delete = [] for scope, stored_token in self._tokens.iteritems(): if stored_token == token: scopes_to_delete.append(scope) token_found = True for scope in scopes_to_delete: del self._tokens[scope] return token_found def remove_all_tokens(self): self._tokens = {}
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __author__ = 'api.jscudder (Jeff Scudder)' import urlparse import urllib DEFAULT_PROTOCOL = 'http' DEFAULT_PORT = 80 def parse_url(url_string): """Creates a Url object which corresponds to the URL string. This method can accept partial URLs, but it will leave missing members of the Url unset. """ parts = urlparse.urlparse(url_string) url = Url() if parts[0]: url.protocol = parts[0] if parts[1]: host_parts = parts[1].split(':') if host_parts[0]: url.host = host_parts[0] if len(host_parts) > 1: url.port = host_parts[1] if parts[2]: url.path = parts[2] if parts[4]: param_pairs = parts[4].split('&') for pair in param_pairs: pair_parts = pair.split('=') if len(pair_parts) > 1: url.params[urllib.unquote_plus(pair_parts[0])] = ( urllib.unquote_plus(pair_parts[1])) elif len(pair_parts) == 1: url.params[urllib.unquote_plus(pair_parts[0])] = None return url class Url(object): """Represents a URL and implements comparison logic. URL strings which are not identical can still be equivalent, so this object provides a better interface for comparing and manipulating URLs than strings. URL parameters are represented as a dictionary of strings, and defaults are used for the protocol (http) and port (80) if not provided. """ def __init__(self, protocol=None, host=None, port=None, path=None, params=None): self.protocol = protocol self.host = host self.port = port self.path = path self.params = params or {} def to_string(self): url_parts = ['', '', '', '', '', ''] if self.protocol: url_parts[0] = self.protocol if self.host: if self.port: url_parts[1] = ':'.join((self.host, str(self.port))) else: url_parts[1] = self.host if self.path: url_parts[2] = self.path if self.params: url_parts[4] = self.get_param_string() return urlparse.urlunparse(url_parts) def get_param_string(self): param_pairs = [] for key, value in self.params.iteritems(): param_pairs.append('='.join((urllib.quote_plus(key), urllib.quote_plus(str(value))))) return '&'.join(param_pairs) def get_request_uri(self): """Returns the path with the parameters escaped and appended.""" param_string = self.get_param_string() if param_string: return '?'.join([self.path, param_string]) else: return self.path def __cmp__(self, other): if not isinstance(other, Url): return cmp(self.to_string(), str(other)) difference = 0 # Compare the protocol if self.protocol and other.protocol: difference = cmp(self.protocol, other.protocol) elif self.protocol and not other.protocol: difference = cmp(self.protocol, DEFAULT_PROTOCOL) elif not self.protocol and other.protocol: difference = cmp(DEFAULT_PROTOCOL, other.protocol) if difference != 0: return difference # Compare the host difference = cmp(self.host, other.host) if difference != 0: return difference # Compare the port if self.port and other.port: difference = cmp(self.port, other.port) elif self.port and not other.port: difference = cmp(self.port, DEFAULT_PORT) elif not self.port and other.port: difference = cmp(DEFAULT_PORT, other.port) if difference != 0: return difference # Compare the path difference = cmp(self.path, other.path) if difference != 0: return difference # Compare the parameters return cmp(self.params, other.params) def __str__(self): return self.to_string()
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. # TODO: add proxy handling. __author__ = 'j.s@google.com (Jeff Scudder)' import os import StringIO import urlparse import urllib import httplib ssl = None try: import ssl except ImportError: pass class Error(Exception): pass class UnknownSize(Error): pass class ProxyError(Error): pass MIME_BOUNDARY = 'END_OF_PART' def get_headers(http_response): """Retrieves all HTTP headers from an HTTP response from the server. This method is provided for backwards compatibility for Python2.2 and 2.3. The httplib.HTTPResponse object in 2.2 and 2.3 does not have a getheaders method so this function will use getheaders if available, but if not it will retrieve a few using getheader. """ if hasattr(http_response, 'getheaders'): return http_response.getheaders() else: headers = [] for header in ( 'location', 'content-type', 'content-length', 'age', 'allow', 'cache-control', 'content-location', 'content-encoding', 'date', 'etag', 'expires', 'last-modified', 'pragma', 'server', 'set-cookie', 'transfer-encoding', 'vary', 'via', 'warning', 'www-authenticate', 'gdata-version'): value = http_response.getheader(header, None) if value is not None: headers.append((header, value)) return headers class HttpRequest(object): """Contains all of the parameters for an HTTP 1.1 request. The HTTP headers are represented by a dictionary, and it is the responsibility of the user to ensure that duplicate field names are combined into one header value according to the rules in section 4.2 of RFC 2616. """ method = None uri = None def __init__(self, uri=None, method=None, headers=None): """Construct an HTTP request. Args: uri: The full path or partial path as a Uri object or a string. method: The HTTP method for the request, examples include 'GET', 'POST', etc. headers: dict of strings The HTTP headers to include in the request. """ self.headers = headers or {} self._body_parts = [] if method is not None: self.method = method if isinstance(uri, (str, unicode)): uri = Uri.parse_uri(uri) self.uri = uri or Uri() def add_body_part(self, data, mime_type, size=None): """Adds data to the HTTP request body. If more than one part is added, this is assumed to be a mime-multipart request. This method is designed to create MIME 1.0 requests as specified in RFC 1341. Args: data: str or a file-like object containing a part of the request body. mime_type: str The MIME type describing the data size: int Required if the data is a file like object. If the data is a string, the size is calculated so this parameter is ignored. """ if isinstance(data, str): size = len(data) if size is None: # TODO: support chunked transfer if some of the body is of unknown size. raise UnknownSize('Each part of the body must have a known size.') if 'Content-Length' in self.headers: content_length = int(self.headers['Content-Length']) else: content_length = 0 # If this is the first part added to the body, then this is not a multipart # request. if len(self._body_parts) == 0: self.headers['Content-Type'] = mime_type content_length = size self._body_parts.append(data) elif len(self._body_parts) == 1: # This is the first member in a mime-multipart request, so change the # _body_parts list to indicate a multipart payload. self._body_parts.insert(0, 'Media multipart posting') boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,) content_length += len(boundary_string) + size self._body_parts.insert(1, boundary_string) content_length += len('Media multipart posting') # Put the content type of the first part of the body into the multipart # payload. original_type_string = 'Content-Type: %s\r\n\r\n' % ( self.headers['Content-Type'],) self._body_parts.insert(2, original_type_string) content_length += len(original_type_string) boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,) self._body_parts.append(boundary_string) content_length += len(boundary_string) # Change the headers to indicate this is now a mime multipart request. self.headers['Content-Type'] = 'multipart/related; boundary="%s"' % ( MIME_BOUNDARY,) self.headers['MIME-version'] = '1.0' # Include the mime type of this part. type_string = 'Content-Type: %s\r\n\r\n' % (mime_type) self._body_parts.append(type_string) content_length += len(type_string) self._body_parts.append(data) ending_boundary_string = '\r\n--%s--' % (MIME_BOUNDARY,) self._body_parts.append(ending_boundary_string) content_length += len(ending_boundary_string) else: # This is a mime multipart request. boundary_string = '\r\n--%s\r\n' % (MIME_BOUNDARY,) self._body_parts.insert(-1, boundary_string) content_length += len(boundary_string) + size # Include the mime type of this part. type_string = 'Content-Type: %s\r\n\r\n' % (mime_type) self._body_parts.insert(-1, type_string) content_length += len(type_string) self._body_parts.insert(-1, data) self.headers['Content-Length'] = str(content_length) # I could add an "append_to_body_part" method as well. AddBodyPart = add_body_part def add_form_inputs(self, form_data, mime_type='application/x-www-form-urlencoded'): """Form-encodes and adds data to the request body. Args: form_data: dict or sequnce or two member tuples which contains the form keys and values. mime_type: str The MIME type of the form data being sent. Defaults to 'application/x-www-form-urlencoded'. """ body = urllib.urlencode(form_data) self.add_body_part(body, mime_type) AddFormInputs = add_form_inputs def _copy(self): """Creates a deep copy of this request.""" copied_uri = Uri(self.uri.scheme, self.uri.host, self.uri.port, self.uri.path, self.uri.query.copy()) new_request = HttpRequest(uri=copied_uri, method=self.method, headers=self.headers.copy()) new_request._body_parts = self._body_parts[:] return new_request def _dump(self): """Converts to a printable string for debugging purposes. In order to preserve the request, it does not read from file-like objects in the body. """ output = 'HTTP Request\n method: %s\n url: %s\n headers:\n' % ( self.method, str(self.uri)) for header, value in self.headers.iteritems(): output += ' %s: %s\n' % (header, value) output += ' body sections:\n' i = 0 for part in self._body_parts: if isinstance(part, (str, unicode)): output += ' %s: %s\n' % (i, part) else: output += ' %s: <file like object>\n' % i i += 1 return output def _apply_defaults(http_request): if http_request.uri.scheme is None: if http_request.uri.port == 443: http_request.uri.scheme = 'https' else: http_request.uri.scheme = 'http' class Uri(object): """A URI as used in HTTP 1.1""" scheme = None host = None port = None path = None def __init__(self, scheme=None, host=None, port=None, path=None, query=None): """Constructor for a URI. Args: scheme: str This is usually 'http' or 'https'. host: str The host name or IP address of the desired server. post: int The server's port number. path: str The path of the resource following the host. This begins with a /, example: '/calendar/feeds/default/allcalendars/full' query: dict of strings The URL query parameters. The keys and values are both escaped so this dict should contain the unescaped values. For example {'my key': 'val', 'second': '!!!'} will become '?my+key=val&second=%21%21%21' which is appended to the path. """ self.query = query or {} if scheme is not None: self.scheme = scheme if host is not None: self.host = host if port is not None: self.port = port if path: self.path = path def _get_query_string(self): param_pairs = [] for key, value in self.query.iteritems(): param_pairs.append('='.join((urllib.quote_plus(key), urllib.quote_plus(str(value))))) return '&'.join(param_pairs) def _get_relative_path(self): """Returns the path with the query parameters escaped and appended.""" param_string = self._get_query_string() if self.path is None: path = '/' else: path = self.path if param_string: return '?'.join([path, param_string]) else: return path def _to_string(self): if self.scheme is None and self.port == 443: scheme = 'https' elif self.scheme is None: scheme = 'http' else: scheme = self.scheme if self.path is None: path = '/' else: path = self.path if self.port is None: return '%s://%s%s' % (scheme, self.host, self._get_relative_path()) else: return '%s://%s:%s%s' % (scheme, self.host, str(self.port), self._get_relative_path()) def __str__(self): return self._to_string() def modify_request(self, http_request=None): """Sets HTTP request components based on the URI.""" if http_request is None: http_request = HttpRequest() if http_request.uri is None: http_request.uri = Uri() # Determine the correct scheme. if self.scheme: http_request.uri.scheme = self.scheme if self.port: http_request.uri.port = self.port if self.host: http_request.uri.host = self.host # Set the relative uri path if self.path: http_request.uri.path = self.path if self.query: http_request.uri.query = self.query.copy() return http_request ModifyRequest = modify_request def parse_uri(uri_string): """Creates a Uri object which corresponds to the URI string. This method can accept partial URIs, but it will leave missing members of the Uri unset. """ parts = urlparse.urlparse(uri_string) uri = Uri() if parts[0]: uri.scheme = parts[0] if parts[1]: host_parts = parts[1].split(':') if host_parts[0]: uri.host = host_parts[0] if len(host_parts) > 1: uri.port = int(host_parts[1]) if parts[2]: uri.path = parts[2] if parts[4]: param_pairs = parts[4].split('&') for pair in param_pairs: pair_parts = pair.split('=') if len(pair_parts) > 1: uri.query[urllib.unquote_plus(pair_parts[0])] = ( urllib.unquote_plus(pair_parts[1])) elif len(pair_parts) == 1: uri.query[urllib.unquote_plus(pair_parts[0])] = None return uri parse_uri = staticmethod(parse_uri) ParseUri = parse_uri parse_uri = Uri.parse_uri ParseUri = Uri.parse_uri class HttpResponse(object): status = None reason = None _body = None def __init__(self, status=None, reason=None, headers=None, body=None): self._headers = headers or {} if status is not None: self.status = status if reason is not None: self.reason = reason if body is not None: if hasattr(body, 'read'): self._body = body else: self._body = StringIO.StringIO(body) def getheader(self, name, default=None): if name in self._headers: return self._headers[name] else: return default def getheaders(self): return self._headers def read(self, amt=None): if self._body is None: return None if not amt: return self._body.read() else: return self._body.read(amt) def _dump_response(http_response): """Converts to a string for printing debug messages. Does not read the body since that may consume the content. """ output = 'HttpResponse\n status: %s\n reason: %s\n headers:' % ( http_response.status, http_response.reason) headers = get_headers(http_response) if isinstance(headers, dict): for header, value in headers.iteritems(): output += ' %s: %s\n' % (header, value) else: for pair in headers: output += ' %s: %s\n' % (pair[0], pair[1]) return output class HttpClient(object): """Performs HTTP requests using httplib.""" debug = None def request(self, http_request): return self._http_request(http_request.method, http_request.uri, http_request.headers, http_request._body_parts) Request = request def _get_connection(self, uri, headers=None): """Opens a socket connection to the server to set up an HTTP request. Args: uri: The full URL for the request as a Uri object. headers: A dict of string pairs containing the HTTP headers for the request. """ connection = None if uri.scheme == 'https': if not uri.port: connection = httplib.HTTPSConnection(uri.host) else: connection = httplib.HTTPSConnection(uri.host, int(uri.port)) else: if not uri.port: connection = httplib.HTTPConnection(uri.host) else: connection = httplib.HTTPConnection(uri.host, int(uri.port)) return connection def _http_request(self, method, uri, headers=None, body_parts=None): """Makes an HTTP request using httplib. Args: method: str example: 'GET', 'POST', 'PUT', 'DELETE', etc. uri: str or atom.http_core.Uri headers: dict of strings mapping to strings which will be sent as HTTP headers in the request. body_parts: list of strings, objects with a read method, or objects which can be converted to strings using str. Each of these will be sent in order as the body of the HTTP request. """ if isinstance(uri, (str, unicode)): uri = Uri.parse_uri(uri) connection = self._get_connection(uri, headers=headers) if self.debug: connection.debuglevel = 1 if connection.host != uri.host: connection.putrequest(method, str(uri)) else: connection.putrequest(method, uri._get_relative_path()) # Overcome a bug in Python 2.4 and 2.5 # httplib.HTTPConnection.putrequest adding # HTTP request header 'Host: www.google.com:443' instead of # 'Host: www.google.com', and thus resulting the error message # 'Token invalid - AuthSub token has wrong scope' in the HTTP response. if (uri.scheme == 'https' and int(uri.port or 443) == 443 and hasattr(connection, '_buffer') and isinstance(connection._buffer, list)): header_line = 'Host: %s:443' % uri.host replacement_header_line = 'Host: %s' % uri.host try: connection._buffer[connection._buffer.index(header_line)] = ( replacement_header_line) except ValueError: # header_line missing from connection._buffer pass # Send the HTTP headers. for header_name, value in headers.iteritems(): connection.putheader(header_name, value) connection.endheaders() # If there is data, send it in the request. if body_parts and filter(lambda x: x != '', body_parts): for part in body_parts: _send_data_part(part, connection) # Return the HTTP Response from the server. return connection.getresponse() def _send_data_part(data, connection): if isinstance(data, (str, unicode)): # I might want to just allow str, not unicode. connection.send(data) return # Check to see if data is a file-like object that has a read method. elif hasattr(data, 'read'): # Read the file and send it a chunk at a time. while 1: binarydata = data.read(100000) if binarydata == '': break connection.send(binarydata) return else: # The data object was not a file. # Try to convert to a string and send the data. connection.send(str(data)) return class ProxiedHttpClient(HttpClient): def _get_connection(self, uri, headers=None): # Check to see if there are proxy settings required for this request. proxy = None if uri.scheme == 'https': proxy = os.environ.get('https_proxy') elif uri.scheme == 'http': proxy = os.environ.get('http_proxy') if not proxy: return HttpClient._get_connection(self, uri, headers=headers) # Now we have the URL of the appropriate proxy server. # Get a username and password for the proxy if required. proxy_auth = _get_proxy_auth() if uri.scheme == 'https': import socket if proxy_auth: proxy_auth = 'Proxy-authorization: %s' % proxy_auth # Construct the proxy connect command. port = uri.port if not port: port = 443 proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (uri.host, port) # Set the user agent to send to the proxy user_agent = '' if headers and 'User-Agent' in headers: user_agent = 'User-Agent: %s\r\n' % (headers['User-Agent']) proxy_pieces = '%s%s%s\r\n' % (proxy_connect, proxy_auth, user_agent) # Find the proxy host and port. proxy_uri = Uri.parse_uri(proxy) if not proxy_uri.port: proxy_uri.port = '80' # Connect to the proxy server, very simple recv and error checking p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) p_sock.connect((proxy_uri.host, int(proxy_uri.port))) p_sock.sendall(proxy_pieces) response = '' # Wait for the full response. while response.find("\r\n\r\n") == -1: response += p_sock.recv(8192) p_status = response.split()[1] if p_status != str(200): raise ProxyError('Error status=%s' % str(p_status)) # Trivial setup for ssl socket. sslobj = None if ssl is not None: sslobj = ssl.wrap_socket(p_sock, None, None) else: sock_ssl = socket.ssl(p_sock, None, Nonesock_) sslobj = httplib.FakeSocket(p_sock, sock_ssl) # Initalize httplib and replace with the proxy socket. connection = httplib.HTTPConnection(proxy_uri.host) connection.sock = sslobj return connection elif uri.scheme == 'http': proxy_uri = Uri.parse_uri(proxy) if not proxy_uri.port: proxy_uri.port = '80' if proxy_auth: headers['Proxy-Authorization'] = proxy_auth.strip() return httplib.HTTPConnection(proxy_uri.host, int(proxy_uri.port)) return None def _get_proxy_auth(): import base64 proxy_username = os.environ.get('proxy-username') if not proxy_username: proxy_username = os.environ.get('proxy_username') proxy_password = os.environ.get('proxy-password') if not proxy_password: proxy_password = os.environ.get('proxy_password') if proxy_username: user_auth = base64.b64encode('%s:%s' % (proxy_username, proxy_password)) return 'Basic %s\r\n' % (user_auth.strip()) else: return ''
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains classes representing Atom elements. Module objective: provide data classes for Atom constructs. These classes hide the XML-ness of Atom and provide a set of native Python classes to interact with. Conversions to and from XML should only be necessary when the Atom classes "touch the wire" and are sent over HTTP. For this reason this module provides methods and functions to convert Atom classes to and from strings. For more information on the Atom data model, see RFC 4287 (http://www.ietf.org/rfc/rfc4287.txt) AtomBase: A foundation class on which Atom classes are built. It handles the parsing of attributes and children which are common to all Atom classes. By default, the AtomBase class translates all XML child nodes into ExtensionElements. ExtensionElement: Atom allows Atom objects to contain XML which is not part of the Atom specification, these are called extension elements. If a classes parser encounters an unexpected XML construct, it is translated into an ExtensionElement instance. ExtensionElement is designed to fully capture the information in the XML. Child nodes in an XML extension are turned into ExtensionElements as well. """ __author__ = 'api.jscudder (Jeffrey Scudder)' try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import warnings # XML namespaces which are often used in Atom entities. ATOM_NAMESPACE = 'http://www.w3.org/2005/Atom' ELEMENT_TEMPLATE = '{http://www.w3.org/2005/Atom}%s' APP_NAMESPACE = 'http://purl.org/atom/app#' APP_TEMPLATE = '{http://purl.org/atom/app#}%s' # This encoding is used for converting strings before translating the XML # into an object. XML_STRING_ENCODING = 'utf-8' # The desired string encoding for object members. set or monkey-patch to # unicode if you want object members to be Python unicode strings, instead of # encoded strings MEMBER_STRING_ENCODING = 'utf-8' #MEMBER_STRING_ENCODING = unicode # If True, all methods which are exclusive to v1 will raise a # DeprecationWarning ENABLE_V1_WARNINGS = False def v1_deprecated(warning=None): """Shows a warning if ENABLE_V1_WARNINGS is True. Function decorator used to mark methods used in v1 classes which may be removed in future versions of the library. """ warning = warning or '' # This closure is what is returned from the deprecated function. def mark_deprecated(f): # The deprecated_function wraps the actual call to f. def optional_warn_function(*args, **kwargs): if ENABLE_V1_WARNINGS: warnings.warn(warning, DeprecationWarning, stacklevel=2) return f(*args, **kwargs) # Preserve the original name to avoid masking all decorated functions as # 'deprecated_function' try: optional_warn_function.func_name = f.func_name except TypeError: pass # In Python2.3 we can't set the func_name return optional_warn_function return mark_deprecated def CreateClassFromXMLString(target_class, xml_string, string_encoding=None): """Creates an instance of the target class from the string contents. Args: target_class: class The class which will be instantiated and populated with the contents of the XML. This class must have a _tag and a _namespace class variable. xml_string: str A string which contains valid XML. The root element of the XML string should match the tag and namespace of the desired class. string_encoding: str The character encoding which the xml_string should be converted to before it is interpreted and translated into objects. The default is None in which case the string encoding is not changed. Returns: An instance of the target class with members assigned according to the contents of the XML - or None if the root XML tag and namespace did not match those of the target class. """ encoding = string_encoding or XML_STRING_ENCODING if encoding and isinstance(xml_string, unicode): xml_string = xml_string.encode(encoding) tree = ElementTree.fromstring(xml_string) return _CreateClassFromElementTree(target_class, tree) CreateClassFromXMLString = v1_deprecated( 'Please use atom.core.parse with atom.data classes instead.')( CreateClassFromXMLString) def _CreateClassFromElementTree(target_class, tree, namespace=None, tag=None): """Instantiates the class and populates members according to the tree. Note: Only use this function with classes that have _namespace and _tag class members. Args: target_class: class The class which will be instantiated and populated with the contents of the XML. tree: ElementTree An element tree whose contents will be converted into members of the new target_class instance. namespace: str (optional) The namespace which the XML tree's root node must match. If omitted, the namespace defaults to the _namespace of the target class. tag: str (optional) The tag which the XML tree's root node must match. If omitted, the tag defaults to the _tag class member of the target class. Returns: An instance of the target class - or None if the tag and namespace of the XML tree's root node did not match the desired namespace and tag. """ if namespace is None: namespace = target_class._namespace if tag is None: tag = target_class._tag if tree.tag == '{%s}%s' % (namespace, tag): target = target_class() target._HarvestElementTree(tree) return target else: return None class ExtensionContainer(object): def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text __init__ = v1_deprecated( 'Please use data model classes in atom.data instead.')( __init__) # Three methods to create an object from an ElementTree def _HarvestElementTree(self, tree): # Fill in the instance members from the contents of the XML tree. for child in tree: self._ConvertElementTreeToMember(child) for attribute, value in tree.attrib.iteritems(): self._ConvertElementAttributeToMember(attribute, value) # Encode the text string according to the desired encoding type. (UTF-8) if tree.text: if MEMBER_STRING_ENCODING is unicode: self.text = tree.text else: self.text = tree.text.encode(MEMBER_STRING_ENCODING) def _ConvertElementTreeToMember(self, child_tree, current_class=None): self.extension_elements.append(_ExtensionElementFromElementTree( child_tree)) def _ConvertElementAttributeToMember(self, attribute, value): # Encode the attribute value's string with the desired type Default UTF-8 if value: if MEMBER_STRING_ENCODING is unicode: self.extension_attributes[attribute] = value else: self.extension_attributes[attribute] = value.encode( MEMBER_STRING_ENCODING) # One method to create an ElementTree from an object def _AddMembersToElementTree(self, tree): for child in self.extension_elements: child._BecomeChildElement(tree) for attribute, value in self.extension_attributes.iteritems(): if value: if isinstance(value, unicode) or MEMBER_STRING_ENCODING is unicode: tree.attrib[attribute] = value else: # Decode the value from the desired encoding (default UTF-8). tree.attrib[attribute] = value.decode(MEMBER_STRING_ENCODING) if self.text: if isinstance(self.text, unicode) or MEMBER_STRING_ENCODING is unicode: tree.text = self.text else: tree.text = self.text.decode(MEMBER_STRING_ENCODING) def FindExtensions(self, tag=None, namespace=None): """Searches extension elements for child nodes with the desired name. Returns a list of extension elements within this object whose tag and/or namespace match those passed in. To find all extensions in a particular namespace, specify the namespace but not the tag name. If you specify only the tag, the result list may contain extension elements in multiple namespaces. Args: tag: str (optional) The desired tag namespace: str (optional) The desired namespace Returns: A list of elements whose tag and/or namespace match the parameters values """ results = [] if tag and namespace: for element in self.extension_elements: if element.tag == tag and element.namespace == namespace: results.append(element) elif tag and not namespace: for element in self.extension_elements: if element.tag == tag: results.append(element) elif namespace and not tag: for element in self.extension_elements: if element.namespace == namespace: results.append(element) else: for element in self.extension_elements: results.append(element) return results class AtomBase(ExtensionContainer): _children = {} _attributes = {} def __init__(self, extension_elements=None, extension_attributes=None, text=None): self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text __init__ = v1_deprecated( 'Please use data model classes in atom.data instead.')( __init__) def _ConvertElementTreeToMember(self, child_tree): # Find the element's tag in this class's list of child members if self.__class__._children.has_key(child_tree.tag): member_name = self.__class__._children[child_tree.tag][0] member_class = self.__class__._children[child_tree.tag][1] # If the class member is supposed to contain a list, make sure the # matching member is set to a list, then append the new member # instance to the list. if isinstance(member_class, list): if getattr(self, member_name) is None: setattr(self, member_name, []) getattr(self, member_name).append(_CreateClassFromElementTree( member_class[0], child_tree)) else: setattr(self, member_name, _CreateClassFromElementTree(member_class, child_tree)) else: ExtensionContainer._ConvertElementTreeToMember(self, child_tree) def _ConvertElementAttributeToMember(self, attribute, value): # Find the attribute in this class's list of attributes. if self.__class__._attributes.has_key(attribute): # Find the member of this class which corresponds to the XML attribute # (lookup in current_class._attributes) and set this member to the # desired value (using self.__dict__). if value: # Encode the string to capture non-ascii characters (default UTF-8) if MEMBER_STRING_ENCODING is unicode: setattr(self, self.__class__._attributes[attribute], value) else: setattr(self, self.__class__._attributes[attribute], value.encode(MEMBER_STRING_ENCODING)) else: ExtensionContainer._ConvertElementAttributeToMember( self, attribute, value) # Three methods to create an ElementTree from an object def _AddMembersToElementTree(self, tree): # Convert the members of this class which are XML child nodes. # This uses the class's _children dictionary to find the members which # should become XML child nodes. member_node_names = [values[0] for tag, values in self.__class__._children.iteritems()] for member_name in member_node_names: member = getattr(self, member_name) if member is None: pass elif isinstance(member, list): for instance in member: instance._BecomeChildElement(tree) else: member._BecomeChildElement(tree) # Convert the members of this class which are XML attributes. for xml_attribute, member_name in self.__class__._attributes.iteritems(): member = getattr(self, member_name) if member is not None: if isinstance(member, unicode) or MEMBER_STRING_ENCODING is unicode: tree.attrib[xml_attribute] = member else: tree.attrib[xml_attribute] = member.decode(MEMBER_STRING_ENCODING) # Lastly, call the ExtensionContainers's _AddMembersToElementTree to # convert any extension attributes. ExtensionContainer._AddMembersToElementTree(self, tree) def _BecomeChildElement(self, tree): """ Note: Only for use with classes that have a _tag and _namespace class member. It is in AtomBase so that it can be inherited but it should not be called on instances of AtomBase. """ new_child = ElementTree.Element('') tree.append(new_child) new_child.tag = '{%s}%s' % (self.__class__._namespace, self.__class__._tag) self._AddMembersToElementTree(new_child) def _ToElementTree(self): """ Note, this method is designed to be used only with classes that have a _tag and _namespace. It is placed in AtomBase for inheritance but should not be called on this class. """ new_tree = ElementTree.Element('{%s}%s' % (self.__class__._namespace, self.__class__._tag)) self._AddMembersToElementTree(new_tree) return new_tree def ToString(self, string_encoding='UTF-8'): """Converts the Atom object to a string containing XML.""" return ElementTree.tostring(self._ToElementTree(), encoding=string_encoding) def __str__(self): return self.ToString() class Name(AtomBase): """The atom:name element""" _tag = 'name' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Name Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def NameFromString(xml_string): return CreateClassFromXMLString(Name, xml_string) class Email(AtomBase): """The atom:email element""" _tag = 'email' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Email Args: extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs text: str The text data in the this element """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def EmailFromString(xml_string): return CreateClassFromXMLString(Email, xml_string) class Uri(AtomBase): """The atom:uri element""" _tag = 'uri' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Uri Args: extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs text: str The text data in the this element """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def UriFromString(xml_string): return CreateClassFromXMLString(Uri, xml_string) class Person(AtomBase): """A foundation class from which atom:author and atom:contributor extend. A person contains information like name, email address, and web page URI for an author or contributor to an Atom feed. """ _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _children['{%s}name' % (ATOM_NAMESPACE)] = ('name', Name) _children['{%s}email' % (ATOM_NAMESPACE)] = ('email', Email) _children['{%s}uri' % (ATOM_NAMESPACE)] = ('uri', Uri) def __init__(self, name=None, email=None, uri=None, extension_elements=None, extension_attributes=None, text=None): """Foundation from which author and contributor are derived. The constructor is provided for illustrative purposes, you should not need to instantiate a Person. Args: name: Name The person's name email: Email The person's email address uri: Uri The URI of the person's webpage extension_elements: list A list of ExtensionElement instances which are children of this element. extension_attributes: dict A dictionary of strings which are the values for additional XML attributes of this element. text: String The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) """ self.name = name self.email = email self.uri = uri self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text class Author(Person): """The atom:author element An author is a required element in Feed. """ _tag = 'author' _namespace = ATOM_NAMESPACE _children = Person._children.copy() _attributes = Person._attributes.copy() #_children = {} #_attributes = {} def __init__(self, name=None, email=None, uri=None, extension_elements=None, extension_attributes=None, text=None): """Constructor for Author Args: name: Name email: Email uri: Uri extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs text: str The text data in the this element """ self.name = name self.email = email self.uri = uri self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text def AuthorFromString(xml_string): return CreateClassFromXMLString(Author, xml_string) class Contributor(Person): """The atom:contributor element""" _tag = 'contributor' _namespace = ATOM_NAMESPACE _children = Person._children.copy() _attributes = Person._attributes.copy() def __init__(self, name=None, email=None, uri=None, extension_elements=None, extension_attributes=None, text=None): """Constructor for Contributor Args: name: Name email: Email uri: Uri extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs text: str The text data in the this element """ self.name = name self.email = email self.uri = uri self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} self.text = text def ContributorFromString(xml_string): return CreateClassFromXMLString(Contributor, xml_string) class Link(AtomBase): """The atom:link element""" _tag = 'link' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _attributes['rel'] = 'rel' _attributes['href'] = 'href' _attributes['type'] = 'type' _attributes['title'] = 'title' _attributes['length'] = 'length' _attributes['hreflang'] = 'hreflang' def __init__(self, href=None, rel=None, link_type=None, hreflang=None, title=None, length=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Link Args: href: string The href attribute of the link rel: string type: string hreflang: string The language for the href title: string length: string The length of the href's destination extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs text: str The text data in the this element """ self.href = href self.rel = rel self.type = link_type self.hreflang = hreflang self.title = title self.length = length self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def LinkFromString(xml_string): return CreateClassFromXMLString(Link, xml_string) class Generator(AtomBase): """The atom:generator element""" _tag = 'generator' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _attributes['uri'] = 'uri' _attributes['version'] = 'version' def __init__(self, uri=None, version=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Generator Args: uri: string version: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.uri = uri self.version = version self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def GeneratorFromString(xml_string): return CreateClassFromXMLString(Generator, xml_string) class Text(AtomBase): """A foundation class from which atom:title, summary, etc. extend. This class should never be instantiated. """ _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _attributes['type'] = 'type' def __init__(self, text_type=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Text Args: text_type: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.type = text_type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Title(Text): """The atom:title element""" _tag = 'title' _namespace = ATOM_NAMESPACE _children = Text._children.copy() _attributes = Text._attributes.copy() def __init__(self, title_type=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Title Args: title_type: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.type = title_type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def TitleFromString(xml_string): return CreateClassFromXMLString(Title, xml_string) class Subtitle(Text): """The atom:subtitle element""" _tag = 'subtitle' _namespace = ATOM_NAMESPACE _children = Text._children.copy() _attributes = Text._attributes.copy() def __init__(self, subtitle_type=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Subtitle Args: subtitle_type: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.type = subtitle_type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SubtitleFromString(xml_string): return CreateClassFromXMLString(Subtitle, xml_string) class Rights(Text): """The atom:rights element""" _tag = 'rights' _namespace = ATOM_NAMESPACE _children = Text._children.copy() _attributes = Text._attributes.copy() def __init__(self, rights_type=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Rights Args: rights_type: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.type = rights_type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def RightsFromString(xml_string): return CreateClassFromXMLString(Rights, xml_string) class Summary(Text): """The atom:summary element""" _tag = 'summary' _namespace = ATOM_NAMESPACE _children = Text._children.copy() _attributes = Text._attributes.copy() def __init__(self, summary_type=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Summary Args: summary_type: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.type = summary_type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SummaryFromString(xml_string): return CreateClassFromXMLString(Summary, xml_string) class Content(Text): """The atom:content element""" _tag = 'content' _namespace = ATOM_NAMESPACE _children = Text._children.copy() _attributes = Text._attributes.copy() _attributes['src'] = 'src' def __init__(self, content_type=None, src=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Content Args: content_type: string src: string text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.type = content_type self.src = src self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def ContentFromString(xml_string): return CreateClassFromXMLString(Content, xml_string) class Category(AtomBase): """The atom:category element""" _tag = 'category' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _attributes['term'] = 'term' _attributes['scheme'] = 'scheme' _attributes['label'] = 'label' def __init__(self, term=None, scheme=None, label=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Category Args: term: str scheme: str label: str text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.term = term self.scheme = scheme self.label = label self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def CategoryFromString(xml_string): return CreateClassFromXMLString(Category, xml_string) class Id(AtomBase): """The atom:id element.""" _tag = 'id' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Id Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def IdFromString(xml_string): return CreateClassFromXMLString(Id, xml_string) class Icon(AtomBase): """The atom:icon element.""" _tag = 'icon' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Icon Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def IconFromString(xml_string): return CreateClassFromXMLString(Icon, xml_string) class Logo(AtomBase): """The atom:logo element.""" _tag = 'logo' _namespace = ATOM_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Logo Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def LogoFromString(xml_string): return CreateClassFromXMLString(Logo, xml_string) class Draft(AtomBase): """The app:draft element which indicates if this entry should be public.""" _tag = 'draft' _namespace = APP_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for app:draft Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def DraftFromString(xml_string): return CreateClassFromXMLString(Draft, xml_string) class Control(AtomBase): """The app:control element indicating restrictions on publication. The APP control element may contain a draft element indicating whether or not this entry should be publicly available. """ _tag = 'control' _namespace = APP_NAMESPACE _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _children['{%s}draft' % APP_NAMESPACE] = ('draft', Draft) def __init__(self, draft=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for app:control""" self.draft = draft self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def ControlFromString(xml_string): return CreateClassFromXMLString(Control, xml_string) class Date(AtomBase): """A parent class for atom:updated, published, etc.""" #TODO Add text to and from time conversion methods to allow users to set # the contents of a Date to a python DateTime object. _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Updated(Date): """The atom:updated element.""" _tag = 'updated' _namespace = ATOM_NAMESPACE _children = Date._children.copy() _attributes = Date._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Updated Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def UpdatedFromString(xml_string): return CreateClassFromXMLString(Updated, xml_string) class Published(Date): """The atom:published element.""" _tag = 'published' _namespace = ATOM_NAMESPACE _children = Date._children.copy() _attributes = Date._attributes.copy() def __init__(self, text=None, extension_elements=None, extension_attributes=None): """Constructor for Published Args: text: str The text data in the this element extension_elements: list A list of ExtensionElement instances extension_attributes: dict A dictionary of attribute value string pairs """ self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def PublishedFromString(xml_string): return CreateClassFromXMLString(Published, xml_string) class LinkFinder(object): """An "interface" providing methods to find link elements Entry elements often contain multiple links which differ in the rel attribute or content type. Often, developers are interested in a specific type of link so this class provides methods to find specific classes of links. This class is used as a mixin in Atom entries and feeds. """ def GetSelfLink(self): """Find the first link with rel set to 'self' Returns: An atom.Link or none if none of the links had rel equal to 'self' """ for a_link in self.link: if a_link.rel == 'self': return a_link return None def GetEditLink(self): for a_link in self.link: if a_link.rel == 'edit': return a_link return None def GetEditMediaLink(self): for a_link in self.link: if a_link.rel == 'edit-media': return a_link return None def GetNextLink(self): for a_link in self.link: if a_link.rel == 'next': return a_link return None def GetLicenseLink(self): for a_link in self.link: if a_link.rel == 'license': return a_link return None def GetAlternateLink(self): for a_link in self.link: if a_link.rel == 'alternate': return a_link return None class FeedEntryParent(AtomBase, LinkFinder): """A super class for atom:feed and entry, contains shared attributes""" _children = AtomBase._children.copy() _attributes = AtomBase._attributes.copy() _children['{%s}author' % ATOM_NAMESPACE] = ('author', [Author]) _children['{%s}category' % ATOM_NAMESPACE] = ('category', [Category]) _children['{%s}contributor' % ATOM_NAMESPACE] = ('contributor', [Contributor]) _children['{%s}id' % ATOM_NAMESPACE] = ('id', Id) _children['{%s}link' % ATOM_NAMESPACE] = ('link', [Link]) _children['{%s}rights' % ATOM_NAMESPACE] = ('rights', Rights) _children['{%s}title' % ATOM_NAMESPACE] = ('title', Title) _children['{%s}updated' % ATOM_NAMESPACE] = ('updated', Updated) def __init__(self, author=None, category=None, contributor=None, atom_id=None, link=None, rights=None, title=None, updated=None, text=None, extension_elements=None, extension_attributes=None): self.author = author or [] self.category = category or [] self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.rights = rights self.title = title self.updated = updated self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Source(FeedEntryParent): """The atom:source element""" _tag = 'source' _namespace = ATOM_NAMESPACE _children = FeedEntryParent._children.copy() _attributes = FeedEntryParent._attributes.copy() _children['{%s}generator' % ATOM_NAMESPACE] = ('generator', Generator) _children['{%s}icon' % ATOM_NAMESPACE] = ('icon', Icon) _children['{%s}logo' % ATOM_NAMESPACE] = ('logo', Logo) _children['{%s}subtitle' % ATOM_NAMESPACE] = ('subtitle', Subtitle) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Source Args: author: list (optional) A list of Author instances which belong to this class. category: list (optional) A list of Category instances contributor: list (optional) A list on Contributor instances generator: Generator (optional) icon: Icon (optional) id: Id (optional) The entry's Id element link: list (optional) A list of Link instances logo: Logo (optional) rights: Rights (optional) The entry's Rights element subtitle: Subtitle (optional) The entry's subtitle element title: Title (optional) the entry's title element updated: Updated (optional) the entry's updated element text: String (optional) The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) extension_elements: list (optional) A list of ExtensionElement instances which are children of this element. extension_attributes: dict (optional) A dictionary of strings which are the values for additional XML attributes of this element. """ self.author = author or [] self.category = category or [] self.contributor = contributor or [] self.generator = generator self.icon = icon self.id = atom_id self.link = link or [] self.logo = logo self.rights = rights self.subtitle = subtitle self.title = title self.updated = updated self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def SourceFromString(xml_string): return CreateClassFromXMLString(Source, xml_string) class Entry(FeedEntryParent): """The atom:entry element""" _tag = 'entry' _namespace = ATOM_NAMESPACE _children = FeedEntryParent._children.copy() _attributes = FeedEntryParent._attributes.copy() _children['{%s}content' % ATOM_NAMESPACE] = ('content', Content) _children['{%s}published' % ATOM_NAMESPACE] = ('published', Published) _children['{%s}source' % ATOM_NAMESPACE] = ('source', Source) _children['{%s}summary' % ATOM_NAMESPACE] = ('summary', Summary) _children['{%s}control' % APP_NAMESPACE] = ('control', Control) def __init__(self, author=None, category=None, content=None, contributor=None, atom_id=None, link=None, published=None, rights=None, source=None, summary=None, control=None, title=None, updated=None, extension_elements=None, extension_attributes=None, text=None): """Constructor for atom:entry Args: author: list A list of Author instances which belong to this class. category: list A list of Category instances content: Content The entry's Content contributor: list A list on Contributor instances id: Id The entry's Id element link: list A list of Link instances published: Published The entry's Published element rights: Rights The entry's Rights element source: Source the entry's source element summary: Summary the entry's summary element title: Title the entry's title element updated: Updated the entry's updated element control: The entry's app:control element which can be used to mark an entry as a draft which should not be publicly viewable. text: String The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) extension_elements: list A list of ExtensionElement instances which are children of this element. extension_attributes: dict A dictionary of strings which are the values for additional XML attributes of this element. """ self.author = author or [] self.category = category or [] self.content = content self.contributor = contributor or [] self.id = atom_id self.link = link or [] self.published = published self.rights = rights self.source = source self.summary = summary self.title = title self.updated = updated self.control = control self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} __init__ = v1_deprecated('Please use atom.data.Entry instead.')(__init__) def EntryFromString(xml_string): return CreateClassFromXMLString(Entry, xml_string) class Feed(Source): """The atom:feed element""" _tag = 'feed' _namespace = ATOM_NAMESPACE _children = Source._children.copy() _attributes = Source._attributes.copy() _children['{%s}entry' % ATOM_NAMESPACE] = ('entry', [Entry]) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, text=None, extension_elements=None, extension_attributes=None): """Constructor for Source Args: author: list (optional) A list of Author instances which belong to this class. category: list (optional) A list of Category instances contributor: list (optional) A list on Contributor instances generator: Generator (optional) icon: Icon (optional) id: Id (optional) The entry's Id element link: list (optional) A list of Link instances logo: Logo (optional) rights: Rights (optional) The entry's Rights element subtitle: Subtitle (optional) The entry's subtitle element title: Title (optional) the entry's title element updated: Updated (optional) the entry's updated element entry: list (optional) A list of the Entry instances contained in the feed. text: String (optional) The text contents of the element. This is the contents of the Entry's XML text node. (Example: <foo>This is the text</foo>) extension_elements: list (optional) A list of ExtensionElement instances which are children of this element. extension_attributes: dict (optional) A dictionary of strings which are the values for additional XML attributes of this element. """ self.author = author or [] self.category = category or [] self.contributor = contributor or [] self.generator = generator self.icon = icon self.id = atom_id self.link = link or [] self.logo = logo self.rights = rights self.subtitle = subtitle self.title = title self.updated = updated self.entry = entry or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} __init__ = v1_deprecated('Please use atom.data.Feed instead.')(__init__) def FeedFromString(xml_string): return CreateClassFromXMLString(Feed, xml_string) class ExtensionElement(object): """Represents extra XML elements contained in Atom classes.""" def __init__(self, tag, namespace=None, attributes=None, children=None, text=None): """Constructor for EtensionElement Args: namespace: string (optional) The XML namespace for this element. tag: string (optional) The tag (without the namespace qualifier) for this element. To reconstruct the full qualified name of the element, combine this tag with the namespace. attributes: dict (optinal) The attribute value string pairs for the XML attributes of this element. children: list (optional) A list of ExtensionElements which represent the XML child nodes of this element. """ self.namespace = namespace self.tag = tag self.attributes = attributes or {} self.children = children or [] self.text = text def ToString(self): element_tree = self._TransferToElementTree(ElementTree.Element('')) return ElementTree.tostring(element_tree, encoding="UTF-8") def _TransferToElementTree(self, element_tree): if self.tag is None: return None if self.namespace is not None: element_tree.tag = '{%s}%s' % (self.namespace, self.tag) else: element_tree.tag = self.tag for key, value in self.attributes.iteritems(): element_tree.attrib[key] = value for child in self.children: child._BecomeChildElement(element_tree) element_tree.text = self.text return element_tree def _BecomeChildElement(self, element_tree): """Converts this object into an etree element and adds it as a child node. Adds self to the ElementTree. This method is required to avoid verbose XML which constantly redefines the namespace. Args: element_tree: ElementTree._Element The element to which this object's XML will be added. """ new_element = ElementTree.Element('') element_tree.append(new_element) self._TransferToElementTree(new_element) def FindChildren(self, tag=None, namespace=None): """Searches child nodes for objects with the desired tag/namespace. Returns a list of extension elements within this object whose tag and/or namespace match those passed in. To find all children in a particular namespace, specify the namespace but not the tag name. If you specify only the tag, the result list may contain extension elements in multiple namespaces. Args: tag: str (optional) The desired tag namespace: str (optional) The desired namespace Returns: A list of elements whose tag and/or namespace match the parameters values """ results = [] if tag and namespace: for element in self.children: if element.tag == tag and element.namespace == namespace: results.append(element) elif tag and not namespace: for element in self.children: if element.tag == tag: results.append(element) elif namespace and not tag: for element in self.children: if element.namespace == namespace: results.append(element) else: for element in self.children: results.append(element) return results def ExtensionElementFromString(xml_string): element_tree = ElementTree.fromstring(xml_string) return _ExtensionElementFromElementTree(element_tree) def _ExtensionElementFromElementTree(element_tree): element_tag = element_tree.tag if '}' in element_tag: namespace = element_tag[1:element_tag.index('}')] tag = element_tag[element_tag.index('}')+1:] else: namespace = None tag = element_tag extension = ExtensionElement(namespace=namespace, tag=tag) for key, value in element_tree.attrib.iteritems(): extension.attributes[key] = value for child in element_tree: extension.children.append(_ExtensionElementFromElementTree(child)) extension.text = element_tree.text return extension def deprecated(warning=None): """Decorator to raise warning each time the function is called. Args: warning: The warning message to be displayed as a string (optinoal). """ warning = warning or '' # This closure is what is returned from the deprecated function. def mark_deprecated(f): # The deprecated_function wraps the actual call to f. def deprecated_function(*args, **kwargs): warnings.warn(warning, DeprecationWarning, stacklevel=2) return f(*args, **kwargs) # Preserve the original name to avoid masking all decorated functions as # 'deprecated_function' try: deprecated_function.func_name = f.func_name except TypeError: # Setting the func_name is not allowed in Python2.3. pass return deprecated_function return mark_deprecated
Python
#!/usr/bin/python # # Copyright (C) 2006, 2007, 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """AtomService provides CRUD ops. in line with the Atom Publishing Protocol. AtomService: Encapsulates the ability to perform insert, update and delete operations with the Atom Publishing Protocol on which GData is based. An instance can perform query, insertion, deletion, and update. HttpRequest: Function that performs a GET, POST, PUT, or DELETE HTTP request to the specified end point. An AtomService object or a subclass can be used to specify information about the request. """ __author__ = 'api.jscudder (Jeff Scudder)' import atom.http_interface import atom.url import atom.http import atom.token_store import os import httplib import urllib import re import base64 import socket import warnings try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom class AtomService(object): """Performs Atom Publishing Protocol CRUD operations. The AtomService contains methods to perform HTTP CRUD operations. """ # Default values for members port = 80 ssl = False # Set the current_token to force the AtomService to use this token # instead of searching for an appropriate token in the token_store. current_token = None auto_store_tokens = True auto_set_current_token = True def _get_override_token(self): return self.current_token def _set_override_token(self, token): self.current_token = token override_token = property(_get_override_token, _set_override_token) #@atom.v1_deprecated('Please use atom.client.AtomPubClient instead.') def __init__(self, server=None, additional_headers=None, application_name='', http_client=None, token_store=None): """Creates a new AtomService client. Args: server: string (optional) The start of a URL for the server to which all operations should be directed. Example: 'www.google.com' additional_headers: dict (optional) Any additional HTTP headers which should be included with CRUD operations. http_client: An object responsible for making HTTP requests using a request method. If none is provided, a new instance of atom.http.ProxiedHttpClient will be used. token_store: Keeps a collection of authorization tokens which can be applied to requests for a specific URLs. Critical methods are find_token based on a URL (atom.url.Url or a string), add_token, and remove_token. """ self.http_client = http_client or atom.http.ProxiedHttpClient() self.token_store = token_store or atom.token_store.TokenStore() self.server = server self.additional_headers = additional_headers or {} self.additional_headers['User-Agent'] = atom.http_interface.USER_AGENT % ( application_name,) # If debug is True, the HTTPConnection will display debug information self._set_debug(False) __init__ = atom.v1_deprecated( 'Please use atom.client.AtomPubClient instead.')( __init__) def _get_debug(self): return self.http_client.debug def _set_debug(self, value): self.http_client.debug = value debug = property(_get_debug, _set_debug, doc='If True, HTTP debug information is printed.') def use_basic_auth(self, username, password, scopes=None): if username is not None and password is not None: if scopes is None: scopes = [atom.token_store.SCOPE_ALL] base_64_string = base64.encodestring('%s:%s' % (username, password)) token = BasicAuthToken('Basic %s' % base_64_string.strip(), scopes=[atom.token_store.SCOPE_ALL]) if self.auto_set_current_token: self.current_token = token if self.auto_store_tokens: return self.token_store.add_token(token) return True return False def UseBasicAuth(self, username, password, for_proxy=False): """Sets an Authenticaiton: Basic HTTP header containing plaintext. Deprecated, use use_basic_auth instead. The username and password are base64 encoded and added to an HTTP header which will be included in each request. Note that your username and password are sent in plaintext. Args: username: str password: str """ self.use_basic_auth(username, password) #@atom.v1_deprecated('Please use atom.client.AtomPubClient for requests.') def request(self, operation, url, data=None, headers=None, url_params=None): if isinstance(url, (str, unicode)): if url.startswith('http:') and self.ssl: # Force all requests to be https if self.ssl is True. url = atom.url.parse_url('https:' + url[5:]) elif not url.startswith('http') and self.ssl: url = atom.url.parse_url('https://%s%s' % (self.server, url)) elif not url.startswith('http'): url = atom.url.parse_url('http://%s%s' % (self.server, url)) else: url = atom.url.parse_url(url) if url_params: for name, value in url_params.iteritems(): url.params[name] = value all_headers = self.additional_headers.copy() if headers: all_headers.update(headers) # If the list of headers does not include a Content-Length, attempt to # calculate it based on the data object. if data and 'Content-Length' not in all_headers: content_length = CalculateDataLength(data) if content_length: all_headers['Content-Length'] = str(content_length) # Find an Authorization token for this URL if one is available. if self.override_token: auth_token = self.override_token else: auth_token = self.token_store.find_token(url) return auth_token.perform_request(self.http_client, operation, url, data=data, headers=all_headers) request = atom.v1_deprecated( 'Please use atom.client.AtomPubClient for requests.')( request) # CRUD operations def Get(self, uri, extra_headers=None, url_params=None, escape_params=True): """Query the APP server with the given URI The uri is the portion of the URI after the server value (server example: 'www.google.com'). Example use: To perform a query against Google Base, set the server to 'base.google.com' and set the uri to '/base/feeds/...', where ... is your query. For example, to find snippets for all digital cameras uri should be set to: '/base/feeds/snippets?bq=digital+camera' Args: uri: string The query in the form of a URI. Example: '/base/feeds/snippets?bq=digital+camera'. extra_headers: dicty (optional) Extra HTTP headers to be included in the GET request. These headers are in addition to those stored in the client's additional_headers property. The client automatically sets the Content-Type and Authorization headers. url_params: dict (optional) Additional URL parameters to be included in the query. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse The server's response to the GET request. """ return self.request('GET', uri, data=None, headers=extra_headers, url_params=url_params) def Post(self, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Insert data into an APP server at the given URI. Args: data: string, ElementTree._Element, or something with a __str__ method The XML to be sent to the uri. uri: string The location (feed) to which the data should be inserted. Example: '/base/feeds/items'. extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse Server's response to the POST request. """ if extra_headers is None: extra_headers = {} if content_type: extra_headers['Content-Type'] = content_type return self.request('POST', uri, data=data, headers=extra_headers, url_params=url_params) def Put(self, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Updates an entry at the given URI. Args: data: string, ElementTree._Element, or xml_wrapper.ElementWrapper The XML containing the updated data. uri: string A URI indicating entry to which the update will be applied. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type, Authorization, and Content-Length headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse Server's response to the PUT request. """ if extra_headers is None: extra_headers = {} if content_type: extra_headers['Content-Type'] = content_type return self.request('PUT', uri, data=data, headers=extra_headers, url_params=url_params) def Delete(self, uri, extra_headers=None, url_params=None, escape_params=True): """Deletes the entry at the given URI. Args: uri: string The URI of the entry to be deleted. Example: '/base/feeds/items/ITEM-ID' extra_headers: dict (optional) HTTP headers which are to be included. The client automatically sets the Content-Type and Authorization headers. url_params: dict (optional) Additional URL parameters to be included in the URI. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: httplib.HTTPResponse Server's response to the DELETE request. """ return self.request('DELETE', uri, data=None, headers=extra_headers, url_params=url_params) class BasicAuthToken(atom.http_interface.GenericToken): def __init__(self, auth_header, scopes=None): """Creates a token used to add Basic Auth headers to HTTP requests. Args: auth_header: str The value for the Authorization header. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' """ self.auth_header = auth_header self.scopes = scopes or [] def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header to the basic auth string.""" if headers is None: headers = {'Authorization':self.auth_header} else: headers['Authorization'] = self.auth_header return http_client.request(operation, url, data=data, headers=headers) def __str__(self): return self.auth_header def valid_for_scope(self, url): """Tells the caller if the token authorizes access to the desired URL. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) for scope in self.scopes: if scope == atom.token_store.SCOPE_ALL: return True if isinstance(scope, (str, unicode)): scope = atom.url.parse_url(scope) if scope == url: return True # Check the host and the path, but ignore the port and protocol. elif scope.host == url.host and not scope.path: return True elif scope.host == url.host and scope.path and not url.path: continue elif scope.host == url.host and url.path.startswith(scope.path): return True return False def PrepareConnection(service, full_uri): """Opens a connection to the server based on the full URI. This method is deprecated, instead use atom.http.HttpClient.request. Examines the target URI and the proxy settings, which are set as environment variables, to open a connection with the server. This connection is used to make an HTTP request. Args: service: atom.AtomService or a subclass. It must have a server string which represents the server host to which the request should be made. It may also have a dictionary of additional_headers to send in the HTTP request. full_uri: str Which is the target relative (lacks protocol and host) or absolute URL to be opened. Example: 'https://www.google.com/accounts/ClientLogin' or 'base/feeds/snippets' where the server is set to www.google.com. Returns: A tuple containing the httplib.HTTPConnection and the full_uri for the request. """ deprecation('calling deprecated function PrepareConnection') (server, port, ssl, partial_uri) = ProcessUrl(service, full_uri) if ssl: # destination is https proxy = os.environ.get('https_proxy') if proxy: (p_server, p_port, p_ssl, p_uri) = ProcessUrl(service, proxy, True) proxy_username = os.environ.get('proxy-username') if not proxy_username: proxy_username = os.environ.get('proxy_username') proxy_password = os.environ.get('proxy-password') if not proxy_password: proxy_password = os.environ.get('proxy_password') if proxy_username: user_auth = base64.encodestring('%s:%s' % (proxy_username, proxy_password)) proxy_authorization = ('Proxy-authorization: Basic %s\r\n' % ( user_auth.strip())) else: proxy_authorization = '' proxy_connect = 'CONNECT %s:%s HTTP/1.0\r\n' % (server, port) user_agent = 'User-Agent: %s\r\n' % ( service.additional_headers['User-Agent']) proxy_pieces = (proxy_connect + proxy_authorization + user_agent + '\r\n') #now connect, very simple recv and error checking p_sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) p_sock.connect((p_server,p_port)) p_sock.sendall(proxy_pieces) response = '' # Wait for the full response. while response.find("\r\n\r\n") == -1: response += p_sock.recv(8192) p_status=response.split()[1] if p_status!=str(200): raise atom.http.ProxyError('Error status=%s' % p_status) # Trivial setup for ssl socket. ssl = socket.ssl(p_sock, None, None) fake_sock = httplib.FakeSocket(p_sock, ssl) # Initalize httplib and replace with the proxy socket. connection = httplib.HTTPConnection(server) connection.sock=fake_sock full_uri = partial_uri else: connection = httplib.HTTPSConnection(server, port) full_uri = partial_uri else: # destination is http proxy = os.environ.get('http_proxy') if proxy: (p_server, p_port, p_ssl, p_uri) = ProcessUrl(service.server, proxy, True) proxy_username = os.environ.get('proxy-username') if not proxy_username: proxy_username = os.environ.get('proxy_username') proxy_password = os.environ.get('proxy-password') if not proxy_password: proxy_password = os.environ.get('proxy_password') if proxy_username: UseBasicAuth(service, proxy_username, proxy_password, True) connection = httplib.HTTPConnection(p_server, p_port) if not full_uri.startswith("http://"): if full_uri.startswith("/"): full_uri = "http://%s%s" % (service.server, full_uri) else: full_uri = "http://%s/%s" % (service.server, full_uri) else: connection = httplib.HTTPConnection(server, port) full_uri = partial_uri return (connection, full_uri) def UseBasicAuth(service, username, password, for_proxy=False): """Sets an Authenticaiton: Basic HTTP header containing plaintext. Deprecated, use AtomService.use_basic_auth insread. The username and password are base64 encoded and added to an HTTP header which will be included in each request. Note that your username and password are sent in plaintext. The auth header is added to the additional_headers dictionary in the service object. Args: service: atom.AtomService or a subclass which has an additional_headers dict as a member. username: str password: str """ deprecation('calling deprecated function UseBasicAuth') base_64_string = base64.encodestring('%s:%s' % (username, password)) base_64_string = base_64_string.strip() if for_proxy: header_name = 'Proxy-Authorization' else: header_name = 'Authorization' service.additional_headers[header_name] = 'Basic %s' % (base_64_string,) def ProcessUrl(service, url, for_proxy=False): """Processes a passed URL. If the URL does not begin with https?, then the default value for server is used This method is deprecated, use atom.url.parse_url instead. """ if not isinstance(url, atom.url.Url): url = atom.url.parse_url(url) server = url.host ssl = False port = 80 if not server: if hasattr(service, 'server'): server = service.server else: server = service if not url.protocol and hasattr(service, 'ssl'): ssl = service.ssl if hasattr(service, 'port'): port = service.port else: if url.protocol == 'https': ssl = True elif url.protocol == 'http': ssl = False if url.port: port = int(url.port) elif port == 80 and ssl: port = 443 return (server, port, ssl, url.get_request_uri()) def DictionaryToParamList(url_parameters, escape_params=True): """Convert a dictionary of URL arguments into a URL parameter string. This function is deprcated, use atom.url.Url instead. Args: url_parameters: The dictionaty of key-value pairs which will be converted into URL parameters. For example, {'dry-run': 'true', 'foo': 'bar'} will become ['dry-run=true', 'foo=bar']. Returns: A list which contains a string for each key-value pair. The strings are ready to be incorporated into a URL by using '&'.join([] + parameter_list) """ # Choose which function to use when modifying the query and parameters. # Use quote_plus when escape_params is true. transform_op = [str, urllib.quote_plus][bool(escape_params)] # Create a list of tuples containing the escaped version of the # parameter-value pairs. parameter_tuples = [(transform_op(param), transform_op(value)) for param, value in (url_parameters or {}).items()] # Turn parameter-value tuples into a list of strings in the form # 'PARAMETER=VALUE'. return ['='.join(x) for x in parameter_tuples] def BuildUri(uri, url_params=None, escape_params=True): """Converts a uri string and a collection of parameters into a URI. This function is deprcated, use atom.url.Url instead. Args: uri: string url_params: dict (optional) escape_params: boolean (optional) uri: string The start of the desired URI. This string can alrady contain URL parameters. Examples: '/base/feeds/snippets', '/base/feeds/snippets?bq=digital+camera' url_parameters: dict (optional) Additional URL parameters to be included in the query. These are translated into query arguments in the form '&dict_key=value&...'. Example: {'max-results': '250'} becomes &max-results=250 escape_params: boolean (optional) If false, the calling code has already ensured that the query will form a valid URL (all reserved characters have been escaped). If true, this method will escape the query and any URL parameters provided. Returns: string The URI consisting of the escaped URL parameters appended to the initial uri string. """ # Prepare URL parameters for inclusion into the GET request. parameter_list = DictionaryToParamList(url_params, escape_params) # Append the URL parameters to the URL. if parameter_list: if uri.find('?') != -1: # If there are already URL parameters in the uri string, add the # parameters after a new & character. full_uri = '&'.join([uri] + parameter_list) else: # The uri string did not have any URL parameters (no ? character) # so put a ? between the uri and URL parameters. full_uri = '%s%s' % (uri, '?%s' % ('&'.join([] + parameter_list))) else: full_uri = uri return full_uri def HttpRequest(service, operation, data, uri, extra_headers=None, url_params=None, escape_params=True, content_type='application/atom+xml'): """Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE. This method is deprecated, use atom.http.HttpClient.request instead. Usage example, perform and HTTP GET on http://www.google.com/: import atom.service client = atom.service.AtomService() http_response = client.Get('http://www.google.com/') or you could set the client.server to 'www.google.com' and use the following: client.server = 'www.google.com' http_response = client.Get('/') Args: service: atom.AtomService object which contains some of the parameters needed to make the request. The following members are used to construct the HTTP call: server (str), additional_headers (dict), port (int), and ssl (bool). operation: str The HTTP operation to be performed. This is usually one of 'GET', 'POST', 'PUT', or 'DELETE' data: ElementTree, filestream, list of parts, or other object which can be converted to a string. Should be set to None when performing a GET or PUT. If data is a file-like object which can be read, this method will read a chunk of 100K bytes at a time and send them. If the data is a list of parts to be sent, each part will be evaluated and sent. uri: The beginning of the URL to which the request should be sent. Examples: '/', '/base/feeds/snippets', '/m8/feeds/contacts/default/base' extra_headers: dict of strings. HTTP headers which should be sent in the request. These headers are in addition to those stored in service.additional_headers. url_params: dict of strings. Key value pairs to be added to the URL as URL parameters. For example {'foo':'bar', 'test':'param'} will become ?foo=bar&test=param. escape_params: bool default True. If true, the keys and values in url_params will be URL escaped when the form is constructed (Special characters converted to %XX form.) content_type: str The MIME type for the data being sent. Defaults to 'application/atom+xml', this is only used if data is set. """ deprecation('call to deprecated function HttpRequest') full_uri = BuildUri(uri, url_params, escape_params) (connection, full_uri) = PrepareConnection(service, full_uri) if extra_headers is None: extra_headers = {} # Turn on debug mode if the debug member is set. if service.debug: connection.debuglevel = 1 connection.putrequest(operation, full_uri) # If the list of headers does not include a Content-Length, attempt to # calculate it based on the data object. if (data and not service.additional_headers.has_key('Content-Length') and not extra_headers.has_key('Content-Length')): content_length = CalculateDataLength(data) if content_length: extra_headers['Content-Length'] = str(content_length) if content_type: extra_headers['Content-Type'] = content_type # Send the HTTP headers. if isinstance(service.additional_headers, dict): for header in service.additional_headers: connection.putheader(header, service.additional_headers[header]) if isinstance(extra_headers, dict): for header in extra_headers: connection.putheader(header, extra_headers[header]) connection.endheaders() # If there is data, send it in the request. if data: if isinstance(data, list): for data_part in data: __SendDataPart(data_part, connection) else: __SendDataPart(data, connection) # Return the HTTP Response from the server. return connection.getresponse() def __SendDataPart(data, connection): """This method is deprecated, use atom.http._send_data_part""" deprecated('call to deprecated function __SendDataPart') if isinstance(data, str): #TODO add handling for unicode. connection.send(data) return elif ElementTree.iselement(data): connection.send(ElementTree.tostring(data)) return # Check to see if data is a file-like object that has a read method. elif hasattr(data, 'read'): # Read the file and send it a chunk at a time. while 1: binarydata = data.read(100000) if binarydata == '': break connection.send(binarydata) return else: # The data object was not a file. # Try to convert to a string and send the data. connection.send(str(data)) return def CalculateDataLength(data): """Attempts to determine the length of the data to send. This method will respond with a length only if the data is a string or and ElementTree element. Args: data: object If this is not a string or ElementTree element this funtion will return None. """ if isinstance(data, str): return len(data) elif isinstance(data, list): return None elif ElementTree.iselement(data): return len(ElementTree.tostring(data)) elif hasattr(data, 'read'): # If this is a file-like object, don't try to guess the length. return None else: return len(str(data)) def deprecation(message): warnings.warn(message, DeprecationWarning, stacklevel=2)
Python
#!/usr/bin/python # # Copyright (C) 2008 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """This module provides a common interface for all HTTP requests. HttpResponse: Represents the server's response to an HTTP request. Provides an interface identical to httplib.HTTPResponse which is the response expected from higher level classes which use HttpClient.request. GenericHttpClient: Provides an interface (superclass) for an object responsible for making HTTP requests. Subclasses of this object are used in AtomService and GDataService to make requests to the server. By changing the http_client member object, the AtomService is able to make HTTP requests using different logic (for example, when running on Google App Engine, the http_client makes requests using the App Engine urlfetch API). """ __author__ = 'api.jscudder (Jeff Scudder)' import StringIO USER_AGENT = '%s GData-Python/2.0.15' class Error(Exception): pass class UnparsableUrlObject(Error): pass class ContentLengthRequired(Error): pass class HttpResponse(object): def __init__(self, body=None, status=None, reason=None, headers=None): """Constructor for an HttpResponse object. HttpResponse represents the server's response to an HTTP request from the client. The HttpClient.request method returns a httplib.HTTPResponse object and this HttpResponse class is designed to mirror the interface exposed by httplib.HTTPResponse. Args: body: A file like object, with a read() method. The body could also be a string, and the constructor will wrap it so that HttpResponse.read(self) will return the full string. status: The HTTP status code as an int. Example: 200, 201, 404. reason: The HTTP status message which follows the code. Example: OK, Created, Not Found headers: A dictionary containing the HTTP headers in the server's response. A common header in the response is Content-Length. """ if body: if hasattr(body, 'read'): self._body = body else: self._body = StringIO.StringIO(body) else: self._body = None if status is not None: self.status = int(status) else: self.status = None self.reason = reason self._headers = headers or {} def getheader(self, name, default=None): if name in self._headers: return self._headers[name] else: return default def read(self, amt=None): if not amt: return self._body.read() else: return self._body.read(amt) class GenericHttpClient(object): debug = False def __init__(self, http_client, headers=None): """ Args: http_client: An object which provides a request method to make an HTTP request. The request method in GenericHttpClient performs a call-through to the contained HTTP client object. headers: A dictionary containing HTTP headers which should be included in every HTTP request. Common persistent headers include 'User-Agent'. """ self.http_client = http_client self.headers = headers or {} def request(self, operation, url, data=None, headers=None): all_headers = self.headers.copy() if headers: all_headers.update(headers) return self.http_client.request(operation, url, data=data, headers=all_headers) def get(self, url, headers=None): return self.request('GET', url, headers=headers) def post(self, url, data, headers=None): return self.request('POST', url, data=data, headers=headers) def put(self, url, data, headers=None): return self.request('PUT', url, data=data, headers=headers) def delete(self, url, headers=None): return self.request('DELETE', url, headers=headers) class GenericToken(object): """Represents an Authorization token to be added to HTTP requests. Some Authorization headers included calculated fields (digital signatures for example) which are based on the parameters of the HTTP request. Therefore the token is responsible for signing the request and adding the Authorization header. """ def perform_request(self, http_client, operation, url, data=None, headers=None): """For the GenericToken, no Authorization token is set.""" return http_client.request(operation, url, data=data, headers=headers) def valid_for_scope(self, url): """Tells the caller if the token authorizes access to the desired URL. Since the generic token doesn't add an auth header, it is not valid for any scope. """ return False
Python
#!/usr/bin/python # # Copyright (C) 2007 - 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import cgi import math import random import re import time import types import urllib import atom.http_interface import atom.token_store import atom.url import gdata.oauth as oauth import gdata.oauth.rsa as oauth_rsa try: import gdata.tlslite.utils.keyfactory as keyfactory except ImportError: from tlslite.tlslite.utils import keyfactory try: import gdata.tlslite.utils.cryptomath as cryptomath except ImportError: from tlslite.tlslite.utils import cryptomath import gdata.gauth __author__ = 'api.jscudder (Jeff Scudder)' PROGRAMMATIC_AUTH_LABEL = 'GoogleLogin auth=' AUTHSUB_AUTH_LABEL = 'AuthSub token=' """This module provides functions and objects used with Google authentication. Details on Google authorization mechanisms used with the Google Data APIs can be found here: http://code.google.com/apis/gdata/auth.html http://code.google.com/apis/accounts/ The essential functions are the following. Related to ClientLogin: generate_client_login_request_body: Constructs the body of an HTTP request to obtain a ClientLogin token for a specific service. extract_client_login_token: Creates a ClientLoginToken with the token from a success response to a ClientLogin request. get_captcha_challenge: If the server responded to the ClientLogin request with a CAPTCHA challenge, this method extracts the CAPTCHA URL and identifying CAPTCHA token. Related to AuthSub: generate_auth_sub_url: Constructs a full URL for a AuthSub request. The user's browser must be sent to this Google Accounts URL and redirected back to the app to obtain the AuthSub token. extract_auth_sub_token_from_url: Once the user's browser has been redirected back to the web app, use this function to create an AuthSubToken with the correct authorization token and scope. token_from_http_body: Extracts the AuthSubToken value string from the server's response to an AuthSub session token upgrade request. """ def generate_client_login_request_body(email, password, service, source, account_type='HOSTED_OR_GOOGLE', captcha_token=None, captcha_response=None): """Creates the body of the autentication request See http://code.google.com/apis/accounts/AuthForInstalledApps.html#Request for more details. Args: email: str password: str service: str source: str account_type: str (optional) Defaul is 'HOSTED_OR_GOOGLE', other valid values are 'GOOGLE' and 'HOSTED' captcha_token: str (optional) captcha_response: str (optional) Returns: The HTTP body to send in a request for a client login token. """ return gdata.gauth.generate_client_login_request_body(email, password, service, source, account_type, captcha_token, captcha_response) GenerateClientLoginRequestBody = generate_client_login_request_body def GenerateClientLoginAuthToken(http_body): """Returns the token value to use in Authorization headers. Reads the token from the server's response to a Client Login request and creates header value to use in requests. Args: http_body: str The body of the server's HTTP response to a Client Login request Returns: The value half of an Authorization header. """ token = get_client_login_token(http_body) if token: return 'GoogleLogin auth=%s' % token return None def get_client_login_token(http_body): """Returns the token value for a ClientLoginToken. Reads the token from the server's response to a Client Login request and creates the token value string to use in requests. Args: http_body: str The body of the server's HTTP response to a Client Login request Returns: The token value string for a ClientLoginToken. """ return gdata.gauth.get_client_login_token_string(http_body) def extract_client_login_token(http_body, scopes): """Parses the server's response and returns a ClientLoginToken. Args: http_body: str The body of the server's HTTP response to a Client Login request. It is assumed that the login request was successful. scopes: list containing atom.url.Urls or strs. The scopes list contains all of the partial URLs under which the client login token is valid. For example, if scopes contains ['http://example.com/foo'] then the client login token would be valid for http://example.com/foo/bar/baz Returns: A ClientLoginToken which is valid for the specified scopes. """ token_string = get_client_login_token(http_body) token = ClientLoginToken(scopes=scopes) token.set_token_string(token_string) return token def get_captcha_challenge(http_body, captcha_base_url='http://www.google.com/accounts/'): """Returns the URL and token for a CAPTCHA challenge issued by the server. Args: http_body: str The body of the HTTP response from the server which contains the CAPTCHA challenge. captcha_base_url: str This function returns a full URL for viewing the challenge image which is built from the server's response. This base_url is used as the beginning of the URL because the server only provides the end of the URL. For example the server provides 'Captcha?ctoken=Hi...N' and the URL for the image is 'http://www.google.com/accounts/Captcha?ctoken=Hi...N' Returns: A dictionary containing the information needed to repond to the CAPTCHA challenge, the image URL and the ID token of the challenge. The dictionary is in the form: {'token': string identifying the CAPTCHA image, 'url': string containing the URL of the image} Returns None if there was no CAPTCHA challenge in the response. """ return gdata.gauth.get_captcha_challenge(http_body, captcha_base_url) GetCaptchaChallenge = get_captcha_challenge def GenerateOAuthRequestTokenUrl( oauth_input_params, scopes, request_token_url='https://www.google.com/accounts/OAuthGetRequestToken', extra_parameters=None): """Generate a URL at which a request for OAuth request token is to be sent. Args: oauth_input_params: OAuthInputParams OAuth input parameters. scopes: list of strings The URLs of the services to be accessed. request_token_url: string The beginning of the request token URL. This is normally 'https://www.google.com/accounts/OAuthGetRequestToken' or '/accounts/OAuthGetRequestToken' extra_parameters: dict (optional) key-value pairs as any additional parameters to be included in the URL and signature while making a request for fetching an OAuth request token. All the OAuth parameters are added by default. But if provided through this argument, any default parameters will be overwritten. For e.g. a default parameter oauth_version 1.0 can be overwritten if extra_parameters = {'oauth_version': '2.0'} Returns: atom.url.Url OAuth request token URL. """ scopes_string = ' '.join([str(scope) for scope in scopes]) parameters = {'scope': scopes_string} if extra_parameters: parameters.update(extra_parameters) oauth_request = oauth.OAuthRequest.from_consumer_and_token( oauth_input_params.GetConsumer(), http_url=request_token_url, parameters=parameters) oauth_request.sign_request(oauth_input_params.GetSignatureMethod(), oauth_input_params.GetConsumer(), None) return atom.url.parse_url(oauth_request.to_url()) def GenerateOAuthAuthorizationUrl( request_token, authorization_url='https://www.google.com/accounts/OAuthAuthorizeToken', callback_url=None, extra_params=None, include_scopes_in_callback=False, scopes_param_prefix='oauth_token_scope'): """Generates URL at which user will login to authorize the request token. Args: request_token: gdata.auth.OAuthToken OAuth request token. authorization_url: string The beginning of the authorization URL. This is normally 'https://www.google.com/accounts/OAuthAuthorizeToken' or '/accounts/OAuthAuthorizeToken' callback_url: string (optional) The URL user will be sent to after logging in and granting access. extra_params: dict (optional) Additional parameters to be sent. include_scopes_in_callback: Boolean (default=False) if set to True, and if 'callback_url' is present, the 'callback_url' will be modified to include the scope(s) from the request token as a URL parameter. The key for the 'callback' URL's scope parameter will be OAUTH_SCOPE_URL_PARAM_NAME. The benefit of including the scope URL as a parameter to the 'callback' URL, is that the page which receives the OAuth token will be able to tell which URLs the token grants access to. scopes_param_prefix: string (default='oauth_token_scope') The URL parameter key which maps to the list of valid scopes for the token. This URL parameter will be included in the callback URL along with the scopes of the token as value if include_scopes_in_callback=True. Returns: atom.url.Url OAuth authorization URL. """ scopes = request_token.scopes if isinstance(scopes, list): scopes = ' '.join(scopes) if include_scopes_in_callback and callback_url: if callback_url.find('?') > -1: callback_url += '&' else: callback_url += '?' callback_url += urllib.urlencode({scopes_param_prefix:scopes}) oauth_token = oauth.OAuthToken(request_token.key, request_token.secret) oauth_request = oauth.OAuthRequest.from_token_and_callback( token=oauth_token, callback=callback_url, http_url=authorization_url, parameters=extra_params) return atom.url.parse_url(oauth_request.to_url()) def GenerateOAuthAccessTokenUrl( authorized_request_token, oauth_input_params, access_token_url='https://www.google.com/accounts/OAuthGetAccessToken', oauth_version='1.0', oauth_verifier=None): """Generates URL at which user will login to authorize the request token. Args: authorized_request_token: gdata.auth.OAuthToken OAuth authorized request token. oauth_input_params: OAuthInputParams OAuth input parameters. access_token_url: string The beginning of the authorization URL. This is normally 'https://www.google.com/accounts/OAuthGetAccessToken' or '/accounts/OAuthGetAccessToken' oauth_version: str (default='1.0') oauth_version parameter. oauth_verifier: str (optional) If present, it is assumed that the client will use the OAuth v1.0a protocol which includes passing the oauth_verifier (as returned by the SP) in the access token step. Returns: atom.url.Url OAuth access token URL. """ oauth_token = oauth.OAuthToken(authorized_request_token.key, authorized_request_token.secret) parameters = {'oauth_version': oauth_version} if oauth_verifier is not None: parameters['oauth_verifier'] = oauth_verifier oauth_request = oauth.OAuthRequest.from_consumer_and_token( oauth_input_params.GetConsumer(), token=oauth_token, http_url=access_token_url, parameters=parameters) oauth_request.sign_request(oauth_input_params.GetSignatureMethod(), oauth_input_params.GetConsumer(), oauth_token) return atom.url.parse_url(oauth_request.to_url()) def GenerateAuthSubUrl(next, scope, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default'): """Generate a URL at which the user will login and be redirected back. Users enter their credentials on a Google login page and a token is sent to the URL specified in next. See documentation for AuthSub login at: http://code.google.com/apis/accounts/AuthForWebApps.html Args: request_url: str The beginning of the request URL. This is normally 'http://www.google.com/accounts/AuthSubRequest' or '/accounts/AuthSubRequest' next: string The URL user will be sent to after logging in. scope: string The URL of the service to be accessed. secure: boolean (optional) Determines whether or not the issued token is a secure token. session: boolean (optional) Determines whether or not the issued token can be upgraded to a session token. domain: str (optional) The Google Apps domain for this account. If this is not a Google Apps account, use 'default' which is the default value. """ # Translate True/False values for parameters into numeric values acceoted # by the AuthSub service. if secure: secure = 1 else: secure = 0 if session: session = 1 else: session = 0 request_params = urllib.urlencode({'next': next, 'scope': scope, 'secure': secure, 'session': session, 'hd': domain}) if request_url.find('?') == -1: return '%s?%s' % (request_url, request_params) else: # The request URL already contained url parameters so we should add # the parameters using the & seperator return '%s&%s' % (request_url, request_params) def generate_auth_sub_url(next, scopes, secure=False, session=True, request_url='https://www.google.com/accounts/AuthSubRequest', domain='default', scopes_param_prefix='auth_sub_scopes'): """Constructs a URL string for requesting a multiscope AuthSub token. The generated token will contain a URL parameter to pass along the requested scopes to the next URL. When the Google Accounts page redirects the broswser to the 'next' URL, it appends the single use AuthSub token value to the URL as a URL parameter with the key 'token'. However, the information about which scopes were requested is not included by Google Accounts. This method adds the scopes to the next URL before making the request so that the redirect will be sent to a page, and both the token value and the list of scopes can be extracted from the request URL. Args: next: atom.url.URL or string The URL user will be sent to after authorizing this web application to access their data. scopes: list containint strings The URLs of the services to be accessed. secure: boolean (optional) Determines whether or not the issued token is a secure token. session: boolean (optional) Determines whether or not the issued token can be upgraded to a session token. request_url: atom.url.Url or str The beginning of the request URL. This is normally 'http://www.google.com/accounts/AuthSubRequest' or '/accounts/AuthSubRequest' domain: The domain which the account is part of. This is used for Google Apps accounts, the default value is 'default' which means that the requested account is a Google Account (@gmail.com for example) scopes_param_prefix: str (optional) The requested scopes are added as a URL parameter to the next URL so that the page at the 'next' URL can extract the token value and the valid scopes from the URL. The key for the URL parameter defaults to 'auth_sub_scopes' Returns: An atom.url.Url which the user's browser should be directed to in order to authorize this application to access their information. """ if isinstance(next, (str, unicode)): next = atom.url.parse_url(next) scopes_string = ' '.join([str(scope) for scope in scopes]) next.params[scopes_param_prefix] = scopes_string if isinstance(request_url, (str, unicode)): request_url = atom.url.parse_url(request_url) request_url.params['next'] = str(next) request_url.params['scope'] = scopes_string if session: request_url.params['session'] = 1 else: request_url.params['session'] = 0 if secure: request_url.params['secure'] = 1 else: request_url.params['secure'] = 0 request_url.params['hd'] = domain return request_url def AuthSubTokenFromUrl(url): """Extracts the AuthSub token from the URL. Used after the AuthSub redirect has sent the user to the 'next' page and appended the token to the URL. This function returns the value to be used in the Authorization header. Args: url: str The URL of the current page which contains the AuthSub token as a URL parameter. """ token = TokenFromUrl(url) if token: return 'AuthSub token=%s' % token return None def TokenFromUrl(url): """Extracts the AuthSub token from the URL. Returns the raw token value. Args: url: str The URL or the query portion of the URL string (after the ?) of the current page which contains the AuthSub token as a URL parameter. """ if url.find('?') > -1: query_params = url.split('?')[1] else: query_params = url for pair in query_params.split('&'): if pair.startswith('token='): return pair[6:] return None def extract_auth_sub_token_from_url(url, scopes_param_prefix='auth_sub_scopes', rsa_key=None): """Creates an AuthSubToken and sets the token value and scopes from the URL. After the Google Accounts AuthSub pages redirect the user's broswer back to the web application (using the 'next' URL from the request) the web app must extract the token from the current page's URL. The token is provided as a URL parameter named 'token' and if generate_auth_sub_url was used to create the request, the token's valid scopes are included in a URL parameter whose name is specified in scopes_param_prefix. Args: url: atom.url.Url or str representing the current URL. The token value and valid scopes should be included as URL parameters. scopes_param_prefix: str (optional) The URL parameter key which maps to the list of valid scopes for the token. Returns: An AuthSubToken with the token value from the URL and set to be valid for the scopes passed in on the URL. If no scopes were included in the URL, the AuthSubToken defaults to being valid for no scopes. If there was no 'token' parameter in the URL, this function returns None. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) if 'token' not in url.params: return None scopes = [] if scopes_param_prefix in url.params: scopes = url.params[scopes_param_prefix].split(' ') token_value = url.params['token'] if rsa_key: token = SecureAuthSubToken(rsa_key, scopes=scopes) else: token = AuthSubToken(scopes=scopes) token.set_token_string(token_value) return token def AuthSubTokenFromHttpBody(http_body): """Extracts the AuthSub token from an HTTP body string. Used to find the new session token after making a request to upgrade a single use AuthSub token. Args: http_body: str The repsonse from the server which contains the AuthSub key. For example, this function would find the new session token from the server's response to an upgrade token request. Returns: The header value to use for Authorization which contains the AuthSub token. """ token_value = token_from_http_body(http_body) if token_value: return '%s%s' % (AUTHSUB_AUTH_LABEL, token_value) return None def token_from_http_body(http_body): """Extracts the AuthSub token from an HTTP body string. Used to find the new session token after making a request to upgrade a single use AuthSub token. Args: http_body: str The repsonse from the server which contains the AuthSub key. For example, this function would find the new session token from the server's response to an upgrade token request. Returns: The raw token value to use in an AuthSubToken object. """ for response_line in http_body.splitlines(): if response_line.startswith('Token='): # Strip off Token= and return the token value string. return response_line[6:] return None TokenFromHttpBody = token_from_http_body def OAuthTokenFromUrl(url, scopes_param_prefix='oauth_token_scope'): """Creates an OAuthToken and sets token key and scopes (if present) from URL. After the Google Accounts OAuth pages redirect the user's broswer back to the web application (using the 'callback' URL from the request) the web app can extract the token from the current page's URL. The token is same as the request token, but it is either authorized (if user grants access) or unauthorized (if user denies access). The token is provided as a URL parameter named 'oauth_token' and if it was chosen to use GenerateOAuthAuthorizationUrl with include_scopes_in_param=True, the token's valid scopes are included in a URL parameter whose name is specified in scopes_param_prefix. Args: url: atom.url.Url or str representing the current URL. The token value and valid scopes should be included as URL parameters. scopes_param_prefix: str (optional) The URL parameter key which maps to the list of valid scopes for the token. Returns: An OAuthToken with the token key from the URL and set to be valid for the scopes passed in on the URL. If no scopes were included in the URL, the OAuthToken defaults to being valid for no scopes. If there was no 'oauth_token' parameter in the URL, this function returns None. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) if 'oauth_token' not in url.params: return None scopes = [] if scopes_param_prefix in url.params: scopes = url.params[scopes_param_prefix].split(' ') token_key = url.params['oauth_token'] token = OAuthToken(key=token_key, scopes=scopes) return token def OAuthTokenFromHttpBody(http_body): """Parses the HTTP response body and returns an OAuth token. The returned OAuth token will just have key and secret parameters set. It won't have any knowledge about the scopes or oauth_input_params. It is your responsibility to make it aware of the remaining parameters. Returns: OAuthToken OAuth token. """ token = oauth.OAuthToken.from_string(http_body) oauth_token = OAuthToken(key=token.key, secret=token.secret) return oauth_token class OAuthSignatureMethod(object): """Holds valid OAuth signature methods. RSA_SHA1: Class to build signature according to RSA-SHA1 algorithm. HMAC_SHA1: Class to build signature according to HMAC-SHA1 algorithm. """ HMAC_SHA1 = oauth.OAuthSignatureMethod_HMAC_SHA1 class RSA_SHA1(oauth_rsa.OAuthSignatureMethod_RSA_SHA1): """Provides implementation for abstract methods to return RSA certs.""" def __init__(self, private_key, public_cert): self.private_key = private_key self.public_cert = public_cert def _fetch_public_cert(self, unused_oauth_request): return self.public_cert def _fetch_private_cert(self, unused_oauth_request): return self.private_key class OAuthInputParams(object): """Stores OAuth input parameters. This class is a store for OAuth input parameters viz. consumer key and secret, signature method and RSA key. """ def __init__(self, signature_method, consumer_key, consumer_secret=None, rsa_key=None, requestor_id=None): """Initializes object with parameters required for using OAuth mechanism. NOTE: Though consumer_secret and rsa_key are optional, either of the two is required depending on the value of the signature_method. Args: signature_method: class which provides implementation for strategy class oauth.oauth.OAuthSignatureMethod. Signature method to be used for signing each request. Valid implementations are provided as the constants defined by gdata.auth.OAuthSignatureMethod. Currently they are gdata.auth.OAuthSignatureMethod.RSA_SHA1 and gdata.auth.OAuthSignatureMethod.HMAC_SHA1. Instead of passing in the strategy class, you may pass in a string for 'RSA_SHA1' or 'HMAC_SHA1'. If you plan to use OAuth on App Engine (or another WSGI environment) I recommend specifying signature method using a string (the only options are 'RSA_SHA1' and 'HMAC_SHA1'). In these environments there are sometimes issues with pickling an object in which a member references a class or function. Storing a string to refer to the signature method mitigates complications when pickling. consumer_key: string Domain identifying third_party web application. consumer_secret: string (optional) Secret generated during registration. Required only for HMAC_SHA1 signature method. rsa_key: string (optional) Private key required for RSA_SHA1 signature method. requestor_id: string (optional) User email adress to make requests on their behalf. This parameter should only be set when performing 2 legged OAuth requests. """ if (signature_method == OAuthSignatureMethod.RSA_SHA1 or signature_method == 'RSA_SHA1'): self.__signature_strategy = 'RSA_SHA1' elif (signature_method == OAuthSignatureMethod.HMAC_SHA1 or signature_method == 'HMAC_SHA1'): self.__signature_strategy = 'HMAC_SHA1' else: self.__signature_strategy = signature_method self.rsa_key = rsa_key self._consumer = oauth.OAuthConsumer(consumer_key, consumer_secret) self.requestor_id = requestor_id def __get_signature_method(self): if self.__signature_strategy == 'RSA_SHA1': return OAuthSignatureMethod.RSA_SHA1(self.rsa_key, None) elif self.__signature_strategy == 'HMAC_SHA1': return OAuthSignatureMethod.HMAC_SHA1() else: return self.__signature_strategy() def __set_signature_method(self, signature_method): if (signature_method == OAuthSignatureMethod.RSA_SHA1 or signature_method == 'RSA_SHA1'): self.__signature_strategy = 'RSA_SHA1' elif (signature_method == OAuthSignatureMethod.HMAC_SHA1 or signature_method == 'HMAC_SHA1'): self.__signature_strategy = 'HMAC_SHA1' else: self.__signature_strategy = signature_method _signature_method = property(__get_signature_method, __set_signature_method, doc="""Returns object capable of signing the request using RSA of HMAC. Replaces the _signature_method member to avoid pickle errors.""") def GetSignatureMethod(self): """Gets the OAuth signature method. Returns: object of supertype <oauth.oauth.OAuthSignatureMethod> """ return self._signature_method def GetConsumer(self): """Gets the OAuth consumer. Returns: object of type <oauth.oauth.Consumer> """ return self._consumer class ClientLoginToken(atom.http_interface.GenericToken): """Stores the Authorization header in auth_header and adds to requests. This token will add it's Authorization header to an HTTP request as it is made. Ths token class is simple but some Token classes must calculate portions of the Authorization header based on the request being made, which is why the token is responsible for making requests via an http_client parameter. Args: auth_header: str The value for the Authorization header. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' """ def __init__(self, auth_header=None, scopes=None): self.auth_header = auth_header self.scopes = scopes or [] def __str__(self): return self.auth_header def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header and makes the HTTP request.""" if headers is None: headers = {'Authorization':self.auth_header} else: headers['Authorization'] = self.auth_header return http_client.request(operation, url, data=data, headers=headers) def get_token_string(self): """Removes PROGRAMMATIC_AUTH_LABEL to give just the token value.""" return self.auth_header[len(PROGRAMMATIC_AUTH_LABEL):] def set_token_string(self, token_string): self.auth_header = '%s%s' % (PROGRAMMATIC_AUTH_LABEL, token_string) def valid_for_scope(self, url): """Tells the caller if the token authorizes access to the desired URL. """ if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) for scope in self.scopes: if scope == atom.token_store.SCOPE_ALL: return True if isinstance(scope, (str, unicode)): scope = atom.url.parse_url(scope) if scope == url: return True # Check the host and the path, but ignore the port and protocol. elif scope.host == url.host and not scope.path: return True elif scope.host == url.host and scope.path and not url.path: continue elif scope.host == url.host and url.path.startswith(scope.path): return True return False class AuthSubToken(ClientLoginToken): def get_token_string(self): """Removes AUTHSUB_AUTH_LABEL to give just the token value.""" return self.auth_header[len(AUTHSUB_AUTH_LABEL):] def set_token_string(self, token_string): self.auth_header = '%s%s' % (AUTHSUB_AUTH_LABEL, token_string) class OAuthToken(atom.http_interface.GenericToken): """Stores the token key, token secret and scopes for which token is valid. This token adds the authorization header to each request made. It re-calculates authorization header for every request since the OAuth signature to be added to the authorization header is dependent on the request parameters. Attributes: key: str The value for the OAuth token i.e. token key. secret: str The value for the OAuth token secret. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' oauth_input_params: OAuthInputParams OAuth input parameters. """ def __init__(self, key=None, secret=None, scopes=None, oauth_input_params=None): self.key = key self.secret = secret self.scopes = scopes or [] self.oauth_input_params = oauth_input_params def __str__(self): return self.get_token_string() def get_token_string(self): """Returns the token string. The token string returned is of format oauth_token=[0]&oauth_token_secret=[1], where [0] and [1] are some strings. Returns: A token string of format oauth_token=[0]&oauth_token_secret=[1], where [0] and [1] are some strings. If self.secret is absent, it just returns oauth_token=[0]. If self.key is absent, it just returns oauth_token_secret=[1]. If both are absent, it returns None. """ if self.key and self.secret: return urllib.urlencode({'oauth_token': self.key, 'oauth_token_secret': self.secret}) elif self.key: return 'oauth_token=%s' % self.key elif self.secret: return 'oauth_token_secret=%s' % self.secret else: return None def set_token_string(self, token_string): """Sets the token key and secret from the token string. Args: token_string: str Token string of form oauth_token=[0]&oauth_token_secret=[1]. If oauth_token is not present, self.key will be None. If oauth_token_secret is not present, self.secret will be None. """ token_params = cgi.parse_qs(token_string, keep_blank_values=False) if 'oauth_token' in token_params: self.key = token_params['oauth_token'][0] if 'oauth_token_secret' in token_params: self.secret = token_params['oauth_token_secret'][0] def GetAuthHeader(self, http_method, http_url, realm=''): """Get the authentication header. Args: http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc. http_url: string or atom.url.Url HTTP URL to which request is made. realm: string (default='') realm parameter to be included in the authorization header. Returns: dict Header to be sent with every subsequent request after authentication. """ if isinstance(http_url, types.StringTypes): http_url = atom.url.parse_url(http_url) header = None token = None if self.key or self.secret: token = oauth.OAuthToken(self.key, self.secret) oauth_request = oauth.OAuthRequest.from_consumer_and_token( self.oauth_input_params.GetConsumer(), token=token, http_url=str(http_url), http_method=http_method, parameters=http_url.params) oauth_request.sign_request(self.oauth_input_params.GetSignatureMethod(), self.oauth_input_params.GetConsumer(), token) header = oauth_request.to_header(realm=realm) header['Authorization'] = header['Authorization'].replace('+', '%2B') return header def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header and makes the HTTP request.""" if not headers: headers = {} if self.oauth_input_params.requestor_id: url.params['xoauth_requestor_id'] = self.oauth_input_params.requestor_id headers.update(self.GetAuthHeader(operation, url)) return http_client.request(operation, url, data=data, headers=headers) def valid_for_scope(self, url): if isinstance(url, (str, unicode)): url = atom.url.parse_url(url) for scope in self.scopes: if scope == atom.token_store.SCOPE_ALL: return True if isinstance(scope, (str, unicode)): scope = atom.url.parse_url(scope) if scope == url: return True # Check the host and the path, but ignore the port and protocol. elif scope.host == url.host and not scope.path: return True elif scope.host == url.host and scope.path and not url.path: continue elif scope.host == url.host and url.path.startswith(scope.path): return True return False class SecureAuthSubToken(AuthSubToken): """Stores the rsa private key, token, and scopes for the secure AuthSub token. This token adds the authorization header to each request made. It re-calculates authorization header for every request since the secure AuthSub signature to be added to the authorization header is dependent on the request parameters. Attributes: rsa_key: string The RSA private key in PEM format that the token will use to sign requests token_string: string (optional) The value for the AuthSub token. scopes: list of str or atom.url.Url specifying the beginnings of URLs for which this token can be used. For example, if scopes contains 'http://example.com/foo', then this token can be used for a request to 'http://example.com/foo/bar' but it cannot be used for a request to 'http://example.com/baz' """ def __init__(self, rsa_key, token_string=None, scopes=None): self.rsa_key = keyfactory.parsePEMKey(rsa_key) self.token_string = token_string or '' self.scopes = scopes or [] def __str__(self): return self.get_token_string() def get_token_string(self): return str(self.token_string) def set_token_string(self, token_string): self.token_string = token_string def GetAuthHeader(self, http_method, http_url): """Generates the Authorization header. The form of the secure AuthSub Authorization header is Authorization: AuthSub token="token" sigalg="sigalg" data="data" sig="sig" and data represents a string in the form data = http_method http_url timestamp nonce Args: http_method: string HTTP method i.e. operation e.g. GET, POST, PUT, etc. http_url: string or atom.url.Url HTTP URL to which request is made. Returns: dict Header to be sent with every subsequent request after authentication. """ timestamp = int(math.floor(time.time())) nonce = '%lu' % random.randrange(1, 2**64) data = '%s %s %d %s' % (http_method, str(http_url), timestamp, nonce) sig = cryptomath.bytesToBase64(self.rsa_key.hashAndSign(data)) header = {'Authorization': '%s"%s" data="%s" sig="%s" sigalg="rsa-sha1"' % (AUTHSUB_AUTH_LABEL, self.token_string, data, sig)} return header def perform_request(self, http_client, operation, url, data=None, headers=None): """Sets the Authorization header and makes the HTTP request.""" if not headers: headers = {} headers.update(self.GetAuthHeader(operation, url)) return http_client.request(operation, url, data=data, headers=headers)
Python
#!/usr/bin/env python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. """Provides classes and constants for the XML in the Google Data namespace. Documentation for the raw XML which these classes represent can be found here: http://code.google.com/apis/gdata/docs/2.0/elements.html """ __author__ = 'j.s@google.com (Jeff Scudder)' import os import atom.core import atom.data GDATA_TEMPLATE = '{http://schemas.google.com/g/2005}%s' GD_TEMPLATE = GDATA_TEMPLATE OPENSEARCH_TEMPLATE_V1 = '{http://a9.com/-/spec/opensearchrss/1.0/}%s' OPENSEARCH_TEMPLATE_V2 = '{http://a9.com/-/spec/opensearch/1.1/}%s' BATCH_TEMPLATE = '{http://schemas.google.com/gdata/batch}%s' # Labels used in batch request entries to specify the desired CRUD operation. BATCH_INSERT = 'insert' BATCH_UPDATE = 'update' BATCH_DELETE = 'delete' BATCH_QUERY = 'query' EVENT_LOCATION = 'http://schemas.google.com/g/2005#event' ALTERNATE_LOCATION = 'http://schemas.google.com/g/2005#event.alternate' PARKING_LOCATION = 'http://schemas.google.com/g/2005#event.parking' CANCELED_EVENT = 'http://schemas.google.com/g/2005#event.canceled' CONFIRMED_EVENT = 'http://schemas.google.com/g/2005#event.confirmed' TENTATIVE_EVENT = 'http://schemas.google.com/g/2005#event.tentative' CONFIDENTIAL_EVENT = 'http://schemas.google.com/g/2005#event.confidential' DEFAULT_EVENT = 'http://schemas.google.com/g/2005#event.default' PRIVATE_EVENT = 'http://schemas.google.com/g/2005#event.private' PUBLIC_EVENT = 'http://schemas.google.com/g/2005#event.public' OPAQUE_EVENT = 'http://schemas.google.com/g/2005#event.opaque' TRANSPARENT_EVENT = 'http://schemas.google.com/g/2005#event.transparent' CHAT_MESSAGE = 'http://schemas.google.com/g/2005#message.chat' INBOX_MESSAGE = 'http://schemas.google.com/g/2005#message.inbox' SENT_MESSAGE = 'http://schemas.google.com/g/2005#message.sent' SPAM_MESSAGE = 'http://schemas.google.com/g/2005#message.spam' STARRED_MESSAGE = 'http://schemas.google.com/g/2005#message.starred' UNREAD_MESSAGE = 'http://schemas.google.com/g/2005#message.unread' BCC_RECIPIENT = 'http://schemas.google.com/g/2005#message.bcc' CC_RECIPIENT = 'http://schemas.google.com/g/2005#message.cc' SENDER = 'http://schemas.google.com/g/2005#message.from' REPLY_TO = 'http://schemas.google.com/g/2005#message.reply-to' TO_RECIPIENT = 'http://schemas.google.com/g/2005#message.to' ASSISTANT_REL = 'http://schemas.google.com/g/2005#assistant' CALLBACK_REL = 'http://schemas.google.com/g/2005#callback' CAR_REL = 'http://schemas.google.com/g/2005#car' COMPANY_MAIN_REL = 'http://schemas.google.com/g/2005#company_main' FAX_REL = 'http://schemas.google.com/g/2005#fax' HOME_REL = 'http://schemas.google.com/g/2005#home' HOME_FAX_REL = 'http://schemas.google.com/g/2005#home_fax' ISDN_REL = 'http://schemas.google.com/g/2005#isdn' MAIN_REL = 'http://schemas.google.com/g/2005#main' MOBILE_REL = 'http://schemas.google.com/g/2005#mobile' OTHER_REL = 'http://schemas.google.com/g/2005#other' OTHER_FAX_REL = 'http://schemas.google.com/g/2005#other_fax' PAGER_REL = 'http://schemas.google.com/g/2005#pager' RADIO_REL = 'http://schemas.google.com/g/2005#radio' TELEX_REL = 'http://schemas.google.com/g/2005#telex' TTL_TDD_REL = 'http://schemas.google.com/g/2005#tty_tdd' WORK_REL = 'http://schemas.google.com/g/2005#work' WORK_FAX_REL = 'http://schemas.google.com/g/2005#work_fax' WORK_MOBILE_REL = 'http://schemas.google.com/g/2005#work_mobile' WORK_PAGER_REL = 'http://schemas.google.com/g/2005#work_pager' NETMEETING_REL = 'http://schemas.google.com/g/2005#netmeeting' OVERALL_REL = 'http://schemas.google.com/g/2005#overall' PRICE_REL = 'http://schemas.google.com/g/2005#price' QUALITY_REL = 'http://schemas.google.com/g/2005#quality' EVENT_REL = 'http://schemas.google.com/g/2005#event' EVENT_ALTERNATE_REL = 'http://schemas.google.com/g/2005#event.alternate' EVENT_PARKING_REL = 'http://schemas.google.com/g/2005#event.parking' AIM_PROTOCOL = 'http://schemas.google.com/g/2005#AIM' MSN_PROTOCOL = 'http://schemas.google.com/g/2005#MSN' YAHOO_MESSENGER_PROTOCOL = 'http://schemas.google.com/g/2005#YAHOO' SKYPE_PROTOCOL = 'http://schemas.google.com/g/2005#SKYPE' QQ_PROTOCOL = 'http://schemas.google.com/g/2005#QQ' GOOGLE_TALK_PROTOCOL = 'http://schemas.google.com/g/2005#GOOGLE_TALK' ICQ_PROTOCOL = 'http://schemas.google.com/g/2005#ICQ' JABBER_PROTOCOL = 'http://schemas.google.com/g/2005#JABBER' REGULAR_COMMENTS = 'http://schemas.google.com/g/2005#regular' REVIEW_COMMENTS = 'http://schemas.google.com/g/2005#reviews' MAIL_BOTH = 'http://schemas.google.com/g/2005#both' MAIL_LETTERS = 'http://schemas.google.com/g/2005#letters' MAIL_PARCELS = 'http://schemas.google.com/g/2005#parcels' MAIL_NEITHER = 'http://schemas.google.com/g/2005#neither' GENERAL_ADDRESS = 'http://schemas.google.com/g/2005#general' LOCAL_ADDRESS = 'http://schemas.google.com/g/2005#local' OPTIONAL_ATENDEE = 'http://schemas.google.com/g/2005#event.optional' REQUIRED_ATENDEE = 'http://schemas.google.com/g/2005#event.required' ATTENDEE_ACCEPTED = 'http://schemas.google.com/g/2005#event.accepted' ATTENDEE_DECLINED = 'http://schemas.google.com/g/2005#event.declined' ATTENDEE_INVITED = 'http://schemas.google.com/g/2005#event.invited' ATTENDEE_TENTATIVE = 'http://schemas.google.com/g/2005#event.tentative' FULL_PROJECTION = 'full' VALUES_PROJECTION = 'values' BASIC_PROJECTION = 'basic' PRIVATE_VISIBILITY = 'private' PUBLIC_VISIBILITY = 'public' OPAQUE_TRANSPARENCY = 'http://schemas.google.com/g/2005#event.opaque' TRANSPARENT_TRANSPARENCY = 'http://schemas.google.com/g/2005#event.transparent' CONFIDENTIAL_EVENT_VISIBILITY = 'http://schemas.google.com/g/2005#event.confidential' DEFAULT_EVENT_VISIBILITY = 'http://schemas.google.com/g/2005#event.default' PRIVATE_EVENT_VISIBILITY = 'http://schemas.google.com/g/2005#event.private' PUBLIC_EVENT_VISIBILITY = 'http://schemas.google.com/g/2005#event.public' CANCELED_EVENT_STATUS = 'http://schemas.google.com/g/2005#event.canceled' CONFIRMED_EVENT_STATUS = 'http://schemas.google.com/g/2005#event.confirmed' TENTATIVE_EVENT_STATUS = 'http://schemas.google.com/g/2005#event.tentative' ACL_REL = 'http://schemas.google.com/acl/2007#accessControlList' class Error(Exception): pass class MissingRequiredParameters(Error): pass class LinkFinder(atom.data.LinkFinder): """Mixin used in Feed and Entry classes to simplify link lookups by type. Provides lookup methods for edit, edit-media, post, ACL and other special links which are common across Google Data APIs. """ def find_html_link(self): """Finds the first link with rel of alternate and type of text/html.""" for link in self.link: if link.rel == 'alternate' and link.type == 'text/html': return link.href return None FindHtmlLink = find_html_link def get_html_link(self): for a_link in self.link: if a_link.rel == 'alternate' and a_link.type == 'text/html': return a_link return None GetHtmlLink = get_html_link def find_post_link(self): """Get the URL to which new entries should be POSTed. The POST target URL is used to insert new entries. Returns: A str for the URL in the link with a rel matching the POST type. """ return self.find_url('http://schemas.google.com/g/2005#post') FindPostLink = find_post_link def get_post_link(self): return self.get_link('http://schemas.google.com/g/2005#post') GetPostLink = get_post_link def find_acl_link(self): acl_link = self.get_acl_link() if acl_link: return acl_link.href return None FindAclLink = find_acl_link def get_acl_link(self): """Searches for a link or feed_link (if present) with the rel for ACL.""" acl_link = self.get_link(ACL_REL) if acl_link: return acl_link elif hasattr(self, 'feed_link'): for a_feed_link in self.feed_link: if a_feed_link.rel == ACL_REL: return a_feed_link return None GetAclLink = get_acl_link def find_feed_link(self): return self.find_url('http://schemas.google.com/g/2005#feed') FindFeedLink = find_feed_link def get_feed_link(self): return self.get_link('http://schemas.google.com/g/2005#feed') GetFeedLink = get_feed_link def find_previous_link(self): return self.find_url('previous') FindPreviousLink = find_previous_link def get_previous_link(self): return self.get_link('previous') GetPreviousLink = get_previous_link class TotalResults(atom.core.XmlElement): """opensearch:TotalResults for a GData feed.""" _qname = (OPENSEARCH_TEMPLATE_V1 % 'totalResults', OPENSEARCH_TEMPLATE_V2 % 'totalResults') class StartIndex(atom.core.XmlElement): """The opensearch:startIndex element in GData feed.""" _qname = (OPENSEARCH_TEMPLATE_V1 % 'startIndex', OPENSEARCH_TEMPLATE_V2 % 'startIndex') class ItemsPerPage(atom.core.XmlElement): """The opensearch:itemsPerPage element in GData feed.""" _qname = (OPENSEARCH_TEMPLATE_V1 % 'itemsPerPage', OPENSEARCH_TEMPLATE_V2 % 'itemsPerPage') class ExtendedProperty(atom.core.XmlElement): """The Google Data extendedProperty element. Used to store arbitrary key-value information specific to your application. The value can either be a text string stored as an XML attribute (.value), or an XML node (XmlBlob) as a child element. This element is used in the Google Calendar data API and the Google Contacts data API. """ _qname = GDATA_TEMPLATE % 'extendedProperty' name = 'name' value = 'value' def get_xml_blob(self): """Returns the XML blob as an atom.core.XmlElement. Returns: An XmlElement representing the blob's XML, or None if no blob was set. """ if self._other_elements: return self._other_elements[0] else: return None GetXmlBlob = get_xml_blob def set_xml_blob(self, blob): """Sets the contents of the extendedProperty to XML as a child node. Since the extendedProperty is only allowed one child element as an XML blob, setting the XML blob will erase any preexisting member elements in this object. Args: blob: str or atom.core.XmlElement representing the XML blob stored in the extendedProperty. """ # Erase any existing extension_elements, clears the child nodes from the # extendedProperty. if isinstance(blob, atom.core.XmlElement): self._other_elements = [blob] else: self._other_elements = [atom.core.parse(str(blob))] SetXmlBlob = set_xml_blob class GDEntry(atom.data.Entry, LinkFinder): """Extends Atom Entry to provide data processing""" etag = '{http://schemas.google.com/g/2005}etag' def get_id(self): if self.id is not None and self.id.text is not None: return self.id.text.strip() return None GetId = get_id def is_media(self): if self.find_edit_media_link(): return True return False IsMedia = is_media def find_media_link(self): """Returns the URL to the media content, if the entry is a media entry. Otherwise returns None. """ if self.is_media(): return self.content.src return None FindMediaLink = find_media_link class GDFeed(atom.data.Feed, LinkFinder): """A Feed from a GData service.""" etag = '{http://schemas.google.com/g/2005}etag' total_results = TotalResults start_index = StartIndex items_per_page = ItemsPerPage entry = [GDEntry] def get_id(self): if self.id is not None and self.id.text is not None: return self.id.text.strip() return None GetId = get_id def get_generator(self): if self.generator and self.generator.text: return self.generator.text.strip() return None class BatchId(atom.core.XmlElement): """Identifies a single operation in a batch request.""" _qname = BATCH_TEMPLATE % 'id' class BatchOperation(atom.core.XmlElement): """The CRUD operation which this batch entry represents.""" _qname = BATCH_TEMPLATE % 'operation' type = 'type' class BatchStatus(atom.core.XmlElement): """The batch:status element present in a batch response entry. A status element contains the code (HTTP response code) and reason as elements. In a single request these fields would be part of the HTTP response, but in a batch request each Entry operation has a corresponding Entry in the response feed which includes status information. See http://code.google.com/apis/gdata/batch.html#Handling_Errors """ _qname = BATCH_TEMPLATE % 'status' code = 'code' reason = 'reason' content_type = 'content-type' class BatchEntry(GDEntry): """An atom:entry for use in batch requests. The BatchEntry contains additional members to specify the operation to be performed on this entry and a batch ID so that the server can reference individual operations in the response feed. For more information, see: http://code.google.com/apis/gdata/batch.html """ batch_operation = BatchOperation batch_id = BatchId batch_status = BatchStatus class BatchInterrupted(atom.core.XmlElement): """The batch:interrupted element sent if batch request was interrupted. Only appears in a feed if some of the batch entries could not be processed. See: http://code.google.com/apis/gdata/batch.html#Handling_Errors """ _qname = BATCH_TEMPLATE % 'interrupted' reason = 'reason' success = 'success' failures = 'failures' parsed = 'parsed' class BatchFeed(GDFeed): """A feed containing a list of batch request entries.""" interrupted = BatchInterrupted entry = [BatchEntry] def add_batch_entry(self, entry=None, id_url_string=None, batch_id_string=None, operation_string=None): """Logic for populating members of a BatchEntry and adding to the feed. If the entry is not a BatchEntry, it is converted to a BatchEntry so that the batch specific members will be present. The id_url_string can be used in place of an entry if the batch operation applies to a URL. For example query and delete operations require just the URL of an entry, no body is sent in the HTTP request. If an id_url_string is sent instead of an entry, a BatchEntry is created and added to the feed. This method also assigns the desired batch id to the entry so that it can be referenced in the server's response. If the batch_id_string is None, this method will assign a batch_id to be the index at which this entry will be in the feed's entry list. Args: entry: BatchEntry, atom.data.Entry, or another Entry flavor (optional) The entry which will be sent to the server as part of the batch request. The item must have a valid atom id so that the server knows which entry this request references. id_url_string: str (optional) The URL of the entry to be acted on. You can find this URL in the text member of the atom id for an entry. If an entry is not sent, this id will be used to construct a new BatchEntry which will be added to the request feed. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. Note that batch_ids should either always be specified or never, mixing could potentially result in duplicate batch ids. operation_string: str (optional) The desired batch operation which will set the batch_operation.type member of the entry. Options are 'insert', 'update', 'delete', and 'query' Raises: MissingRequiredParameters: Raised if neither an id_ url_string nor an entry are provided in the request. Returns: The added entry. """ if entry is None and id_url_string is None: raise MissingRequiredParameters('supply either an entry or URL string') if entry is None and id_url_string is not None: entry = BatchEntry(id=atom.data.Id(text=id_url_string)) if batch_id_string is not None: entry.batch_id = BatchId(text=batch_id_string) elif entry.batch_id is None or entry.batch_id.text is None: entry.batch_id = BatchId(text=str(len(self.entry))) if operation_string is not None: entry.batch_operation = BatchOperation(type=operation_string) self.entry.append(entry) return entry AddBatchEntry = add_batch_entry def add_insert(self, entry, batch_id_string=None): """Add an insert request to the operations in this batch request feed. If the entry doesn't yet have an operation or a batch id, these will be set to the insert operation and a batch_id specified as a parameter. Args: entry: BatchEntry The entry which will be sent in the batch feed as an insert request. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. Note that batch_ids should either always be specified or never, mixing could potentially result in duplicate batch ids. """ self.add_batch_entry(entry=entry, batch_id_string=batch_id_string, operation_string=BATCH_INSERT) AddInsert = add_insert def add_update(self, entry, batch_id_string=None): """Add an update request to the list of batch operations in this feed. Sets the operation type of the entry to insert if it is not already set and assigns the desired batch id to the entry so that it can be referenced in the server's response. Args: entry: BatchEntry The entry which will be sent to the server as an update (HTTP PUT) request. The item must have a valid atom id so that the server knows which entry to replace. batch_id_string: str (optional) The batch ID to be used to reference this batch operation in the results feed. If this parameter is None, the current length of the feed's entry array will be used as a count. See also comments for AddInsert. """ self.add_batch_entry(entry=entry, batch_id_string=batch_id_string, operation_string=BATCH_UPDATE) AddUpdate = add_update def add_delete(self, url_string=None, entry=None, batch_id_string=None): """Adds a delete request to the batch request feed. This method takes either the url_string which is the atom id of the item to be deleted, or the entry itself. The atom id of the entry must be present so that the server knows which entry should be deleted. Args: url_string: str (optional) The URL of the entry to be deleted. You can find this URL in the text member of the atom id for an entry. entry: BatchEntry (optional) The entry to be deleted. batch_id_string: str (optional) Raises: MissingRequiredParameters: Raised if neither a url_string nor an entry are provided in the request. """ self.add_batch_entry(entry=entry, id_url_string=url_string, batch_id_string=batch_id_string, operation_string=BATCH_DELETE) AddDelete = add_delete def add_query(self, url_string=None, entry=None, batch_id_string=None): """Adds a query request to the batch request feed. This method takes either the url_string which is the query URL whose results will be added to the result feed. The query URL will be encapsulated in a BatchEntry, and you may pass in the BatchEntry with a query URL instead of sending a url_string. Args: url_string: str (optional) entry: BatchEntry (optional) batch_id_string: str (optional) Raises: MissingRequiredParameters """ self.add_batch_entry(entry=entry, id_url_string=url_string, batch_id_string=batch_id_string, operation_string=BATCH_QUERY) AddQuery = add_query def find_batch_link(self): return self.find_url('http://schemas.google.com/g/2005#batch') FindBatchLink = find_batch_link class EntryLink(atom.core.XmlElement): """The gd:entryLink element. Represents a logically nested entry. For example, a <gd:who> representing a contact might have a nested entry from a contact feed. """ _qname = GDATA_TEMPLATE % 'entryLink' entry = GDEntry rel = 'rel' read_only = 'readOnly' href = 'href' class FeedLink(atom.core.XmlElement): """The gd:feedLink element. Represents a logically nested feed. For example, a calendar feed might have a nested feed representing all comments on entries. """ _qname = GDATA_TEMPLATE % 'feedLink' feed = GDFeed rel = 'rel' read_only = 'readOnly' count_hint = 'countHint' href = 'href' class AdditionalName(atom.core.XmlElement): """The gd:additionalName element. Specifies additional (eg. middle) name of the person. Contains an attribute for the phonetic representaton of the name. """ _qname = GDATA_TEMPLATE % 'additionalName' yomi = 'yomi' class Comments(atom.core.XmlElement): """The gd:comments element. Contains a comments feed for the enclosing entry (such as a calendar event). """ _qname = GDATA_TEMPLATE % 'comments' rel = 'rel' feed_link = FeedLink class Country(atom.core.XmlElement): """The gd:country element. Country name along with optional country code. The country code is given in accordance with ISO 3166-1 alpha-2: http://www.iso.org/iso/iso-3166-1_decoding_table """ _qname = GDATA_TEMPLATE % 'country' code = 'code' class EmailImParent(atom.core.XmlElement): address = 'address' label = 'label' rel = 'rel' primary = 'primary' class Email(EmailImParent): """The gd:email element. An email address associated with the containing entity (which is usually an entity representing a person or a location). """ _qname = GDATA_TEMPLATE % 'email' display_name = 'displayName' class FamilyName(atom.core.XmlElement): """The gd:familyName element. Specifies family name of the person, eg. "Smith". """ _qname = GDATA_TEMPLATE % 'familyName' yomi = 'yomi' class Im(EmailImParent): """The gd:im element. An instant messaging address associated with the containing entity. """ _qname = GDATA_TEMPLATE % 'im' protocol = 'protocol' class GivenName(atom.core.XmlElement): """The gd:givenName element. Specifies given name of the person, eg. "John". """ _qname = GDATA_TEMPLATE % 'givenName' yomi = 'yomi' class NamePrefix(atom.core.XmlElement): """The gd:namePrefix element. Honorific prefix, eg. 'Mr' or 'Mrs'. """ _qname = GDATA_TEMPLATE % 'namePrefix' class NameSuffix(atom.core.XmlElement): """The gd:nameSuffix element. Honorific suffix, eg. 'san' or 'III'. """ _qname = GDATA_TEMPLATE % 'nameSuffix' class FullName(atom.core.XmlElement): """The gd:fullName element. Unstructured representation of the name. """ _qname = GDATA_TEMPLATE % 'fullName' class Name(atom.core.XmlElement): """The gd:name element. Allows storing person's name in a structured way. Consists of given name, additional name, family name, prefix, suffix and full name. """ _qname = GDATA_TEMPLATE % 'name' given_name = GivenName additional_name = AdditionalName family_name = FamilyName name_prefix = NamePrefix name_suffix = NameSuffix full_name = FullName class OrgDepartment(atom.core.XmlElement): """The gd:orgDepartment element. Describes a department within an organization. Must appear within a gd:organization element. """ _qname = GDATA_TEMPLATE % 'orgDepartment' class OrgJobDescription(atom.core.XmlElement): """The gd:orgJobDescription element. Describes a job within an organization. Must appear within a gd:organization element. """ _qname = GDATA_TEMPLATE % 'orgJobDescription' class OrgName(atom.core.XmlElement): """The gd:orgName element. The name of the organization. Must appear within a gd:organization element. Contains a Yomigana attribute (Japanese reading aid) for the organization name. """ _qname = GDATA_TEMPLATE % 'orgName' yomi = 'yomi' class OrgSymbol(atom.core.XmlElement): """The gd:orgSymbol element. Provides a symbol of an organization. Must appear within a gd:organization element. """ _qname = GDATA_TEMPLATE % 'orgSymbol' class OrgTitle(atom.core.XmlElement): """The gd:orgTitle element. The title of a person within an organization. Must appear within a gd:organization element. """ _qname = GDATA_TEMPLATE % 'orgTitle' class Organization(atom.core.XmlElement): """The gd:organization element. An organization, typically associated with a contact. """ _qname = GDATA_TEMPLATE % 'organization' label = 'label' primary = 'primary' rel = 'rel' department = OrgDepartment job_description = OrgJobDescription name = OrgName symbol = OrgSymbol title = OrgTitle class When(atom.core.XmlElement): """The gd:when element. Represents a period of time or an instant. """ _qname = GDATA_TEMPLATE % 'when' end = 'endTime' start = 'startTime' value = 'valueString' class OriginalEvent(atom.core.XmlElement): """The gd:originalEvent element. Equivalent to the Recurrence ID property specified in section 4.8.4.4 of RFC 2445. Appears in every instance of a recurring event, to identify the original event. Contains a <gd:when> element specifying the original start time of the instance that has become an exception. """ _qname = GDATA_TEMPLATE % 'originalEvent' id = 'id' href = 'href' when = When class PhoneNumber(atom.core.XmlElement): """The gd:phoneNumber element. A phone number associated with the containing entity (which is usually an entity representing a person or a location). """ _qname = GDATA_TEMPLATE % 'phoneNumber' label = 'label' rel = 'rel' uri = 'uri' primary = 'primary' class PostalAddress(atom.core.XmlElement): """The gd:postalAddress element.""" _qname = GDATA_TEMPLATE % 'postalAddress' label = 'label' rel = 'rel' uri = 'uri' primary = 'primary' class Rating(atom.core.XmlElement): """The gd:rating element. Represents a numeric rating of the enclosing entity, such as a comment. Each rating supplies its own scale, although it may be normalized by a service; for example, some services might convert all ratings to a scale from 1 to 5. """ _qname = GDATA_TEMPLATE % 'rating' average = 'average' max = 'max' min = 'min' num_raters = 'numRaters' rel = 'rel' value = 'value' class Recurrence(atom.core.XmlElement): """The gd:recurrence element. Represents the dates and times when a recurring event takes place. The string that defines the recurrence consists of a set of properties, each of which is defined in the iCalendar standard (RFC 2445). Specifically, the string usually begins with a DTSTART property that indicates the starting time of the first instance of the event, and often a DTEND property or a DURATION property to indicate when the first instance ends. Next come RRULE, RDATE, EXRULE, and/or EXDATE properties, which collectively define a recurring event and its exceptions (but see below). (See section 4.8.5 of RFC 2445 for more information about these recurrence component properties.) Last comes a VTIMEZONE component, providing detailed timezone rules for any timezone ID mentioned in the preceding properties. Google services like Google Calendar don't generally generate EXRULE and EXDATE properties to represent exceptions to recurring events; instead, they generate <gd:recurrenceException> elements. However, Google services may include EXRULE and/or EXDATE properties anyway; for example, users can import events and exceptions into Calendar, and if those imported events contain EXRULE or EXDATE properties, then Calendar will provide those properties when it sends a <gd:recurrence> element. Note the the use of <gd:recurrenceException> means that you can't be sure just from examining a <gd:recurrence> element whether there are any exceptions to the recurrence description. To ensure that you find all exceptions, look for <gd:recurrenceException> elements in the feed, and use their <gd:originalEvent> elements to match them up with <gd:recurrence> elements. """ _qname = GDATA_TEMPLATE % 'recurrence' class RecurrenceException(atom.core.XmlElement): """The gd:recurrenceException element. Represents an event that's an exception to a recurring event-that is, an instance of a recurring event in which one or more aspects of the recurring event (such as attendance list, time, or location) have been changed. Contains a <gd:originalEvent> element that specifies the original recurring event that this event is an exception to. When you change an instance of a recurring event, that instance becomes an exception. Depending on what change you made to it, the exception behaves in either of two different ways when the original recurring event is changed: - If you add, change, or remove comments, attendees, or attendee responses, then the exception remains tied to the original event, and changes to the original event also change the exception. - If you make any other changes to the exception (such as changing the time or location) then the instance becomes "specialized," which means that it's no longer as tightly tied to the original event. If you change the original event, specialized exceptions don't change. But see below. For example, say you have a meeting every Tuesday and Thursday at 2:00 p.m. If you change the attendance list for this Thursday's meeting (but not for the regularly scheduled meeting), then it becomes an exception. If you change the time for this Thursday's meeting (but not for the regularly scheduled meeting), then it becomes specialized. Regardless of whether an exception is specialized or not, if you do something that deletes the instance that the exception was derived from, then the exception is deleted. Note that changing the day or time of a recurring event deletes all instances, and creates new ones. For example, after you've specialized this Thursday's meeting, say you change the recurring meeting to happen on Monday, Wednesday, and Friday. That change deletes all of the recurring instances of the Tuesday/Thursday meeting, including the specialized one. If a particular instance of a recurring event is deleted, then that instance appears as a <gd:recurrenceException> containing a <gd:entryLink> that has its <gd:eventStatus> set to "http://schemas.google.com/g/2005#event.canceled". (For more information about canceled events, see RFC 2445.) """ _qname = GDATA_TEMPLATE % 'recurrenceException' specialized = 'specialized' entry_link = EntryLink original_event = OriginalEvent class Reminder(atom.core.XmlElement): """The gd:reminder element. A time interval, indicating how long before the containing entity's start time or due time attribute a reminder should be issued. Alternatively, may specify an absolute time at which a reminder should be issued. Also specifies a notification method, indicating what medium the system should use to remind the user. """ _qname = GDATA_TEMPLATE % 'reminder' absolute_time = 'absoluteTime' method = 'method' days = 'days' hours = 'hours' minutes = 'minutes' class Transparency(atom.core.XmlElement): """The gd:transparency element: Extensible enum corresponding to the TRANSP property defined in RFC 244. """ _qname = GDATA_TEMPLATE % 'transparency' value = 'value' class Agent(atom.core.XmlElement): """The gd:agent element. The agent who actually receives the mail. Used in work addresses. Also for 'in care of' or 'c/o'. """ _qname = GDATA_TEMPLATE % 'agent' class HouseName(atom.core.XmlElement): """The gd:housename element. Used in places where houses or buildings have names (and not necessarily numbers), eg. "The Pillars". """ _qname = GDATA_TEMPLATE % 'housename' class Street(atom.core.XmlElement): """The gd:street element. Can be street, avenue, road, etc. This element also includes the house number and room/apartment/flat/floor number. """ _qname = GDATA_TEMPLATE % 'street' class PoBox(atom.core.XmlElement): """The gd:pobox element. Covers actual P.O. boxes, drawers, locked bags, etc. This is usually but not always mutually exclusive with street. """ _qname = GDATA_TEMPLATE % 'pobox' class Neighborhood(atom.core.XmlElement): """The gd:neighborhood element. This is used to disambiguate a street address when a city contains more than one street with the same name, or to specify a small place whose mail is routed through a larger postal town. In China it could be a county or a minor city. """ _qname = GDATA_TEMPLATE % 'neighborhood' class City(atom.core.XmlElement): """The gd:city element. Can be city, village, town, borough, etc. This is the postal town and not necessarily the place of residence or place of business. """ _qname = GDATA_TEMPLATE % 'city' class Subregion(atom.core.XmlElement): """The gd:subregion element. Handles administrative districts such as U.S. or U.K. counties that are not used for mail addressing purposes. Subregion is not intended for delivery addresses. """ _qname = GDATA_TEMPLATE % 'subregion' class Region(atom.core.XmlElement): """The gd:region element. A state, province, county (in Ireland), Land (in Germany), departement (in France), etc. """ _qname = GDATA_TEMPLATE % 'region' class Postcode(atom.core.XmlElement): """The gd:postcode element. Postal code. Usually country-wide, but sometimes specific to the city (e.g. "2" in "Dublin 2, Ireland" addresses). """ _qname = GDATA_TEMPLATE % 'postcode' class Country(atom.core.XmlElement): """The gd:country element. The name or code of the country. """ _qname = GDATA_TEMPLATE % 'country' class FormattedAddress(atom.core.XmlElement): """The gd:formattedAddress element. The full, unstructured postal address. """ _qname = GDATA_TEMPLATE % 'formattedAddress' class StructuredPostalAddress(atom.core.XmlElement): """The gd:structuredPostalAddress element. Postal address split into components. It allows to store the address in locale independent format. The fields can be interpreted and used to generate formatted, locale dependent address. The following elements reperesent parts of the address: agent, house name, street, P.O. box, neighborhood, city, subregion, region, postal code, country. The subregion element is not used for postal addresses, it is provided for extended uses of addresses only. In order to store postal address in an unstructured form formatted address field is provided. """ _qname = GDATA_TEMPLATE % 'structuredPostalAddress' rel = 'rel' mail_class = 'mailClass' usage = 'usage' label = 'label' primary = 'primary' agent = Agent house_name = HouseName street = Street po_box = PoBox neighborhood = Neighborhood city = City subregion = Subregion region = Region postcode = Postcode country = Country formatted_address = FormattedAddress class Where(atom.core.XmlElement): """The gd:where element. A place (such as an event location) associated with the containing entity. The type of the association is determined by the rel attribute; the details of the location are contained in an embedded or linked-to Contact entry. A <gd:where> element is more general than a <gd:geoPt> element. The former identifies a place using a text description and/or a Contact entry, while the latter identifies a place using a specific geographic location. """ _qname = GDATA_TEMPLATE % 'where' label = 'label' rel = 'rel' value = 'valueString' entry_link = EntryLink class AttendeeType(atom.core.XmlElement): """The gd:attendeeType element.""" _qname = GDATA_TEMPLATE % 'attendeeType' value = 'value' class AttendeeStatus(atom.core.XmlElement): """The gd:attendeeStatus element.""" _qname = GDATA_TEMPLATE % 'attendeeStatus' value = 'value' class EventStatus(atom.core.XmlElement): """The gd:eventStatus element.""" _qname = GDATA_TEMPLATE % 'eventStatus' value = 'value' class Visibility(atom.core.XmlElement): """The gd:visibility element.""" _qname = GDATA_TEMPLATE % 'visibility' value = 'value' class Who(atom.core.XmlElement): """The gd:who element. A person associated with the containing entity. The type of the association is determined by the rel attribute; the details about the person are contained in an embedded or linked-to Contact entry. The <gd:who> element can be used to specify email senders and recipients, calendar event organizers, and so on. """ _qname = GDATA_TEMPLATE % 'who' email = 'email' rel = 'rel' value = 'valueString' attendee_status = AttendeeStatus attendee_type = AttendeeType entry_link = EntryLink class Deleted(atom.core.XmlElement): """gd:deleted when present, indicates the containing entry is deleted.""" _qname = GD_TEMPLATE % 'deleted' class Money(atom.core.XmlElement): """Describes money""" _qname = GD_TEMPLATE % 'money' amount = 'amount' currency_code = 'currencyCode' class MediaSource(object): """GData Entries can refer to media sources, so this class provides a place to store references to these objects along with some metadata. """ def __init__(self, file_handle=None, content_type=None, content_length=None, file_path=None, file_name=None): """Creates an object of type MediaSource. Args: file_handle: A file handle pointing to the file to be encapsulated in the MediaSource. content_type: string The MIME type of the file. Required if a file_handle is given. content_length: int The size of the file. Required if a file_handle is given. file_path: string (optional) A full path name to the file. Used in place of a file_handle. file_name: string The name of the file without any path information. Required if a file_handle is given. """ self.file_handle = file_handle self.content_type = content_type self.content_length = content_length self.file_name = file_name if (file_handle is None and content_type is not None and file_path is not None): self.set_file_handle(file_path, content_type) def set_file_handle(self, file_name, content_type): """A helper function which can create a file handle from a given filename and set the content type and length all at once. Args: file_name: string The path and file name to the file containing the media content_type: string A MIME type representing the type of the media """ self.file_handle = open(file_name, 'rb') self.content_type = content_type self.content_length = os.path.getsize(file_name) self.file_name = os.path.basename(file_name) SetFileHandle = set_file_handle def modify_request(self, http_request): http_request.add_body_part(self.file_handle, self.content_type, self.content_length) return http_request ModifyRequest = modify_request
Python
#!/usr/bin/env python # # Copyright (C) 2010 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. __author__ = 'j.s@google.com (Jeff Scudder)' """Provides classes and methods for working with JSON-C. This module is experimental and subject to backwards incompatible changes. Jsonc: Class which represents JSON-C data and provides pythonic member access which is a bit cleaner than working with plain old dicts. parse_json: Converts a JSON-C string into a Jsonc object. jsonc_to_string: Converts a Jsonc object into a string of JSON-C. """ try: import simplejson except ImportError: try: # Try to import from django, should work on App Engine from django.utils import simplejson except ImportError: # Should work for Python2.6 and higher. import json as simplejson def _convert_to_jsonc(x): """Builds a Jsonc objects which wraps the argument's members.""" if isinstance(x, dict): jsonc_obj = Jsonc() # Recursively transform all members of the dict. # When converting a dict, we do not convert _name items into private # Jsonc members. for key, value in x.iteritems(): jsonc_obj._dict[key] = _convert_to_jsonc(value) return jsonc_obj elif isinstance(x, list): # Recursively transform all members of the list. members = [] for item in x: members.append(_convert_to_jsonc(item)) return members else: # Return the base object. return x def parse_json(json_string): """Converts a JSON-C string into a Jsonc object. Args: json_string: str or unicode The JSON to be parsed. Returns: A new Jsonc object. """ return _convert_to_jsonc(simplejson.loads(json_string)) def parse_json_file(json_file): return _convert_to_jsonc(simplejson.load(json_file)) def jsonc_to_string(jsonc_obj): """Converts a Jsonc object into a string of JSON-C.""" return simplejson.dumps(_convert_to_object(jsonc_obj)) def prettify_jsonc(jsonc_obj, indentation=2): """Converts a Jsonc object to a pretified (intented) JSON string.""" return simplejson.dumps(_convert_to_object(jsonc_obj), indent=indentation) def _convert_to_object(jsonc_obj): """Creates a new dict or list which has the data in the Jsonc object. Used to convert the Jsonc object to a plain old Python object to simplify conversion to a JSON-C string. Args: jsonc_obj: A Jsonc object to be converted into simple Python objects (dicts, lists, etc.) Returns: Either a dict, list, or other object with members converted from Jsonc objects to the corresponding simple Python object. """ if isinstance(jsonc_obj, Jsonc): plain = {} for key, value in jsonc_obj._dict.iteritems(): plain[key] = _convert_to_object(value) return plain elif isinstance(jsonc_obj, list): plain = [] for item in jsonc_obj: plain.append(_convert_to_object(item)) return plain else: return jsonc_obj def _to_jsonc_name(member_name): """Converts a Python style member name to a JSON-C style name. JSON-C uses camelCaseWithLower while Python tends to use lower_with_underscores so this method converts as follows: spam becomes spam spam_and_eggs becomes spamAndEggs Args: member_name: str or unicode The Python syle name which should be converted to JSON-C style. Returns: The JSON-C style name as a str or unicode. """ characters = [] uppercase_next = False for character in member_name: if character == '_': uppercase_next = True elif uppercase_next: characters.append(character.upper()) uppercase_next = False else: characters.append(character) return ''.join(characters) class Jsonc(object): """Represents JSON-C data in an easy to access object format. To access the members of a JSON structure which looks like this: { "data": { "totalItems": 800, "items": [ { "content": { "1": "rtsp://v5.cache3.c.youtube.com/CiILENy.../0/0/0/video.3gp" }, "viewCount": 220101, "commentCount": 22, "favoriteCount": 201 } ] }, "apiVersion": "2.0" } You would do the following: x = gdata.core.parse_json(the_above_string) # Gives you 800 x.data.total_items # Should be 22 x.data.items[0].comment_count # The apiVersion is '2.0' x.api_version To create a Jsonc object which would produce the above JSON, you would do: gdata.core.Jsonc( api_version='2.0', data=gdata.core.Jsonc( total_items=800, items=[ gdata.core.Jsonc( view_count=220101, comment_count=22, favorite_count=201, content={ '1': ('rtsp://v5.cache3.c.youtube.com' '/CiILENy.../0/0/0/video.3gp')})])) or x = gdata.core.Jsonc() x.api_version = '2.0' x.data = gdata.core.Jsonc() x.data.total_items = 800 x.data.items = [] # etc. How it works: The JSON-C data is stored in an internal dictionary (._dict) and the getattr, setattr, and delattr methods rewrite the name which you provide to mirror the expected format in JSON-C. (For more details on name conversion see _to_jsonc_name.) You may also access members using getitem, setitem, delitem as you would for a dictionary. For example x.data.total_items is equivalent to x['data']['totalItems'] (Not all dict methods are supported so if you need something other than the item operations, then you will want to use the ._dict member). You may need to use getitem or the _dict member to access certain properties in cases where the JSON-C syntax does not map neatly to Python objects. For example the YouTube Video feed has some JSON like this: "content": {"1": "rtsp://v5.cache3.c.youtube.com..."...} You cannot do x.content.1 in Python, so you would use the getitem as follows: x.content['1'] or you could use the _dict member as follows: x.content._dict['1'] If you need to create a new object with such a mapping you could use. x.content = gdata.core.Jsonc(_dict={'1': 'rtsp://cache3.c.youtube.com...'}) """ def __init__(self, _dict=None, **kwargs): json = _dict or {} for key, value in kwargs.iteritems(): if key.startswith('_'): object.__setattr__(self, key, value) else: json[_to_jsonc_name(key)] = _convert_to_jsonc(value) object.__setattr__(self, '_dict', json) def __setattr__(self, name, value): if name.startswith('_'): object.__setattr__(self, name, value) else: object.__getattribute__( self, '_dict')[_to_jsonc_name(name)] = _convert_to_jsonc(value) def __getattr__(self, name): if name.startswith('_'): object.__getattribute__(self, name) else: try: return object.__getattribute__(self, '_dict')[_to_jsonc_name(name)] except KeyError: raise AttributeError( 'No member for %s or [\'%s\']' % (name, _to_jsonc_name(name))) def __delattr__(self, name): if name.startswith('_'): object.__delattr__(self, name) else: try: del object.__getattribute__(self, '_dict')[_to_jsonc_name(name)] except KeyError: raise AttributeError( 'No member for %s (or [\'%s\'])' % (name, _to_jsonc_name(name))) # For container methods pass-through to the underlying dict. def __getitem__(self, key): return self._dict[key] def __setitem__(self, key, value): self._dict[key] = value def __delitem__(self, key): del self._dict[key]
Python
#!/usr/bin/env python # # Copyright (C) 2008, 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This module is used for version 2 of the Google Data APIs. """Provides a client to interact with Google Data API servers. This module is used for version 2 of the Google Data APIs. The primary class in this module is GDClient. GDClient: handles auth and CRUD operations when communicating with servers. GDataClient: deprecated client for version one services. Will be removed. """ __author__ = 'j.s@google.com (Jeff Scudder)' import re import atom.client import atom.core import atom.http_core import gdata.gauth import gdata.data class Error(Exception): pass class RequestError(Error): status = None reason = None body = None headers = None class RedirectError(RequestError): pass class CaptchaChallenge(RequestError): captcha_url = None captcha_token = None class ClientLoginTokenMissing(Error): pass class MissingOAuthParameters(Error): pass class ClientLoginFailed(RequestError): pass class UnableToUpgradeToken(RequestError): pass class Unauthorized(Error): pass class BadAuthenticationServiceURL(RedirectError): pass class BadAuthentication(RequestError): pass class NotModified(RequestError): pass class NotImplemented(RequestError): pass def error_from_response(message, http_response, error_class, response_body=None): """Creates a new exception and sets the HTTP information in the error. Args: message: str human readable message to be displayed if the exception is not caught. http_response: The response from the server, contains error information. error_class: The exception to be instantiated and populated with information from the http_response response_body: str (optional) specify if the response has already been read from the http_response object. """ if response_body is None: body = http_response.read() else: body = response_body error = error_class('%s: %i, %s' % (message, http_response.status, body)) error.status = http_response.status error.reason = http_response.reason error.body = body error.headers = atom.http_core.get_headers(http_response) return error def get_xml_version(version): """Determines which XML schema to use based on the client API version. Args: version: string which is converted to an int. The version string is in the form 'Major.Minor.x.y.z' and only the major version number is considered. If None is provided assume version 1. """ if version is None: return 1 return int(version.split('.')[0]) class GDClient(atom.client.AtomPubClient): """Communicates with Google Data servers to perform CRUD operations. This class is currently experimental and may change in backwards incompatible ways. This class exists to simplify the following three areas involved in using the Google Data APIs. CRUD Operations: The client provides a generic 'request' method for making HTTP requests. There are a number of convenience methods which are built on top of request, which include get_feed, get_entry, get_next, post, update, and delete. These methods contact the Google Data servers. Auth: Reading user-specific private data requires authorization from the user as do any changes to user data. An auth_token object can be passed into any of the HTTP requests to set the Authorization header in the request. You may also want to set the auth_token member to a an object which can use modify_request to set the Authorization header in the HTTP request. If you are authenticating using the email address and password, you can use the client_login method to obtain an auth token and set the auth_token member. If you are using browser redirects, specifically AuthSub, you will want to use gdata.gauth.AuthSubToken.from_url to obtain the token after the redirect, and you will probably want to updgrade this since use token to a multiple use (session) token using the upgrade_token method. API Versions: This client is multi-version capable and can be used with Google Data API version 1 and version 2. The version should be specified by setting the api_version member to a string, either '1' or '2'. """ # The gsessionid is used by Google Calendar to prevent redirects. __gsessionid = None api_version = None # Name of the Google Data service when making a ClientLogin request. auth_service = None # URL prefixes which should be requested for AuthSub and OAuth. auth_scopes = None # Name of alternate auth service to use in certain cases alt_auth_service = None def request(self, method=None, uri=None, auth_token=None, http_request=None, converter=None, desired_class=None, redirects_remaining=4, **kwargs): """Make an HTTP request to the server. See also documentation for atom.client.AtomPubClient.request. If a 302 redirect is sent from the server to the client, this client assumes that the redirect is in the form used by the Google Calendar API. The same request URI and method will be used as in the original request, but a gsessionid URL parameter will be added to the request URI with the value provided in the server's 302 redirect response. If the 302 redirect is not in the format specified by the Google Calendar API, a RedirectError will be raised containing the body of the server's response. The method calls the client's modify_request method to make any changes required by the client before the request is made. For example, a version 2 client could add a GData-Version: 2 header to the request in its modify_request method. Args: method: str The HTTP verb for this request, usually 'GET', 'POST', 'PUT', or 'DELETE' uri: atom.http_core.Uri, str, or unicode The URL being requested. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. http_request: (optional) atom.http_core.HttpRequest converter: function which takes the body of the response as its only argument and returns the desired object. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (converter=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. redirects_remaining: (optional) int, if this number is 0 and the server sends a 302 redirect, the request method will raise an exception. This parameter is used in recursive request calls to avoid an infinite loop. Any additional arguments are passed through to atom.client.AtomPubClient.request. Returns: An HTTP response object (see atom.http_core.HttpResponse for a description of the object's interface) if no converter was specified and no desired_class was specified. If a converter function was provided, the results of calling the converter are returned. If no converter was specified but a desired_class was provided, the response body will be converted to the class using atom.core.parse. """ if isinstance(uri, (str, unicode)): uri = atom.http_core.Uri.parse_uri(uri) # Add the gsession ID to the URL to prevent further redirects. # TODO: If different sessions are using the same client, there will be a # multitude of redirects and session ID shuffling. # If the gsession ID is in the URL, adopt it as the standard location. if uri is not None and uri.query is not None and 'gsessionid' in uri.query: self.__gsessionid = uri.query['gsessionid'] # The gsession ID could also be in the HTTP request. elif (http_request is not None and http_request.uri is not None and http_request.uri.query is not None and 'gsessionid' in http_request.uri.query): self.__gsessionid = http_request.uri.query['gsessionid'] # If the gsession ID is stored in the client, and was not present in the # URI then add it to the URI. elif self.__gsessionid is not None: uri.query['gsessionid'] = self.__gsessionid # The AtomPubClient should call this class' modify_request before # performing the HTTP request. #http_request = self.modify_request(http_request) response = atom.client.AtomPubClient.request(self, method=method, uri=uri, auth_token=auth_token, http_request=http_request, **kwargs) # On success, convert the response body using the desired converter # function if present. if response is None: return None if response.status == 200 or response.status == 201: if converter is not None: return converter(response) elif desired_class is not None: if self.api_version is not None: return atom.core.parse(response.read(), desired_class, version=get_xml_version(self.api_version)) else: # No API version was specified, so allow parse to # use the default version. return atom.core.parse(response.read(), desired_class) else: return response # TODO: move the redirect logic into the Google Calendar client once it # exists since the redirects are only used in the calendar API. elif response.status == 302: if redirects_remaining > 0: location = (response.getheader('Location') or response.getheader('location')) if location is not None: # Make a recursive call with the gsession ID in the URI to follow # the redirect. return self.request(method=method, uri=location, auth_token=auth_token, http_request=http_request, converter=converter, desired_class=desired_class, redirects_remaining=redirects_remaining-1, **kwargs) else: raise error_from_response('302 received without Location header', response, RedirectError) else: raise error_from_response('Too many redirects from server', response, RedirectError) elif response.status == 401: raise error_from_response('Unauthorized - Server responded with', response, Unauthorized) elif response.status == 304: raise error_from_response('Entry Not Modified - Server responded with', response, NotModified) elif response.status == 501: raise error_from_response( 'This API operation is not implemented. - Server responded with', response, NotImplemented) # If the server's response was not a 200, 201, 302, 304, 401, or 501, raise # an exception. else: raise error_from_response('Server responded with', response, RequestError) Request = request def request_client_login_token( self, email, password, source, service=None, account_type='HOSTED_OR_GOOGLE', auth_url=atom.http_core.Uri.parse_uri( 'https://www.google.com/accounts/ClientLogin'), captcha_token=None, captcha_response=None): service = service or self.auth_service # Set the target URL. http_request = atom.http_core.HttpRequest(uri=auth_url, method='POST') http_request.add_body_part( gdata.gauth.generate_client_login_request_body(email=email, password=password, service=service, source=source, account_type=account_type, captcha_token=captcha_token, captcha_response=captcha_response), 'application/x-www-form-urlencoded') # Use the underlying http_client to make the request. response = self.http_client.request(http_request) response_body = response.read() if response.status == 200: token_string = gdata.gauth.get_client_login_token_string(response_body) if token_string is not None: return gdata.gauth.ClientLoginToken(token_string) else: raise ClientLoginTokenMissing( 'Recieved a 200 response to client login request,' ' but no token was present. %s' % (response_body,)) elif response.status == 403: captcha_challenge = gdata.gauth.get_captcha_challenge(response_body) if captcha_challenge: challenge = CaptchaChallenge('CAPTCHA required') challenge.captcha_url = captcha_challenge['url'] challenge.captcha_token = captcha_challenge['token'] raise challenge elif response_body.splitlines()[0] == 'Error=BadAuthentication': raise BadAuthentication('Incorrect username or password') else: raise error_from_response('Server responded with a 403 code', response, RequestError, response_body) elif response.status == 302: # Google tries to redirect all bad URLs back to # http://www.google.<locale>. If a redirect # attempt is made, assume the user has supplied an incorrect # authentication URL raise error_from_response('Server responded with a redirect', response, BadAuthenticationServiceURL, response_body) else: raise error_from_response('Server responded to ClientLogin request', response, ClientLoginFailed, response_body) RequestClientLoginToken = request_client_login_token def client_login(self, email, password, source, service=None, account_type='HOSTED_OR_GOOGLE', auth_url=atom.http_core.Uri.parse_uri( 'https://www.google.com/accounts/ClientLogin'), captcha_token=None, captcha_response=None): """Performs an auth request using the user's email address and password. In order to modify user specific data and read user private data, your application must be authorized by the user. One way to demonstrage authorization is by including a Client Login token in the Authorization HTTP header of all requests. This method requests the Client Login token by sending the user's email address, password, the name of the application, and the service code for the service which will be accessed by the application. If the username and password are correct, the server will respond with the client login code and a new ClientLoginToken object will be set in the client's auth_token member. With the auth_token set, future requests from this client will include the Client Login token. For a list of service names, see http://code.google.com/apis/gdata/faq.html#clientlogin For more information on Client Login, see: http://code.google.com/apis/accounts/docs/AuthForInstalledApps.html Args: email: str The user's email address or username. password: str The password for the user's account. source: str The name of your application. This can be anything you like but should should give some indication of which app is making the request. service: str The service code for the service you would like to access. For example, 'cp' for contacts, 'cl' for calendar. For a full list see http://code.google.com/apis/gdata/faq.html#clientlogin If you are using a subclass of the gdata.client.GDClient, the service will usually be filled in for you so you do not need to specify it. For example see BloggerClient, SpreadsheetsClient, etc. account_type: str (optional) The type of account which is being authenticated. This can be either 'GOOGLE' for a Google Account, 'HOSTED' for a Google Apps Account, or the default 'HOSTED_OR_GOOGLE' which will select the Google Apps Account if the same email address is used for both a Google Account and a Google Apps Account. auth_url: str (optional) The URL to which the login request should be sent. captcha_token: str (optional) If a previous login attempt was reponded to with a CAPTCHA challenge, this is the token which identifies the challenge (from the CAPTCHA's URL). captcha_response: str (optional) If a previous login attempt was reponded to with a CAPTCHA challenge, this is the response text which was contained in the challenge. Returns: Generated token, which is also stored in this object. Raises: A RequestError or one of its suclasses: BadAuthentication, BadAuthenticationServiceURL, ClientLoginFailed, ClientLoginTokenMissing, or CaptchaChallenge """ service = service or self.auth_service self.auth_token = self.request_client_login_token(email, password, source, service=service, account_type=account_type, auth_url=auth_url, captcha_token=captcha_token, captcha_response=captcha_response) if self.alt_auth_service is not None: self.alt_auth_token = self.request_client_login_token( email, password, source, service=self.alt_auth_service, account_type=account_type, auth_url=auth_url, captcha_token=captcha_token, captcha_response=captcha_response) return self.auth_token ClientLogin = client_login def upgrade_token(self, token=None, url=atom.http_core.Uri.parse_uri( 'https://www.google.com/accounts/AuthSubSessionToken')): """Asks the Google auth server for a multi-use AuthSub token. For details on AuthSub, see: http://code.google.com/apis/accounts/docs/AuthSub.html Args: token: gdata.gauth.AuthSubToken or gdata.gauth.SecureAuthSubToken (optional) If no token is passed in, the client's auth_token member is used to request the new token. The token object will be modified to contain the new session token string. url: str or atom.http_core.Uri (optional) The URL to which the token upgrade request should be sent. Defaults to: https://www.google.com/accounts/AuthSubSessionToken Returns: The upgraded gdata.gauth.AuthSubToken object. """ # Default to using the auth_token member if no token is provided. if token is None: token = self.auth_token # We cannot upgrade a None token. if token is None: raise UnableToUpgradeToken('No token was provided.') if not isinstance(token, gdata.gauth.AuthSubToken): raise UnableToUpgradeToken( 'Cannot upgrade the token because it is not an AuthSubToken object.') http_request = atom.http_core.HttpRequest(uri=url, method='GET') token.modify_request(http_request) # Use the lower level HttpClient to make the request. response = self.http_client.request(http_request) if response.status == 200: token._upgrade_token(response.read()) return token else: raise UnableToUpgradeToken( 'Server responded to token upgrade request with %s: %s' % ( response.status, response.read())) UpgradeToken = upgrade_token def revoke_token(self, token=None, url=atom.http_core.Uri.parse_uri( 'https://www.google.com/accounts/AuthSubRevokeToken')): """Requests that the token be invalidated. This method can be used for both AuthSub and OAuth tokens (to invalidate a ClientLogin token, the user must change their password). Returns: True if the server responded with a 200. Raises: A RequestError if the server responds with a non-200 status. """ # Default to using the auth_token member if no token is provided. if token is None: token = self.auth_token http_request = atom.http_core.HttpRequest(uri=url, method='GET') token.modify_request(http_request) response = self.http_client.request(http_request) if response.status != 200: raise error_from_response('Server sent non-200 to revoke token', response, RequestError, response.read()) return True RevokeToken = revoke_token def get_oauth_token(self, scopes, next, consumer_key, consumer_secret=None, rsa_private_key=None, url=gdata.gauth.REQUEST_TOKEN_URL): """Obtains an OAuth request token to allow the user to authorize this app. Once this client has a request token, the user can authorize the request token by visiting the authorization URL in their browser. After being redirected back to this app at the 'next' URL, this app can then exchange the authorized request token for an access token. For more information see the documentation on Google Accounts with OAuth: http://code.google.com/apis/accounts/docs/OAuth.html#AuthProcess Args: scopes: list of strings or atom.http_core.Uri objects which specify the URL prefixes which this app will be accessing. For example, to access the Google Calendar API, you would want to use scopes: ['https://www.google.com/calendar/feeds/', 'http://www.google.com/calendar/feeds/'] next: str or atom.http_core.Uri object, The URL which the user's browser should be sent to after they authorize access to their data. This should be a URL in your application which will read the token information from the URL and upgrade the request token to an access token. consumer_key: str This is the identifier for this application which you should have received when you registered your application with Google to use OAuth. consumer_secret: str (optional) The shared secret between your app and Google which provides evidence that this request is coming from you application and not another app. If present, this libraries assumes you want to use an HMAC signature to verify requests. Keep this data a secret. rsa_private_key: str (optional) The RSA private key which is used to generate a digital signature which is checked by Google's server. If present, this library assumes that you want to use an RSA signature to verify requests. Keep this data a secret. url: The URL to which a request for a token should be made. The default is Google's OAuth request token provider. """ http_request = None if rsa_private_key is not None: http_request = gdata.gauth.generate_request_for_request_token( consumer_key, gdata.gauth.RSA_SHA1, scopes, rsa_key=rsa_private_key, auth_server_url=url, next=next) elif consumer_secret is not None: http_request = gdata.gauth.generate_request_for_request_token( consumer_key, gdata.gauth.HMAC_SHA1, scopes, consumer_secret=consumer_secret, auth_server_url=url, next=next) else: raise MissingOAuthParameters( 'To request an OAuth token, you must provide your consumer secret' ' or your private RSA key.') response = self.http_client.request(http_request) response_body = response.read() if response.status != 200: raise error_from_response('Unable to obtain OAuth request token', response, RequestError, response_body) if rsa_private_key is not None: return gdata.gauth.rsa_token_from_body(response_body, consumer_key, rsa_private_key, gdata.gauth.REQUEST_TOKEN) elif consumer_secret is not None: return gdata.gauth.hmac_token_from_body(response_body, consumer_key, consumer_secret, gdata.gauth.REQUEST_TOKEN) GetOAuthToken = get_oauth_token def get_access_token(self, request_token, url=gdata.gauth.ACCESS_TOKEN_URL): """Exchanges an authorized OAuth request token for an access token. Contacts the Google OAuth server to upgrade a previously authorized request token. Once the request token is upgraded to an access token, the access token may be used to access the user's data. For more details, see the Google Accounts OAuth documentation: http://code.google.com/apis/accounts/docs/OAuth.html#AccessToken Args: request_token: An OAuth token which has been authorized by the user. url: (optional) The URL to which the upgrade request should be sent. Defaults to: https://www.google.com/accounts/OAuthAuthorizeToken """ http_request = gdata.gauth.generate_request_for_access_token( request_token, auth_server_url=url) response = self.http_client.request(http_request) response_body = response.read() if response.status != 200: raise error_from_response( 'Unable to upgrade OAuth request token to access token', response, RequestError, response_body) return gdata.gauth.upgrade_to_access_token(request_token, response_body) GetAccessToken = get_access_token def modify_request(self, http_request): """Adds or changes request before making the HTTP request. This client will add the API version if it is specified. Subclasses may override this method to add their own request modifications before the request is made. """ http_request = atom.client.AtomPubClient.modify_request(self, http_request) if self.api_version is not None: http_request.headers['GData-Version'] = self.api_version return http_request ModifyRequest = modify_request def get_feed(self, uri, auth_token=None, converter=None, desired_class=gdata.data.GDFeed, **kwargs): return self.request(method='GET', uri=uri, auth_token=auth_token, converter=converter, desired_class=desired_class, **kwargs) GetFeed = get_feed def get_entry(self, uri, auth_token=None, converter=None, desired_class=gdata.data.GDEntry, etag=None, **kwargs): http_request = atom.http_core.HttpRequest() # Conditional retrieval if etag is not None: http_request.headers['If-None-Match'] = etag return self.request(method='GET', uri=uri, auth_token=auth_token, http_request=http_request, converter=converter, desired_class=desired_class, **kwargs) GetEntry = get_entry def get_next(self, feed, auth_token=None, converter=None, desired_class=None, **kwargs): """Fetches the next set of results from the feed. When requesting a feed, the number of entries returned is capped at a service specific default limit (often 25 entries). You can specify your own entry-count cap using the max-results URL query parameter. If there are more results than could fit under max-results, the feed will contain a next link. This method performs a GET against this next results URL. Returns: A new feed object containing the next set of entries in this feed. """ if converter is None and desired_class is None: desired_class = feed.__class__ return self.get_feed(feed.find_next_link(), auth_token=auth_token, converter=converter, desired_class=desired_class, **kwargs) GetNext = get_next # TODO: add a refresh method to re-fetch the entry/feed from the server # if it has been updated. def post(self, entry, uri, auth_token=None, converter=None, desired_class=None, **kwargs): if converter is None and desired_class is None: desired_class = entry.__class__ http_request = atom.http_core.HttpRequest() http_request.add_body_part( entry.to_string(get_xml_version(self.api_version)), 'application/atom+xml') return self.request(method='POST', uri=uri, auth_token=auth_token, http_request=http_request, converter=converter, desired_class=desired_class, **kwargs) Post = post def update(self, entry, auth_token=None, force=False, uri=None, **kwargs): """Edits the entry on the server by sending the XML for this entry. Performs a PUT and converts the response to a new entry object with a matching class to the entry passed in. Args: entry: auth_token: force: boolean stating whether an update should be forced. Defaults to False. Normally, if a change has been made since the passed in entry was obtained, the server will not overwrite the entry since the changes were based on an obsolete version of the entry. Setting force to True will cause the update to silently overwrite whatever version is present. uri: The uri to put to. If provided, this uri is PUT to rather than the inferred uri from the entry's edit link. Returns: A new Entry object of a matching type to the entry which was passed in. """ http_request = atom.http_core.HttpRequest() http_request.add_body_part( entry.to_string(get_xml_version(self.api_version)), 'application/atom+xml') # Include the ETag in the request if present. if force: http_request.headers['If-Match'] = '*' elif hasattr(entry, 'etag') and entry.etag: http_request.headers['If-Match'] = entry.etag if uri is None: uri = entry.find_edit_link() return self.request(method='PUT', uri=uri, auth_token=auth_token, http_request=http_request, desired_class=entry.__class__, **kwargs) Update = update def delete(self, entry_or_uri, auth_token=None, force=False, **kwargs): http_request = atom.http_core.HttpRequest() # Include the ETag in the request if present. if force: http_request.headers['If-Match'] = '*' elif hasattr(entry_or_uri, 'etag') and entry_or_uri.etag: http_request.headers['If-Match'] = entry_or_uri.etag # If the user passes in a URL, just delete directly, may not work as # the service might require an ETag. if isinstance(entry_or_uri, (str, unicode, atom.http_core.Uri)): return self.request(method='DELETE', uri=entry_or_uri, http_request=http_request, auth_token=auth_token, **kwargs) return self.request(method='DELETE', uri=entry_or_uri.find_edit_link(), http_request=http_request, auth_token=auth_token, **kwargs) Delete = delete def batch(self, feed, uri=None, force=False, auth_token=None, **kwargs): """Sends a batch request to the server to execute operation entries. Args: feed: A batch feed containing batch entries, each is an operation. uri: (optional) The uri to which the batch request feed should be POSTed. If none is provided, then the feed's edit link will be used. force: (optional) boolean set to True if you want the batch update to clobber all data. If False, the version in the information in the feed object will cause the server to check to see that no changes intervened between when you fetched the data and when you sent the changes. auth_token: (optional) An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. """ http_request = atom.http_core.HttpRequest() http_request.add_body_part( feed.to_string(get_xml_version(self.api_version)), 'application/atom+xml') if force: http_request.headers['If-Match'] = '*' elif hasattr(feed, 'etag') and feed.etag: http_request.headers['If-Match'] = feed.etag if uri is None: uri = feed.find_edit_link() return self.request(method='POST', uri=uri, auth_token=auth_token, http_request=http_request, desired_class=feed.__class__, **kwargs) Batch = batch # TODO: add a refresh method to request a conditional update to an entry # or feed. def _add_query_param(param_string, value, http_request): if value: http_request.uri.query[param_string] = value class Query(object): def __init__(self, text_query=None, categories=None, author=None, alt=None, updated_min=None, updated_max=None, pretty_print=False, published_min=None, published_max=None, start_index=None, max_results=None, strict=False, **custom_parameters): """Constructs a Google Data Query to filter feed contents serverside. Args: text_query: Full text search str (optional) categories: list of strings (optional). Each string is a required category. To include an 'or' query, put a | in the string between terms. For example, to find everything in the Fitz category and the Laurie or Jane category (Fitz and (Laurie or Jane)) you would set categories to ['Fitz', 'Laurie|Jane']. author: str (optional) The service returns entries where the author name and/or email address match your query string. alt: str (optional) for the Alternative representation type you'd like the feed in. If you don't specify an alt parameter, the service returns an Atom feed. This is equivalent to alt='atom'. alt='rss' returns an RSS 2.0 result feed. alt='json' returns a JSON representation of the feed. alt='json-in-script' Requests a response that wraps JSON in a script tag. alt='atom-in-script' Requests an Atom response that wraps an XML string in a script tag. alt='rss-in-script' Requests an RSS response that wraps an XML string in a script tag. updated_min: str (optional), RFC 3339 timestamp format, lower bounds. For example: 2005-08-09T10:57:00-08:00 updated_max: str (optional) updated time must be earlier than timestamp. pretty_print: boolean (optional) If True the server's XML response will be indented to make it more human readable. Defaults to False. published_min: str (optional), Similar to updated_min but for published time. published_max: str (optional), Similar to updated_max but for published time. start_index: int or str (optional) 1-based index of the first result to be retrieved. Note that this isn't a general cursoring mechanism. If you first send a query with ?start-index=1&max-results=10 and then send another query with ?start-index=11&max-results=10, the service cannot guarantee that the results are equivalent to ?start-index=1&max-results=20, because insertions and deletions could have taken place in between the two queries. max_results: int or str (optional) Maximum number of results to be retrieved. Each service has a default max (usually 25) which can vary from service to service. There is also a service-specific limit to the max_results you can fetch in a request. strict: boolean (optional) If True, the server will return an error if the server does not recognize any of the parameters in the request URL. Defaults to False. custom_parameters: other query parameters that are not explicitly defined. """ self.text_query = text_query self.categories = categories or [] self.author = author self.alt = alt self.updated_min = updated_min self.updated_max = updated_max self.pretty_print = pretty_print self.published_min = published_min self.published_max = published_max self.start_index = start_index self.max_results = max_results self.strict = strict self.custom_parameters = custom_parameters def add_custom_parameter(self, key, value): self.custom_parameters[key] = value AddCustomParameter = add_custom_parameter def modify_request(self, http_request): _add_query_param('q', self.text_query, http_request) if self.categories: http_request.uri.query['category'] = ','.join(self.categories) _add_query_param('author', self.author, http_request) _add_query_param('alt', self.alt, http_request) _add_query_param('updated-min', self.updated_min, http_request) _add_query_param('updated-max', self.updated_max, http_request) if self.pretty_print: http_request.uri.query['prettyprint'] = 'true' _add_query_param('published-min', self.published_min, http_request) _add_query_param('published-max', self.published_max, http_request) if self.start_index is not None: http_request.uri.query['start-index'] = str(self.start_index) if self.max_results is not None: http_request.uri.query['max-results'] = str(self.max_results) if self.strict: http_request.uri.query['strict'] = 'true' http_request.uri.query.update(self.custom_parameters) ModifyRequest = modify_request class GDQuery(atom.http_core.Uri): def _get_text_query(self): return self.query['q'] def _set_text_query(self, value): self.query['q'] = value text_query = property(_get_text_query, _set_text_query, doc='The q parameter for searching for an exact text match on content') class ResumableUploader(object): """Resumable upload helper for the Google Data protocol.""" DEFAULT_CHUNK_SIZE = 5242880 # 5MB # Initial chunks which are smaller than 256KB might be dropped. The last # chunk for a file can be smaller tan this. MIN_CHUNK_SIZE = 262144 # 256KB def __init__(self, client, file_handle, content_type, total_file_size, chunk_size=None, desired_class=None): """Starts a resumable upload to a service that supports the protocol. Args: client: gdata.client.GDClient A Google Data API service. file_handle: object A file-like object containing the file to upload. content_type: str The mimetype of the file to upload. total_file_size: int The file's total size in bytes. chunk_size: int The size of each upload chunk. If None, the DEFAULT_CHUNK_SIZE will be used. desired_class: object (optional) The type of gdata.data.GDEntry to parse the completed entry as. This should be specific to the API. """ self.client = client self.file_handle = file_handle self.content_type = content_type self.total_file_size = total_file_size self.chunk_size = chunk_size or self.DEFAULT_CHUNK_SIZE if self.chunk_size < self.MIN_CHUNK_SIZE: self.chunk_size = self.MIN_CHUNK_SIZE self.desired_class = desired_class or gdata.data.GDEntry self.upload_uri = None # Send the entire file if the chunk size is less than fize's total size. if self.total_file_size <= self.chunk_size: self.chunk_size = total_file_size def _init_session(self, resumable_media_link, entry=None, headers=None, auth_token=None, method='POST'): """Starts a new resumable upload to a service that supports the protocol. The method makes a request to initiate a new upload session. The unique upload uri returned by the server (and set in this method) should be used to send upload chunks to the server. Args: resumable_media_link: str The full URL for the #resumable-create-media or #resumable-edit-media link for starting a resumable upload request or updating media using a resumable PUT. entry: A (optional) gdata.data.GDEntry containging metadata to create the upload from. headers: dict (optional) Additional headers to send in the initial request to create the resumable upload request. These headers will override any default headers sent in the request. For example: headers={'Slug': 'MyTitle'}. auth_token: (optional) An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. method: (optional) Type of HTTP request to start the session with. Defaults to 'POST', but may also be 'PUT'. Returns: Result of HTTP request to intialize the session. See atom.client.request. Raises: RequestError if the unique upload uri is not set or the server returns something other than an HTTP 308 when the upload is incomplete. """ http_request = atom.http_core.HttpRequest() # Send empty body if Atom XML wasn't specified. if entry is None: http_request.add_body_part('', self.content_type, size=0) else: http_request.add_body_part(str(entry), 'application/atom+xml', size=len(str(entry))) http_request.headers['X-Upload-Content-Type'] = self.content_type http_request.headers['X-Upload-Content-Length'] = str(self.total_file_size) if headers is not None: http_request.headers.update(headers) response = self.client.request(method=method, uri=resumable_media_link, auth_token=auth_token, http_request=http_request) self.upload_uri = (response.getheader('location') or response.getheader('Location')) return response _InitSession = _init_session def upload_chunk(self, start_byte, content_bytes): """Uploads a byte range (chunk) to the resumable upload server. Args: start_byte: int The byte offset of the total file where the byte range passed in lives. content_bytes: str The file contents of this chunk. Returns: The final Atom entry created on the server. The entry object's type will be the class specified in self.desired_class. Raises: RequestError if the unique upload uri is not set or the server returns something other than an HTTP 308 when the upload is incomplete. """ if self.upload_uri is None: raise RequestError('Resumable upload request not initialized.') # Adjustment if last byte range is less than defined chunk size. chunk_size = self.chunk_size if len(content_bytes) <= chunk_size: chunk_size = len(content_bytes) http_request = atom.http_core.HttpRequest() http_request.add_body_part(content_bytes, self.content_type, size=len(content_bytes)) http_request.headers['Content-Range'] = ('bytes %s-%s/%s' % (start_byte, start_byte + chunk_size - 1, self.total_file_size)) try: response = self.client.request(method='PUT', uri=self.upload_uri, http_request=http_request, desired_class=self.desired_class) return response except RequestError, error: if error.status == 308: return None else: raise error UploadChunk = upload_chunk def upload_file(self, resumable_media_link, entry=None, headers=None, auth_token=None, **kwargs): """Uploads an entire file in chunks using the resumable upload protocol. If you are interested in pausing an upload or controlling the chunking yourself, use the upload_chunk() method instead. Args: resumable_media_link: str The full URL for the #resumable-create-media for starting a resumable upload request. entry: A (optional) gdata.data.GDEntry containging metadata to create the upload from. headers: dict Additional headers to send in the initial request to create the resumable upload request. These headers will override any default headers sent in the request. For example: headers={'Slug': 'MyTitle'}. auth_token: (optional) An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. kwargs: (optional) Other args to pass to self._init_session. Returns: The final Atom entry created on the server. The entry object's type will be the class specified in self.desired_class. Raises: RequestError if anything other than a HTTP 308 is returned when the request raises an exception. """ self._init_session(resumable_media_link, headers=headers, auth_token=auth_token, entry=entry, **kwargs) start_byte = 0 entry = None while not entry: entry = self.upload_chunk( start_byte, self.file_handle.read(self.chunk_size)) start_byte += self.chunk_size return entry UploadFile = upload_file def update_file(self, entry_or_resumable_edit_link, headers=None, force=False, auth_token=None, update_metadata=False, uri_params=None): """Updates the contents of an existing file using the resumable protocol. If you are interested in pausing an upload or controlling the chunking yourself, use the upload_chunk() method instead. Args: entry_or_resumable_edit_link: object or string A gdata.data.GDEntry for the entry/file to update or the full uri of the link with rel #resumable-edit-media. headers: dict Additional headers to send in the initial request to create the resumable upload request. These headers will override any default headers sent in the request. For example: headers={'Slug': 'MyTitle'}. force boolean (optional) True to force an update and set the If-Match header to '*'. If False and entry_or_resumable_edit_link is a gdata.data.GDEntry object, its etag value is used. Otherwise this parameter should be set to True to force the update. auth_token: (optional) An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. update_metadata: (optional) True to also update the entry's metadata with that in the given GDEntry object in entry_or_resumable_edit_link. uri_params: (optional) Dict of additional parameters to attach to the URI. Some non-dict types are valid here, too, like list of tuple pairs. Returns: The final Atom entry created on the server. The entry object's type will be the class specified in self.desired_class. Raises: RequestError if anything other than a HTTP 308 is returned when the request raises an exception. """ custom_headers = {} if headers is not None: custom_headers.update(headers) uri = None entry = None if isinstance(entry_or_resumable_edit_link, gdata.data.GDEntry): uri = entry_or_resumable_edit_link.find_url( 'http://schemas.google.com/g/2005#resumable-edit-media') custom_headers['If-Match'] = entry_or_resumable_edit_link.etag if update_metadata: entry = entry_or_resumable_edit_link else: uri = entry_or_resumable_edit_link uri = atom.http_core.parse_uri(uri) if uri_params is not None: uri.query.update(uri_params) if force: custom_headers['If-Match'] = '*' return self.upload_file(str(uri), entry=entry, headers=custom_headers, auth_token=auth_token, method='PUT') UpdateFile = update_file def query_upload_status(self, uri=None): """Queries the current status of a resumable upload request. Args: uri: str (optional) A resumable upload uri to query and override the one that is set in this object. Returns: An integer representing the file position (byte) to resume the upload from or True if the upload is complete. Raises: RequestError if anything other than a HTTP 308 is returned when the request raises an exception. """ # Override object's unique upload uri. if uri is None: uri = self.upload_uri http_request = atom.http_core.HttpRequest() http_request.headers['Content-Length'] = '0' http_request.headers['Content-Range'] = 'bytes */%s' % self.total_file_size try: response = self.client.request( method='POST', uri=uri, http_request=http_request) if response.status == 201: return True else: raise error_from_response( '%s returned by server' % response.status, response, RequestError) except RequestError, error: if error.status == 308: for pair in error.headers: if pair[0].capitalize() == 'Range': return int(pair[1].split('-')[1]) + 1 else: raise error QueryUploadStatus = query_upload_status
Python
#!/usr/bin/python # # Copyright (C) 2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains the data classes of the Google Calendar Data API""" __author__ = 'j.s@google.com (Jeff Scudder)' import atom.core import atom.data import gdata.acl.data import gdata.data import gdata.geo.data import gdata.opensearch.data GCAL_NAMESPACE = 'http://schemas.google.com/gCal/2005' GCAL_TEMPLATE = '{%s}%%s' % GCAL_NAMESPACE WEB_CONTENT_LINK_REL = '%s/%s' % (GCAL_NAMESPACE, 'webContent') class AccessLevelProperty(atom.core.XmlElement): """Describes how much a given user may do with an event or calendar""" _qname = GCAL_TEMPLATE % 'accesslevel' value = 'value' class AllowGSync2Property(atom.core.XmlElement): """Whether the user is permitted to run Google Apps Sync""" _qname = GCAL_TEMPLATE % 'allowGSync2' value = 'value' class AllowGSyncProperty(atom.core.XmlElement): """Whether the user is permitted to run Google Apps Sync""" _qname = GCAL_TEMPLATE % 'allowGSync' value = 'value' class AnyoneCanAddSelfProperty(atom.core.XmlElement): """Whether anyone can add self as attendee""" _qname = GCAL_TEMPLATE % 'anyoneCanAddSelf' value = 'value' class CalendarAclRole(gdata.acl.data.AclRole): """Describes the Calendar roles of an entry in the Calendar access control list""" _qname = gdata.acl.data.GACL_TEMPLATE % 'role' class CalendarCommentEntry(gdata.data.GDEntry): """Describes an entry in a feed of a Calendar event's comments""" class CalendarCommentFeed(gdata.data.GDFeed): """Describes feed of a Calendar event's comments""" entry = [CalendarCommentEntry] class CalendarComments(gdata.data.Comments): """Describes a container of a feed link for Calendar comment entries""" _qname = gdata.data.GD_TEMPLATE % 'comments' class CalendarExtendedProperty(gdata.data.ExtendedProperty): """Defines a value for the realm attribute that is used only in the calendar API""" _qname = gdata.data.GD_TEMPLATE % 'extendedProperty' class CalendarWhere(gdata.data.Where): """Extends the base Where class with Calendar extensions""" _qname = gdata.data.GD_TEMPLATE % 'where' class ColorProperty(atom.core.XmlElement): """Describes the color of a calendar""" _qname = GCAL_TEMPLATE % 'color' value = 'value' class GuestsCanInviteOthersProperty(atom.core.XmlElement): """Whether guests can invite others to the event""" _qname = GCAL_TEMPLATE % 'guestsCanInviteOthers' value = 'value' class GuestsCanModifyProperty(atom.core.XmlElement): """Whether guests can modify event""" _qname = GCAL_TEMPLATE % 'guestsCanModify' value = 'value' class GuestsCanSeeGuestsProperty(atom.core.XmlElement): """Whether guests can see other attendees""" _qname = GCAL_TEMPLATE % 'guestsCanSeeGuests' value = 'value' class HiddenProperty(atom.core.XmlElement): """Describes whether a calendar is hidden""" _qname = GCAL_TEMPLATE % 'hidden' value = 'value' class IcalUIDProperty(atom.core.XmlElement): """Describes the UID in the ical export of the event""" _qname = GCAL_TEMPLATE % 'uid' value = 'value' class OverrideNameProperty(atom.core.XmlElement): """Describes the override name property of a calendar""" _qname = GCAL_TEMPLATE % 'overridename' value = 'value' class PrivateCopyProperty(atom.core.XmlElement): """Indicates whether this is a private copy of the event, changes to which should not be sent to other calendars""" _qname = GCAL_TEMPLATE % 'privateCopy' value = 'value' class QuickAddProperty(atom.core.XmlElement): """Describes whether gd:content is for quick-add processing""" _qname = GCAL_TEMPLATE % 'quickadd' value = 'value' class ResourceProperty(atom.core.XmlElement): """Describes whether gd:who is a resource such as a conference room""" _qname = GCAL_TEMPLATE % 'resource' value = 'value' id = 'id' class EventWho(gdata.data.Who): """Extends the base Who class with Calendar extensions""" _qname = gdata.data.GD_TEMPLATE % 'who' resource = ResourceProperty class SelectedProperty(atom.core.XmlElement): """Describes whether a calendar is selected""" _qname = GCAL_TEMPLATE % 'selected' value = 'value' class SendAclNotificationsProperty(atom.core.XmlElement): """Describes whether to send ACL notifications to grantees""" _qname = GCAL_TEMPLATE % 'sendAclNotifications' value = 'value' class CalendarAclEntry(gdata.acl.data.AclEntry): """Describes an entry in a feed of a Calendar access control list (ACL)""" send_acl_notifications = SendAclNotificationsProperty class CalendarAclFeed(gdata.data.GDFeed): """Describes a Calendar access contorl list (ACL) feed""" entry = [CalendarAclEntry] class SendEventNotificationsProperty(atom.core.XmlElement): """Describes whether to send event notifications to other participants of the event""" _qname = GCAL_TEMPLATE % 'sendEventNotifications' value = 'value' class SequenceNumberProperty(atom.core.XmlElement): """Describes sequence number of an event""" _qname = GCAL_TEMPLATE % 'sequence' value = 'value' class CalendarRecurrenceExceptionEntry(gdata.data.GDEntry): """Describes an entry used by a Calendar recurrence exception entry link""" uid = IcalUIDProperty sequence = SequenceNumberProperty class CalendarRecurrenceException(gdata.data.RecurrenceException): """Describes an exception to a recurring Calendar event""" _qname = gdata.data.GD_TEMPLATE % 'recurrenceException' class SettingsProperty(atom.core.XmlElement): """User preference name-value pair""" _qname = GCAL_TEMPLATE % 'settingsProperty' name = 'name' value = 'value' class SettingsEntry(gdata.data.GDEntry): """Describes a Calendar Settings property entry""" settings_property = SettingsProperty class CalendarSettingsFeed(gdata.data.GDFeed): """Personal settings for Calendar application""" entry = [SettingsEntry] class SuppressReplyNotificationsProperty(atom.core.XmlElement): """Lists notification methods to be suppressed for this reply""" _qname = GCAL_TEMPLATE % 'suppressReplyNotifications' methods = 'methods' class SyncEventProperty(atom.core.XmlElement): """Describes whether this is a sync scenario where the Ical UID and Sequence number are honored during inserts and updates""" _qname = GCAL_TEMPLATE % 'syncEvent' value = 'value' class When(gdata.data.When): """Extends the gd:when element to add reminders""" reminder = [gdata.data.Reminder] class CalendarEventEntry(gdata.data.BatchEntry): """Describes a Calendar event entry""" quick_add = QuickAddProperty send_event_notifications = SendEventNotificationsProperty sync_event = SyncEventProperty anyone_can_add_self = AnyoneCanAddSelfProperty extended_property = [CalendarExtendedProperty] sequence = SequenceNumberProperty guests_can_invite_others = GuestsCanInviteOthersProperty guests_can_modify = GuestsCanModifyProperty guests_can_see_guests = GuestsCanSeeGuestsProperty georss_where = gdata.geo.data.GeoRssWhere private_copy = PrivateCopyProperty suppress_reply_notifications = SuppressReplyNotificationsProperty uid = IcalUIDProperty where = [gdata.data.Where] when = [When] who = [gdata.data.Who] transparency = gdata.data.Transparency comments = gdata.data.Comments event_status = gdata.data.EventStatus visibility = gdata.data.Visibility recurrence = gdata.data.Recurrence recurrence_exception = [gdata.data.RecurrenceException] original_event = gdata.data.OriginalEvent reminder = [gdata.data.Reminder] class TimeZoneProperty(atom.core.XmlElement): """Describes the time zone of a calendar""" _qname = GCAL_TEMPLATE % 'timezone' value = 'value' class TimesCleanedProperty(atom.core.XmlElement): """Describes how many times calendar was cleaned via Manage Calendars""" _qname = GCAL_TEMPLATE % 'timesCleaned' value = 'value' class CalendarEntry(gdata.data.GDEntry): """Describes a Calendar entry in the feed of a user's calendars""" timezone = TimeZoneProperty overridename = OverrideNameProperty hidden = HiddenProperty selected = SelectedProperty times_cleaned = TimesCleanedProperty color = ColorProperty where = [CalendarWhere] accesslevel = AccessLevelProperty class CalendarEventFeed(gdata.data.BatchFeed): """Describes a Calendar event feed""" allow_g_sync2 = AllowGSync2Property timezone = TimeZoneProperty entry = [CalendarEventEntry] times_cleaned = TimesCleanedProperty allow_g_sync = AllowGSyncProperty class CalendarFeed(gdata.data.GDFeed): """Describes a feed of Calendars""" entry = [CalendarEntry] class WebContentGadgetPref(atom.core.XmlElement): """Describes a single web content gadget preference""" _qname = GCAL_TEMPLATE % 'webContentGadgetPref' name = 'name' value = 'value' class WebContent(atom.core.XmlElement): """Describes a "web content" extension""" _qname = GCAL_TEMPLATE % 'webContent' height = 'height' width = 'width' web_content_gadget_pref = [WebContentGadgetPref] url = 'url' display = 'display' class WebContentLink(atom.data.Link): """Describes a "web content" link""" def __init__(self, title=None, href=None, link_type=None, web_content=None): atom.data.Link.__init__(self, rel=WEB_CONTENT_LINK_REL, title=title, href=href, link_type=link_type) web_content = WebContent
Python
#!/usr/bin/python # # Copyright (C) 2011 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """CalendarClient extends the GDataService to streamline Google Calendar operations. CalendarService: Provides methods to query feeds and manipulate items. Extends GDataService. DictionaryToParamList: Function which converts a dictionary into a list of URL arguments (represented as strings). This is a utility function used in CRUD operations. """ __author__ = 'alainv (Alain Vongsouvanh)' import urllib import gdata.client import gdata.calendar.data import atom.data import atom.http_core import gdata.gauth DEFAULT_BATCH_URL = ('https://www.google.com/calendar/feeds/default/private' '/full/batch') class CalendarClient(gdata.client.GDClient): """Client for the Google Calendar service.""" api_version = '2' auth_service = 'cl' server = "www.google.com" contact_list = "default" auth_scopes = gdata.gauth.AUTH_SCOPES['cl'] def __init__(self, domain=None, auth_token=None, **kwargs): """Constructs a new client for the Calendar API. Args: domain: string The Google Apps domain (if any). kwargs: The other parameters to pass to the gdata.client.GDClient constructor. """ gdata.client.GDClient.__init__(self, auth_token=auth_token, **kwargs) self.domain = domain def get_calendar_feed_uri(self, feed='', projection='full', scheme="https"): """Builds a feed URI. Args: projection: The projection to apply to the feed contents, for example 'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'. scheme: The URL scheme such as 'http' or 'https', None to return a relative URI without hostname. Returns: A feed URI using the given scheme and projection. Example: '/calendar/feeds/default/owncalendars/full'. """ prefix = scheme and '%s://%s' % (scheme, self.server) or '' suffix = feed and '/%s/%s' % (feed, projection) or '' return '%s/calendar/feeds/default%s' % (prefix, suffix) GetCalendarFeedUri = get_calendar_feed_uri def get_calendar_event_feed_uri(self, calendar='default', visibility='private', projection='full', scheme="https"): """Builds a feed URI. Args: projection: The projection to apply to the feed contents, for example 'full', 'base', 'base/12345', 'full/batch'. Default value: 'full'. scheme: The URL scheme such as 'http' or 'https', None to return a relative URI without hostname. Returns: A feed URI using the given scheme and projection. Example: '/calendar/feeds/default/private/full'. """ prefix = scheme and '%s://%s' % (scheme, self.server) or '' return '%s/calendar/feeds/%s/%s/%s' % (prefix, calendar, visibility, projection) GetCalendarEventFeedUri = get_calendar_event_feed_uri def get_calendars_feed(self, uri, desired_class=gdata.calendar.data.CalendarFeed, auth_token=None, **kwargs): """Obtains a calendar feed. Args: uri: The uri of the calendar feed to request. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarFeed. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.get_feed(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetCalendarsFeed = get_calendars_feed def get_own_calendars_feed(self, desired_class=gdata.calendar.data.CalendarFeed, auth_token=None, **kwargs): """Obtains a feed containing the calendars owned by the current user. Args: desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarFeed. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.GetCalendarsFeed(uri=self.GetCalendarFeedUri(feed='owncalendars'), desired_class=desired_class, auth_token=auth_token, **kwargs) GetOwnCalendarsFeed = get_own_calendars_feed def get_all_calendars_feed(self, desired_class=gdata.calendar.data.CalendarFeed, auth_token=None, **kwargs): """Obtains a feed containing all the ccalendars the current user has access to. Args: desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarFeed. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.GetCalendarsFeed(uri=self.GetCalendarFeedUri(feed='allcalendars'), desired_class=desired_class, auth_token=auth_token, **kwargs) GetAllCalendarsFeed = get_all_calendars_feed def get_calendar_entry(self, uri, desired_class=gdata.calendar.data.CalendarEntry, auth_token=None, **kwargs): """Obtains a single calendar entry. Args: uri: The uri of the desired calendar entry. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarEntry. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetCalendarEntry = get_calendar_entry def get_calendar_event_feed(self, uri=None, desired_class=gdata.calendar.data.CalendarEventFeed, auth_token=None, **kwargs): """Obtains a feed of events for the desired calendar. Args: uri: The uri of the desired calendar entry. Defaults to https://www.google.com/calendar/feeds/default/private/full. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarEventFeed. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ uri = uri or self.GetCalendarEventFeedUri() return self.get_feed(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetCalendarEventFeed = get_calendar_event_feed def get_event_entry(self, uri, desired_class=gdata.calendar.data.CalendarEventEntry, auth_token=None, **kwargs): """Obtains a single event entry. Args: uri: The uri of the desired calendar event entry. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarEventEntry. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetEventEntry = get_event_entry def get_calendar_acl_feed(self, uri='https://www.google.com/calendar/feeds/default/acl/full', desired_class=gdata.calendar.data.CalendarAclFeed, auth_token=None, **kwargs): """Obtains an Access Control List feed. Args: uri: The uri of the desired Acl feed. Defaults to https://www.google.com/calendar/feeds/default/acl/full. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarAclFeed. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.get_feed(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetCalendarAclFeed = get_calendar_acl_feed def get_calendar_acl_entry(self, uri, desired_class=gdata.calendar.data.CalendarAclEntry, auth_token=None, **kwargs): """Obtains a single Access Control List entry. Args: uri: The uri of the desired Acl feed. desired_class: class descended from atom.core.XmlElement to which a successful response should be converted. If there is no converter function specified (desired_class=None) then the desired_class will be used in calling the atom.core.parse function. If neither the desired_class nor the converter is specified, an HTTP reponse object will be returned. Defaults to gdata.calendar.data.CalendarAclEntry. auth_token: An object which sets the Authorization HTTP header in its modify_request method. Recommended classes include gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken among others. Represents the current user. Defaults to None and if None, this method will look for a value in the auth_token member of SpreadsheetsClient. """ return self.get_entry(uri, auth_token=auth_token, desired_class=desired_class, **kwargs) GetCalendarAclEntry = get_calendar_acl_entry def insert_calendar(self, new_calendar, insert_uri=None, auth_token=None, **kwargs): """Adds an new calendar to Google Calendar. Args: new_calendar: atom.Entry or subclass A new calendar which is to be added to Google Calendar. insert_uri: the URL to post new contacts to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the contact created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ insert_uri = insert_uri or self.GetCalendarFeedUri(feed='owncalendars') return self.Post(new_calendar, insert_uri, auth_token=auth_token, **kwargs) InsertCalendar = insert_calendar def insert_calendar_subscription(self, calendar, insert_uri=None, auth_token=None, **kwargs): """Subscribes the authenticated user to the provided calendar. Args: calendar: The calendar to which the user should be subscribed. url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the subscription created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ insert_uri = insert_uri or self.GetCalendarFeedUri(feed='allcalendars') return self.Post(calendar, insert_uri, auth_token=auth_token, **kwargs) InsertCalendarSubscription = insert_calendar_subscription def insert_event(self, new_event, insert_uri=None, auth_token=None, **kwargs): """Adds an new event to Google Calendar. Args: new_event: atom.Entry or subclass A new event which is to be added to Google Calendar. insert_uri: the URL to post new contacts to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the contact created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ insert_uri = insert_uri or self.GetCalendarEventFeedUri() return self.Post(new_event, insert_uri, auth_token=auth_token, **kwargs) InsertEvent = insert_event def insert_acl_entry(self, new_acl_entry, insert_uri = 'https://www.google.com/calendar/feeds/default/acl/full', auth_token=None, **kwargs): """Adds an new Acl entry to Google Calendar. Args: new_acl_event: atom.Entry or subclass A new acl which is to be added to Google Calendar. insert_uri: the URL to post new contacts to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the contact created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ return self.Post(new_acl_entry, insert_uri, auth_token=auth_token, **kwargs) InsertAclEntry = insert_acl_entry def execute_batch(self, batch_feed, url, desired_class=None): """Sends a batch request feed to the server. Args: batch_feed: gdata.contacts.CalendarEventFeed A feed containing batch request entries. Each entry contains the operation to be performed on the data contained in the entry. For example an entry with an operation type of insert will be used as if the individual entry had been inserted. url: str The batch URL to which these operations should be applied. converter: Function (optional) The function used to convert the server's response to an object. Returns: The results of the batch request's execution on the server. If the default converter is used, this is stored in a ContactsFeed. """ return self.Post(batch_feed, url, desired_class=desired_class) ExecuteBatch = execute_batch def update(self, entry, auth_token=None, **kwargs): """Edits the entry on the server by sending the XML for this entry. Performs a PUT and converts the response to a new entry object with a matching class to the entry passed in. Args: entry: auth_token: Returns: A new Entry object of a matching type to the entry which was passed in. """ return gdata.client.GDClient.Update(self, entry, auth_token=auth_token, force=True, **kwargs) Update = update class CalendarEventQuery(gdata.client.Query): """ Create a custom Calendar Query Full specs can be found at: U{Calendar query parameters reference <http://code.google.com/apis/calendar/data/2.0/reference.html#Parameters>} """ def __init__(self, feed=None, ctz=None, fields=None, futureevents=None, max_attendees=None, orderby=None, recurrence_expansion_start=None, recurrence_expansion_end=None, singleevents=None, showdeleted=None, showhidden=None, sortorder=None, start_min=None, start_max=None, updated_min=None, **kwargs): """ @param max_results: The maximum number of entries to return. If you want to receive all of the contacts, rather than only the default maximum, you can specify a very large number for max-results. @param start-index: The 1-based index of the first result to be retrieved. @param updated-min: The lower bound on entry update dates. @param group: Constrains the results to only the contacts belonging to the group specified. Value of this parameter specifies group ID @param orderby: Sorting criterion. The only supported value is lastmodified. @param showdeleted: Include deleted contacts in the returned contacts feed @pram sortorder: Sorting order direction. Can be either ascending or descending. @param requirealldeleted: Only relevant if showdeleted and updated-min are also provided. It dictates the behavior of the server in case it detects that placeholders of some entries deleted since the point in time specified as updated-min may have been lost. """ gdata.client.Query.__init__(self, **kwargs) self.ctz = ctz self.fields = fields self.futureevents = futureevents self.max_attendees = max_attendees self.orderby = orderby self.recurrence_expansion_start = recurrence_expansion_start self.recurrence_expansion_end = recurrence_expansion_end self.singleevents = singleevents self.showdeleted = showdeleted self.showhidden = showhidden self.sortorder = sortorder self.start_min = start_min self.start_max = start_max self.updated_min = updated_min def modify_request(self, http_request): if self.ctz: gdata.client._add_query_param('ctz', self.ctz, http_request) if self.fields: gdata.client._add_query_param('fields', self.fields, http_request) if self.futureevents: gdata.client._add_query_param('futureevents', self.futureevents, http_request) if self.max_attendees: gdata.client._add_query_param('max-attendees', self.max_attendees, http_request) if self.orderby: gdata.client._add_query_param('orderby', self.orderby, http_request) if self.recurrence_expansion_start: gdata.client._add_query_param('recurrence-expansion-start', self.recurrence_expansion_start, http_request) if self.recurrence_expansion_end: gdata.client._add_query_param('recurrence-expansion-end', self.recurrence_expansion_end, http_request) if self.singleevents: gdata.client._add_query_param('singleevents', self.singleevents, http_request) if self.showdeleted: gdata.client._add_query_param('showdeleted', self.showdeleted, http_request) if self.showhidden: gdata.client._add_query_param('showhidden', self.showhidden, http_request) if self.sortorder: gdata.client._add_query_param('sortorder', self.sortorder, http_request) if self.start_min: gdata.client._add_query_param('start-min', self.start_min, http_request) if self.start_max: gdata.client._add_query_param('start-max', self.start_max, http_request) if self.updated_min: gdata.client._add_query_param('updated-min', self.updated_min, http_request) gdata.client.Query.modify_request(self, http_request) ModifyRequest = modify_request
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Contains extensions to ElementWrapper objects used with Google Calendar.""" __author__ = 'api.vli (Vivian Li), api.rboyd (Ryan Boyd)' try: from xml.etree import cElementTree as ElementTree except ImportError: try: import cElementTree as ElementTree except ImportError: try: from xml.etree import ElementTree except ImportError: from elementtree import ElementTree import atom import gdata # XML namespaces which are often used in Google Calendar entities. GCAL_NAMESPACE = 'http://schemas.google.com/gCal/2005' GCAL_TEMPLATE = '{http://schemas.google.com/gCal/2005}%s' WEB_CONTENT_LINK_REL = '%s/%s' % (GCAL_NAMESPACE, 'webContent') GACL_NAMESPACE = gdata.GACL_NAMESPACE GACL_TEMPLATE = gdata.GACL_TEMPLATE class ValueAttributeContainer(atom.AtomBase): """A parent class for all Calendar classes which have a value attribute. Children include Color, AccessLevel, Hidden """ _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, extension_elements=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Color(ValueAttributeContainer): """The Google Calendar color element""" _tag = 'color' _namespace = GCAL_NAMESPACE _children = ValueAttributeContainer._children.copy() _attributes = ValueAttributeContainer._attributes.copy() class AccessLevel(ValueAttributeContainer): """The Google Calendar accesslevel element""" _tag = 'accesslevel' _namespace = GCAL_NAMESPACE _children = ValueAttributeContainer._children.copy() _attributes = ValueAttributeContainer._attributes.copy() class Hidden(ValueAttributeContainer): """The Google Calendar hidden element""" _tag = 'hidden' _namespace = GCAL_NAMESPACE _children = ValueAttributeContainer._children.copy() _attributes = ValueAttributeContainer._attributes.copy() class Selected(ValueAttributeContainer): """The Google Calendar selected element""" _tag = 'selected' _namespace = GCAL_NAMESPACE _children = ValueAttributeContainer._children.copy() _attributes = ValueAttributeContainer._attributes.copy() class Timezone(ValueAttributeContainer): """The Google Calendar timezone element""" _tag = 'timezone' _namespace = GCAL_NAMESPACE _children = ValueAttributeContainer._children.copy() _attributes = ValueAttributeContainer._attributes.copy() class Where(atom.AtomBase): """The Google Calendar Where element""" _tag = 'where' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['valueString'] = 'value_string' def __init__(self, value_string=None, extension_elements=None, extension_attributes=None, text=None): self.value_string = value_string self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class CalendarListEntry(gdata.GDataEntry, gdata.LinkFinder): """A Google Calendar meta Entry flavor of an Atom Entry """ _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}color' % GCAL_NAMESPACE] = ('color', Color) _children['{%s}accesslevel' % GCAL_NAMESPACE] = ('access_level', AccessLevel) _children['{%s}hidden' % GCAL_NAMESPACE] = ('hidden', Hidden) _children['{%s}selected' % GCAL_NAMESPACE] = ('selected', Selected) _children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone) _children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', Where) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, color=None, access_level=None, hidden=None, timezone=None, selected=None, where=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=None) self.color = color self.access_level = access_level self.hidden = hidden self.selected = selected self.timezone = timezone self.where = where class CalendarListFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Calendar meta feed flavor of an Atom Feed""" _tag = gdata.GDataFeed._tag _namespace = gdata.GDataFeed._namespace _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarListEntry]) class Scope(atom.AtomBase): """The Google ACL scope element""" _tag = 'scope' _namespace = GACL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' _attributes['type'] = 'type' def __init__(self, extension_elements=None, value=None, scope_type=None, extension_attributes=None, text=None): self.value = value self.type = scope_type self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Role(ValueAttributeContainer): """The Google Calendar timezone element""" _tag = 'role' _namespace = GACL_NAMESPACE _children = ValueAttributeContainer._children.copy() _attributes = ValueAttributeContainer._attributes.copy() class CalendarAclEntry(gdata.GDataEntry, gdata.LinkFinder): """A Google Calendar ACL Entry flavor of an Atom Entry """ _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() _children['{%s}scope' % GACL_NAMESPACE] = ('scope', Scope) _children['{%s}role' % GACL_NAMESPACE] = ('role', Role) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, scope=None, role=None, extension_elements=None, extension_attributes=None, text=None): gdata.GDataEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, title=title, updated=updated, text=None) self.scope = scope self.role = role class CalendarAclFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Calendar ACL feed flavor of an Atom Feed""" _tag = gdata.GDataFeed._tag _namespace = gdata.GDataFeed._namespace _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarAclEntry]) class CalendarEventCommentEntry(gdata.GDataEntry, gdata.LinkFinder): """A Google Calendar event comments entry flavor of an Atom Entry""" _tag = gdata.GDataEntry._tag _namespace = gdata.GDataEntry._namespace _children = gdata.GDataEntry._children.copy() _attributes = gdata.GDataEntry._attributes.copy() class CalendarEventCommentFeed(gdata.GDataFeed, gdata.LinkFinder): """A Google Calendar event comments feed flavor of an Atom Feed""" _tag = gdata.GDataFeed._tag _namespace = gdata.GDataFeed._namespace _children = gdata.GDataFeed._children.copy() _attributes = gdata.GDataFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarEventCommentEntry]) class ExtendedProperty(gdata.ExtendedProperty): """A transparent subclass of gdata.ExtendedProperty added to this module for backwards compatibility.""" class Reminder(atom.AtomBase): """The Google Calendar reminder element""" _tag = 'reminder' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['absoluteTime'] = 'absolute_time' _attributes['days'] = 'days' _attributes['hours'] = 'hours' _attributes['minutes'] = 'minutes' _attributes['method'] = 'method' def __init__(self, absolute_time=None, days=None, hours=None, minutes=None, method=None, extension_elements=None, extension_attributes=None, text=None): self.absolute_time = absolute_time if days is not None: self.days = str(days) else: self.days = None if hours is not None: self.hours = str(hours) else: self.hours = None if minutes is not None: self.minutes = str(minutes) else: self.minutes = None self.method = method self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class When(atom.AtomBase): """The Google Calendar When element""" _tag = 'when' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}reminder' % gdata.GDATA_NAMESPACE] = ('reminder', [Reminder]) _attributes['startTime'] = 'start_time' _attributes['endTime'] = 'end_time' def __init__(self, start_time=None, end_time=None, reminder=None, extension_elements=None, extension_attributes=None, text=None): self.start_time = start_time self.end_time = end_time self.reminder = reminder or [] self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Recurrence(atom.AtomBase): """The Google Calendar Recurrence element""" _tag = 'recurrence' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() class UriEnumElement(atom.AtomBase): _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() def __init__(self, tag, enum_map, attrib_name='value', extension_elements=None, extension_attributes=None, text=None): self.tag=tag self.enum_map=enum_map self.attrib_name=attrib_name self.value=None self.text=text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def findKey(self, value): res=[item[0] for item in self.enum_map.items() if item[1] == value] if res is None or len(res) == 0: return None return res[0] def _ConvertElementAttributeToMember(self, attribute, value): # Special logic to use the enum_map to set the value of the object's value member. if attribute == self.attrib_name and value != '': self.value = self.enum_map[value] return # Find the attribute in this class's list of attributes. if self.__class__._attributes.has_key(attribute): # Find the member of this class which corresponds to the XML attribute # (lookup in current_class._attributes) and set this member to the # desired value (using self.__dict__). setattr(self, self.__class__._attributes[attribute], value) else: # The current class doesn't map this attribute, so try to parent class. atom.ExtensionContainer._ConvertElementAttributeToMember(self, attribute, value) def _AddMembersToElementTree(self, tree): # Convert the members of this class which are XML child nodes. # This uses the class's _children dictionary to find the members which # should become XML child nodes. member_node_names = [values[0] for tag, values in self.__class__._children.iteritems()] for member_name in member_node_names: member = getattr(self, member_name) if member is None: pass elif isinstance(member, list): for instance in member: instance._BecomeChildElement(tree) else: member._BecomeChildElement(tree) # Special logic to set the desired XML attribute. key = self.findKey(self.value) if key is not None: tree.attrib[self.attrib_name]=key # Convert the members of this class which are XML attributes. for xml_attribute, member_name in self.__class__._attributes.iteritems(): member = getattr(self, member_name) if member is not None: tree.attrib[xml_attribute] = member # Lastly, call the parent's _AddMembersToElementTree to get any # extension elements. atom.ExtensionContainer._AddMembersToElementTree(self, tree) class AttendeeStatus(UriEnumElement): """The Google Calendar attendeeStatus element""" _tag = 'attendeeStatus' _namespace = gdata.GDATA_NAMESPACE _children = UriEnumElement._children.copy() _attributes = UriEnumElement._attributes.copy() attendee_enum = { 'http://schemas.google.com/g/2005#event.accepted' : 'ACCEPTED', 'http://schemas.google.com/g/2005#event.declined' : 'DECLINED', 'http://schemas.google.com/g/2005#event.invited' : 'INVITED', 'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'} def __init__(self, extension_elements=None, extension_attributes=None, text=None): UriEnumElement.__init__(self, 'attendeeStatus', AttendeeStatus.attendee_enum, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class AttendeeType(UriEnumElement): """The Google Calendar attendeeType element""" _tag = 'attendeeType' _namespace = gdata.GDATA_NAMESPACE _children = UriEnumElement._children.copy() _attributes = UriEnumElement._attributes.copy() attendee_type_enum = { 'http://schemas.google.com/g/2005#event.optional' : 'OPTIONAL', 'http://schemas.google.com/g/2005#event.required' : 'REQUIRED' } def __init__(self, extension_elements=None, extension_attributes=None, text=None): UriEnumElement.__init__(self, 'attendeeType', AttendeeType.attendee_type_enum, extension_elements=extension_elements, extension_attributes=extension_attributes,text=text) class Visibility(UriEnumElement): """The Google Calendar Visibility element""" _tag = 'visibility' _namespace = gdata.GDATA_NAMESPACE _children = UriEnumElement._children.copy() _attributes = UriEnumElement._attributes.copy() visibility_enum = { 'http://schemas.google.com/g/2005#event.confidential' : 'CONFIDENTIAL', 'http://schemas.google.com/g/2005#event.default' : 'DEFAULT', 'http://schemas.google.com/g/2005#event.private' : 'PRIVATE', 'http://schemas.google.com/g/2005#event.public' : 'PUBLIC' } def __init__(self, extension_elements=None, extension_attributes=None, text=None): UriEnumElement.__init__(self, 'visibility', Visibility.visibility_enum, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Transparency(UriEnumElement): """The Google Calendar Transparency element""" _tag = 'transparency' _namespace = gdata.GDATA_NAMESPACE _children = UriEnumElement._children.copy() _attributes = UriEnumElement._attributes.copy() transparency_enum = { 'http://schemas.google.com/g/2005#event.opaque' : 'OPAQUE', 'http://schemas.google.com/g/2005#event.transparent' : 'TRANSPARENT' } def __init__(self, extension_elements=None, extension_attributes=None, text=None): UriEnumElement.__init__(self, tag='transparency', enum_map=Transparency.transparency_enum, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Comments(atom.AtomBase): """The Google Calendar comments element""" _tag = 'comments' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}feedLink' % gdata.GDATA_NAMESPACE] = ('feed_link', gdata.FeedLink) _attributes['rel'] = 'rel' def __init__(self, rel=None, feed_link=None, extension_elements=None, extension_attributes=None, text=None): self.rel = rel self.feed_link = feed_link self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class EventStatus(UriEnumElement): """The Google Calendar eventStatus element""" _tag = 'eventStatus' _namespace = gdata.GDATA_NAMESPACE _children = UriEnumElement._children.copy() _attributes = UriEnumElement._attributes.copy() status_enum = { 'http://schemas.google.com/g/2005#event.canceled' : 'CANCELED', 'http://schemas.google.com/g/2005#event.confirmed' : 'CONFIRMED', 'http://schemas.google.com/g/2005#event.tentative' : 'TENTATIVE'} def __init__(self, extension_elements=None, extension_attributes=None, text=None): UriEnumElement.__init__(self, tag='eventStatus', enum_map=EventStatus.status_enum, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) class Who(UriEnumElement): """The Google Calendar Who element""" _tag = 'who' _namespace = gdata.GDATA_NAMESPACE _children = UriEnumElement._children.copy() _attributes = UriEnumElement._attributes.copy() _children['{%s}attendeeStatus' % gdata.GDATA_NAMESPACE] = ( 'attendee_status', AttendeeStatus) _children['{%s}attendeeType' % gdata.GDATA_NAMESPACE] = ('attendee_type', AttendeeType) _attributes['valueString'] = 'name' _attributes['email'] = 'email' relEnum = { 'http://schemas.google.com/g/2005#event.attendee' : 'ATTENDEE', 'http://schemas.google.com/g/2005#event.organizer' : 'ORGANIZER', 'http://schemas.google.com/g/2005#event.performer' : 'PERFORMER', 'http://schemas.google.com/g/2005#event.speaker' : 'SPEAKER', 'http://schemas.google.com/g/2005#message.bcc' : 'BCC', 'http://schemas.google.com/g/2005#message.cc' : 'CC', 'http://schemas.google.com/g/2005#message.from' : 'FROM', 'http://schemas.google.com/g/2005#message.reply-to' : 'REPLY_TO', 'http://schemas.google.com/g/2005#message.to' : 'TO' } def __init__(self, name=None, email=None, attendee_status=None, attendee_type=None, rel=None, extension_elements=None, extension_attributes=None, text=None): UriEnumElement.__init__(self, 'who', Who.relEnum, attrib_name='rel', extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.name = name self.email = email self.attendee_status = attendee_status self.attendee_type = attendee_type self.rel = rel class OriginalEvent(atom.AtomBase): """The Google Calendar OriginalEvent element""" _tag = 'originalEvent' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() # TODO: The when tag used to map to a EntryLink, make sure it should really be a When. _children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', When) _attributes['id'] = 'id' _attributes['href'] = 'href' def __init__(self, id=None, href=None, when=None, extension_elements=None, extension_attributes=None, text=None): self.id = id self.href = href self.when = when self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def GetCalendarEventEntryClass(): return CalendarEventEntry # This class is not completely defined here, because of a circular reference # in which CalendarEventEntryLink and CalendarEventEntry refer to one another. class CalendarEventEntryLink(gdata.EntryLink): """An entryLink which contains a calendar event entry Within an event's recurranceExceptions, an entry link points to a calendar event entry. This class exists to capture the calendar specific extensions in the entry. """ _tag = 'entryLink' _namespace = gdata.GDATA_NAMESPACE _children = gdata.EntryLink._children.copy() _attributes = gdata.EntryLink._attributes.copy() # The CalendarEventEntryLink should like CalendarEventEntry as a child but # that class hasn't been defined yet, so we will wait until after defining # CalendarEventEntry to list it in _children. class RecurrenceException(atom.AtomBase): """The Google Calendar RecurrenceException element""" _tag = 'recurrenceException' _namespace = gdata.GDATA_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}entryLink' % gdata.GDATA_NAMESPACE] = ('entry_link', CalendarEventEntryLink) _children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event', OriginalEvent) _attributes['specialized'] = 'specialized' def __init__(self, specialized=None, entry_link=None, original_event=None, extension_elements=None, extension_attributes=None, text=None): self.specialized = specialized self.entry_link = entry_link self.original_event = original_event self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class SendEventNotifications(atom.AtomBase): """The Google Calendar sendEventNotifications element""" _tag = 'sendEventNotifications' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, extension_elements=None, value=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class QuickAdd(atom.AtomBase): """The Google Calendar quickadd element""" _tag = 'quickadd' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, extension_elements=None, value=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} def _TransferToElementTree(self, element_tree): if self.value: element_tree.attrib['value'] = self.value element_tree.tag = GCAL_TEMPLATE % 'quickadd' atom.AtomBase._TransferToElementTree(self, element_tree) return element_tree def _TakeAttributeFromElementTree(self, attribute, element_tree): if attribute == 'value': self.value = element_tree.attrib[attribute] del element_tree.attrib[attribute] else: atom.AtomBase._TakeAttributeFromElementTree(self, attribute, element_tree) class SyncEvent(atom.AtomBase): _tag = 'syncEvent' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value='false', extension_elements=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class UID(atom.AtomBase): _tag = 'uid' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, extension_elements=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class Sequence(atom.AtomBase): _tag = 'sequence' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value=None, extension_elements=None, extension_attributes=None, text=None): self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class WebContentGadgetPref(atom.AtomBase): _tag = 'webContentGadgetPref' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _attributes['name'] = 'name' _attributes['value'] = 'value' """The Google Calendar Web Content Gadget Preferences element""" def __init__(self, name=None, value=None, extension_elements=None, extension_attributes=None, text=None): self.name = name self.value = value self.text = text self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class WebContent(atom.AtomBase): _tag = 'webContent' _namespace = GCAL_NAMESPACE _children = atom.AtomBase._children.copy() _attributes = atom.AtomBase._attributes.copy() _children['{%s}webContentGadgetPref' % GCAL_NAMESPACE] = ('gadget_pref', [WebContentGadgetPref]) _attributes['url'] = 'url' _attributes['width'] = 'width' _attributes['height'] = 'height' def __init__(self, url=None, width=None, height=None, text=None, gadget_pref=None, extension_elements=None, extension_attributes=None): self.url = url self.width = width self.height = height self.text = text self.gadget_pref = gadget_pref or [] self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} class WebContentLink(atom.Link): _tag = 'link' _namespace = atom.ATOM_NAMESPACE _children = atom.Link._children.copy() _attributes = atom.Link._attributes.copy() _children['{%s}webContent' % GCAL_NAMESPACE] = ('web_content', WebContent) def __init__(self, title=None, href=None, link_type=None, web_content=None): atom.Link.__init__(self, rel=WEB_CONTENT_LINK_REL, title=title, href=href, link_type=link_type) self.web_content = web_content class GuestsCanInviteOthers(atom.AtomBase): """Indicates whether event attendees may invite others to the event. This element may only be changed by the organizer of the event. If not included as part of the event entry, this element will default to true during a POST request, and will inherit its previous value during a PUT request. """ _tag = 'guestsCanInviteOthers' _namespace = GCAL_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value='true', *args, **kwargs): atom.AtomBase.__init__(self, *args, **kwargs) self.value = value class GuestsCanSeeGuests(atom.AtomBase): """Indicates whether attendees can see other people invited to the event. The organizer always sees all attendees. Guests always see themselves. This property affects what attendees see in the event's guest list via both the Calendar UI and API feeds. This element may only be changed by the organizer of the event. If not included as part of the event entry, this element will default to true during a POST request, and will inherit its previous value during a PUT request. """ _tag = 'guestsCanSeeGuests' _namespace = GCAL_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value='true', *args, **kwargs): atom.AtomBase.__init__(self, *args, **kwargs) self.value = value class GuestsCanModify(atom.AtomBase): """Indicates whether event attendees may modify the original event. If yes, changes are visible to organizer and other attendees. Otherwise, any changes made by attendees will be restricted to that attendee's calendar. This element may only be changed by the organizer of the event, and may be set to 'true' only if both gCal:guestsCanInviteOthers and gCal:guestsCanSeeGuests are set to true in the same PUT/POST request. Otherwise, request fails with HTTP error code 400 (Bad Request). If not included as part of the event entry, this element will default to false during a POST request, and will inherit its previous value during a PUT request.""" _tag = 'guestsCanModify' _namespace = GCAL_NAMESPACE _attributes = atom.AtomBase._attributes.copy() _attributes['value'] = 'value' def __init__(self, value='false', *args, **kwargs): atom.AtomBase.__init__(self, *args, **kwargs) self.value = value class CalendarEventEntry(gdata.BatchEntry): """A Google Calendar flavor of an Atom Entry """ _tag = gdata.BatchEntry._tag _namespace = gdata.BatchEntry._namespace _children = gdata.BatchEntry._children.copy() _attributes = gdata.BatchEntry._attributes.copy() # This class also contains WebContentLinks but converting those members # is handled in a special version of _ConvertElementTreeToMember. _children['{%s}where' % gdata.GDATA_NAMESPACE] = ('where', [Where]) _children['{%s}when' % gdata.GDATA_NAMESPACE] = ('when', [When]) _children['{%s}who' % gdata.GDATA_NAMESPACE] = ('who', [Who]) _children['{%s}extendedProperty' % gdata.GDATA_NAMESPACE] = ( 'extended_property', [ExtendedProperty]) _children['{%s}visibility' % gdata.GDATA_NAMESPACE] = ('visibility', Visibility) _children['{%s}transparency' % gdata.GDATA_NAMESPACE] = ('transparency', Transparency) _children['{%s}eventStatus' % gdata.GDATA_NAMESPACE] = ('event_status', EventStatus) _children['{%s}recurrence' % gdata.GDATA_NAMESPACE] = ('recurrence', Recurrence) _children['{%s}recurrenceException' % gdata.GDATA_NAMESPACE] = ( 'recurrence_exception', [RecurrenceException]) _children['{%s}sendEventNotifications' % GCAL_NAMESPACE] = ( 'send_event_notifications', SendEventNotifications) _children['{%s}quickadd' % GCAL_NAMESPACE] = ('quick_add', QuickAdd) _children['{%s}comments' % gdata.GDATA_NAMESPACE] = ('comments', Comments) _children['{%s}originalEvent' % gdata.GDATA_NAMESPACE] = ('original_event', OriginalEvent) _children['{%s}sequence' % GCAL_NAMESPACE] = ('sequence', Sequence) _children['{%s}reminder' % gdata.GDATA_NAMESPACE] = ('reminder', [Reminder]) _children['{%s}syncEvent' % GCAL_NAMESPACE] = ('sync_event', SyncEvent) _children['{%s}uid' % GCAL_NAMESPACE] = ('uid', UID) _children['{%s}guestsCanInviteOthers' % GCAL_NAMESPACE] = ( 'guests_can_invite_others', GuestsCanInviteOthers) _children['{%s}guestsCanModify' % GCAL_NAMESPACE] = ( 'guests_can_modify', GuestsCanModify) _children['{%s}guestsCanSeeGuests' % GCAL_NAMESPACE] = ( 'guests_can_see_guests', GuestsCanSeeGuests) def __init__(self, author=None, category=None, content=None, atom_id=None, link=None, published=None, title=None, updated=None, transparency=None, comments=None, event_status=None, send_event_notifications=None, visibility=None, recurrence=None, recurrence_exception=None, where=None, when=None, who=None, quick_add=None, extended_property=None, original_event=None, batch_operation=None, batch_id=None, batch_status=None, sequence=None, reminder=None, sync_event=None, uid=None, guests_can_invite_others=None, guests_can_modify=None, guests_can_see_guests=None, extension_elements=None, extension_attributes=None, text=None): gdata.BatchEntry.__init__(self, author=author, category=category, content=content, atom_id=atom_id, link=link, published=published, batch_operation=batch_operation, batch_id=batch_id, batch_status=batch_status, title=title, updated=updated) self.transparency = transparency self.comments = comments self.event_status = event_status self.send_event_notifications = send_event_notifications self.visibility = visibility self.recurrence = recurrence self.recurrence_exception = recurrence_exception or [] self.where = where or [] self.when = when or [] self.who = who or [] self.quick_add = quick_add self.extended_property = extended_property or [] self.original_event = original_event self.sequence = sequence self.reminder = reminder or [] self.sync_event = sync_event self.uid = uid self.text = text self.guests_can_invite_others = guests_can_invite_others self.guests_can_modify = guests_can_modify self.guests_can_see_guests = guests_can_see_guests self.extension_elements = extension_elements or [] self.extension_attributes = extension_attributes or {} # We needed to add special logic to _ConvertElementTreeToMember because we # want to make links with a rel of WEB_CONTENT_LINK_REL into a # WebContentLink def _ConvertElementTreeToMember(self, child_tree): # Special logic to handle Web Content links if (child_tree.tag == '{%s}link' % atom.ATOM_NAMESPACE and child_tree.attrib['rel'] == WEB_CONTENT_LINK_REL): if self.link is None: self.link = [] self.link.append(atom._CreateClassFromElementTree(WebContentLink, child_tree)) return # Find the element's tag in this class's list of child members if self.__class__._children.has_key(child_tree.tag): member_name = self.__class__._children[child_tree.tag][0] member_class = self.__class__._children[child_tree.tag][1] # If the class member is supposed to contain a list, make sure the # matching member is set to a list, then append the new member # instance to the list. if isinstance(member_class, list): if getattr(self, member_name) is None: setattr(self, member_name, []) getattr(self, member_name).append(atom._CreateClassFromElementTree( member_class[0], child_tree)) else: setattr(self, member_name, atom._CreateClassFromElementTree(member_class, child_tree)) else: atom.ExtensionContainer._ConvertElementTreeToMember(self, child_tree) def GetWebContentLink(self): """Finds the first link with rel set to WEB_CONTENT_REL Returns: A gdata.calendar.WebContentLink or none if none of the links had rel equal to WEB_CONTENT_REL """ for a_link in self.link: if a_link.rel == WEB_CONTENT_LINK_REL: return a_link return None def CalendarEventEntryFromString(xml_string): return atom.CreateClassFromXMLString(CalendarEventEntry, xml_string) def CalendarEventCommentEntryFromString(xml_string): return atom.CreateClassFromXMLString(CalendarEventCommentEntry, xml_string) CalendarEventEntryLink._children = {'{%s}entry' % atom.ATOM_NAMESPACE: ('entry', CalendarEventEntry)} def CalendarEventEntryLinkFromString(xml_string): return atom.CreateClassFromXMLString(CalendarEventEntryLink, xml_string) class CalendarEventFeed(gdata.BatchFeed, gdata.LinkFinder): """A Google Calendar event feed flavor of an Atom Feed""" _tag = gdata.BatchFeed._tag _namespace = gdata.BatchFeed._namespace _children = gdata.BatchFeed._children.copy() _attributes = gdata.BatchFeed._attributes.copy() _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [CalendarEventEntry]) _children['{%s}timezone' % GCAL_NAMESPACE] = ('timezone', Timezone) def __init__(self, author=None, category=None, contributor=None, generator=None, icon=None, atom_id=None, link=None, logo=None, rights=None, subtitle=None, title=None, updated=None, entry=None, total_results=None, start_index=None, items_per_page=None, interrupted=None, timezone=None, extension_elements=None, extension_attributes=None, text=None): gdata.BatchFeed.__init__(self, author=author, category=category, contributor=contributor, generator=generator, icon=icon, atom_id=atom_id, link=link, logo=logo, rights=rights, subtitle=subtitle, title=title, updated=updated, entry=entry, total_results=total_results, start_index=start_index, items_per_page=items_per_page, interrupted=interrupted, extension_elements=extension_elements, extension_attributes=extension_attributes, text=text) self.timezone = timezone def CalendarListEntryFromString(xml_string): return atom.CreateClassFromXMLString(CalendarListEntry, xml_string) def CalendarAclEntryFromString(xml_string): return atom.CreateClassFromXMLString(CalendarAclEntry, xml_string) def CalendarListFeedFromString(xml_string): return atom.CreateClassFromXMLString(CalendarListFeed, xml_string) def CalendarAclFeedFromString(xml_string): return atom.CreateClassFromXMLString(CalendarAclFeed, xml_string) def CalendarEventFeedFromString(xml_string): return atom.CreateClassFromXMLString(CalendarEventFeed, xml_string) def CalendarEventCommentFeedFromString(xml_string): return atom.CreateClassFromXMLString(CalendarEventCommentFeed, xml_string)
Python
#!/usr/bin/python # # Copyright (C) 2006 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """CalendarService extends the GDataService to streamline Google Calendar operations. CalendarService: Provides methods to query feeds and manipulate items. Extends GDataService. DictionaryToParamList: Function which converts a dictionary into a list of URL arguments (represented as strings). This is a utility function used in CRUD operations. """ __author__ = 'api.vli (Vivian Li)' import urllib import gdata import atom.service import gdata.service import gdata.calendar import atom DEFAULT_BATCH_URL = ('http://www.google.com/calendar/feeds/default/private' '/full/batch') class Error(Exception): pass class RequestError(Error): pass class CalendarService(gdata.service.GDataService): """Client for the Google Calendar service.""" def __init__(self, email=None, password=None, source=None, server='www.google.com', additional_headers=None, **kwargs): """Creates a client for the Google Calendar service. Args: email: string (optional) The user's email address, used for authentication. password: string (optional) The user's password. source: string (optional) The name of the user's application. server: string (optional) The name of the server to which a connection will be opened. Default value: 'www.google.com'. **kwargs: The other parameters to pass to gdata.service.GDataService constructor. """ gdata.service.GDataService.__init__( self, email=email, password=password, service='cl', source=source, server=server, additional_headers=additional_headers, **kwargs) def GetCalendarEventFeed(self, uri='/calendar/feeds/default/private/full'): return self.Get(uri, converter=gdata.calendar.CalendarEventFeedFromString) def GetCalendarEventEntry(self, uri): return self.Get(uri, converter=gdata.calendar.CalendarEventEntryFromString) def GetCalendarListFeed(self, uri='/calendar/feeds/default/allcalendars/full'): return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString) def GetAllCalendarsFeed(self, uri='/calendar/feeds/default/allcalendars/full'): return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString) def GetOwnCalendarsFeed(self, uri='/calendar/feeds/default/owncalendars/full'): return self.Get(uri, converter=gdata.calendar.CalendarListFeedFromString) def GetCalendarListEntry(self, uri): return self.Get(uri, converter=gdata.calendar.CalendarListEntryFromString) def GetCalendarAclFeed(self, uri='/calendar/feeds/default/acl/full'): return self.Get(uri, converter=gdata.calendar.CalendarAclFeedFromString) def GetCalendarAclEntry(self, uri): return self.Get(uri, converter=gdata.calendar.CalendarAclEntryFromString) def GetCalendarEventCommentFeed(self, uri): return self.Get(uri, converter=gdata.calendar.CalendarEventCommentFeedFromString) def GetCalendarEventCommentEntry(self, uri): return self.Get(uri, converter=gdata.calendar.CalendarEventCommentEntryFromString) def Query(self, uri, converter=None): """Performs a query and returns a resulting feed or entry. Args: feed: string The feed which is to be queried Returns: On success, a GDataFeed or Entry depending on which is sent from the server. On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ if converter: result = self.Get(uri, converter=converter) else: result = self.Get(uri) return result def CalendarQuery(self, query): if isinstance(query, CalendarEventQuery): return self.Query(query.ToUri(), converter=gdata.calendar.CalendarEventFeedFromString) elif isinstance(query, CalendarListQuery): return self.Query(query.ToUri(), converter=gdata.calendar.CalendarListFeedFromString) elif isinstance(query, CalendarEventCommentQuery): return self.Query(query.ToUri(), converter=gdata.calendar.CalendarEventCommentFeedFromString) else: return self.Query(query.ToUri()) def InsertEvent(self, new_event, insert_uri, url_params=None, escape_params=True): """Adds an event to Google Calendar. Args: new_event: atom.Entry or subclass A new event which is to be added to Google Calendar. insert_uri: the URL to post new events to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the event created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ return self.Post(new_event, insert_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarEventEntryFromString) def InsertCalendarSubscription(self, calendar, url_params=None, escape_params=True): """Subscribes the authenticated user to the provided calendar. Args: calendar: The calendar to which the user should be subscribed. url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the subscription created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ insert_uri = '/calendar/feeds/default/allcalendars/full' return self.Post(calendar, insert_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarListEntryFromString) def InsertCalendar(self, new_calendar, url_params=None, escape_params=True): """Creates a new calendar. Args: new_calendar: The calendar to be created url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the calendar created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ insert_uri = '/calendar/feeds/default/owncalendars/full' response = self.Post(new_calendar, insert_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarListEntryFromString) return response def UpdateCalendar(self, calendar, url_params=None, escape_params=True): """Updates a calendar. Args: calendar: The calendar which should be updated url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the calendar created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ update_uri = calendar.GetEditLink().href response = self.Put(data=calendar, uri=update_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarListEntryFromString) return response def InsertAclEntry(self, new_entry, insert_uri, url_params=None, escape_params=True): """Adds an ACL entry (rule) to Google Calendar. Args: new_entry: atom.Entry or subclass A new ACL entry which is to be added to Google Calendar. insert_uri: the URL to post new entries to the ACL feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the ACL entry created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ return self.Post(new_entry, insert_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarAclEntryFromString) def InsertEventComment(self, new_entry, insert_uri, url_params=None, escape_params=True): """Adds an entry to Google Calendar. Args: new_entry: atom.Entry or subclass A new entry which is to be added to Google Calendar. insert_uri: the URL to post new entrys to the feed url_params: dict (optional) Additional URL parameters to be included in the insertion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful insert, an entry containing the comment created On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ return self.Post(new_entry, insert_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarEventCommentEntryFromString) def _RemoveStandardUrlPrefix(self, url): url_prefix = 'http://%s/' % self.server if url.startswith(url_prefix): return url[len(url_prefix) - 1:] return url def DeleteEvent(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): """Removes an event with the specified ID from Google Calendar. Args: edit_uri: string The edit URL of the entry to be deleted. Example: 'http://www.google.com/calendar/feeds/default/private/full/abx' url_params: dict (optional) Additional URL parameters to be included in the deletion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful delete, a httplib.HTTPResponse containing the server's response to the DELETE request. On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ edit_uri = self._RemoveStandardUrlPrefix(edit_uri) return self.Delete('%s' % edit_uri, url_params=url_params, escape_params=escape_params) def DeleteAclEntry(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): """Removes an ACL entry at the given edit_uri from Google Calendar. Args: edit_uri: string The edit URL of the entry to be deleted. Example: 'http://www.google.com/calendar/feeds/liz%40gmail.com/acl/full/default' url_params: dict (optional) Additional URL parameters to be included in the deletion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful delete, a httplib.HTTPResponse containing the server's response to the DELETE request. On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ edit_uri = self._RemoveStandardUrlPrefix(edit_uri) return self.Delete('%s' % edit_uri, url_params=url_params, escape_params=escape_params) def DeleteCalendarEntry(self, edit_uri, extra_headers=None, url_params=None, escape_params=True): """Removes a calendar entry at the given edit_uri from Google Calendar. Args: edit_uri: string The edit URL of the entry to be deleted. Example: 'http://www.google.com/calendar/feeds/default/allcalendars/abcdef@group.calendar.google.com' url_params: dict (optional) Additional URL parameters to be included in the deletion request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful delete, True is returned On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ return self.Delete(edit_uri, url_params=url_params, escape_params=escape_params) def UpdateEvent(self, edit_uri, updated_event, url_params=None, escape_params=True): """Updates an existing event. Args: edit_uri: string The edit link URI for the element being updated updated_event: string, atom.Entry, or subclass containing the Atom Entry which will replace the event which is stored at the edit_url url_params: dict (optional) Additional URL parameters to be included in the update request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful update, a httplib.HTTPResponse containing the server's response to the PUT request. On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ edit_uri = self._RemoveStandardUrlPrefix(edit_uri) return self.Put(updated_event, '%s' % edit_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarEventEntryFromString) def UpdateAclEntry(self, edit_uri, updated_rule, url_params=None, escape_params=True): """Updates an existing ACL rule. Args: edit_uri: string The edit link URI for the element being updated updated_rule: string, atom.Entry, or subclass containing the Atom Entry which will replace the event which is stored at the edit_url url_params: dict (optional) Additional URL parameters to be included in the update request. escape_params: boolean (optional) If true, the url_parameters will be escaped before they are included in the request. Returns: On successful update, a httplib.HTTPResponse containing the server's response to the PUT request. On failure, a RequestError is raised of the form: {'status': HTTP status code from server, 'reason': HTTP reason from the server, 'body': HTTP body of the server's response} """ edit_uri = self._RemoveStandardUrlPrefix(edit_uri) return self.Put(updated_rule, '%s' % edit_uri, url_params=url_params, escape_params=escape_params, converter=gdata.calendar.CalendarAclEntryFromString) def ExecuteBatch(self, batch_feed, url, converter=gdata.calendar.CalendarEventFeedFromString): """Sends a batch request feed to the server. The batch request needs to be sent to the batch URL for a particular calendar. You can find the URL by calling GetBatchLink().href on the CalendarEventFeed. Args: batch_feed: gdata.calendar.CalendarEventFeed A feed containing batch request entries. Each entry contains the operation to be performed on the data contained in the entry. For example an entry with an operation type of insert will be used as if the individual entry had been inserted. url: str The batch URL for the Calendar to which these operations should be applied. converter: Function (optional) The function used to convert the server's response to an object. The default value is CalendarEventFeedFromString. Returns: The results of the batch request's execution on the server. If the default converter is used, this is stored in a CalendarEventFeed. """ return self.Post(batch_feed, url, converter=converter) class CalendarEventQuery(gdata.service.Query): def __init__(self, user='default', visibility='private', projection='full', text_query=None, params=None, categories=None): gdata.service.Query.__init__(self, feed='http://www.google.com/calendar/feeds/%s/%s/%s' % ( urllib.quote(user), urllib.quote(visibility), urllib.quote(projection)), text_query=text_query, params=params, categories=categories) def _GetStartMin(self): if 'start-min' in self.keys(): return self['start-min'] else: return None def _SetStartMin(self, val): self['start-min'] = val start_min = property(_GetStartMin, _SetStartMin, doc="""The start-min query parameter""") def _GetStartMax(self): if 'start-max' in self.keys(): return self['start-max'] else: return None def _SetStartMax(self, val): self['start-max'] = val start_max = property(_GetStartMax, _SetStartMax, doc="""The start-max query parameter""") def _GetOrderBy(self): if 'orderby' in self.keys(): return self['orderby'] else: return None def _SetOrderBy(self, val): if val is not 'lastmodified' and val is not 'starttime': raise Error, "Order By must be either 'lastmodified' or 'starttime'" self['orderby'] = val orderby = property(_GetOrderBy, _SetOrderBy, doc="""The orderby query parameter""") def _GetSortOrder(self): if 'sortorder' in self.keys(): return self['sortorder'] else: return None def _SetSortOrder(self, val): if (val is not 'ascending' and val is not 'descending' and val is not 'a' and val is not 'd' and val is not 'ascend' and val is not 'descend'): raise Error, "Sort order must be either ascending, ascend, " + ( "a or descending, descend, or d") self['sortorder'] = val sortorder = property(_GetSortOrder, _SetSortOrder, doc="""The sortorder query parameter""") def _GetSingleEvents(self): if 'singleevents' in self.keys(): return self['singleevents'] else: return None def _SetSingleEvents(self, val): self['singleevents'] = val singleevents = property(_GetSingleEvents, _SetSingleEvents, doc="""The singleevents query parameter""") def _GetFutureEvents(self): if 'futureevents' in self.keys(): return self['futureevents'] else: return None def _SetFutureEvents(self, val): self['futureevents'] = val futureevents = property(_GetFutureEvents, _SetFutureEvents, doc="""The futureevents query parameter""") def _GetRecurrenceExpansionStart(self): if 'recurrence-expansion-start' in self.keys(): return self['recurrence-expansion-start'] else: return None def _SetRecurrenceExpansionStart(self, val): self['recurrence-expansion-start'] = val recurrence_expansion_start = property(_GetRecurrenceExpansionStart, _SetRecurrenceExpansionStart, doc="""The recurrence-expansion-start query parameter""") def _GetRecurrenceExpansionEnd(self): if 'recurrence-expansion-end' in self.keys(): return self['recurrence-expansion-end'] else: return None def _SetRecurrenceExpansionEnd(self, val): self['recurrence-expansion-end'] = val recurrence_expansion_end = property(_GetRecurrenceExpansionEnd, _SetRecurrenceExpansionEnd, doc="""The recurrence-expansion-end query parameter""") def _SetTimezone(self, val): self['ctz'] = val def _GetTimezone(self): if 'ctz' in self.keys(): return self['ctz'] else: return None ctz = property(_GetTimezone, _SetTimezone, doc="""The ctz query parameter which sets report time on the server.""") class CalendarListQuery(gdata.service.Query): """Queries the Google Calendar meta feed""" def __init__(self, userId=None, text_query=None, params=None, categories=None): if userId is None: userId = 'default' gdata.service.Query.__init__(self, feed='http://www.google.com/calendar/feeds/' +userId, text_query=text_query, params=params, categories=categories) class CalendarEventCommentQuery(gdata.service.Query): """Queries the Google Calendar event comments feed""" def __init__(self, feed=None): gdata.service.Query.__init__(self, feed=feed)
Python
#!/usr/bin/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 Provisioning API '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/'), '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', **kwargs): """Returns a URI to redirect to the provider. Args: redirect_uri: string, Either the string 'oob' for a non-web-based application, or a URI that handles the callback from the authorization server. response_type: string, Either the string 'code' for server-side or native application, or the string 'token' for client- side application. 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, } 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 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