def callback(message):
    global nest_metadata_last_refresh
    try:
        logger.debug(message.data.decode('UTF-8'))
    except Exception as e:
        message = eh.formatexception(e)
        logger.critical(message)
    logger.debug('Starting Callback')
    try:
        payload = message.data.decode('UTF-8')
        json_payload_1 = json.loads(payload)
        json_payload_2 = scrubpayload(json_payload_1)
        nest_metadata_last_refresh = pullmetainfo(nest_metadata_last_refresh)
        json_payload_3 = applymetadata(json_payload_2)
        json_payload_4 = pullimages(json_payload_3)
        insert_id = mi.insertnestpayload(json_payload_4)
        logger.debug(insert_id)
    except Exception as e:
        message = eh.formatexception(e)
        logger.critical(message)

    logger.debug('Starting ack')
    try:
        message.ack()
    except Exception as e:
        message = eh.formatexception(e)
        logger.critical(message)
def scrubpayload(payload):
    try:
        if 'events' in payload['resourceUpdate']:
            logger.info('An "event" was raised...')
            list = []
            for key in payload['resourceUpdate']['events'].keys():
                logger.info(f'event:{key}')
                list.append(key)
            for this_key in list:
                payload['resourceUpdate']['events'][this_key.replace('.', '_')] = \
                    payload['resourceUpdate']['events'].pop(this_key)
    except Exception as e:
        message = eh.formatexception(e)
        logger.critical(message)

    try:
        if 'traits' in payload['resourceUpdate']:
            logger.info('A "trait" was raised...')
            list = []
            for key in payload['resourceUpdate']['traits'].keys():
                logger.info(f'trait:{key}')
                list.append(key)
            for this_key in list:
                payload['resourceUpdate']['traits'][this_key.replace('.', '_')] = \
                    payload['resourceUpdate']['traits'].pop(this_key)
    except Exception as e:
        message = eh.formatexception(e)
        logger.critical(message)

    return payload
def pullmetainfo(last_refresh):
    perform_refresh = False
    if last_refresh < datetime.now(timezone.utc):
        last_refresh = datetime.now(
            timezone.utc) + timedelta(minutes=nest_metadata_expiration_seconds)
        perform_refresh = True
    if perform_refresh:
        try:
            logger.info('Connecting to MongoDB, pulling auth')
            token = mi.getnestapiaccesstoken()
            logger.info('Retrieving Devices')
            url = f'https://smartdevicemanagement.googleapis.com/v1/enterprises/{os.getenv("Google_Nest_Prodect_ID")}/devices'
            headers = {
                'Content-Type': 'application/json',
                'Authorization': f'Bearer {token}'
            }
            response = requests.get(url=url, headers=headers)
            response_json = json.loads(response.text)
            for device in response_json['devices']:
                nest_metadata['devices'][device['name']] = \
                    {
                        'type': device['type'].replace('.', '_'),
                        'displayName': device['parentRelations'][0]['displayName']
                    }

            logger.info(f'Meta Downloaded')
        except Exception as e:
            message = eh.formatexception(e)
            logger.critical(message)
    return last_refresh
def applymetadata(payload):
    try:
        payload['resourceUpdate']['type'] = nest_metadata['devices'][
            payload['resourceUpdate']['name']]['type']
        payload['resourceUpdate']['displayName'] = \
            nest_metadata['devices'][payload['resourceUpdate']['name']]['displayName']
    except Exception as e:
        message = eh.formatexception(e)
        logger.critical(message)
    return payload
def pullimages(payload):
    try:
        if 'events' in payload['resourceUpdate']:
            for key in payload['resourceUpdate']['events'].keys():
                if 'Camera' in key:
                    access_token = mi.getnestapiaccesstoken()
                    image_uid = pullimage(
                        device_id=payload['resourceUpdate']['name'],
                        event_id=payload['resourceUpdate']['events'][key]
                        ['eventId'],
                        access_token=access_token,
                        payload=payload)
                    payload['resourceUpdate']['events'][key][
                        'image_uid'] = image_uid

    except Exception as e:
        message = eh.formatexception(e)
        logger.critical(message)

    return payload
예제 #6
0
                    'client_id': connection['client_id'],
                    'client_secret': connection['client_secret'],
                    'refresh_token': connection['refresh_token'],
                    'grant_type': 'refresh_token'
                }
                response = requests.post(connection['token_uri'],
                                         params=payload)

                refresh_response = json.loads((response.text))

                new_experation = (datetime.now(timezone.utc) + timedelta(
                    seconds=refresh_response['expires_in'])).timestamp()

                my_query = {'_id': connection['_id']}
                new_values = {
                    "$set": {
                        "access_token": refresh_response['access_token'],
                        'expires_in': refresh_response['expires_in'],
                        'expires_at': new_experation
                    }
                }

                mi.updateauthrecord(my_query, new_values)
                logger.info(f'Refresh {str(connection["_id"])} complete')
            except Exception as e:
                message = eh.formatexception(e)
                logger.critical(message)
    except Exception as e:
        message = eh.formatexception(e)
        logger.critical(message)