def validateConfiguration(host, entId, key, prefix="Bearer", maxAttempt=Globals.MAX_RETRY): configuration = esperclient.Configuration() configuration.host = host configuration.api_key["Authorization"] = key configuration.api_key_prefix["Authorization"] = prefix api_instance = esperclient.EnterpriseApi( esperclient.ApiClient(configuration)) enterprise_id = entId try: api_response = None for attempt in range(maxAttempt): try: api_response = api_instance.get_enterprise(enterprise_id) break except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(Globals.RETRY_SLEEP) if hasattr(api_response, "id"): return True except ApiException as e: print("Exception when calling EnterpriseApi->get_enterprise: %s\n" % e) ApiToolLog().LogError(e) return False
def main(): """Launches Main App""" sys.excepthook = ApiToolLog().excepthook try: Globals.app = MyApp(0) Globals.app.MainLoop() except Exception as e: ApiToolLog().LogError(e)
def toggleKioskMode( frame, deviceid, appToUse, isKiosk, timeout=Globals.COMMAND_TIMEOUT, maxAttempt=Globals.MAX_RETRY, ): """Toggles Kiosk Mode On/Off""" api_instance = getCommandsApiInstance() if isKiosk: command_args = esperclient.V0CommandArgs(package_name=appToUse) else: command_args = {} command = esperclient.V0CommandRequest( enterprise=Globals.enterprise_id, command_type="DEVICE", device_type=Globals.CMD_DEVICE_TYPE, devices=[deviceid], command="SET_KIOSK_APP", command_args=command_args, ) api_response = None for attempt in range(maxAttempt): try: api_response = api_instance.create_command(Globals.enterprise_id, command) break except Exception as e: if hasattr(e, "body") and "invalid device id" in e.body: logBadResponse("create command api", api_response, None) return None if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(Globals.RETRY_SLEEP) response = None for attempt in range(maxAttempt): try: response = api_instance.get_command_request_status( Globals.enterprise_id, api_response.id) break except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(Globals.RETRY_SLEEP) status = response.results[0].state ignoreQueued = False if Globals.REACH_QUEUED_ONLY else True status = waitForCommandToFinish(frame, api_response.id, ignoreQueue=ignoreQueued, timeout=timeout) return status
def logPlaceDone(func): try: if Globals.RECORD_PLACE: place = "Finshed " currThread = threading.current_thread() if func.__name__ and func.__doc__: place += str(func.__name__ + "\t:\t" + func.__doc__ + "\t:\t" + currThread.name) elif func.__name__: place += str(func.__name__ + "\t:\t" + currThread.name) ApiToolLog().LogPlace(place) except Exception as e: ApiToolLog().LogError(e)
def getAllDevices(groupToUse, maxAttempt=Globals.MAX_RETRY): """ Make a API call to get all Devices belonging to the Enterprise """ if not groupToUse: return None try: api_instance = esperclient.DeviceApi( esperclient.ApiClient(Globals.configuration)) api_response = None if type(groupToUse) == list: for group in groupToUse: for attempt in range(maxAttempt): try: response = api_instance.get_all_devices( Globals.enterprise_id, group=group, limit=Globals.limit, offset=Globals.offset, ) break except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(Globals.RETRY_SLEEP) if not api_response: api_response = response else: api_response.results = api_response.results + response.results else: for attempt in range(maxAttempt): try: api_response = api_instance.get_all_devices( Globals.enterprise_id, group=groupToUse, limit=Globals.limit, offset=Globals.offset, ) break except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(Globals.RETRY_SLEEP) postEventToFrame(wxThread.myEVT_LOG, "---> Device API Request Finished") return api_response except ApiException as e: raise Exception( "Exception when calling DeviceApi->get_all_devices: %s\n" % e)
def getInstallDevices(version_id, application_id, maxAttempt=Globals.MAX_RETRY): api_instance = esperclient.ApplicationApi( esperclient.ApiClient(Globals.configuration)) enterprise_id = Globals.enterprise_id for attempt in range(maxAttempt): try: # List install devices api_response = api_instance.get_install_devices( version_id, application_id, enterprise_id, limit=Globals.limit, offset=Globals.offset, ) return api_response except ApiException as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) print( "Exception when calling ApplicationApi->get_install_devices: %s\n" % e) raise e time.sleep(1)
def getAppVersions(application_id, version_code="", build_number="", maxAttempt=Globals.MAX_RETRY): api_instance = esperclient.ApplicationApi( esperclient.ApiClient(Globals.configuration)) enterprise_id = Globals.enterprise_id for attempt in range(maxAttempt): try: api_response = api_instance.get_app_versions( application_id, enterprise_id, version_code=version_code, build_number=build_number, limit=Globals.limit, offset=Globals.offset, ) return api_response except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) print( "Exception when calling ApplicationApi->get_app_versions: %s\n" % e) raise e time.sleep(1)
def postEsperCommand(command_data, useV0=True): json_resp = None resp = None try: headers = getHeader() url = "" if useV0: url = "https://%s-api.esper.cloud/api/v0/enterprise/%s/command/" % ( Globals.configuration.host.split("-api")[0].replace( "https://", ""), Globals.enterprise_id, ) else: url = "https://%s-api.esper.cloud/api/enterprise/%s/command/" % ( Globals.configuration.host.split("-api")[0].replace( "https://", ""), Globals.enterprise_id, ) resp = performPostRequestWithRetry(url, headers=headers, json=command_data) json_resp = resp.json() logBadResponse(url, resp, json_resp) except Exception as e: ApiToolLog().LogError(e) return resp, json_resp
def uploadMissingApk(self, app, template, newTemplate, config, entId): try: postEventToFrame( wxThread.myEVT_LOG, "Attempting to download %s to upload to endpoint" % app["packageName"], ) file = "%s.apk" % app["applicationName"] deleteFile(file) download(app["downloadUrl"], file) res = uploadApplicationForHost(config, entId, file) if type(res) != InlineResponse201: deleteFile(file) raise Exception("Upload failed!") deleteFile(file) if template["template"]["application"]["startOnBoot"] == app[ "packageName"]: newTemplate["application"]["appMode"] = template["template"][ "application"]["appMode"] newTemplate["application"]["startOnBoot"] = template[ "template"]["application"]["startOnBoot"] except Exception as e: print(e) ApiToolLog().LogError(e) postEventToFrame( wxThread.myEVT_LOG, "To Enterprise is missing app, %s, not adding to template" % app["applicationName"], ) self.missingApps += str(app["applicationName"]) + ", "
def getAllApplicationsForHost(config, enterprise_id, maxAttempt=Globals.MAX_RETRY): """ Make a API call to get all Applications belonging to the Enterprise """ try: api_instance = esperclient.ApplicationApi( esperclient.ApiClient(config)) api_response = None for attempt in range(maxAttempt): try: api_response = api_instance.get_all_applications( enterprise_id, limit=Globals.limit, offset=0, is_hidden=False, ) break except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(Globals.RETRY_SLEEP) return api_response except Exception as e: raise Exception( "Exception when calling ApplicationApi->get_all_applications: %s\n" % e)
def downloadFileFromUrl(url, fileName, filepath="", redirects=True, chunk_size=1024): if not filepath: filepath = str(os.path.join(Path.home(), "Downloads")) fullPath = os.path.join(filepath, fileName) num = 1 while os.path.exists(fullPath): parts = fileName.split(".") parts.insert(1, (" (%s)" % num)) parts[len(parts) - 1] = ".%s" % parts[len(parts) - 1] tmpFileName = "".join(parts) fullPath = os.path.join(filepath, tmpFileName) num += 1 parentPath = os.path.abspath(os.path.join(fullPath, os.pardir)) if not os.path.exists(parentPath): os.makedirs(parentPath) try: r = requests.get(url, stream=True, allow_redirects=redirects) with open(fullPath, "wb") as file: for chunk in r.iter_content(chunk_size=chunk_size): if chunk: file.write(chunk) return fullPath except Exception as e: print(e) ApiToolLog().LogError(e) return None
def getAllApplications(maxAttempt=Globals.MAX_RETRY): """ Make a API call to get all Applications belonging to the Enterprise """ try: api_instance = esperclient.ApplicationApi( esperclient.ApiClient(Globals.configuration)) api_response = None for attempt in range(maxAttempt): try: api_response = api_instance.get_all_applications( Globals.enterprise_id, limit=Globals.limit, offset=Globals.offset, is_hidden=False, ) break except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(Globals.RETRY_SLEEP) postEventToFrame(wxThread.myEVT_LOG, "---> App API Request Finished") return api_response except ApiException as e: raise Exception( "Exception when calling ApplicationApi->get_all_applications: %s\n" % e)
def updateCheck(self): icon = wx.ICON_INFORMATION msg = "" json = None try: json = checkForUpdate() except Exception as e: print(e) ApiToolLog().LogError(e) if json: tagVersion = json["tag_name"].replace("v", "") if float(tagVersion) > float(Globals.VERSION.replace("v", "")): downloadURL = "" name = "" assets = json["assets"] for asset in assets: name = asset["name"] if "win" in name.lower() and self.WINDOWS: downloadURL = asset["browser_download_url"] break elif "mac" in name.lower() and not self.WINDOWS: downloadURL = asset["browser_download_url"] break if downloadURL: result = None try: result = downloadFileFromUrl(downloadURL, name) except Exception as e: print(e) ApiToolLog().LogError(e) if result: msg = ( "Download Succeeded! File should be located at:\n\n%s\nPlease open the executable from the download!" % result) else: icon = wx.ICON_ERROR msg = "An error occured while downloading the update. Please try again later." else: msg = "You are up-to-date!" else: icon = wx.ICON_ERROR msg = ( "An error occured while downloading the update. Please try again later." ) wx.MessageBox(msg, style=icon) self.isCheckingForUpdates = False
def setAppState(device_id, pkg_name, appVer=None, state="HIDE", maxAttempt=Globals.MAX_RETRY): pkgName = pkg_name if not appVer: _, app = getdeviceapps(device_id, createAppList=False, useEnterprise=Globals.USE_ENTERPRISE_APP) if app["results"] and "application" in app["results"][0]: app = list( filter( lambda x: x["application"]["package_name"] == pkg_name, app["results"], )) else: app = list( filter( lambda x: x["package_name"] == pkg_name, app["results"], )) if app: app = app[0] if "application" in app: appVer = app["application"]["version"]["version_code"] elif "version_code" in app: appVer = app["version_code"] if pkgName and appVer: args = V0CommandArgs( app_state=state, app_version=appVer, package_name=pkgName, ) args.version_code = appVer request = esperclient.V0CommandRequest( enterprise=Globals.enterprise_id, command_type="DEVICE", device_type=Globals.CMD_DEVICE_TYPE, devices=[device_id], command="SET_APP_STATE", command_args=args, ) api_instance = getCommandsApiInstance() for attempt in range(maxAttempt): try: api_response = api_instance.create_command( Globals.enterprise_id, request) break except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(1) ignoreQueued = False if Globals.REACH_QUEUED_ONLY else True return waitForCommandToFinish(Globals.frame, api_response.id, ignoreQueue=ignoreQueued)
def deleteFile(file): try: if os.path.exists(file): os.remove(file) return True except Exception as e: print(e) ApiToolLog().LogError(e) return False
def getTokenInfo(maxAttempt=Globals.MAX_RETRY): api_instance = esperclient.TokenApi( esperclient.ApiClient(Globals.configuration)) try: api_response = None for attempt in range(maxAttempt): try: api_response = api_instance.get_token_info() break except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(Globals.RETRY_SLEEP) return api_response except ApiException as e: print("Exception when calling TokenApi->get_token_info: %s\n" % e) ApiToolLog().LogError(e)
def postEventToFrame(eventType, eventValue=None): """ Post an Event to the Main Thread """ if eventType: try: evt = wxThread.CustomEvent(eventType, -1, eventValue) if Globals.frame: wx.PostEvent(Globals.frame, evt) except Exception as e: ApiToolLog().LogError(e)
def setdevicename( frame, deviceid, devicename, ignoreQueue, timeout=Globals.COMMAND_TIMEOUT, maxAttempt=Globals.MAX_RETRY, ): """Pushes New Name To Name""" api_instance = getCommandsApiInstance() args = esperclient.V0CommandArgs(device_alias_name=devicename) command = esperclient.V0CommandRequest( command_type="DEVICE", devices=[deviceid], command="UPDATE_DEVICE_CONFIG", command_args=args, device_type=Globals.CMD_DEVICE_TYPE, ) api_response = None for attempt in range(maxAttempt): try: api_response = api_instance.create_command(Globals.enterprise_id, command) break except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(Globals.RETRY_SLEEP) response = None for attempt in range(maxAttempt): try: response = api_instance.get_command_request_status( Globals.enterprise_id, api_response.id) break except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(Globals.RETRY_SLEEP) status = response.results[0].state status = waitForCommandToFinish(frame, api_response.id, ignoreQueue, timeout) return status
def getDeviceById(deviceToUse, maxAttempt=Globals.MAX_RETRY): """ Make a API call to get a Device belonging to the Enterprise by its Id """ try: api_instance = esperclient.DeviceApi( esperclient.ApiClient(Globals.configuration)) api_response_list = [] api_response = None if type(deviceToUse) == list: for device in deviceToUse: for attempt in range(maxAttempt): try: api_response = api_instance.get_device_by_id( Globals.enterprise_id, device_id=device) break except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(Globals.RETRY_SLEEP) if api_response: api_response_list.append(api_response) else: for attempt in range(maxAttempt): try: api_response = api_instance.get_device_by_id( Globals.enterprise_id, device_id=deviceToUse) break except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(Globals.RETRY_SLEEP) if api_response and api_response_list: api_response.results = api_response_list elif api_response: api_response.results = [api_response] postEventToFrame(wxThread.myEVT_LOG, "---> Device API Request Finished") return api_response except ApiException as e: print("Exception when calling DeviceApi->get_device_by_id: %s\n" % e) ApiToolLog().LogError(e)
def setAppStateForAllAppsListed(state, maxAttempt=Globals.MAX_RETRY): api_instance = esperclient.DeviceApi( esperclient.ApiClient(Globals.configuration)) api_response = None for attempt in range(maxAttempt): try: api_response = api_instance.get_all_devices( Globals.enterprise_id, limit=Globals.limit, offset=Globals.offset, ) break except Exception as e: if attempt == maxAttempt - 1: postEventToFrame( wxThread.myEVT_LOG, "---> ERROR: Failed to get devices ids to modify tags and aliases", ) print(e) ApiToolLog().LogError(e) return time.sleep(Globals.RETRY_SLEEP) deviceIdentifers = Globals.frame.gridPanel.getDeviceIdentifersFromGrid() if api_response: tempRes = [] for device in api_response.results: for deviceIds in deviceIdentifers: if (device.device_name in deviceIds or device.hardware_info["serialNumber"] in deviceIds): tempRes.append(device) if tempRes: api_response.results = tempRes threads = [] for device in api_response.results: if (device.device_name in deviceIdentifers or device.hardware_info["serialNumber"] in deviceIdentifers): t = wxThread.GUIThread( Globals.frame, setAllAppsState, args=(Globals.frame, device, state), name="setAllAppsState", ) threads.append(t) t.start() limitActiveThreads(threads) t = wxThread.GUIThread( Globals.frame, waitTillThreadsFinish, args=(tuple(threads), state, -1, 4), name="waitTillThreadsFinish%s" % state, ) t.start()
def download(url, file_name, overwrite=True): try: if os.path.exists(file_name) and overwrite: os.remove(file_name) except Exception as e: print(e) ApiToolLog().LogError(e) # open in binary mode with open(file_name, "wb") as file: # get request response = requests.get(url) # write to file file.write(response.content)
def fetchGroupName(groupURL): headers = getHeader() resp = performGetRequestWithRetry(groupURL, headers=headers) try: if resp.status_code < 300: json_resp = resp.json() logBadResponse(groupURL, resp, json_resp) if "name" in json_resp: return json_resp["name"] except Exception as e: ApiToolLog().LogError(e) logBadResponse(groupURL, resp, None) return None
def clearAppData(frame, device): json_resp = None try: appToUse = frame.sidePanel.appChoice.GetClientData( frame.sidePanel.appChoice.GetSelection()) _, apps = getdeviceapps(device.id, createAppList=False, useEnterprise=Globals.USE_ENTERPRISE_APP) cmdArgs = {} for app in apps["results"]: if app["package_name"] == appToUse: cmdArgs["package_name"] = app["package_name"] cmdArgs["application_name"] = app["app_name"] cmdArgs["version_code"] = app["version_code"] cmdArgs["version_name"] = app["version_name"] if app["app_type"] == "GOOGLE": cmdArgs["is_g_play"] = True else: cmdArgs["is_g_play"] = False break if cmdArgs: reqData = { "command_type": "DEVICE", "command_args": cmdArgs, "devices": [device.id], "groups": [], "device_type": Globals.CMD_DEVICE_TYPE, "command": "CLEAR_APP_DATA", } resp, json_resp = postEsperCommand(reqData) logBadResponse(resp.request.url, resp, json_resp) if resp.status_code > 300: postEventToFrame(wxThread.myEVT_ON_FAILED, device) if resp.status_code < 300: frame.Logging( "---> Clear %s App Data Command has been sent to %s" % (cmdArgs["application_name"], device.device_name)) else: frame.Logging( "ERROR: Failed to send Clear %s App Data Command to %s" % (frame.sidePanel.appChoice.GetValue(), device.device_name)) except Exception as e: ApiToolLog().LogError(e) frame.Logging("ERROR: Failed to send Clear App Data Command to %s" % (device.device_name)) postEventToFrame(wxThread.myEVT_ON_FAILED, device) return json_resp
def performDeleteRequestWithRetry(url, headers=None, json=None, data=None, maxRetry=Globals.MAX_RETRY): resp = None for attempt in range(maxRetry): try: resp = requests.delete(url, headers=headers, data=data, json=json) if resp.status_code < 300: break except Exception as e: if attempt == maxRetry - 1: ApiToolLog().LogError(e) time.sleep(Globals.RETRY_SLEEP) return resp
def getDeviceApplicationById(device_id, application_id): try: headers = getHeader() url = "https://%s-api.esper.cloud/api/enterprise/%s/device/%s/app/%s" % ( Globals.configuration.host.split("-api")[0].replace( "https://", ""), Globals.enterprise_id, device_id, application_id, ) resp = performGetRequestWithRetry(url, headers=headers) json_resp = resp.json() logBadResponse(url, resp, json_resp) except Exception as e: ApiToolLog().LogError(e) return resp, json_resp
def processDevices(chunk, number_of_devices, action, isUpdate=False): """ Try to obtain more device info for a given device """ deviceList = {} for device in chunk: try: number_of_devices = number_of_devices + 1 deviceInfo = {} deviceInfo.update({"num": number_of_devices}) deviceInfo = populateDeviceInfoDictionary(device, deviceInfo) deviceList[number_of_devices] = [device, deviceInfo] # if deviceInfo not in Globals.GRID_DEVICE_INFO_LIST: # Globals.GRID_DEVICE_INFO_LIST.append(deviceInfo) except Exception as e: print(e) ApiToolLog().LogError(e) return (action, deviceList)
def fillInDeviceInfoDict(chunk, number_of_devices, maxGauge): deviceList = {} for device in chunk: try: deviceInfo = {} deviceInfo = populateDeviceInfoDictionary(device, deviceInfo) deviceList[number_of_devices] = [device, deviceInfo] number_of_devices += 1 Globals.deviceInfo_lock.acquire() value = int(Globals.frame.gauge.GetValue() + 1 / maxGauge * 100) Globals.frame.setGaugeValue(value) Globals.deviceInfo_lock.release() except Exception as e: print(e) ApiToolLog().LogError(e) return deviceList
def executeCommandOnDevice( frame, command_args, schedule=None, schedule_type="IMMEDIATE", command_type="UPDATE_DEVICE_CONFIG", maxAttempt=Globals.MAX_RETRY, ): """ Execute a Command on a Device """ statusList = [] for deviceToUse in frame.sidePanel.selectedDevicesList: request = esperclient.V0CommandRequest( enterprise=Globals.enterprise_id, command_type="DEVICE", device_type=Globals.CMD_DEVICE_TYPE, devices=[deviceToUse], command=command_type, command_args=command_args, schedule="IMMEDIATE" if command_type != "UPDATE_LATEST_DPC" else "WINDOW", schedule_args=schedule, ) api_instance = getCommandsApiInstance() api_response = None for attempt in range(maxAttempt): try: api_response = api_instance.create_command( Globals.enterprise_id, request) break except Exception as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) raise e time.sleep(Globals.RETRY_SLEEP) ignoreQueued = False if Globals.REACH_QUEUED_ONLY else True last_status = waitForCommandToFinish(frame, api_response.id, ignoreQueue=ignoreQueued) if hasattr(last_status, "state"): entry = {"Device": deviceToUse, "status": last_status.state} if hasattr(last_status, "reason"): entry["Reason"] = last_status.reason statusList.append(entry) else: statusList.append({"Device": deviceToUse, "Status": last_status}) return statusList
def changeAliasForDevice(device, aliasDic, frame, maxGaugeAction): numNewName = 0 succeeded = 0 logString = "" # Alias modification if (device.device_name in aliasDic.keys() or device.hardware_info["serialNumber"] in aliasDic.keys()): newName = None if device.device_name in aliasDic: newName = aliasDic[device.device_name] else: newName = aliasDic[device.hardware_info["serialNumber"]] logString = str("--->" + str(device.device_name) + " : " + str(newName) + "--->") if not newName and not device.alias_name: return if newName != str(device.alias_name): numNewName += 1 status = "" try: ignoreQueued = False if Globals.REACH_QUEUED_ONLY else True status = apiCalls.setdevicename(frame, device.id, newName, ignoreQueued) except Exception as e: ApiToolLog().LogError(e) if "Success" in str(status): logString = logString + " <success>" succeeded += 1 elif "Queued" in str(status): logString = logString + " <Queued> Make sure device is online." postEventToFrame(wxThread.myEVT_ON_FAILED, (device, "Queued")) else: logString = logString + " <failed>" postEventToFrame(wxThread.myEVT_ON_FAILED, device) else: logString = logString + " (Alias Name already set)" if "Success" in logString or "Queued" in logString: postEventToFrame(wxThread.myEVT_UPDATE_GRID_CONTENT, (device, "alias")) postEventToFrame( wxThread.myEVT_UPDATE_GAUGE, int(frame.gauge.GetValue() + 1 / maxGaugeAction * 100), ) postEventToFrame(wxThread.myEVT_LOG, logString) return (numNewName, succeeded)
def getAppVersion(version_id, application_id, maxAttempt=Globals.MAX_RETRY): api_instance = esperclient.ApplicationApi( esperclient.ApiClient(Globals.configuration)) enterprise_id = Globals.enterprise_id for attempt in range(maxAttempt): try: # Get app version information api_response = api_instance.get_app_version( version_id, application_id, enterprise_id) return api_response except ApiException as e: if attempt == maxAttempt - 1: ApiToolLog().LogError(e) print( "Exception when calling ApplicationApi->get_app_version: %s\n" % e) raise e time.sleep(1)