def patch_endpoints(self): try: full_host = "{}://{}/{}".format(settings.schema_pub, settings.host_pub, settings.api_version) data = { "authorize": "{}/authorize".format(full_host), "receive_token": "{}/receive-token".format(full_host), "devices_list": "{}/devices-list".format(full_host), "select_device": "{}/select-device".format(full_host) } url = settings.webhook_url logger.debug("Initiated PATCH - {} {}".format( url, self.session.headers)) logger.verbose(format_str(data, is_json=True)) resp = requests.patch(url, data=json.dumps(data), headers=self.session.headers) logger.verbose( "[patch_endpoints] Received response code[{}]".format( resp.status_code)) logger.verbose(format_str(resp.json(), is_json=True)) self.set_confirmation_hash() except Exception: logger.alert("Failed at patch endpoints! {}".format( traceback.format_exc(limit=5))) raise
def create_channel_id(self, device, channel_template, client_id): # Creating a new channel for the particular device"s id data = { "name": device.get("content", "Device"), "channeltemplate_id": channel_template, "remote_key": device.get('id'), "requesting_client_id": client_id } logger.debug("Initiated POST - {}".format(settings.api_server_full)) logger.verbose(format_str(data, is_json=True)) resp = self.session.post("{}/managers/self/channels".format( settings.api_server_full), json=data) logger.debug("[create_channel_id] Received response code[{}]".format( resp.status_code)) if resp.status_code == 412 and resp.json().get('code') == 2000: raise UnauthorizedException(resp.json().get('text')) if resp.status_code != 201: logger.debug(format_str(resp.json(), is_json=True)) raise Exception( f"Failed to create channel for channel template {channel_template} " f"{traceback.format_exc(limit=5)}") return resp.json()["id"]
def select_device(self, request): logger.debug( "\n\n\n\n\n\t\t\t\t\t*******************SELECT_DEVICE****************************" ) logger.debug("Received {} - {}".format(request.method, request.path)) logger.verbose("headers: {}".format(request.headers)) try: received_hash = request.headers.get("Authorization", "").replace("Bearer ", "") if self._validate_confirmation_hash(received_hash): if request.is_json: payload = request.get_json() logger.verbose(format_str(payload, is_json=True)) paired_devices = payload["channels"] if not paired_devices: logger.error( "No paired devices found in request: {}".format( payload)) else: return Response(status=422) owner_id = request.headers["X-Owner-Id"] client_id = request.headers["X-Client-Id"] channel_template = request.headers["X-Channeltemplate-Id"] channels, credentials = self.handle_channel_requests( client_id, owner_id, channel_template, paired_devices) sender = { "channel_template_id": channel_template, "client_id": client_id, "owner_id": owner_id } self.implementer.did_pair_devices( sender=sender, credentials=credentials, paired_devices=paired_devices, channels=channels) return Response(response=json.dumps(channels), status=200, mimetype="application/json") else: logger.debug("Provided invalid confirmation hash!") return Response(status=403) except Exception: logger.error("Couldn't complete processing request, {}".format( traceback.format_exc(limit=5))) return Response(status=403)
def inbox(self, request): logger.debug( "\n\n\n\n\n\t\t\t\t\t*******************INBOX****************************" ) logger.info("Received {} - {}".format(request.method, request.path)) logger.info("\n{}".format(request.headers)) if request.is_json: logger.info(format_str(request.get_json(), is_json=True)) else: logger.info("\n{}".format(request.get_data(as_text=True))) return self.handle_request(request)
def on_message(self, client, userdata, msg): try: topic = msg.topic payload = json.loads(msg.payload.decode("utf-8")) logger.debug( "\n\n\n\n\n\t\t\t\t\t******************* ON MESSAGE ****************************" ) logger.debug("Mqtt - Received on_message {topic} {payload}".format( topic=topic, payload=format_str(payload, is_json=True))) data = { "type": settings.implementor_type, "topic": topic, "payload": payload } if "io" in payload and payload["io"] in ("r", "w"): self.queue.put(data) except Exception: logger.error("Mqtt - Failed to handle payload. {}".format( traceback.format_exc(limit=5)))
channel_id=channel_id, component=case["component"], property=case["property"]) else: logger.warning( "Mqtt - Invalid arguments provided to publisher.") raise Exception (rc, mid) = self.mqtt_client.publish(topic=topic, payload=json.dumps(payload)) if rc == 0: logger.info( "Mqtt - Published successfully, result code({}) and mid({}) to topic: {} with payload:{}" .format(rc, mid, topic, format_str(payload, is_json=True))) else: raise Exception( "Mqtt - Failed to publish , result code({})".format(rc)) except Exception as e: logger.alert("Mqtt - Failed to publish , ex {}".format(e)) def mqtt_decongif(self): try: self.mqtt_client.unsubscribe( "/{api_version}/managers/{client_id}/channels/#".format( api_version=settings.api_version, client_id=settings.client_id))
def channels_grant(self, device, client_id, owner_id, channel_template, credentials): try: channel_template = self.implementer.update_channel_template( device['id']) or channel_template channel_id = self.get_or_create_channel(device, channel_template, client_id) if not channel_id: logger.warning("[channels_grant] No channel found") return False # Granting permission to intervenient with id X-Client-Id url = "{}/channels/{}/grant-access".format( settings.api_server_full, channel_id) try: data = { "client_id": client_id, "requesting_client_id": client_id, "role": "application", "remote_key": device.get('id') } logger.debug("Initiated POST - {}".format(url)) logger.verbose(format_str(data, is_json=True)) resp_app = self.session.post(url, json=data) logger.debug( "[channels_grant] Received response code[{}]".format( resp_app.status_code)) if resp_app.status_code == 412 and resp_app.json().get( 'code') == 2000: raise UnauthorizedException(resp_app.json().get('text')) if resp_app.status_code not in (201, 200): logger.debug(format_str(resp_app.json(), is_json=True)) return False except UnauthorizedException as e: logger.error(f"{e}") return False except Exception: logger.error("Failed to grant access to client {} {}".format( client_id, traceback.format_exc(limit=5))) return False # Granting permission to intervenient with id X-Owner-Id try: data = { "client_id": owner_id, "requesting_client_id": client_id, "role": "user", "remote_key": device.get('id') } logger.debug("Initiated POST - {}".format(url)) logger.verbose(format_str(data, is_json=True)) resp_user = self.session.post(url, json=data) logger.verbose( "[channels_grant] Received response code[{}]".format( resp_user.status_code)) if resp_app.status_code == 412 and resp_app.json().get( 'code') == 2000: raise UnauthorizedException(resp_app.json().get('text')) if resp_user.status_code not in (201, 200): logger.debug(format_str(resp_user.json(), is_json=True)) return False except UnauthorizedException as e: logger.error(f"{e}") return False except Exception: logger.error("Failed to grant access to owner {} {}".format( channel_template, traceback.format_exc(limit=5))) return False return channel_id except Exception: logger.error('Error while requesting grant: {}'.format( traceback.format_exc(limit=5))) return None