Пример #1
0
def getHoldInfo():
    v = buildGAPIObject()
    hold = sys.argv[3]
    matterId = None
    i = 4
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'matter':
            matterId = getMatterItem(v, sys.argv[i+1])
            holdId = convertHoldNameToID(v, hold, matterId)
            i += 2
        else:
            controlflow.invalid_argument_exit(myarg, "gam info hold")
    if not matterId:
        controlflow.system_error_exit(
            3, 'you must specify a matter for the hold.')
    results = gapi.call(v.matters().holds(), 'get',
                        matterId=matterId, holdId=holdId)
    cd = __main__.buildGAPIObject('directory')
    if 'accounts' in results:
        account_type = 'group' if results['corpus'] == 'GROUPS' else 'user'
        for i in range(0, len(results['accounts'])):
            uid = f'uid:{results["accounts"][i]["accountId"]}'
            acct_email = __main__.convertUIDtoEmailAddress(
                uid, cd, [account_type])
            results['accounts'][i]['email'] = acct_email
    if 'orgUnit' in results:
        results['orgUnit']['orgUnitPath'] = __main__.doGetOrgInfo(
            results['orgUnit']['orgUnitId'], return_attrib='orgUnitPath')
    display.print_json(results)
Пример #2
0
def getExportInfo():
    v = buildGAPIObject()
    matterId = getMatterItem(v, sys.argv[3])
    exportId = convertExportNameToID(v, sys.argv[4], matterId)
    export = gapi.call(v.matters().exports(), 'get',
                       matterId=matterId, exportId=exportId)
    display.print_json(export)
Пример #3
0
def infoEvent():
    calendarId, cal = buildCalendarDataGAPIObject(sys.argv[2])
    if not cal:
        return
    eventId = sys.argv[4]
    result = gapi.call(cal.events(), 'get',
                       calendarId=calendarId, eventId=eventId)
    display.print_json(result)
Пример #4
0
def getMatterInfo():
    v = buildGAPIObject()
    matterId = getMatterItem(v, sys.argv[3])
    result = gapi.call(v.matters(), 'get', matterId=matterId, view='FULL')
    if 'matterPermissions' in result:
        cd = __main__.buildGAPIObject('directory')
        for i in range(0, len(result['matterPermissions'])):
            uid = f'uid:{result["matterPermissions"][i]["accountId"]}'
            user_email = __main__.convertUIDtoEmailAddress(uid, cd)
            result['matterPermissions'][i]['email'] = user_email
    display.print_json(result)
Пример #5
0
def getBuildingInfo():
    cd = gapi.directory.buildGAPIObject()
    buildingId = getBuildingByNameOrId(cd, sys.argv[3])
    building = gapi.call(cd.resources().buildings(),
                         'get',
                         customer=GC_Values[GC_CUSTOMER_ID],
                         buildingId=buildingId)
    if 'buildingId' in building:
        building['buildingId'] = f'id:{building["buildingId"]}'
    if 'floorNames' in building:
        building['floorNames'] = ','.join(building['floorNames'])
    if 'buildingName' in building:
        sys.stdout.write(building.pop('buildingName'))
    display.print_json(building)
Пример #6
0
def getResourceCalendarInfo():
    cd = gapi.directory.buildGAPIObject()
    resId = sys.argv[3]
    resource = gapi.call(cd.resources().calendars(),
                         'get',
                         customer=GC_Values[GC_CUSTOMER_ID],
                         calendarResourceId=resId)
    if 'featureInstances' in resource:
        features = []
        for a_feature in resource.pop('featureInstances'):
            features.append(a_feature['feature']['name'])
        resource['features'] = ', '.join(features)
    if 'buildingId' in resource:
        resource['buildingName'] = getBuildingNameById(cd,
                                                       resource['buildingId'])
        resource['buildingId'] = f'id:{resource["buildingId"]}'
    display.print_json(resource)
Пример #7
0
def doGetCrosInfo():
    cd = gapi.directory.buildGAPIObject()
    i, devices = getCrOSDeviceEntity(3, cd)
    downloadfile = None
    targetFolder = GC_Values[GC_DRIVE_DIR]
    projection = None
    fieldsList = []
    noLists = False
    startDate = endDate = None
    listLimit = 0
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'nolists':
            noLists = True
            i += 1
        elif myarg == 'listlimit':
            listLimit = __main__.getInteger(sys.argv[i+1], myarg, minVal=-1)
            i += 2
        elif myarg in CROS_START_ARGUMENTS:
            startDate = _getFilterDate(sys.argv[i+1])
            i += 2
        elif myarg in CROS_END_ARGUMENTS:
            endDate = _getFilterDate(sys.argv[i+1])
            i += 2
        elif myarg == 'allfields':
            projection = 'FULL'
            fieldsList = []
            i += 1
        elif myarg in PROJECTION_CHOICES_MAP:
            projection = PROJECTION_CHOICES_MAP[myarg]
            if projection == 'FULL':
                fieldsList = []
            else:
                fieldsList = CROS_BASIC_FIELDS_LIST[:]
            i += 1
        elif myarg in CROS_ARGUMENT_TO_PROPERTY_MAP:
            fieldsList.extend(CROS_ARGUMENT_TO_PROPERTY_MAP[myarg])
            i += 1
        elif myarg == 'fields':
            fieldNameList = sys.argv[i+1]
            for field in fieldNameList.lower().replace(',', ' ').split():
                if field in CROS_ARGUMENT_TO_PROPERTY_MAP:
                    fieldsList.extend(CROS_ARGUMENT_TO_PROPERTY_MAP[field])
                    if field in CROS_ACTIVE_TIME_RANGES_ARGUMENTS + \
                                CROS_DEVICE_FILES_ARGUMENTS + \
                                CROS_RECENT_USERS_ARGUMENTS:
                        projection = 'FULL'
                        noLists = False
                else:
                    controlflow.invalid_argument_exit(
                        field, "gam info cros fields")
            i += 2
        elif myarg == 'downloadfile':
            downloadfile = sys.argv[i+1]
            if downloadfile.lower() == 'latest':
                downloadfile = downloadfile.lower()
            i += 2
        elif myarg == 'targetfolder':
            targetFolder = os.path.expanduser(sys.argv[i+1])
            if not os.path.isdir(targetFolder):
                os.makedirs(targetFolder)
            i += 2
        else:
            controlflow.invalid_argument_exit(sys.argv[i], "gam info cros")
    if fieldsList:
        fieldsList.append('deviceId')
        fields = ','.join(set(fieldsList)).replace('.', '/')
    else:
        fields = None
    i = 0
    device_count = len(devices)
    for deviceId in devices:
        i += 1
        cros = gapi.call(cd.chromeosdevices(), 'get',
                         customerId=GC_Values[GC_CUSTOMER_ID],
                         deviceId=deviceId, projection=projection,
                         fields=fields)
        print(f'CrOS Device: {deviceId} ({i} of {device_count})')
        if 'notes' in cros:
            cros['notes'] = cros['notes'].replace('\n', '\\n')
        if 'autoUpdateExpiration' in cros:
            cros['autoUpdateExpiration'] = utils.formatTimestampYMD(
                cros['autoUpdateExpiration'])
        _checkTPMVulnerability(cros)
        for up in CROS_SCALAR_PROPERTY_PRINT_ORDER:
            if up in cros:
                if isinstance(cros[up], str):
                    print(f'  {up}: {cros[up]}')
                else:
                    sys.stdout.write(f'  {up}:')
                    display.print_json(cros[up], '  ')
        if not noLists:
            activeTimeRanges = _filterTimeRanges(
                cros.get('activeTimeRanges', []), startDate, endDate)
            lenATR = len(activeTimeRanges)
            if lenATR:
                print('  activeTimeRanges')
                num_ranges = min(lenATR, listLimit or lenATR)
                for activeTimeRange in activeTimeRanges[:num_ranges]:
                    active_date = activeTimeRange["date"]
                    active_time = activeTimeRange["activeTime"]
                    duration = utils.formatMilliSeconds(active_time)
                    minutes = active_time // 60000
                    print(f'    date: {active_date}')
                    print(f'      activeTime: {active_time}')
                    print(f'      duration: {duration}')
                    print(f'      minutes: {minutes}')
            recentUsers = cros.get('recentUsers', [])
            lenRU = len(recentUsers)
            if lenRU:
                print('  recentUsers')
                num_ranges = min(lenRU, listLimit or lenRU)
                for recentUser in recentUsers[:num_ranges]:
                    useremail = recentUser.get("email")
                    if not useremail:
                        if recentUser["type"] == "USER_TYPE_UNMANAGED":
                            useremail = 'UnmanagedUser'
                        else:
                            useremail = 'Unknown'
                    print(f'    type: {recentUser["type"]}')
                    print(f'      email: {useremail}')
            deviceFiles = _filterCreateReportTime(
                cros.get('deviceFiles', []), 'createTime', startDate, endDate)
            lenDF = len(deviceFiles)
            if lenDF:
                num_ranges = min(lenDF, listLimit or lenDF)
                print('  deviceFiles')
                for deviceFile in deviceFiles[:num_ranges]:
                    device_type = deviceFile['type']
                    create_time = deviceFile['createTime']
                    print(f'    {device_type}: {create_time}')
            if downloadfile:
                deviceFiles = cros.get('deviceFiles', [])
                lenDF = len(deviceFiles)
                if lenDF:
                    if downloadfile == 'latest':
                        deviceFile = deviceFiles[-1]
                    else:
                        for deviceFile in deviceFiles:
                            if deviceFile['createTime'] == downloadfile:
                                break
                        else:
                            print(f'ERROR: file {downloadfile} not ' \
                                  f'available to download.')
                            deviceFile = None
                    if deviceFile:
                        created = deviceFile["createTime"]
                        downloadfile = f'cros-logs-{deviceId}-{created}.zip'
                        downloadfilename = os.path.join(targetFolder,
                                                        downloadfile)
                        dl_url = deviceFile['downloadUrl']
                        _, content = cd._http.request(dl_url)
                        fileutils.write_file(downloadfilename, content,
                                             mode='wb',
                                             continue_on_error=True)
                        print(f'Downloaded: {downloadfilename}')
                elif downloadfile:
                    print('ERROR: no files to download.')
            cpuStatusReports = _filterCreateReportTime(
                cros.get('cpuStatusReports', []),
                'reportTime',
                startDate,
                endDate)
            lenCSR = len(cpuStatusReports)
            if lenCSR:
                print('  cpuStatusReports')
                num_ranges = min(lenCSR, listLimit or lenCSR)
                for cpuStatusReport in cpuStatusReports[:num_ranges]:
                    print(f'    reportTime: {cpuStatusReport["reportTime"]}')
                    print('      cpuTemperatureInfo')
                    tempInfos = cpuStatusReport.get('cpuTemperatureInfo', [])
                    for tempInfo in tempInfos:
                        temp_label = tempInfo['label'].strip()
                        temperature = tempInfo['temperature']
                        print(f'        {temp_label}: {temperature}')
                    pct_info = cpuStatusReport["cpuUtilizationPercentageInfo"]
                    util = ",".join([str(x) for x in pct_info])
                    print(f'      cpuUtilizationPercentageInfo: {util}')
            diskVolumeReports = cros.get('diskVolumeReports', [])
            lenDVR = len(diskVolumeReports)
            if lenDVR:
                print('  diskVolumeReports')
                print('    volumeInfo')
                num_ranges = min(lenDVR, listLimit or lenDVR)
                for diskVolumeReport in diskVolumeReports[:num_ranges]:
                    volumeInfo = diskVolumeReport['volumeInfo']
                    for volume in volumeInfo:
                        vid = volume['volumeId']
                        vstorage_free = volume['storageFree']
                        vstorage_total = volume['storageTotal']
                        print(f'      volumeId: {vid}')
                        print(f'        storageFree: {vstorage_free}')
                        print(f'        storageTotal: {vstorage_total}')
            systemRamFreeReports = _filterCreateReportTime(
                cros.get('systemRamFreeReports', []),
                'reportTime', startDate, endDate)
            lenSRFR = len(systemRamFreeReports)
            if lenSRFR:
                print('  systemRamFreeReports')
                num_ranges = min(lenSRFR, listLimit or lenSRFR)
                for systemRamFreeReport in systemRamFreeReports[:num_ranges]:
                    report_time = systemRamFreeReport["reportTime"]
                    free_info = systemRamFreeReport["systemRamFreeInfo"]
                    free_ram = ",".join(free_info)
                    print(f'    reportTime: {report_time}')
                    print(f'      systemRamFreeInfo: {free_ram}')
Пример #8
0
def createExport():
    v = buildGAPIObject()
    allowed_corpuses = gapi.get_enum_values_minus_unspecified(
        v._rootDesc['schemas']['Query']['properties']['corpus']['enum'])
    allowed_scopes = gapi.get_enum_values_minus_unspecified(
        v._rootDesc['schemas']['Query']['properties']['dataScope']['enum'])
    allowed_formats = gapi.get_enum_values_minus_unspecified(
        v._rootDesc['schemas']['MailExportOptions']['properties']
        ['exportFormat']['enum'])
    export_format = 'MBOX'
    showConfidentialModeContent = None  # default to not even set
    matterId = None
    body = {'query': {'dataScope': 'ALL_DATA'}, 'exportOptions': {}}
    i = 3
    while i < len(sys.argv):
        myarg = sys.argv[i].lower().replace('_', '')
        if myarg == 'matter':
            matterId = getMatterItem(v, sys.argv[i+1])
            body['matterId'] = matterId
            i += 2
        elif myarg == 'name':
            body['name'] = sys.argv[i+1]
            i += 2
        elif myarg == 'corpus':
            body['query']['corpus'] = sys.argv[i+1].upper()
            if body['query']['corpus'] not in allowed_corpuses:
                controlflow.expected_argument_exit(
                    "corpus", ", ".join(allowed_corpuses), sys.argv[i+1])
            i += 2
        elif myarg in VAULT_SEARCH_METHODS_MAP:
            if body['query'].get('searchMethod'):
                message = f'Multiple search methods ' \
                          f'({", ".join(VAULT_SEARCH_METHODS_LIST)})' \
                          f'specified, only one is allowed'
                controlflow.system_error_exit(3, message)
            searchMethod = VAULT_SEARCH_METHODS_MAP[myarg]
            body['query']['searchMethod'] = searchMethod
            if searchMethod == 'ACCOUNT':
                body['query']['accountInfo'] = {
                    'emails': sys.argv[i+1].split(',')}
                i += 2
            elif searchMethod == 'ORG_UNIT':
                body['query']['orgUnitInfo'] = {
                    'orgUnitId': __main__.getOrgUnitId(sys.argv[i+1])[1]}
                i += 2
            elif searchMethod == 'SHARED_DRIVE':
                body['query']['sharedDriveInfo'] = {
                    'sharedDriveIds': sys.argv[i+1].split(',')}
                i += 2
            elif searchMethod == 'ROOM':
                body['query']['hangoutsChatInfo'] = {
                    'roomId': sys.argv[i+1].split(',')}
                i += 2
            else:
                i += 1
        elif myarg == 'scope':
            body['query']['dataScope'] = sys.argv[i+1].upper()
            if body['query']['dataScope'] not in allowed_scopes:
                controlflow.expected_argument_exit(
                    "scope", ", ".join(allowed_scopes), sys.argv[i+1])
            i += 2
        elif myarg in ['terms']:
            body['query']['terms'] = sys.argv[i+1]
            i += 2
        elif myarg in ['start', 'starttime']:
            body['query']['startTime'] = utils.get_date_zero_time_or_full_time(
                sys.argv[i+1])
            i += 2
        elif myarg in ['end', 'endtime']:
            body['query']['endTime'] = utils.get_date_zero_time_or_full_time(
                sys.argv[i+1])
            i += 2
        elif myarg in ['timezone']:
            body['query']['timeZone'] = sys.argv[i+1]
            i += 2
        elif myarg in ['excludedrafts']:
            body['query']['mailOptions'] = {
                'excludeDrafts': __main__.getBoolean(sys.argv[i+1], myarg)}
            i += 2
        elif myarg in ['driveversiondate']:
            body['query'].setdefault('driveOptions', {})['versionDate'] = \
                utils.get_date_zero_time_or_full_time(sys.argv[i+1])
            i += 2
        elif myarg in ['includeshareddrives', 'includeteamdrives']:
            body['query'].setdefault('driveOptions', {})[
                'includeSharedDrives'] = __main__.getBoolean(sys.argv[i+1], myarg)
            i += 2
        elif myarg in ['includerooms']:
            body['query']['hangoutsChatOptions'] = {
                'includeRooms': __main__.getBoolean(sys.argv[i+1], myarg)}
            i += 2
        elif myarg in ['format']:
            export_format = sys.argv[i+1].upper()
            if export_format not in allowed_formats:
                controlflow.expected_argument_exit(
                    "export format", ", ".join(allowed_formats), export_format)
            i += 2
        elif myarg in ['showconfidentialmodecontent']:
            showConfidentialModeContent = __main__.getBoolean(sys.argv[i+1], myarg)
            i += 2
        elif myarg in ['region']:
            allowed_regions = gapi.get_enum_values_minus_unspecified(
                v._rootDesc['schemas']['ExportOptions']['properties'][
                    'region']['enum'])
            body['exportOptions']['region'] = sys.argv[i+1].upper()
            if body['exportOptions']['region'] not in allowed_regions:
                controlflow.expected_argument_exit("region", ", ".join(
                    allowed_regions), body['exportOptions']['region'])
            i += 2
        elif myarg in ['includeaccessinfo']:
            body['exportOptions'].setdefault('driveOptions', {})[
                'includeAccessInfo'] = __main__.getBoolean(sys.argv[i+1], myarg)
            i += 2
        else:
            controlflow.invalid_argument_exit(sys.argv[i], "gam create export")
    if not matterId:
        controlflow.system_error_exit(
            3, 'you must specify a matter for the new export.')
    if 'corpus' not in body['query']:
        controlflow.system_error_exit(3, f'you must specify a corpus for the ' \
          f'new export. Choose one of {", ".join(allowed_corpuses)}')
    if 'searchMethod' not in body['query']:
        controlflow.system_error_exit(3, f'you must specify a search method ' \
          'for the new export. Choose one of ' \
          f'{", ".join(VAULT_SEARCH_METHODS_LIST)}')
    if 'name' not in body:
        corpus_name = body["query"]["corpus"]
        corpus_date = datetime.datetime.now()
        body['name'] = f'GAM {corpus_name} export - {corpus_date}'
    options_field = None
    if body['query']['corpus'] == 'MAIL':
        options_field = 'mailOptions'
    elif body['query']['corpus'] == 'GROUPS':
        options_field = 'groupsOptions'
    elif body['query']['corpus'] == 'HANGOUTS_CHAT':
        options_field = 'hangoutsChatOptions'
    if options_field:
        body['exportOptions'].pop('driveOptions', None)
        body['exportOptions'][options_field] = {'exportFormat': export_format}
        if showConfidentialModeContent is not None:
            body['exportOptions'][options_field][
                'showConfidentialModeContent'] = showConfidentialModeContent
    results = gapi.call(v.matters().exports(), 'create',
                        matterId=matterId, body=body)
    print(f'Created export {results["id"]}')
    display.print_json(results)