Пример #1
0
def generate_chart_from_couchdb(data_type, couchdb_db_name, chart_info,
                                ct_offset):

    # Get the data from couchdb
    couch_query = couchdb_location_url + couchdb_db_name + '/'\
                     + '_design/doc/_view/attribute_value?'\
                     + 'startkey=["{0}","{1}",{2}]&endkey=["{0}"]&descending=true&limit=60'.format(
                     chart_info['attribute'], chart_info['couchdb_name'], '{}')

    logger.debug('prepared couchdb query: {}'.format(couch_query))

    r = requests.get(
        couch_query,
        auth=(decrypt(couchdb_username_b64_cipher).decode('ascii'),
              decrypt(couchdb_password_b64_cipher).decode('ascii')))

    #- logger.info('couchdb response: status {}, text {}'.format(r.status_code, r.text))

    if r.status_code == 200:

        try:

            global enable_display_unit_error_msg
            enable_display_unit_error_msg = True
            v_lst = [
                float(apply_unit_conversion(x, chart_info))
                for x in r.json()['rows']
            ]

            td = timedelta(hours=ct_offset)
            ts_lst = [(datetime.fromtimestamp(x['value']['timestamp']) + td).strftime('%m/%d %I:%M %p')\
                      for x in r.json()['rows']]
            ts_lst.reverse()

            line_chart = pygal.Line(x_label_rotation=20,
                                    show_minor_x_labels=False)
            line_chart.title = chart_info['chart_title']
            line_chart.y_title = chart_info['y_axis_title']
            line_chart.x_title = chart_info['x_axis_title']

            line_chart.x_labels = ts_lst
            line_chart.x_labels_major = ts_lst[::8]

            #need to reverse order to go from earliest to latest
            v_lst.reverse()

            line_chart.add(chart_info['data_stream_name'], v_lst)

            f = line_chart.render()
            return {'bytes': f}

        except:
            logger.error('Chart generation failed: {}'.format(exc_info()[0]))
            return {'bytes': None}
    else:
        logger.error('Couchdb returned a bad status code: {}'.format(
            r.status_code))
        return {'bytes': None}
Пример #2
0
    def __enter__(self):
        try:

            self.s3 = boto3.Session(
                aws_access_key_id=decrypt(
                    fop_aws_access_key_id_b64_cipher).decode('utf-8'),
                aws_secret_access_key=decrypt(
                    fop_aws_secret_access_key_b64_cipher).decode('utf-8'),
                region_name="us-east-2").resource('s3')
            return self

        except:
            logger.error(
                'Exception encountered while connecting to s3: {}, {}, {}'.
                format(exc_info()[0],
                       exc_info()[1],
                       exc_info()[2]))
            raise
Пример #3
0
def send_file_to_s3(f: 'Open File', file_name: 'uuid'):

    try:
        session = boto3.Session(
            aws_access_key_id=decrypt(fop_aws_access_key_id_b64_cipher).decode(
                'utf-8'),
            aws_secret_access_key=decrypt(
                fop_aws_secret_access_key_b64_cipher).decode('utf-8'),
            region_name="us-east-2")

        s3 = session.resource('s3')

        s3.Bucket(image_file_bucket_name).put_object(Key=file_name.hex, Body=f)

    except:
        logger.error(
            'Exception encountered while uploading file to S3: {},{},{}'.
            format(exc_info()[0],
                   exc_info()[1],
                   exc_info()[2]))
        raise
Пример #4
0
def send_text(text_number, body):

    try:

        client = Client(
            decrypt(twilio_account_sid_b64_cipher).decode('utf-8'),
            decrypt(twilio_auth_token_b64_cipher).decode('utf-8'))

        message = client.messages\
            .create(
                body = body,
                from_ = decrypt(twilio_from_number_b64_cipher).decode('utf-8'),
                to = text_number)

        return {'error': False}

    except:

        logger.error('send_text: exception: {}, {}'.format(
            exc_info()[0],
            exc_info()[1]))
        return {'error': True}
Пример #5
0
def get_jws_secret_key(jws_value, issuer_types):

    iss_id = get_jwt_issuer(jws_value)
    logger.info('iss_id: {}'.format(iss_id))
    logger.info('issuer_types: {}'.format(issuer_types))
    sk = None
    
    if 'device' in issuer_types:
        sk = get_device_config_item(iss_id, 'hmac_secret_key_b64_cipher_text')

    if sk == None and 'configured' in issuer_types:
        sk = get_configured_issuer_jws_key(iss_id)

    if sk != None:
        return decrypt(sk)
    else:
        logger.warning('unable to find issuer key for issuer: {}'.format(iss_id))
        raise JwtError('cannot find issuer key')
Пример #6
0
def mqtt_connect(*args):
   """ args[0] = socketio
       args[1] = repl_state """
   try:
     
      #- emit('response', 'connecting to mqtt..')
      args[0].emit('response', 'connecting to mqtt..')

      mqtt_client = mqtt.Client('fopws')
      mqtt_client.on_message = make_on_message_handler(args[0])
      mqtt_client.on_subscribe = on_subscribe
      
      # Enforce tls certificate checking 
      mqtt_client.tls_set()
      mqtt_client.enable_logger(logger)

      mqtt_client.username_pw_set(mqtt_username, decrypt(mqtt_password))
      mqtt_client.connect(mqtt_url, mqtt_port, 60)

      # Start the MQTT client - loop_start causes the mqtt_client to spawn a background thread which
      #                         handles the mqtt commuications.  The loop_start call thus returns
      #                         control to this thread immediately.

      args[1]['mqtt_client'] = mqtt_client
      logger.info('starting an mqtt thread...')
      #- mqtt_client.loop_forever()
      mqtt_client.loop_start()

      # Camp out forever in order to keep Gunicorn happy
      while True:
          args[0].sleep(10)
          args[0].emit('mqtt thread alive')
      
      """-
      mqtt_client.loop_start()
      emit('response', 'connected as foobar')
      logger.info('started MQTT client')
      return mqtt_client
      """

   except:
      logger.error('Unable to create MQTT client: {} {}'.format(exc_info()[0], exc_info()[1]))
Пример #7
0
def make_image_request_jwt(org_id, camera_id):

    return jws.sign(get_image_request_claim(org_id, camera_id), 
                    decrypt(jws_secret_key_b64_enc),
                    algorithm='HS256')
Пример #8
0
def get_jws(path_name, camera_id):

    return jws.sign(claim_info(get_file_hash(path_name), extract_timestamp(path_name), camera_id), 
                    decrypt(jws_secret_key_b64_enc),
                    algorithm='HS256')
Пример #9
0
def get_jws(image_datetime, path_name, camera_id):

    return jws.sign(claim_info(get_file_hash(path_name),
                               image_datetime.timestamp(), camera_id),
                    decrypt(hmac_secret_key_b64_cipher),
                    algorithm='HS256')
Пример #10
0
            block_end_string='%)',
            variable_start_string='((',
            variable_end_string='))',
            comment_start_string='(#',
            comment_end_string='#)',
        ))


app = FopwFlask(__name__)

# TODO - Consider generating a new secret key everytime Flask is restarted. Flask
#        stores session data in the client on an enrypted cookie.  If you set a
#        new secret key everytime Flask is restarted then pre-restart sessions
#        become invalid after the restart.
#
app.secret_key = decrypt(flask_app_secret_key_b64_cipher)

# Inject Flask app into the socketio object.
socketio = SocketIO(app)

# This function has the side effect of injecting the fopdcw log handler into the
# flask.app logger.
logger = get_top_level_logger()

from logging import getLogger, DEBUG, INFO
from logger import get_the_fopdcw_log_handler

getLogger('flask_cors').level = INFO
getLogger('flask_cors').addHandler(get_the_fopdcw_log_handler())

#TODO: move this stuff to the configuration file