def refresh_token(user, cnx, cursor):
    request_params = {
        'grant_type': 'refresh_token',
        'refresh_token': user.get('refresh_token', '')
    }
    url = 'https://api.fitbit.com/oauth2/token'
    try:
        cres = (client_id + ":" + client_secret).encode()
        headers = {
            'Content-type': 'application/x-www-form-urlencoded',
            'Authorization': 'Basic ' + base64.b64encode(cres).decode()
        }

        request = Request(url,
                          urllib.parse.urlencode(request_params).encode(),
                          headers=headers)
        print(request_params)
        response = json.loads(
            urllib.request.urlopen(request).read().decode('utf-8'))

        dbhandler.updateTokens(response, cnx, cursor)

    except urllib.error.HTTPError as e:
        return err.fail(str(e))
    except urllib.error.URLError as e:
        return err.fail(str(e))
    def POST(self, var=None):

        # end point for eyetrack to send data
        if (var == 'eyetrack'):
            try:
                cnx = mysql.connector.connect(user=user,
                                              database='fitbittokens',
                                              password=password)
                cursor = cnx.cursor(buffered=True)

                data = json.loads(cherrypy.request.body.read().decode('utf-8'))
                print(data)

                # to do : check if data is valid...
                returni = dbhandler.addTrackerdata(data, cnx, cursor)
                cursor.close()
                cnx.close()
                return returni

            except Exception as e:
                return err.fail(str(e))

        # end point for benchmark to send data
        if (var == 'benchmark'):
            try:

                cnx = mysql.connector.connect(user=user,
                                              database='fitbittokens',
                                              password=password)
                cursor = cnx.cursor(buffered=True)

                data = json.loads(cherrypy.request.body.read().decode('utf-8'))
                print(data)

                returni = dbhandler.addBenchmark(data, cnx, cursor)
                cursor.close()
                cnx.close()
                return returni

            except Exception as e:
                return err.fail(str(e))

    # End point to get access token for DEVELOPMENT PUPROSE ONLY!
    # SOS STOP SEIS SECURITY RISK - WILL BE REMOVED WHEN NOT NEEDED!

        if (var == 'access_token'):
            cnx = mysql.connector.connect(user=user,
                                          database='fitbittokens',
                                          password=password)
            cursor = cnx.cursor(buffered=True)
            data = json.loads(cherrypy.request.body.read().decode('utf-8'))

            if ('user_id' not in data):
                err.fail()
            returni = dbhandler.getAccesstoken(data, cnx, cursor)
            cursor.close()
            cnx.close()

            return returni
Exemple #3
0
def getProcessed(user_id, date_from, date_to, interval, cnx, cursor):

    global query_getProcessed

    date_from_in = date_from
    date_to_in = date_to

    date_from = datetime.strptime(date_from, "%B %d, %Y %H:%M:%S")
    date_to = datetime.strptime(date_to, "%B %d, %Y %H:%M:%S")

    maindata = (user_id, date_from, date_to, int(interval))

    try:
        cursor.execute(query_getProcessed, maindata)
        cnx.commit()

        if (cursor.rowcount == 0):
            return err.fail('no data for this period')

        data = {
            "success": True,
            "time_from": str(date_from_in),
            "time_to": str(date_to_in),
            "datapoints": []
        }

        for (user_id, dt, sleep_eff, sleeping, main_sleep, heartrate, eyetrack,
             dynamic_eff, omfg, predict) in cursor:
            if (eyetrack == None):
                eyetrack = "{}"
            data['datapoints'].append({
                "user_id":
                user_id,
                "datetime":
                dt.strftime("%B %d, %Y %H:%M:%S"),
                "sleep_eff":
                sleep_eff,
                "sleeping":
                sleeping,
                "main_sleep":
                main_sleep,
                "heartrate":
                heartrate,
                "eyetrack":
                json.loads(eyetrack),
                "dynamic_eff":
                dynamic_eff,
                "omfg":
                omfg,
                "predict":
                predict
            })
        return data

    except Exception as e:
        return err.fail(str(e))
def get_sleep_data_by_date(user_id, datetime, cnx=None, cursor=None):
    try:
        maindata = (user_id, datetime)
        cursor.execute(query_get_sleep_data, maindata)
        cnx.commit()
        
        for val, in cursor:
            return {"success": True, "data" : json.loads(val)}       
        
        return err.fail()
    
    except Exception as e:
        return err.fail(str(e))
def get_eye_tracker_data_by_date(user_id, datetime, cnx=None, cursor=None):
    
    try:
        maindata = (user_id, datetime)
        print(f"maindata:{maindata}")
        cursor.execute(query_eyetracker_data_by_date, maindata)
        cnx.commit()
        
        for val, in cursor:
            return {"success": True, "data" : json.loads(val)}       
        
        return err.fail()
    
    except Exception as e:
        return err.fail(str(e))
def get_predicted_data_entries(user_id, datetime_from, cnx=None, cursor=None):
    # TODO: how to ensure all rows are fetched? 

    try:
        maindata = (user_id, datetime_from)
        cursor.execute(query_predicted_time_entries_by_user, maindata)
        cnx.commit()
        result = cursor.fetchall()   
        if(result):            
            return {"success": True, "data" : result}       
        
        return err.fail("No predicted data found.")
    
    except Exception as e:
        return err.fail(str(e))
def import_detailed_hr(data, cnx, cursor, date):

    try:
        url = 'https://api.fitbit.com/1/user/-/activities/heart/date/' + date + '/1d/1sec.json'

        request = Request(url)

        request.add_header('Authorization',
                           'Bearer ' + data.get('access_token', ''))
        hrs = json.loads(
            urllib.request.urlopen(request).read().decode('utf-8'))

        intradata = hrs.get('activities-heart-intraday', '')
        for hr in hrs.get('activities-heart', []):
            day = {}
            day['user_id'] = data.get('user_id', '')

            day['uniqueid'] = str(
                hashlib.sha256(
                    bytes(
                        day.get('user_id', '') + json.dumps(intradata),
                        'utf-8')).hexdigest())
            day['data'] = json.dumps(intradata)
            day['datetime'] = hr.get('dateTime', '')
            theday = dbhandler.addHrDetailed(day, cnx, cursor)

            if (not theday.get('success', False)):
                return theday
        return {"success": True}

    except Exception as e:
        return err.fail(str(e))
Exemple #8
0
def addTrackerdata(data, cnx, cursor):

    global query_setTrackerdata
    global query_addTrackerdata

    try:

        data['data']['datetime'] = data['datetime']
        dt = dateutil.parser.parse(data['datetime'])
        data['datetime'] = str(datetime(dt.year, dt.month, dt.day))
        data['unique_id'] = str(
            hashlib.sha256(
                bytes(
                    data.get('user_id', '') +
                    json.dumps(data.get('datetime', '')),
                    'utf-8')).hexdigest())

        maindata = (data['unique_id'], data['user_id'], data['datetime'], '[]')

        # set the data if not set
        cursor.execute(query_setTrackerdata, maindata)
        cnx.commit()

        # append data
        maindata = (str(json.dumps(data['data'])), data['unique_id'])

        cursor.execute(query_addTrackerdata, maindata)
        cnx.commit()

        return {"success": True}

    except Exception as e:
        return err.fail(str(e))
Exemple #9
0
def addBenchmark(data, cnx, cursor):

    global query_addBenchmark

    try:

        data['unique_id'] = str(
            hashlib.sha256(
                bytes(data['userId'] + json.dumps(data['data']['timeStamp']),
                      'utf-8')).hexdigest())
        data['data']['timeStamp'] = datetime.strptime(
            data['data']['timeStamp'], "%B %d, %Y %H:%M:%S")
        #(uniqueid, datetime, user_id, accuracy, averageReactionTime, memoryTestGrade, diaryEntry)
        maindata = (data['unique_id'], data['data']['timeStamp'],
                    data['userId'], data['data']['accuracy'],
                    data['data']['averageReactionTime'],
                    data['data']['memoryTestGrade'],
                    data['data']['diaryEntry'])
        cursor.execute(query_addBenchmark, maindata)
        cnx.commit()

        return {"success": True}

    except Exception as e:
        return err.fail(str(e))
def update_processed_entries(user_id, data_entries,cnx=None, cursor=None):
    global insert_processed_row
    print(f"going to update {len(data_entries)} rows")
    try:
        for entry in data_entries:
            columns, values = entry.get_values_to_sql_query(user_id)
            parameters = []

            for i in range(len(columns)):
                parameters.append("%s")
            parameters = ", ".join(parameters)
            query = insert_processed_row.replace("COLUMNS", ", ".join(columns)) 
            query = query.replace("PARAMETERS", parameters)       
            # print(query)
            
            
            maindata = []
            maindata.extend(values)
            maindata = tuple(maindata)
            
            # print(maindata)        
            cursor.execute(query, maindata)        
            cnx.commit()
        
        print("database updated")
        

    except Exception as e:
        return err.fail(str(e))
def confirm_predicted_values_before_time(user_id, datetime, cnx=None, cursor=None):
    
    try:
        maindata = (user_id, datetime)        
        cursor.execute(confirm_predicted_values_before_datetime, maindata)        
        cnx.commit()
        return {"success": True}
    
    except Exception as e:
        return err.fail(str(e))
Exemple #12
0
def getAccesstoken(data, cnx, cursor):

    global query_getAccesstoken

    try:
        cursor.execute(query_getAccesstoken, (data.get('user_id', ''), ))
        cnx.commit()
        if (cursor.rowcount == 0):
            return err.fail('no user')

        for (user_id, access_token) in cursor:
            asd = {
                'success': True,
                'user_id': user_id,
                'access_token': access_token
            }
            return asd

    except Exception as e:
        return err.fail(str(e))
Exemple #13
0
def getExpired(cnx, cursor):

    global query_getExpired

    try:
        cursor.execute(query_getExpired)
        cnx.commit()
        if (cursor.rowcount == 0):
            return err.fail("no expired users")
        expired_users = {"users": [], "success": True}
        for (user_id, refresh_token) in cursor:
            expired_users['users'].append({
                "user_id": user_id,
                "refresh_token": refresh_token
            })

        return expired_users

    except Exception as e:
        print()
        return err.fail()
def get_users(cnx=None, cursor=None):    
    try:
        cursor.execute(query_get_users)
        cnx.commit()
        data = {"success": True, "users":[]}
        for (user_id, access_token) in cursor:
            data['users'].append({"user_id": user_id, "access_token": access_token})

        return data
    
    except Exception as e:
        print("get_users encountered exception")
        return err.fail(str(e))
Exemple #15
0
def addTokens(data, cnx, cursor):

    global query_addTokens

    try:
        maindata = (data['user_id'], data['access_token'],
                    data['refresh_token'], data['expires_in'],
                    data['datetime'])
        cursor.execute(query_addTokens, maindata)
        cnx.commit()
        return {'success': True}

    except Exception as e:
        return err.fail(str(e))
Exemple #16
0
def getHrDetailed(data, cnx, cursor):
    global query_getHr_detailed

    try:
        maindata = (data['user_id'], data['datetime'])
        cursor.execute(query_getHr_detailed, maindata)
        cnx.commit()

        # Fetch the hr data if not found in db
        if (cursor.rowcount == 0):

            access = getAccesstoken(data, cnx, cursor)
            data.update({'access_token': access.get('access_token', '')})
            if (access.get('success', False)):
                if (functions.import_detailed_hr(data, data['datetime'], cnx,
                                                 cursor).get('success',
                                                             False)):

                    # Makes new request to db if the record would be now there.
                    try:
                        maindata = (data['user_id'], data['datetime'])
                        print(maindata)
                        cursor.execute(query_getHr_detailed, maindata)
                        cnx.commit()
                        if (cursor.rowcount == 0):
                            print("rawrarwar")

                    except Exception as e:
                        return err.fail(str(e))

        for val, in cursor:
            return {"success": True, "data": json.loads(val)}

        return err.fail()

    except Exception as e:
        return err.fail(str(e))
Exemple #17
0
def getUsers(cnx, cursor):

    global query_getUsers

    try:
        cursor.execute(query_getUsers)
        cnx.commit()
        data = {"success": True, "users": []}
        for (user_id, access_token) in cursor:
            data['users'].append({
                "user_id": user_id,
                "access_token": access_token
            })
        return data

    except Exception as e:
        return err.fail(str(e))
Exemple #18
0
def addSleepdata(data, cnx, cursor):

    global query_addSleepdata
    global query_getSleepCountDup
    global query_deleteSleep

    try:
        maindata = (data['user_id'], data['datetime'], data['uniqueid'])
        cursor.execute(query_getSleepCountDup, maindata)
        cnx.commit()
        for i, in cursor:
            if (int(i) != 0):
                maindata = (data['user_id'], data['datetime'])
                cursor.execute(query_deleteSleep, maindata)
                cnx.commit()

        maindata = (data['uniqueid'], data['user_id'], data['datetime'],
                    data['data'])
        cursor.execute(query_addSleepdata, maindata)
        cnx.commit()
        return {"success": True}

    except Exception as e:
        return err.fail(str(e.code))
Exemple #19
0
def addHrDetailed(data, cnx, cursor):

    global query_addHR_detaileddata
    global query_getHr_detailedCountDup
    global query_deleteHr_detailed

    try:
        maindata = (data['user_id'], data['datetime'], data['uniqueid'])
        cursor.execute(query_getHr_detailedCountDup, maindata)
        cnx.commit()
        i = cursor.fetchone()
        if (int(i[0]) != 0):
            maindata = (data['user_id'], data['datetime'])
            cursor.execute(query_deleteHr_detailed, maindata)
            cnx.commit()

        maindata = (data['uniqueid'], data['user_id'], data['datetime'],
                    data['data'])
        cursor.execute(query_addHR_detaileddata, maindata)
        cnx.commit()
        return {"success": True}

    except Exception as e:
        return err.fail(str(e))
    def GET(self,
            var=None,
            code='',
            user_id=None,
            date_time=None,
            time_from=None,
            time_to=None,
            interval=None):

        global client_id
        global client_secret

        ##################################################################
        # Endpoint for giving user consent to use their fitbit data.     #
        ##################################################################

        if (var == 'fitbit-permission'):
            params = {
                'client_id': client_id,
                'response_type': 'code',
                'scope':
                'activity heartrate location nutrition profile settings sleep social weight',
                'redirect_uri': 'https://riski.business/fitbit-callback'
            }
            url = 'https://www.fitbit.com/oauth2/authorize?'
            raise cherrypy.HTTPRedirect(url + urllib.parse.urlencode(params))

        ##################################################################
        # Callback from fitbit servers after user has given consent.     #
        ##################################################################

        # To do :  scope checks.

        if (var == 'fitbit-callback'):

            cnx = mysql.connector.connect(user=user,
                                          database='fitbittokens',
                                          password=password)
            cursor = cnx.cursor(buffered=True)

            request_params = {
                'grant_type': 'authorization_code',
                'code': code,
                'redirect_uri': 'https://riski.business/fitbit-callback',
                'client_id': client_id,
            }
            url = 'https://api.fitbit.com/oauth2/token'
            try:
                cres = (client_id + ":" + client_secret).encode()
                headers = {
                    'Content-type': 'application/x-www-form-urlencoded',
                    'Authorization':
                    'Basic ' + base64.b64encode(cres).decode()
                }
                request = Request(
                    url,
                    urllib.parse.urlencode(request_params).encode(),
                    headers=headers)
                response = json.loads(urlopen(request).read().decode())

                response['datetime'] = datetime.now()
                dbresponse = dbhandler.addTokens(response, cnx, cursor)
                cursor.close()
                cnx.close()
                return dbresponse

            except urllib.error.HTTPError as e:
                return err.fail(str(e.code))
            except urllib.error.URLError as e:
                return err.fail(str(e.code))

        if (var == 'eyetrack' and user_id is not None
                and date_time is not None):
            cnx = mysql.connector.connect(user=user,
                                          database='fitbittokens',
                                          password=password)
            cursor = cnx.cursor(buffered=True)
            try:
                params = cherrypy.request.params
                data = {
                    "user_id": params.get("user_id"),
                    "datetime": params.get("date_time")
                }
                returni = dbhandler.getTrackerdata(data, cnx, cursor)
                return returni

            except Exception as e:
                return err.fail(str(e))

        if (var == 'processed' and user_id is not None
                and time_from is not None and time_to is not None
                and interval is not None):

            cnx = mysql.connector.connect(user=user,
                                          database='fitbittokens',
                                          password=password)
            cursor = cnx.cursor(buffered=True)
            try:
                returni = dbhandler.getProcessed(user_id, time_from, time_to,
                                                 interval, cnx, cursor)
                return returni
            except Exception as e:
                return err.fail(str(e))