def getChoice(choices, **opts):
if Cmd.ArgumentsRemaining():
choice = Cmd.Current().strip().lower()
if choice:
if choice in opts.get(CHOICE_ALIASES, []):
choice = opts[CHOICE_ALIASES][choice]
if choice not in choices:
choice = choice.replace(u'_', u'').replace(u'-', u'')
if choice in opts.get(CHOICE_ALIASES, []):
choice = opts[CHOICE_ALIASES][choice]
if choice in choices:
Cmd.Advance()
return choice if not opts.get(MAP_CHOICE, False) else choices[choice]
if opts.get(DEFAULT_CHOICE, NO_DEFAULT) != NO_DEFAULT:
return opts[DEFAULT_CHOICE]
invalidChoiceExit(choices, False)
elif opts.get(DEFAULT_CHOICE, NO_DEFAULT) != NO_DEFAULT:
return opts[DEFAULT_CHOICE]
missingChoiceExit(choices)
python类get()的实例源码
def buildGAPIObject(api):
GM.Globals[GM.CURRENT_API_USER] = None
_, httpObj, service, cred_family = getAPIversionHttpService(api)
credentials = getClientCredentials(cred_family)
try:
API_Scopes = set(list(service._rootDesc[u'auth'][u'oauth2'][u'scopes']))
except KeyError:
API_Scopes = set(API.VAULT_SCOPES) if api == API.VAULT else set()
GM.Globals[GM.CURRENT_API_SCOPES] = list(API_Scopes.intersection(credentials.scopes))
if not GM.Globals[GM.CURRENT_API_SCOPES]:
systemErrorExit(NO_SCOPES_FOR_API_RC, Msg.NO_SCOPES_FOR_API.format(service._rootDesc[u'title']))
try:
service._http = credentials.authorize(httpObj)
except httplib2.ServerNotFoundError as e:
systemErrorExit(NETWORK_ERROR_RC, str(e))
except oauth2client.client.AccessTokenRefreshError as e:
return handleOAuthTokenError(str(e), False)
if not GC.Values[GC.DOMAIN]:
GC.Values[GC.DOMAIN] = credentials.id_token.get(u'hd', u'UNKNOWN').lower()
if not GC.Values[GC.CUSTOMER_ID]:
GC.Values[GC.CUSTOMER_ID] = GC.MY_CUSTOMER
GM.Globals[GM.ADMIN] = credentials.id_token.get(u'email', u'UNKNOWN').lower()
GM.Globals[GM.OAUTH2_CLIENT_ID] = credentials.client_id
return service
def initGDataObject(gdataObj, api):
if hasattr(sys, u'_MEIPASS') and not GM.Globals[GM.CACERTS_TXT]:
GM.Globals[GM.CACERTS_TXT] = os.path.join(sys._MEIPASS, u'httplib2', u'cacerts.txt')
os.environ['REQUESTS_CA_BUNDLE'] = GM.Globals[GM.CACERTS_TXT]
os.environ['DEFAULT_CA_BUNDLE_PATH'] = GM.Globals[GM.CACERTS_TXT]
_, _, api_version, cred_family = API.getVersion(api)
disc_file, discovery = readDiscoveryFile(api_version)
GM.Globals[GM.CURRENT_API_USER] = None
credentials = getClientCredentials(cred_family)
try:
GM.Globals[GM.CURRENT_API_SCOPES] = list(set(list(discovery[u'auth'][u'oauth2'][u'scopes'])).intersection(credentials.scopes))
except KeyError:
invalidDiscoveryJsonExit(disc_file)
if not GM.Globals[GM.CURRENT_API_SCOPES]:
systemErrorExit(NO_SCOPES_FOR_API_RC, Msg.NO_SCOPES_FOR_API.format(discovery.get(u'title', api_version)))
getGDataOAuthToken(gdataObj, credentials)
if GC.Values[GC.DEBUG_LEVEL] > 0:
gdataObj.debug = True
return gdataObj
def splitEmailAddressOrUID(emailAddressOrUID):
normalizedEmailAddressOrUID = normalizeEmailAddressOrUID(emailAddressOrUID)
atLoc = normalizedEmailAddressOrUID.find(u'@')
if atLoc > 0:
return (normalizedEmailAddressOrUID, normalizedEmailAddressOrUID[:atLoc], normalizedEmailAddressOrUID[atLoc+1:])
try:
cd = buildGAPIObject(API.DIRECTORY)
result = callGAPI(cd.users(), u'get',
throw_reasons=GAPI.USER_GET_THROW_REASONS,
userKey=normalizedEmailAddressOrUID, fields=u'primaryEmail')
if u'primaryEmail' in result:
normalizedEmailAddressOrUID = result[u'primaryEmail'].lower()
atLoc = normalizedEmailAddressOrUID.find(u'@')
return (normalizedEmailAddressOrUID, normalizedEmailAddressOrUID[:atLoc], normalizedEmailAddressOrUID[atLoc+1:])
except (GAPI.userNotFound, GAPI.domainNotFound, GAPI.domainCannotUseApis, GAPI.forbidden, GAPI.badRequest, GAPI.backendError, GAPI.systemError):
pass
return (normalizedEmailAddressOrUID, normalizedEmailAddressOrUID, GC.Values[GC.DOMAIN])
# Convert Org Unit Id to Org Unit Path
def convertOrgUnitIDtoPath(orgUnitId, cd):
if GM.Globals[GM.MAP_ORGUNIT_ID_TO_NAME] is None:
GM.Globals[GM.MAP_ORGUNIT_ID_TO_NAME] = {}
orgUnitPath = None
else:
orgUnitPath = GM.Globals[GM.MAP_ORGUNIT_ID_TO_NAME].get(orgUnitId)
if not orgUnitPath:
if cd is None:
cd = buildGAPIObject(API.DIRECTORY)
try:
orgUnitPath = callGAPI(cd.orgunits(), u'get',
throw_reasons=[GAPI.INVALID_ORGUNIT, GAPI.ORGUNIT_NOT_FOUND, GAPI.BACKEND_ERROR, GAPI.BAD_REQUEST, GAPI.INVALID_CUSTOMER_ID, GAPI.LOGIN_REQUIRED],
customerId=GC.Values[GC.CUSTOMER_ID], orgUnitPath=orgUnitId, fields=u'orgUnitPath')[u'orgUnitPath']
except (GAPI.invalidOrgunit, GAPI.orgunitNotFound, GAPI.backendError, GAPI.badRequest, GAPI.invalidCustomerId, GAPI.loginRequired):
orgUnitPath = orgUnitId
GM.Globals[GM.MAP_ORGUNIT_ID_TO_NAME][orgUnitId] = orgUnitPath
return orgUnitPath
def doInfoResoldCustomer():
res = buildGAPIObject(API.RESELLER)
customerId = getString(Cmd.OB_CUSTOMER_ID)
checkForExtraneousArguments()
try:
customerInfo = callGAPI(res.customers(), u'get',
throw_reasons=[GAPI.BAD_REQUEST, GAPI.RESOURCE_NOT_FOUND, GAPI.FORBIDDEN],
customerId=customerId)
printKeyValueList([u'Customer ID', customerInfo[u'customerId']])
printKeyValueList([u'Customer Domain', customerInfo[u'customerDomain']])
printKeyValueList([u'Customer Domain Verified', customerInfo[u'customerDomainVerified']])
_showCustomerAddressPhoneNumber(customerInfo)
printKeyValueList([u'Customer Alternate Email', customerInfo[u'alternateEmail']])
printKeyValueList([u'Customer Admin Console URL', customerInfo[u'resourceUiUrl']])
except (GAPI.badRequest, GAPI.resourceNotFound, GAPI.forbidden) as e:
entityActionFailedWarning([Ent.CUSTOMER_ID, customerId], str(e))
def doInfoDomainAlias():
cd = buildGAPIObject(API.DIRECTORY)
domainAliasName = getString(Cmd.OB_DOMAIN_ALIAS)
checkForExtraneousArguments()
try:
result = callGAPI(cd.domainAliases(), u'get',
throw_reasons=[GAPI.DOMAIN_ALIAS_NOT_FOUND, GAPI.BAD_REQUEST, GAPI.NOT_FOUND, GAPI.FORBIDDEN],
customer=GC.Values[GC.CUSTOMER_ID], domainAliasName=domainAliasName)
aliasSkipObjects = [u'domainAliasName',]
_showDomainAlias(result, aliasSkipObjects)
except GAPI.domainAliasNotFound:
entityActionFailedWarning([Ent.DOMAIN_ALIAS, domainAliasName], Msg.DOES_NOT_EXIST)
except (GAPI.badRequest, GAPI.notFound, GAPI.forbidden):
accessErrorExit(cd)
# gam print domainaliases [todrive [<ToDriveAttributes>]]
def doInfoCustomer():
cd = buildGAPIObject(API.DIRECTORY)
checkForExtraneousArguments()
try:
customerInfo = callGAPI(cd.customers(), u'get',
throw_reasons=[GAPI.BAD_REQUEST, GAPI.RESOURCE_NOT_FOUND, GAPI.FORBIDDEN],
customerKey=GC.Values[GC.CUSTOMER_ID])
printKeyValueList([u'Customer ID', customerInfo[u'id']])
printKeyValueList([u'Primary Domain', customerInfo[u'customerDomain']])
printKeyValueList([u'Customer Creation Time', formatLocalTime(customerInfo[u'customerCreationTime'])])
verified = callGAPI(cd.domains(), u'get',
customer=customerInfo[u'id'], domainName=customerInfo[u'customerDomain'], fields=u'verified')[u'verified']
printKeyValueList([u'Primary Domain Verified', verified])
printKeyValueList([u'Default Language', customerInfo[u'language']])
_showCustomerAddressPhoneNumber(customerInfo)
printKeyValueList([u'Admin Secondary Email', customerInfo[u'alternateEmail']])
_showCustomerLicenseInfo(customerInfo[u'id'])
except (GAPI.badRequest, GAPI.resourceNotFound, GAPI.forbidden):
accessErrorExit(cd)
# gam update customer [primary <DomainName>] [adminsecondaryemail|alternateemail <EmailAddress>] [language <LanguageCode] [phone|phonenumber <String>]
# [contact|contactname <String>] [name|organizationname <String>]
# [address1|addressline1 <String>] [address2|addressline2 <String>] [address3|addressline3 <String>]
# [locality <String>] [region <String>] [postalcode <String>] [country|countrycode <String>]
def _showMailboxExportRequestStatus(request, i, count, showFilter=False, showDates=False, showFiles=False):
printEntity([Ent.REQUEST_ID, request[u'requestId']], i, count)
Ind.Increment()
printEntity([Ent.USER, request[u'userEmailAddress']])
printKeyValueList([u'Status', request[u'status']])
printKeyValueList([u'Request Date', request[u'requestDate']])
printKeyValueList([u'Requested By', request[u'adminEmailAddress']])
printKeyValueList([u'Requested Parts', request[u'packageContent']])
if showFilter:
printKeyValueList([u'Request Filter', request.get(u'searchQuery', u'None')])
printKeyValueList([u'Include Deleted', request[u'includeDeleted']])
if showDates:
printKeyValueList([u'Begin', request.get(u'beginDate', u'Account creation date')])
printKeyValueList([u'End', request.get(u'endDate', u'Export request date')])
if showFiles:
_showFileURLs(request)
Ind.Decrement()
# gam audit export request <EmailAddress> [begin <DateTime>] [end <DateTime>] [search <QueryGmail>] [headersonly] [includedeleted]
def doInfoMobileDevices():
entityList, cd = getMobileDeviceEntity()
parameters = _initMobileFieldsParameters()
while Cmd.ArgumentsRemaining():
myarg = getArgument()
_getMobileFieldsArguments(myarg, parameters)
fields = u','.join(set(parameters[u'fieldsList'])) if parameters[u'fieldsList'] else None
i = 0
count = len(entityList)
for resourceId in entityList:
i += 1
try:
info = callGAPI(cd.mobiledevices(), u'get',
throw_reasons=[GAPI.INTERNAL_ERROR, GAPI.RESOURCE_ID_NOT_FOUND, GAPI.BAD_REQUEST, GAPI.RESOURCE_NOT_FOUND, GAPI.FORBIDDEN],
customerId=GC.Values[GC.CUSTOMER_ID], resourceId=resourceId, projection=parameters[u'projection'], fields=fields)
printEntity([Ent.MOBILE_DEVICE, resourceId], i, count)
Ind.Increment()
showJSON(None, info, timeObjects=MOBILE_TIME_OBJECTS)
Ind.Decrement()
except GAPI.internalError:
entityActionFailedWarning([Ent.MOBILE_DEVICE, resourceId], Msg.DOES_NOT_EXIST, i, count)
except (GAPI.resourceIdNotFound, GAPI.badRequest, GAPI.resourceNotFound, GAPI.forbidden) as e:
entityActionFailedWarning([Ent.MOBILE_DEVICE, resourceId], str(e), i, count)
def _showBuilding(building, delimiter=u',', i=0, count=0):
if u'buildingName' in building:
printEntity([Ent.BUILDING, building[u'buildingName']], i, count)
Ind.Increment()
printKeyValueList([u'buildingId', u'id:{0}'.format(building[u'buildingId'])])
else:
printEntity([Ent.BUILDING_ID, u'id:{0}'.format(building[u'buildingId'])], i, count)
Ind.Increment()
if u'description' in building:
printKeyValueList([u'description', building[u'description']])
if u'floorNames' in building:
printKeyValueList([u'floorNames', delimiter.join(building[u'floorNames'])])
if u'coordinates' in building:
printKeyValueList([u'coordinates', None])
Ind.Increment()
printKeyValueList([u'latitude', building[u'coordinates'].get(u'latitude', 0)])
printKeyValueList([u'longitude', building[u'coordinates'].get(u'longitude', 0)])
Ind.Decrement()
Ind.Decrement()
# gam info building <BuildingID>
def _infoCalendarACLs(cal, entityType, calId, j, jcount, ruleIds, kcount):
Ind.Increment()
k = 0
for ruleId in ruleIds:
k += 1
ruleId = normalizeRuleId(ruleId)
try:
result = callGAPI(cal.acl(), u'get',
throw_reasons=[GAPI.NOT_FOUND, GAPI.INVALID, GAPI.INVALID_SCOPE_VALUE, GAPI.FORBIDDEN],
calendarId=calId, ruleId=ruleId, fields=u'id,role')
printEntity([entityType, calId, Ent.CALENDAR_ACL, formatACLScopeRole(result[u'id'], result[u'role'])], k, kcount)
except (GAPI.notFound, GAPI.invalid) as e:
if not checkCalendarExists(cal, calId):
entityUnknownWarning(entityType, calId, j, jcount)
break
else:
entityActionFailedWarning([entityType, calId, Ent.CALENDAR_ACL, formatACLScopeRole(ruleId, None)], str(e), k, kcount)
except (GAPI.invalidScopeValue, GAPI.forbidden) as e:
entityActionFailedWarning([entityType, calId, Ent.CALENDAR_ACL, formatACLScopeRole(ruleId, None)], str(e), k, kcount)
Ind.Decrement()
def _getCalendarListEventsProperty(myarg, attributes, kwargs):
attrName, attribute = attributes.get(myarg, (None, None))
if not attrName:
return False
attrType = attribute[GC.VAR_TYPE]
if attrType == GC.TYPE_BOOLEAN:
kwargs[attrName] = True
elif attrType == GC.TYPE_STRING:
kwargs[attrName] = getString(Cmd.OB_STRING)
elif attrType == GC.TYPE_CHOICE:
kwargs[attrName] = getChoice(attribute[u'choices'], mapChoice=True)
elif attrType == GC.TYPE_DATETIME:
kwargs[attrName] = getTimeOrDeltaFromNow()
else: # GC.TYPE_INTEGER
kwargs[attrName] = getInteger()
return True
def doInfoVaultHold():
v = buildGAPIObject(API.VAULT)
holdName = getString(Cmd.OB_HOLD_ITEM)
cd = matterId = None
while Cmd.ArgumentsRemaining():
myarg = getArgument()
if myarg == u'matter':
matterId, matterNameId = getMatterItem(v)
holdId, holdName, holdNameId = convertHoldNameToID(v, holdName, matterId, matterNameId)
elif myarg == u'shownames':
cd = buildGAPIObject(API.DIRECTORY)
else:
unknownArgumentExit()
if matterId is None:
missingArgumentExit(Cmd.OB_MATTER_ITEM)
try:
hold = callGAPI(v.matters().holds(), u'get',
throw_reasons=[GAPI.NOT_FOUND, GAPI.BAD_REQUEST, GAPI.FORBIDDEN],
matterId=matterId, holdId=holdId)
entityActionPerformed([Ent.VAULT_MATTER, matterNameId, Ent.VAULT_HOLD, formatHoldNameId(hold[u'name'], hold[u'holdId'])])
_showVaultHold(hold, cd)
except (GAPI.notFound, GAPI.badRequest, GAPI.forbidden) as e:
entityActionFailedWarning([Ent.VAULT_MATTER, matterNameId, Ent.VAULT_HOLD, holdNameId], str(e))
def FieldsToSite(fields):
import atom
import gdata.apps.sites
def GetField(fieldName):
return fields.get(fieldName)
def GetSiteField(fieldName, fieldClass):
value = fields.get(fieldName)
if value:
return fieldClass(text=value)
return None
site_entry = gdata.apps.sites.SiteEntry(sourceSite=GetField(SITE_SOURCELINK))
site_entry.siteName = GetSiteField(SITE_SITE, gdata.apps.sites.SiteName)
site_entry.title = GetSiteField(SITE_NAME, atom.Title)
site_entry.summary = GetSiteField(SITE_SUMMARY, atom.Summary)
site_entry.theme = GetSiteField(SITE_THEME, gdata.apps.sites.Theme)
value = GetField(SITE_CATEGORIES)
if value:
for category in value:
site_entry.category.append(atom.Category(term=category, scheme=gdata.apps.sites.TAG_KIND_TERM))
return site_entry
def _processTags(tagReplacements, message):
while True:
match = RT_PATTERN.search(message)
if not match:
break
if tagReplacements.get(match.group(1)):
message = RT_OPEN_PATTERN.sub(u'', message, count=1)
message = RT_CLOSE_PATTERN.sub(u'', message, count=1)
else:
message = RT_STRIP_PATTERN.sub(u'', message, count=1)
while True:
match = RT_TAG_REPLACE_PATTERN.search(message)
if not match:
break
message = re.sub(match.group(0), tagReplacements.get(match.group(1), u''), message)
return message
# Substitute for #user#, #email#, #usernamne#
def sendCreateUserNotification(notify, body, i=0, count=0):
def _makeSubstitutions(field):
notify[field] = _substituteForUser(notify[field], body[u'primaryEmail'], userName)
notify[field] = notify[field].replace(u'#domain#', domain)
notify[field] = notify[field].replace(u'#givenname#', body[u'name'][u'givenName'])
notify[field] = notify[field].replace(u'#familyname#', body[u'name'][u'familyName'])
notify[field] = notify[field].replace(u'#password#', notify[u'password'])
userName, domain = splitEmailAddress(body[u'primaryEmail'])
if not notify.get(u'subject'):
notify[u'subject'] = Msg.CREATE_USER_NOTIFY_SUBJECT
_makeSubstitutions(u'subject')
if not notify.get(u'message'):
notify[u'message'] = Msg.CREATE_USER_NOTIFY_MESSAGE
_makeSubstitutions(u'message')
send_email(notify[u'subject'], notify[u'message'], notify[u'emailAddress'], i, count)
# gam create user <EmailAddress> <UserAttributes> [notify <EmailAddress>] [subject <String>] [message <String>|(file <FileName> [charset <CharSet>])]
def getPrinterScopeListsForRole(cp, printerId, i, count, role):
try:
result = callGCP(cp.printers(), u'get',
throw_messages=[GCP.UNKNOWN_PRINTER],
printerid=printerId)
try:
jcount = len(result[u'printers'][0][u'access'])
except KeyError:
jcount = 0
scopeList = []
if jcount > 0:
for acl in result[u'printers'][0][u'access']:
if acl.get(u'role') == role:
scopeList.append(acl[u'scope'].lower())
return scopeList
except GCP.unknownPrinter as e:
entityActionFailedWarning([Ent.PRINTER, printerId], str(e), i, count)
return None
# gam printer|printers <PrinterIDEntity> sync user|manager|owner <PrinterACLScopeEntity> [notify]
def _showBackupCodes(user, codes, i, count):
Act.Set(Act.SHOW)
jcount = 0
for code in codes:
if code.get(u'verificationCode'):
jcount += 1
entityPerformActionNumItems([Ent.USER, user], jcount, Ent.BACKUP_VERIFICATION_CODES, i, count)
if jcount == 0:
setSysExitRC(NO_ENTITIES_FOUND)
return
Ind.Increment()
j = 0
for code in codes:
j += 1
printKeyValueList([u'{0:2}'.format(j), code.get(u'verificationCode')])
Ind.Decrement()
# gam <UserTypeEntity> update backupcodes|verificationcodes
def infoCalendars(users):
calendarEntity = getCalendarEntity()
checkForExtraneousArguments()
i, count, users = getEntityArgument(users)
for user in users:
i += 1
user, cal, calIds, jcount = _validateUserGetCalendarIds(user, i, count, calendarEntity)
if jcount == 0:
continue
Ind.Increment()
j = 0
for calId in calIds:
j += 1
calId = normalizeCalendarId(calId, user)
_processCalendarList(user, calId, j, jcount, cal, u'get',
calendarId=calId)
Ind.Decrement()
# <CalendarSettings> ::==
# [description <String>] [location <String>] [summary <String>] [timezone <String>]
def _getCalendarSettings(summaryRequired=False):
body = {}
while Cmd.ArgumentsRemaining():
myarg = getArgument()
if myarg == u'description':
body[u'description'] = getString(Cmd.OB_STRING, minLen=0).replace(u'\\n', u'\n')
elif myarg == u'location':
body[u'location'] = getString(Cmd.OB_STRING, minLen=0)
elif myarg == u'summary':
body[u'summary'] = getString(Cmd.OB_STRING)
elif myarg == u'timezone':
body[u'timeZone'] = getString(Cmd.OB_STRING)
else:
unknownArgumentExit()
if summaryRequired and not body.get(u'summary', None):
missingArgumentExit(u'summary <String>')
return body
# gam <UserTypeEntity> create calendars <CalendarSettings>
def doDriveSearch(drive, user, i, count, query=None, parentQuery=False, orderBy=None, teamDriveOnly=False, **kwargs):
if GC.Values[GC.SHOW_GETTINGS]:
printGettingAllEntityItemsForWhom(Ent.DRIVE_FILE_OR_FOLDER, user, i, count, query=query)
try:
files = callGAPIpages(drive.files(), u'list', VX_PAGES_FILES,
page_message=getPageMessageForWhom(noNL=True),
throw_reasons=GAPI.DRIVE_USER_THROW_REASONS+[GAPI.INVALID_QUERY, GAPI.INVALID, GAPI.FILE_NOT_FOUND, GAPI.TEAMDRIVE_NOT_FOUND],
q=query, orderBy=orderBy, fields=u'nextPageToken,files(id,teamDriveId)', pageSize=GC.Values[GC.DRIVE_MAX_RESULTS], **kwargs)
if files or not parentQuery:
return [f_file[u'id'] for f_file in files if not teamDriveOnly or f_file.get(u'teamDriveId')]
entityActionFailedWarning([Ent.USER, user, Ent.DRIVE_FILE, None], invalidQuery(query), i, count)
except (GAPI.invalidQuery, GAPI.invalid):
entityActionFailedWarning([Ent.USER, user, Ent.DRIVE_FILE, None], invalidQuery(query), i, count)
except GAPI.fileNotFound:
printGotEntityItemsForWhom(0)
except GAPI.teamDriveNotFound as e:
entityActionFailedWarning([Ent.USER, user, Ent.TEAMDRIVE_ID, kwargs[u'teamDriveId']], str(e), i, count)
except (GAPI.serviceNotAvailable, GAPI.authError, GAPI.domainPolicy) as e:
userSvcNotApplicableOrDriveDisabled(user, str(e), i, count)
return None
def _getDriveFileNameFromId(drive, fileId, combineTitleId=True):
try:
result = callGAPI(drive.files(), u'get',
throw_reasons=GAPI.DRIVE_ACCESS_THROW_REASONS,
fileId=fileId, fields=VX_FILENAME_MIMETYPE_TEAMDRIVEID, supportsTeamDrives=True)
if result:
fileName = result[VX_FILENAME]
if (result[u'mimeType'] == MIMETYPE_GA_FOLDER) and (result[VX_FILENAME] == TEAM_DRIVE) and result.get(u'teamDriveId'):
fileName = _getTeamDriveNameFromId(drive, result[u'teamDriveId'])
if combineTitleId:
fileName += u'('+fileId+u')'
return (fileName, _getEntityMimeType(result))
except (GAPI.fileNotFound, GAPI.forbidden, GAPI.internalError, GAPI.insufficientFilePermissions, GAPI.internalError,
GAPI.serviceNotAvailable, GAPI.authError, GAPI.domainPolicy):
pass
return (fileId, Ent.DRIVE_FILE_OR_FOLDER_ID)
def _validateUserGetTeamDriveFileIDs(user, i, count, fileIdEntity, drive=None, entityType=None):
if fileIdEntity[u'dict']:
cleanFileIDsList(fileIdEntity, fileIdEntity[u'dict'][user])
if not drive:
user, drive = buildGAPIServiceObject(API.DRIVE3, user)
if not drive:
return (user, None, 0)
else:
user = convertUIDtoEmailAddress(user)
if fileIdEntity.get(u'teamdrivename') and not _convertTeamDriveNameToId(drive, user, i, count, fileIdEntity):
return (user, None, 0)
if fileIdEntity[u'teamdrivefilequery']:
fileIdEntity[u'list'] = doDriveSearch(drive, user, i, count, query=fileIdEntity[u'teamdrivefilequery'], teamDriveOnly=True, **fileIdEntity[u'teamdrive'])
if fileIdEntity[u'list'] is None or not fileIdEntity[u'list']:
setSysExitRC(NO_ENTITIES_FOUND)
return (user, None, 0)
fileIdEntity[u'teamdrive'].pop(u'teamDriveId', None)
fileIdEntity[u'teamdrive'].pop(u'corpora', None)
l = len(fileIdEntity[u'list'])
if l == 0:
setSysExitRC(NO_ENTITIES_FOUND)
if entityType:
entityPerformActionNumItems([Ent.USER, user], l, entityType, i, count)
return (user, drive, l)
def _showTeamDriveThemes(users):
checkForExtraneousArguments()
i, count, users = getEntityArgument(users)
for user in users:
i += 1
user, drive = buildGAPIServiceObject(API.DRIVE3, user)
if not drive:
continue
try:
themes = callGAPIitems(drive.about(), u'get', u'teamDriveThemes',
throw_reasons=GAPI.DRIVE_USER_THROW_REASONS,
fields=u'teamDriveThemes')
jcount = len(themes)
entityPerformActionNumItems([Ent.USER, user], jcount, Ent.TEAMDRIVE_THEME, i, count)
_showTeamDriveThemeSettings(themes)
except (GAPI.serviceNotAvailable, GAPI.authError, GAPI.domainPolicy) as e:
userSvcNotApplicableOrDriveDisabled(user, str(e), i, count)
# gam <UserTypeEntity> show teamdrivethemes
def _setShowProfile(users, function, **kwargs):
cd = buildGAPIObject(API.DIRECTORY)
checkForExtraneousArguments()
i, count, users = getEntityArgument(users)
for user in users:
i += 1
user = normalizeEmailAddressOrUID(user)
try:
result = callGAPI(cd.users(), function,
throw_reasons=[GAPI.USER_NOT_FOUND, GAPI.FORBIDDEN],
userKey=user, fields=u'includeInGlobalAddressList', **kwargs)
printEntity([Ent.USER, user, Ent.PROFILE_SHARING_ENABLED, result.get(u'includeInGlobalAddressList', u'Unknown')], i, count)
except (GAPI.userNotFound, GAPI.forbidden):
entityUnknownWarning(Ent.USER, user, i, count)
# gam <UserTypeEntity> profile share|shared|unshare|unshared
def deleteTokens(users):
cd = buildGAPIObject(API.DIRECTORY)
checkArgumentPresent(u'clientid', required=True)
clientId = commonClientIds(getString(Cmd.OB_CLIENT_ID))
checkForExtraneousArguments()
i, count, users = getEntityArgument(users)
for user in users:
i += 1
user = normalizeEmailAddressOrUID(user)
try:
callGAPI(cd.tokens(), u'get',
throw_reasons=[GAPI.USER_NOT_FOUND, GAPI.DOMAIN_NOT_FOUND, GAPI.DOMAIN_CANNOT_USE_APIS, GAPI.FORBIDDEN, GAPI.NOT_FOUND, GAPI.RESOURCE_NOT_FOUND],
userKey=user, clientId=clientId, fields=u'')
callGAPI(cd.tokens(), u'delete',
throw_reasons=[GAPI.USER_NOT_FOUND, GAPI.DOMAIN_NOT_FOUND, GAPI.DOMAIN_CANNOT_USE_APIS, GAPI.FORBIDDEN, GAPI.NOT_FOUND, GAPI.RESOURCE_NOT_FOUND],
userKey=user, clientId=clientId)
entityActionPerformed([Ent.USER, user, Ent.ACCESS_TOKEN, clientId], i, count)
except (GAPI.notFound, GAPI.resourceNotFound) as e:
entityActionFailedWarning([Ent.USER, user, Ent.ACCESS_TOKEN, clientId], str(e), i, count)
except (GAPI.userNotFound, GAPI.domainNotFound, GAPI.domainCannotUseApis, GAPI.forbidden):
entityUnknownWarning(Ent.USER, user, i, count)
def _checkDelegator(cd, delegatorEmail, i, count, jcount):
try:
result = callGAPI(cd.users(), u'get',
throw_reasons=GAPI.USER_GET_THROW_REASONS,
userKey=delegatorEmail, fields=u'suspended,changePasswordAtNextLogin')
if result[u'suspended']:
entityNumEntitiesActionFailedWarning(Ent.DELEGATOR, delegatorEmail, Ent.DELEGATE, jcount, Ent.TypeMessage(Ent.DELEGATOR, Msg.IS_SUSPENDED_NO_DELEGATION), i, count)
setSysExitRC(USER_SUSPENDED_ERROR_RC)
elif result[u'changePasswordAtNextLogin']:
entityNumEntitiesActionFailedWarning(Ent.DELEGATOR, delegatorEmail, Ent.DELEGATE, jcount, Ent.TypeMessage(Ent.DELEGATOR, Msg.IS_REQD_TO_CHG_PWD_NO_DELEGATION), i, count)
setSysExitRC(USER_REQUIRED_TO_CHANGE_PASSWORD_ERROR_RC)
else:
return True
except (GAPI.userNotFound, GAPI.domainNotFound, GAPI.domainCannotUseApis, GAPI.forbidden, GAPI.badRequest, GAPI.backendError, GAPI.systemError) as e:
entityNumEntitiesActionFailedWarning(Ent.DELEGATOR, delegatorEmail, Ent.DELEGATE, jcount, Ent.TypeMessage(Ent.DELEGATOR, str(e)), i, count)
return False
def _checkDelegate(cd, delegatorEmail, delegateEmail, j, jcount):
try:
result = callGAPI(cd.users(), u'get',
throw_reasons=GAPI.USER_GET_THROW_REASONS,
userKey=delegateEmail, fields=u'suspended,changePasswordAtNextLogin')
if result[u'suspended']:
entityActionFailedWarning([Ent.DELEGATOR, delegatorEmail, Ent.DELEGATE, delegateEmail], Ent.TypeMessage(Ent.DELEGATE, Msg.IS_SUSPENDED_NO_DELEGATION), j, jcount)
setSysExitRC(USER_SUSPENDED_ERROR_RC)
elif result[u'changePasswordAtNextLogin']:
entityActionFailedWarning([Ent.DELEGATOR, delegatorEmail, Ent.DELEGATE, delegateEmail], Ent.TypeMessage(Ent.DELEGATE, Msg.IS_REQD_TO_CHG_PWD_NO_DELEGATION), j, jcount)
setSysExitRC(USER_REQUIRED_TO_CHANGE_PASSWORD_ERROR_RC)
else:
entityActionFailedWarning([Ent.DELEGATOR, delegatorEmail, Ent.DELEGATE, delegateEmail], Msg.GOOGLE_DELEGATION_ERROR, j, jcount)
setSysExitRC(GOOGLE_API_ERROR_RC)
except (GAPI.userNotFound, GAPI.domainNotFound, GAPI.domainCannotUseApis, GAPI.forbidden, GAPI.badRequest, GAPI.backendError, GAPI.systemError) as e:
entityActionFailedWarning([Ent.DELEGATOR, delegatorEmail, Ent.DELEGATE, delegateEmail], Ent.TypeMessage(Ent.DELEGATE, str(e)), j, jcount)
def _processForwardingAddress(user, i, count, emailAddress, j, jcount, gmail, function, **kwargs):
userDefined = True
try:
result = callGAPI(gmail.users().settings().forwardingAddresses(), function,
throw_reasons=GAPI.GMAIL_THROW_REASONS+[GAPI.NOT_FOUND, GAPI.ALREADY_EXISTS, GAPI.DUPLICATE],
userId=u'me', **kwargs)
if function == u'get':
_showForwardingAddress(j, count, result)
else:
entityActionPerformed([Ent.USER, user, Ent.FORWARDING_ADDRESS, emailAddress], j, jcount)
except (GAPI.notFound, GAPI.alreadyExists, GAPI.duplicate) as e:
entityActionFailedWarning([Ent.USER, user, Ent.FORWARDING_ADDRESS, emailAddress], str(e), j, jcount)
except (GAPI.serviceNotAvailable, GAPI.badRequest):
entityServiceNotApplicableWarning(Ent.USER, user, i, count)
userDefined = False
return userDefined
# gam <UserTypeEntity> create|add forwardingaddresses <EmailAddressEntity>