def calculate_social(self): db=SQLConnection() db.daily_xp_difference() db.update_score_si() db.set_last_day_xp_to_xp() #social().calculate_social() # def hash_password(password): # # uuid is used to generate a random number # salt = uuid.uuid4().hex # return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt # def check_password(hashed_password, user_password): # password, salt = hashed_password.split(':') # return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest() # # new_pass = raw_input('Please enter a password: '******'The string to store in the db is: ' + hashed_password) # old_pass = raw_input('Now please enter the password again to check: ') # if check_password(hashed_password, old_pass): # print('You entered the right password') # else: # print('I am sorry but the password does not match')
def use_token(self, username): obj = SQLConnection() token = obj.get_plaid_token(username) self.client = Client(client_id='57cccae6cfbf49f67b01fd5a', secret='2c13981884395fc691fda11148ed67', access_token=token) response = self.client.connect_get(token) self.plaid_results = response.content return response.content
def __init__(self, f_id): db = SQLConnection() feed_info = db.get_feed(f_id) self.previous_frame = None if feed_info: self.url = feed_info["url"] self.vid_cap = cv2.VideoCapture(self.url) self.exist = True else: self.exist = False
def make_score_sleep(self): type = "sleep" db = SQLConnection() users = db.get_all_users() for username in users: if db.is_fitbit_setup(username): pet_name = db.find_pet_of_user(username) result = self.get_user_data(username, type) print result result = result['summary']['totalTimeInBed'] db.change_xp(username, result) print result db = SQLConnection() current_xp = db.get_xp(username) if result == 0: db.insert_events( username, "sleep", "home", 0, "You did not sleep with your fitbit, so your score was uneffected", "1", current_xp) elif result <= 400: db.insert_events( username, "sleep", "tired", -250, pet_name + " is tired from the lack of sleep. -250 xp", "1", current_xp) elif result <= 420: db.insert_events( username, "sleep", "tired", -125, pet_name + " is tired from the lack of sleep. -250 xp", "1", current_xp) else: db.insert_events( username, "sleep", "home", 250, pet_name + " feels great today! It must be from getting enough sleep. +250 xp", "1", current_xp)
def GetNewAccessToken(self, RefToken, username): print "Getting a new access token" #Form the data payload BodyText = {'grant_type': 'refresh_token', 'refresh_token': RefToken} #URL Encode it BodyURLEncoded = urllib.urlencode(BodyText) print "Using this as the body when getting access token >>" + BodyURLEncoded #Start the request tokenreq = urllib2.Request(self.TokenURL, BodyURLEncoded) #Add the headers, first we base64 encode the client id and client secret with a : inbetween and create the authorisation header tokenreq.add_header( 'Authorization', 'Basic ' + base64.b64encode(self.OAuthTwoClientID + ":" + self.ClientOrConsumerSecret)) tokenreq.add_header('Content-Type', 'application/x-www-form-urlencoded') #Fire off the request try: db = SQLConnection() tokenresponse = urllib2.urlopen(tokenreq) #See what we got back. If it's this part of the code it was OK FullResponse = tokenresponse.read() #Need to pick out the access token and write it to the config file. Use a JSON manipluation module ResponseJSON = json.loads(FullResponse) #Read the access token as a string NewAccessToken = str(ResponseJSON['access_token']) NewRefreshToken = str(ResponseJSON['refresh_token']) #Write the access token to the ini file db.update_fitbit_acc_token(username, NewAccessToken, NewRefreshToken) #self.WriteConfig(NewAccessToken,NewRefreshToken) #HERE YOU GO ROOS LOOK HERE BUDDY LOOK LOOK LOOK ################) print "New access token output >>> " + FullResponse except urllib2.URLError as e: #Gettin to this part of the code means we got an error print "An error was raised when getting the access token. Need to stop here" print e.code print e.read() sys.exit()
def first_time_plaid_transactions( self, username ): # add all plaid transactions that already occured into db obj = SQLConnection() id = obj.find_id_of_user(username) data = self.use_token(username) data = json.loads(data) for items in data['transactions']: add = False try: for things in items["category"]: if things == "Fast Food" or things == "Restaurants": add = True except: pass if add == True: obj.add_plaid_transactions_in_db( id, items["_id"] ) #adds the transaction id of any restraunts/fast_food
def GetConfig(self, username): print "Reading from the config file" db = SQLConnection() #Open the file # FileObj = open(IniFile,'r') # #Read first two lines - first is the access token, second is the refresh token # AccToken = FileObj.readline() # RefToken = FileObj.readline() AccToken = db.get_fitbit_acc_token(username) RefToken = db.get_fitbit_ref_token(username) # #Close the file # FileObj.close() #See if the strings have newline characters on the end. If so, strip them if (AccToken.find("\n") > 0): AccToken = AccToken[:-1] if (RefToken.find("\n") > 0): RefToken = RefToken[:-1] #Return values return AccToken, RefToken
def add_events_fitness(self): db = SQLConnection() users = db.get_all_users() category = "fitness" for username in users: if db.is_fitbit_setup(username): pet_name = db.find_pet_of_user(username) xp_change = self.make_score_fitness(username) type1 = 1 wore_fitbit = True if xp_change == None: db.insert_events( username, category, "no_effect", 0, "You did not sleep with your fitbit, so your score was uneffected", type1) wore_fitbit = False if wore_fitbit: db.change_xp(username, xp_change) if xp_change <= -300: message = "You have seriously harmed " + pet_name + " from neglagence yesterday. Make it up to " + pet_name + " by exercising today" pet_status = "sick" elif xp_change <= 100: message = pet_name + " is sad from the lack of exercise yesterday" pet_status = "sick" elif xp_change <= 300: message = pet_name + " got some exercise yesterday, but is still eager to play today " pet_status = "happy" else: message = pet_name + " got plenty of exercise yesterday and as a result he is very happy! +" + str( xp_change) + " xp" pet_status = "happy" print "added" current_xp = db.get_xp(username) db.insert_events(username, category, pet_status, xp_change, message, type1, current_xp)
def csv_to_db(db_name): # Create db object db = open(f'data/{db_name}.db', 'w') # Close file db.close() # Connect to created database conn = SQLConnection(f'data/{db_name}.db') # Get data from CSV using pandas sea_level_data = pd.read_csv(f'data/{db_name}.csv') # if_exists can be 'replace', 'append' or 'error' and defines behaviour when chosen table name already exists # conn defines the db this table is being added to sea_level_data.to_sql(db_name, conn, if_exists = 'replace', index = False) # Define a queue q = f'SELECT * FROM {db_name}' # Iterate through connection printing each row for r in conn.queue(q): print(r)
def check_plaid_event( self, username): #checks the database ids and plaid ids for differences plaid_list = self.get_list_of_restraunt_transactions(username) obj = SQLConnection() user_id = obj.find_id_of_user(username) database_list = obj.get_users_transactions(username) test = list(set(plaid_list) - set(database_list)) if test != []: #if there is a difference aka update data = self.plaid_results data = json.loads(data) for items in test: for things in data['transactions']: if things['_id'] == items: fast_food = False for classifications in things["category"]: if classifications == "Fast Food": fast_food = True if fast_food == True: obj.add_event_list(user_id, "1") obj.add_plaid_transactions_in_db( user_id, things['_id']) obj.change_xp(username, -500) else: obj.add_event_list(user_id, "2") obj.add_plaid_transactions_in_db( user_id, things['_id']) obj.change_xp(username, -250) return "done" # plaid().check_plaid_event("rwr21") #plaid().check_plaid_event("rwr21") # print type(response) # print type (response.content) # d = json.loads(response.content) # #print d # print type(d) # # print response.content # for items in d['transactions']: # #TODO SQL DATABSE TO KEEP TRACK OF LVL FAST FOOD -200 restraunt -100 # # print items['date'] # try: # for things in items['category']: # fast_food=False # if things=="Fast Food": #finds if user bought fast food # fast_food=True # #print items['name'] # if fast_food==False: # for things in items['category']: # if things=="Restaurants": # print things # print items['name']#finds name of restraunt that is not fast food # except: # pass # #print items # #print type (response.content.) # # User connected # data = response.json() # #rint SQLConnection().get_users_transactions("rwr21") #plaid().first_time_plaid_transactions("rwr21") #print plaid().use_token("rwr21") #plaid().create_user("rwr21","chase","rratcliffe57",p) #plaid().check_plaid_event("rwr21")
def create_user_plaid(self, username, account_type, bank_username, bank_password): try: response = self.client.connect(account_type, { 'username': bank_username, 'password': bank_password }) d = json.loads(response.content) access_token = d["access_token"] print access_token except plaid_errors.PlaidError, e: print e else: if response.status_code == 200: #print response.content db = SQLConnection() db.first_time_plaid(username, access_token) data = response.json() elif response.status_code == 201: print "yo" # MFA required try: mfa_response = answer_mfa(response.json()) except plaid_errors.PlaidError, e: print e else: print "@@@@@@@@@@@@@@@@@@" # check for 200 vs 201 responses # 201 indicates that additional MFA steps required # db.close()
def prediction(a_id): db = SQLConnection() return db.get_predictions(a_id, time_end=datetime.now() + timedelta(days=1))
def count(a_id): db = SQLConnection() return db.get_counts(a_id, time_start=datetime.now() - timedelta(days=1))
def feeds(a_id): db = SQLConnection() feeds = db.get_area_feeds(a_id) if not feeds: return {"Error": "Could not area with given a_id"}, 404 return feeds
def areas(): # https://stackoverflow.com/questions/48218065/programmingerror-sqlite-objects-created-in-a-thread-can-only-be-used-in-that-sa # using different connection and cursor instead of not checking same thread, in case of data corruption db = SQLConnection() return db.get_all_area()
def feed(f_id): db = SQLConnection() feed = db.get_feed(f_id) if not feed: return {"Error": "Could not find the feed with given f_id"}, 404 return feed