def apiv1_server_devicetypes_index(webinterface, request, session): try: offset = request.args.get('offset')[0] except: offset = 0 try: limit = request.args.get('limit')[0] except: limit = 50 try: search = request.args.get('search')[0] except: search = None url = '/v1/device_type?_pagestart=%s&_pagelimit=%s' % (offset, limit) if search is not None: url = url + "&?_filters[label]*%s&_filters[description]*%s&_filters[machine_label]*%s&_filteroperator=or" % ( search, search, search) try: results = yield webinterface._YomboAPI.request('GET', url) except YomboWarning as e: return return_error(request, e.message, e.errorno) data = { 'total': results['content']['pages']['total_items'], 'rows': results['data'], } request.setHeader('Content-Type', 'application/json') return json.dumps(data)
def apiv1_gateway_details_get(webinterface, request, session, gateway_id): session.has_access("gateway", gateway_id, "view", raise_error=True) if len(gateway_id) > 50 or isinstance(gateway_id, str) is False: return return_error(request, "invalid gateway_id format", 400) if gateway_id in webinterface._Gateways: gateway = webinterface._Gateways[gateway_id] return return_good(request, payload=gateway.asdict())
def page_module_phone_bandwidth_control_post(webinterface, request, session, apiauth): phonemodule = webinterface._Modules['Phone'] phone_bandwidth = webinterface._Modules['Phone_Bandwidth'] print("got apiauth: %s" % apiauth) if apiauth != phone_bandwidth.apiauth.auth_id: return return_error(request, message="invalid API Auth", code=400) try: data = json.loads(request.content.read()) except: return return_error(request, message="invalid JSON sent", code=400) results = "PHONE Bandwidth incoming request: %s" % data print(results) return results
def page_module_amazonalexa_reportstate_post(webinterface, request, session): amazonalexa = webinterface._Modules['AmazonAlexa'] try: data = json.loads(request.content.read()) except: return return_error(message="invalid JSON sent", code=400) # print("Alex data: %s - %s" % (type(data), data)) return "yes"
def apiv1_server_modules_show_one(webinterface, request, session, module_id): # action = request.args.get('action')[0] try: results = yield webinterface._YomboAPI.request( 'GET', '/v1/module/%s' % module_id) except YomboWarning as e: return return_error(request, e.message, e.errorno) request.setHeader('Content-Type', 'application/json') return json.dumps(results['data'])
def apiv1_server_dns_check_available(webinterface, request, session, dnsname): url = f"/v1/dns_domains/check_available/{dnsname}" auth_header = yield session.authorization_header(request) try: response = yield webinterface._YomboAPI.request("GET", url, authorization_header=auth_header) except YomboWarning as e: return return_error(request, e.message, e.errorno) return webinterface.render_api_raw(request, session, data=response.content["data"] )
def apiv1_server_dns_check_available(webinterface, request, session, dnsname): url = '/v1/dns/check_available/%s' % dnsname # url = '/v1/dns/check_available/sam' try: results = yield webinterface._YomboAPI.request('GET', url) except YomboWarning as e: return return_error(request, e.message, e.errorno) request.setHeader('Content-Type', 'application/json') return json.dumps(results['data'])
def apiv1_yombo_resources_dns_check_available(webinterface, request, session, dnsname): webinterface._Validate.id_string(dnsname) auth_header = yield session.authorization_header(request) try: response = yield webinterface._YomboAPI.request( "GET", f"/v1/dns_domains/check_available/{dnsname}", authorization_header=auth_header) except YomboWarning as e: print(f"aaaaaaaaaa = meta = {e.meta}") print(f"aaaaaaaaaa = content = {e.meta.content}") print(f"aaaaaaaaaa = response_code = {e.meta.response_code}") if hasattr(e, "meta") and "errors" in e.meta.content: return return_error(request, e.meta.content["errors"], e.meta.response_code) return return_error(request, e.message, e.error_code) return webinterface.render_api_raw( request, data=response.content["data"], data_type="dns_available", )
def apiv1_automation_list_items_get(webinterface, request, session): try: platform = request.args.get('platform')[0] except: return return_error(request, 'platform must be specified.') # try: # type = request.args.get('type')[0] # except: # return return_error('type must be specified.') webinterface._Automation.get_available_items(platform=platform) a = return_good(request, 'The list') request.setHeader('Content-Type', 'application/json') return json.dumps(a)
def apiv1_authkeys_rotate_get(webinterface, request, session, auth_id): webinterface._Validate.id_string(auth_id) session.is_allowed(AUTH_PLATFORM_AUTHKEY, "edit", auth_id) if len(auth_id) > 100 or isinstance(auth_id, str) is False: return return_error(request, "invalid auth_id format", 400) authkey = webinterface._AuthKeys[auth_id] auth_key_id_full = authkey.rotate() results = authkey.to_external() results["auth_key_id_full"] = auth_key_id_full return webinterface.render_api(request, data=JSONApi(authkey), data_type="auth_keys", )
def apiv1_device_details_get(webinterface, request, session, device_id): session.has_access("device", device_id, "view", raise_error=True) arguments = args_to_dict(request.args) if len(device_id) > 200 or isinstance(device_id, str) is False: return return_error(request, "invalid device_id format", 400) if device_id in webinterface._Devices: device = webinterface._Devices[device_id] else: return return_not_found(request, "Device not found") payload = device.asdict() if "item" in arguments: payload = payload[arguments["item"]] return return_good(request, payload=payload)
def page_module_amazonalexa_control_post(webinterface, request, session): session.has_access('device', '*', 'control', raise_error=True) amazonalexa = webinterface._Modules['AmazonAlexa'] try: data = json.loads(request.content.read()) except: logger.info("Invalid JSON sent to us, discarding.") return return_error(message="invalid JSON sent", code=400) logger.debug("Receiving incoming request data: {data}", data=data) message = data['directive'] results = yield amazonalexa.get_api_response(message) # print("Alex data control: %s - %s" % (type(data), data)) print("sending results: %s" % json.dumps(results)) return json.dumps(results)
def apiv1_system_tools_uptime(webinterface, request, session): if webinterface.starting == True: return return_error(request, payload='Not ready yet.') try: request_id = str(request.args.get('timeonly')[0]) if request_id == '1': return str(webinterface._Atoms['running_since']) except Exception as e: pass try: request_id = request.args.get('id')[0] except Exception as e: request_id = random_string(length=12) return return_good(request, payload={ 'id': request_id, 'time': str(webinterface._Atoms['running_since']), })
def apiv1_device_command_get_post(webinterface, request, session, device_id, command_id): session.has_access("device", device_id, "control", raise_error=True) if len(device_id) > 200 or isinstance(device_id, str) is False: return return_error(request, "invalid device_id format", 400) if len(command_id) > 200 or isinstance(command_id, str) is False: return return_error(request, "invalid command_id format", 400) try: wait_time = float(request.args.get("_wait")[0]) except: wait_time = 2 arguments = args_to_dict(request.args) pin_code = arguments.get("pin_code", None) delay = arguments.get("delay", None) max_delay = arguments.get("max_delay", None) not_before = arguments.get("not_before", None) not_after = arguments.get("not_after", None) inputs = arguments.get("inputs", None) if device_id in webinterface._Devices: device = webinterface._Devices[device_id] else: return return_not_found(request, "Device not found") try: device_command_id = device.command( cmd=command_id, auth=session, pin=pin_code, delay=delay, max_delay=max_delay, not_before=not_before, not_after=not_after, inputs=inputs, idempotence=request.idempotence, ) except KeyError as e: print( f"error with apiv1_device_command_get_post keyerror: {e}") return return_not_found( request, f"Error with command, it is not found: {e}") except YomboWarning as e: print(f"error with apiv1_device_command_get_post warning: {e}") return return_error(request, f"Error with command: {e}") DC = webinterface._DeviceCommands.device_commands[ device_command_id] if wait_time > 0: exit_while = False start_time = time() while (start_time > (time() - wait_time) and exit_while is False): yield sleep(.075) if DC.status_id >= 100: exit_while = True if len(device.status_history) > 0: status_current = device.status_history[0].asdict() else: status_current = None if len(device.status_history) > 1: status_previous = device.status_history[1].asdict() else: status_previous = None return return_good(request, payload={ "device_command_id": device_command_id, "device_command": DC.asdict(), "status_current": status_current, "status_previous": status_previous, })
def apiv1_statistics_echarts_buckets(webinterface, request, session): session.is_allowed(AUTH_PLATFORM_STATISTIC, "view") requested_stats = [] chart_label = request.args.get("chart_label", [None, ])[0] time_last = request.args.get("last", [1209600, ])[0] time_start = request.args.get("start", [None, ])[0] time_end = request.args.get("end", [None, ])[0] stat_chart_type = request.args.get("stat_chart_type", [None, ]) stat_chart_label = request.args.get("stat_chart_label", [None, ]) stat_type = request.args.get("stat_type", [None, ]) stat_name = request.args.get("stat_name", [None, ]) bucket_size = request.args.get("bucket_size", [3600, ]) if chart_label is None: chart_label = stat_name try: if time_start is not None: try: time_start = int(time_start) except Exception as e: return return_error(request, "'time_start' must be an int and must be greater than 0") if time_start < 0: return return_error(request, "'time_start' must be an int and must be greater than 0") my_time_start = time_start else: my_time_start = 0 except Exception as e: my_time_start = None try: if time_last is not None: time_last = int(time_last) if time_last < 0: return return_error(request, "'time_last' must be an int and must be greater than 0.") my_time_start = int(time()) - time_last except Exception as e: pass if my_time_start is None: return return_error(request, f"'time_start' not included for stat: {stat_name}") try: if time_end is not None: if not isinstance(time_end, int) or time_end < 0: return return_error(request, "'time_end' must be an int and must be greater than 0") my_time_end = time_end else: my_time_end = time() except Exception as e: return return_error(request, f"'time_end' not included for stat: {stat_name}") for idx, item in enumerate(stat_name): # print(" checking: %s - %s" % (idx, item)) if item is None: break if stat_name[idx] is None: return return_error(request, "'stat_name' is required.") if not isinstance(stat_name[idx], str): return return_error(request, f"'stat_name' Must be a string. Got: {stat_name}") my_stat_name = stat_name[idx] try: if stat_type[idx] is not None: if isinstance(stat_type[idx], str) is False: return return_error(request, "'stat_type' Must be a string") if stat_type[idx] not in ("counter", "datapoint", "average"): return return_error(request, "'stat_type' must be either: 'counter', 'datapoint', or 'average'") my_stat_type = stat_type[idx] else: my_stat_type = None # return return_error(request, "'stat_type' is None, must be either: 'counter', 'datapoint', or 'average'") except Exception as e: my_stat_type = None # return return_error(request, "'stat_type' not included for stat: %s" % stat_name[idx]) try: if stat_chart_type[idx] is not None: if isinstance(stat_chart_type[idx], str) is False: return return_error(request, f"'stat_chart_type' Must be a string, got: {type(stat_chart_type[idx])}") if stat_chart_type[idx] not in ("bar", "line"): return return_error(request, "'stat_chart_type' must be either: 'bar' or 'line'") my_stat_chart_type = stat_chart_type[idx] else: my_stat_chart_type = "bar" except Exception as e: my_stat_chart_type = "bar" try: if stat_chart_label[idx] is not None: if isinstance(stat_chart_label[idx], str) is False: return return_error(request, "'stat_chart_label' Must be a string") my_stat_chart_label = stat_chart_type[idx] else: my_stat_chart_label = my_stat_name except Exception as e: my_stat_chart_label = my_stat_name try: if bucket_size[idx] is not None: try: bucket_size[idx] = int(bucket_size[idx]) except Exception as e: return return_error(request, "'bucket_size' must be an int and must be greater than 0") if bucket_size[idx] < 0: return return_error(request, "'bucket_size' must be an int and must be greater than 0") if bucket_size[idx] < 0: return return_error(request, "'bucket_size' must be an int and must be greater than 0.") my_bucket_size = int(bucket_size[idx]) else: my_bucket_size = bucket_size except Exception as e: my_bucket_size = bucket_size records = yield webinterface._LocalDB.database.get_stats_sums(my_stat_name, bucket_size=my_bucket_size, bucket_type=my_stat_type, time_start=my_time_start, time_end=my_time_end, ) labels = [] data = [] live_stats = webinterface._Statistics.get_stat(my_stat_name, my_stat_type) for record in records: labels.append(epoch_to_string(record["bucket"], "%Y/%-m/%-d %H:%M")) data.append(record["value"]) for record in live_stats: labels.append(epoch_to_string(record["bucket"], "%Y/%-m/%-d %H:%M")) data.append(record["value"]) requested_stats.append({ "name": my_stat_chart_label, "type": my_stat_chart_type, "data": data, }) if len(requested_stats) == 0: return return_error(request, "Not enough valid requested stats.") results = { "title": {"text": chart_label}, "toolbox": { "show": "true", "feature": { "dataZoom": { "show": "true", "title": { "zoom": "Select Zoom", "back": "Reset Zoom" }, }, "dataView": { "show": "true", "title": "View", "lang": ["View", "Cancel", "Save"] }, "restore": { "show": "true", "title": "Restore" }, "saveAsImage": { "show": "true", "title": "Save as image", "type": "png", "lang": ["Save as image"] }, }, }, "dataZoom": { "show": "true", }, "tooltip": {"show": "true"}, "legend": {"data": ["Legend here"]}, "xAxis": [{"type": "category", "data": labels}], "yAxis": [{"type": "value"}], "series": requested_stats, } request.setHeader("Content-Type", CONTENT_TYPE_JSON) return json.dumps(results)
def apiv1_devices_command_get_post(webinterface, request, session, device_id, command_id): webinterface._Validate.id_string(device_id) webinterface._Validate.id_string(command_id) session.is_allowed(AUTH_PLATFORM_DEVICE, "control", device_id) try: wait_time = float(request.args.get("_wait")[0]) except: wait_time = 2 print(f"rrequest.content.read(): {request.content.read()}") print(f"request.processed_body: {request.processed_body}") print( f"request.processed_body_encoding: {request.processed_body_encoding}" ) print(f"request.args: {request.args}") if request.processed_body is not None: arguments = request.processed_body else: arguments = request_args(request) pin_code = arguments.get("pin_code", None) delay = arguments.get("delay", None) max_delay = arguments.get("max_delay", None) not_before = arguments.get("not_before", None) not_after = arguments.get("not_after", None) inputs = arguments.get("inputs", None) if device_id in webinterface._Devices: device = webinterface._Devices[device_id] else: return return_not_found(request, "Device id not found") if command_id in webinterface._Commands: command = webinterface._Commands[command_id] else: return return_not_found(request, "Command id not found") print(f"device control, input: {inputs}") try: device_command_id = yield device.command( command=command, authentication=session, pin=pin_code, delay=delay, max_delay=max_delay, not_before=not_before, not_after=not_after, inputs=inputs, request_context=f"api/v1:{request.getClientIP()}" # idempotence=request.idempotence, ) except KeyError as e: print( f"error with apiv1_device_command_get_post keyerror: {e}") return return_not_found( request, f"Error with command, it is not found: {e}") except YomboWarning as e: print(f"error with apiv1_device_command_get_post warning: {e}") return return_error(request, f"Error with command: {e}") DC = webinterface._DeviceCommands.device_commands[ device_command_id] if wait_time > 0: exit_while = False start_time = time() while (start_time > (time() - wait_time) and exit_while is False): yield sleep(.075) if DC.status_id >= 100: exit_while = True if len(device.state_history) > 0: status_current = device.state_history[0].to_dict( include_meta=False) else: status_current = None if len(device.state_history) > 1: status_previous = device.state_history[1].to_dict( include_meta=False) else: status_previous = None return webinterface.render_api( request, data=JSONApi( data={ "type": device_command_id, "id": device_command_id, "attributes": { "id": device_command_id, "device_id": device.device_id, "command_id": DC.command_id, "device_command_id": device_command_id, "device_command": DC.to_dict(include_meta=False), "status_current": status_current, "status_previous": status_previous, } }), data_type="device_commands", )