PageRenderTime 60ms CodeModel.GetById 11ms app.highlight 43ms RepoModel.GetById 2ms app.codeStats 0ms

/gdata/apps/adminsettings/service.py

http://radioappz.googlecode.com/
Python | 471 lines | 357 code | 28 blank | 86 comment | 2 complexity | 43773d5ccc7a197f9719dfe7fd23335c MD5 | raw file
  1#!/usr/bin/python
  2#
  3# Copyright (C) 2008 Google, Inc.
  4#
  5# Licensed under the Apache License, Version 2.0 (the "License");
  6# you may not use this file except in compliance with the License.
  7# You may obtain a copy of the License at
  8#
  9#      http://www.apache.org/licenses/LICENSE-2.0
 10#
 11# Unless required by applicable law or agreed to in writing, software
 12# distributed under the License is distributed on an "AS IS" BASIS,
 13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 14# See the License for the specific language governing permissions and
 15# limitations under the License.
 16
 17"""Allow Google Apps domain administrators to set domain admin settings.
 18
 19  AdminSettingsService: Set admin settings."""
 20
 21__author__ = 'jlee@pbu.edu'
 22
 23
 24import gdata.apps
 25import gdata.apps.service
 26import gdata.service
 27
 28
 29API_VER='2.0'
 30
 31class AdminSettingsService(gdata.apps.service.PropertyService):
 32  """Client for the Google Apps Admin Settings service."""
 33
 34  def _serviceUrl(self, setting_id, domain=None):
 35    if domain is None:
 36      domain = self.domain
 37    return '/a/feeds/domain/%s/%s/%s' % (API_VER, domain, setting_id)
 38
 39  def genericGet(self, location):
 40    """Generic HTTP Get Wrapper
 41
 42    Args:
 43      location: relative uri to Get
 44
 45    Returns:
 46      A dict containing the result of the get operation."""
 47
 48    uri = self._serviceUrl(location)
 49    try:
 50      return self._GetProperties(uri)
 51    except gdata.service.RequestError, e:
 52      raise AppsForYourDomainException(e.args[0])
 53
 54  def GetDefaultLanguage(self):
 55    """Gets Domain Default Language
 56
 57    Args:
 58      None
 59
 60    Returns:
 61      Default Language as a string.  All possible values are listed at:
 62        http://code.google.com/apis/apps/email_settings/developers_guide_protocol.html#GA_email_language_tags"""
 63
 64    result = self.genericGet('general/defaultLanguage')
 65    return result['defaultLanguage']
 66
 67  def UpdateDefaultLanguage(self, defaultLanguage):
 68    """Updates Domain Default Language
 69
 70    Args:
 71      defaultLanguage: Domain Language to set
 72        possible values are at:
 73        http://code.google.com/apis/apps/email_settings/developers_guide_protocol.html#GA_email_language_tags
 74
 75    Returns:
 76      A dict containing the result of the put operation"""
 77
 78    uri = self._serviceUrl('general/defaultLanguage')
 79    properties = {'defaultLanguage': defaultLanguage}
 80    return self._PutProperties(uri, properties)
 81
 82  def GetOrganizationName(self):
 83    """Gets Domain Default Language
 84
 85    Args:
 86      None
 87
 88    Returns:
 89      Organization Name as a string."""
 90
 91    result = self.genericGet('general/organizationName')
 92    return result['organizationName']
 93
 94
 95  def UpdateOrganizationName(self, organizationName):
 96    """Updates Organization Name
 97
 98    Args:
 99      organizationName: Name of organization
100
101    Returns:
102      A dict containing the result of the put operation"""
103
104    uri = self._serviceUrl('general/organizationName')
105    properties = {'organizationName': organizationName}
106    return self._PutProperties(uri, properties)
107
108  def GetMaximumNumberOfUsers(self):
109    """Gets Maximum Number of Users Allowed
110
111    Args:
112      None
113
114    Returns: An integer, the maximum number of users"""
115
116    result = self.genericGet('general/maximumNumberOfUsers')
117    return int(result['maximumNumberOfUsers'])
118
119  def GetCurrentNumberOfUsers(self):
120    """Gets Current Number of Users
121
122    Args:
123      None
124
125    Returns: An integer, the current number of users"""
126
127    result = self.genericGet('general/currentNumberOfUsers')
128    return int(result['currentNumberOfUsers'])
129
130  def IsDomainVerified(self):
131    """Is the domain verified
132
133    Args:
134      None
135
136    Returns: Boolean, is domain verified"""
137
138    result = self.genericGet('accountInformation/isVerified')
139    if result['isVerified'] == 'true':
140      return True
141    else:
142      return False
143
144  def GetSupportPIN(self):
145    """Gets Support PIN
146
147    Args:
148      None
149
150    Returns: A string, the Support PIN"""
151
152    result = self.genericGet('accountInformation/supportPIN')
153    return result['supportPIN']
154
155  def GetEdition(self):
156    """Gets Google Apps Domain Edition
157
158    Args:
159      None
160
161    Returns: A string, the domain's edition (premier, education, partner)"""
162
163    result = self.genericGet('accountInformation/edition')
164    return result['edition']
165
166  def GetCustomerPIN(self):
167    """Gets Customer PIN
168
169    Args:
170      None
171
172    Returns: A string, the customer PIN"""
173
174    result = self.genericGet('accountInformation/customerPIN')
175    return result['customerPIN']
176
177  def GetCreationTime(self):
178    """Gets Domain Creation Time
179
180    Args:
181      None
182
183    Returns: A string, the domain's creation time"""
184
185    result = self.genericGet('accountInformation/creationTime')
186    return result['creationTime']
187
188  def GetCountryCode(self):
189    """Gets Domain Country Code
190
191    Args:
192      None
193
194    Returns: A string, the domain's country code. Possible values at:
195      http://www.iso.org/iso/country_codes/iso_3166_code_lists/english_country_names_and_code_elements.htm"""
196
197    result = self.genericGet('accountInformation/countryCode')
198    return result['countryCode']
199
200  def GetAdminSecondaryEmail(self):
201    """Gets Domain Admin Secondary Email Address
202
203    Args:
204      None
205
206    Returns: A string, the secondary email address for domain admin"""
207
208    result = self.genericGet('accountInformation/adminSecondaryEmail')
209    return result['adminSecondaryEmail']
210
211  def UpdateAdminSecondaryEmail(self, adminSecondaryEmail):
212    """Gets Domain Creation Time
213
214    Args:
215      adminSecondaryEmail: string, secondary email address of admin
216
217    Returns: A dict containing the result of the put operation"""
218
219    uri = self._serviceUrl('accountInformation/adminSecondaryEmail')
220    properties = {'adminSecondaryEmail': adminSecondaryEmail}
221    return self._PutProperties(uri, properties)
222
223  def GetDomainLogo(self):
224    """Gets Domain Logo
225
226    This function does not make use of the Google Apps Admin Settings API,
227    it does an HTTP Get of a url specific to the Google Apps domain. It is
228    included for completeness sake.
229
230    Args:
231      None
232
233    Returns: binary image file"""
234 
235    import urllib
236    url = 'http://www.google.com/a/cpanel/'+self.domain+'/images/logo.gif'
237    response = urllib.urlopen(url)
238    return response.read()
239
240  def UpdateDomainLogo(self, logoImage):
241    """Update Domain's Custom Logo
242
243    Args:
244      logoImage: binary image data
245
246    Returns: A dict containing the result of the put operation"""
247
248    from base64 import base64encode
249    uri = self._serviceUrl('appearance/customLogo')
250    properties = {'logoImage': base64encode(logoImage)}
251    return self._PutProperties(uri, properties)
252
253  def GetCNAMEVerificationStatus(self):
254    """Gets Domain CNAME Verification Status
255
256    Args:
257      None
258
259    Returns: A dict {recordName, verified, verifiedMethod}"""
260
261    return self.genericGet('verification/cname')
262
263  def UpdateCNAMEVerificationStatus(self, verified):
264    """Updates CNAME Verification Status
265
266    Args:
267      verified: boolean, True will retry verification process
268
269    Returns: A dict containing the result of the put operation"""
270
271    uri = self._serviceUrl('verification/cname')
272    properties = self.GetCNAMEVerificationStatus()
273    properties['verified'] = verified
274    return self._PutProperties(uri, properties)
275
276  def GetMXVerificationStatus(self):
277    """Gets Domain MX Verification Status
278
279    Args:
280      None
281
282    Returns: A dict {verified, verifiedMethod}"""
283
284    return self.genericGet('verification/mx')
285
286  def UpdateMXVerificationStatus(self, verified):
287    """Updates MX Verification Status
288
289    Args:
290      verified: boolean, True will retry verification process
291
292    Returns: A dict containing the result of the put operation"""
293
294    uri = self._serviceUrl('verification/mx')
295    properties = self.GetMXVerificationStatus()
296    properties['verified'] = verified
297    return self._PutProperties(uri, properties)
298
299  def GetSSOSettings(self):
300    """Gets Domain Single Sign-On Settings
301
302    Args:
303      None
304
305    Returns: A dict {samlSignonUri, samlLogoutUri, changePasswordUri, enableSSO, ssoWhitelist, useDomainSpecificIssuer}"""
306
307    return self.genericGet('sso/general')
308
309  def UpdateSSOSettings(self, enableSSO=None, samlSignonUri=None,
310                        samlLogoutUri=None, changePasswordUri=None,
311                        ssoWhitelist=None, useDomainSpecificIssuer=None):
312    """Update SSO Settings.
313
314    Args:
315      enableSSO: boolean, SSO Master on/off switch
316      samlSignonUri: string, SSO Login Page
317      samlLogoutUri: string, SSO Logout Page
318      samlPasswordUri: string, SSO Password Change Page
319      ssoWhitelist: string, Range of IP Addresses which will see SSO
320      useDomainSpecificIssuer: boolean, Include Google Apps Domain in Issuer
321
322    Returns:
323      A dict containing the result of the update operation.
324    """
325    uri = self._serviceUrl('sso/general')
326
327    #Get current settings, replace Nones with ''
328    properties = self.GetSSOSettings()
329    if properties['samlSignonUri'] == None:
330      properties['samlSignonUri'] = ''
331    if properties['samlLogoutUri'] == None:
332      properties['samlLogoutUri'] = ''
333    if properties['changePasswordUri'] == None:
334      properties['changePasswordUri'] = ''
335    if properties['ssoWhitelist'] == None:
336      properties['ssoWhitelist'] = ''
337
338    #update only the values we were passed
339    if enableSSO != None:
340      properties['enableSSO'] = gdata.apps.service._bool2str(enableSSO)
341    if samlSignonUri != None:
342      properties['samlSignonUri'] = samlSignonUri
343    if samlLogoutUri != None:
344      properties['samlLogoutUri'] = samlLogoutUri
345    if changePasswordUri != None:
346      properties['changePasswordUri'] = changePasswordUri
347    if ssoWhitelist != None:
348      properties['ssoWhitelist'] = ssoWhitelist
349    if useDomainSpecificIssuer != None:
350      properties['useDomainSpecificIssuer'] = gdata.apps.service._bool2str(useDomainSpecificIssuer)
351
352    return self._PutProperties(uri, properties)
353
354  def GetSSOKey(self):
355    """Gets Domain Single Sign-On Signing Key
356
357    Args:
358      None
359
360    Returns: A dict {modulus, exponent, algorithm, format}"""
361
362    return self.genericGet('sso/signingkey')
363
364  def UpdateSSOKey(self, signingKey):
365    """Update SSO Settings.
366
367    Args:
368      signingKey: string, public key to be uploaded
369
370    Returns:
371      A dict containing the result of the update operation."""
372
373    uri = self._serviceUrl('sso/signingkey')
374    properties = {'signingKey': signingKey}
375    return self._PutProperties(uri, properties)
376
377  def IsUserMigrationEnabled(self):
378    """Is User Migration Enabled
379
380    Args:
381      None
382
383    Returns:
384      boolean, is user migration enabled"""
385
386    result = self.genericGet('email/migration')
387    if result['enableUserMigration'] == 'true':
388      return True
389    else:
390      return False
391
392  def UpdateUserMigrationStatus(self, enableUserMigration):
393    """Update User Migration Status
394
395    Args:
396      enableUserMigration: boolean, user migration enable/disable
397
398    Returns:
399      A dict containing the result of the update operation."""
400
401    uri = self._serviceUrl('email/migration')
402    properties = {'enableUserMigration': enableUserMigration}
403    return self._PutProperties(uri, properties)
404
405  def GetOutboundGatewaySettings(self):
406    """Get Outbound Gateway Settings
407
408    Args:
409      None
410
411    Returns:
412      A dict {smartHost, smtpMode}"""
413
414    uri = self._serviceUrl('email/gateway')
415    try:
416      return self._GetProperties(uri)
417    except gdata.service.RequestError, e:
418      raise AppsForYourDomainException(e.args[0])
419    except TypeError:
420      #if no outbound gateway is set, we get a TypeError,
421      #catch it and return nothing...
422      return {'smartHost': None, 'smtpMode': None}
423
424  def UpdateOutboundGatewaySettings(self, smartHost=None, smtpMode=None):
425    """Update Outbound Gateway Settings
426
427    Args:
428      smartHost: string, ip address or hostname of outbound gateway
429      smtpMode: string, SMTP or SMTP_TLS
430
431    Returns:
432      A dict containing the result of the update operation."""
433
434    uri = self._serviceUrl('email/gateway')
435
436    #Get current settings, replace Nones with ''
437    properties = GetOutboundGatewaySettings()
438    if properties['smartHost'] == None:
439      properties['smartHost'] = ''
440    if properties['smtpMode'] == None:
441      properties['smtpMode'] = ''
442
443    #If we were passed new values for smartHost or smtpMode, update them
444    if smartHost != None:
445      properties['smartHost'] = smartHost
446    if smtpMode != None:
447      properties['smtpMode'] = smtpMode
448
449    return self._PutProperties(uri, properties)
450
451  def AddEmailRoute(self, routeDestination, routeRewriteTo, routeEnabled, bounceNotifications, accountHandling):
452    """Adds Domain Email Route
453
454    Args:
455      routeDestination: string, destination ip address or hostname
456      routeRewriteTo: boolean, rewrite smtp envelop To:
457      routeEnabled: boolean, enable disable email routing
458      bounceNotifications: boolean, send bound notificiations to sender
459      accountHandling: string, which to route, "allAccounts", "provisionedAccounts", "unknownAccounts"
460
461    Returns:
462      A dict containing the result of the update operation."""
463
464    uri = self._serviceUrl('emailrouting')
465    properties = {}
466    properties['routeDestination'] = routeDestination
467    properties['routeRewriteTo'] = gdata.apps.service._bool2str(routeRewriteTo)
468    properties['routeEnabled'] = gdata.apps.service._bool2str(routeEnabled)
469    properties['bounceNotifications'] = gdata.apps.service._bool2str(bounceNotifications)
470    properties['accountHandling'] = accountHandling
471    return self._PostProperties(uri, properties)