def run(self): #open the slot GPIO.output(SLOTS[self.slot - 1], True) UserDB.fillSlot(self.rfid, self.slot) #time.sleep(30) #wait the car till enter the slot. if not come after 6 min close the slot t = time.time() dt = 0 dd = distance(self.slot - 1) #wait if time is less than 6 min and dd greater than 11 #wait if dd between 12 cm and 2.5 meter while ((dt < 600 and dd > 11) or (dd > 4 and dd < 12)): dt = time.time() - t dd = distance(self.slot - 1) print(dd) #close the slot print('the slot is closed') time.sleep(1) GPIO.output(SLOTS[self.slot - 1], False) #change state of the slot from empty to busy if dd < 11: UserDB.changestate(self.slot, 1)
def restore_prcss(): code = request.session['restore'] print("CODE IS POST!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! = "+code) username = request.forms.get('username') new_psw = request.forms.get('new_password') new_psw_conf = request.forms.get('new_password_repeated') print(code, username, new_psw, new_psw_conf) if UserDB.check_link(code): print('check_link=checked') if UserDB.check_code(username, code): print('check_code=checked') if new_psw == new_psw_conf: UserDB.set(username, 'pw', hsh(new_psw)) cmnd = "DELETE FROM RestoreList WHERE username='******';" % username UserDB.db.query(cmnd) response.set_cookie("forgot", "from_restore") redirect('/') return "done" else: response.set_cookie("restore", "Пароли не совпадают") redirect('/restore') return ("err pw") #psw dont match response.set_cookie("restore", "Что-то не так :(") redirect('/restore') #something wrong
def main(): #intialize the components of the project setupComponents() # This loop keeps checking for chips. If one is near it will get the UID and authenticate nfc = TwoRfid.Nfc522() #create object to read from 2 different rfid while continue_reading: #read RFID of people entry and car entry gid1, gid2 = nfc.obtem_nfc_rfid() #handle car gate if not gid1 == 0: print("rfid reader of car gate read: ", gid1) buzzer.beep(1) name, slot, state = UserDB.AllowAccess(str(gid1), 0) if (state == 0): #this person has a reservation lcd.message("WELCOME ", name) time.sleep(2) lcd.message("Go To Slot", str(slot)) ServoMotor.OpenGate() #open the gate #wait till the car pass the gate if (UltraSonicSensor.IsPassed()): UserDB.changeState(gid1) time.sleep(3) ServoMotor.CloseGate() #close the gate #make microController open specific slot openSlot(str(gid1), slot) lcd.message("WELCOME IN", "SMART PARKING") elif (state == -2): #this person not has a reservation lcd.message("Please ", "Reserve First") time.sleep(5) lcd.message("WELCOME IN", "SMART PARKING") #handle person gate if not gid2 == 0: print("rfid reader of person gate read: ", gid2) buzzer.beep(1) name, slot, state = UserDB.IsReserve(str(gid2), 1) if state == 1: #this person has a car inside the garage #open the gate lcd.message("Here you are", "The Gate is open") GPIO.output(PERSON_GATE, True) time.sleep(6) GPIO.output(PERSON_GATE, False) else: lcd.message("Sorry You don't ", "Have car inside") time.sleep(5) lcd.message("WELCOME IN", "SMART PARKING")
def delusr(): if access_is('admin'): username = str(request.query.username) #username is the one we entered if UserDB.check(username): # deleting user UserDB.delete(username) return ("User "+username+" deleted!") else: return "No such user"
def forgot(): username = request.body.read() #response.set_cookie("forgot", "not_yet") if UserDB.check(username): response.set_cookie("forgot", "OK") code = str(uuid.uuid4()) email = UserDB.get(username).email print(email) send_message(email, code) UserDB.new_restore(username, code) return "Проверьте свою почту" else: response.set_cookie("forgot", "failed")
def addusr(): if access_is('admin'): his_username = request.forms.get('username') #getting info from the form his_password = hsh(request.forms.get('password')) his_access_level = request.forms.get('access_level') his_email = request.forms.get('email') his_FIO = request.forms.get('FIO') if UserDB.check(his_username): return "User already exists" UserDB.add(his_username, his_password, his_FIO, his_access_level, his_email) return ("created user: username="******", password="******", access_level="+his_access_level+", FIO="+his_email)
def restore_psw(): code = request.query.code request.session['restore'] = code #response.set_cookie("test", "cookietest") if UserDB.check_link(code): print('check_link') return stat_file("restore_pswd.html") return "wrong link"
def bind_user_QQ(): if request.method == 'POST': userid = request.form['userid'] userqq = request.form['userqq'] if UserDB.binding_qq(userid,userqq): return json.dumps({'status':'OK','data':'succ'}) else: return json.dumps({'status':'Fail','data':'succ'})
def get_following(api, centre, max_depth=3, curr_depth=0): if curr_depth > max_depth: return userfname = os.path.join(USER_DIR, str(centre) + ".json") if os.path.exists(userfname): return logging.info("User being mined is %s" % str(centre)) print("User being mined %s" % str(centre)) following = [] while True: try: i = 1 for friends in tweepy.Cursor(api.friends, screen_name=centre, count=200).items(): # print i,friends.screen_name i += 1 following.append(friends.screen_name) if i % 200 == 0: time.sleep(60) for name in following: get_following(api, name, max_depth, curr_depth + 1) UserDB.store_friends(api, centre, following) mentions.get_mentions(api, centre) break except tweepy.TweepError as error: print(str(error)) if str(error) == 'Not authorized.': print('Can' 't access user data - not authorized.') break if str(error) == 'User has been suspended.': print('User suspended.') break if str( error ) == "[{'message': 'Rate limit exceeded', 'code': 88}]" or str( error ) == "[{u'message': u'Rate limit exceeded', u'code': 88}]": print('Rate limited. Sleeping for 15 minutes.') logging.info('Rate limit exceeded at %s' % str(datetime.now())) time.sleep(15 * 60 + 15) continue return following
def chngpsw_process(): its_username = request.session['username'] old_password = request.forms.get('old_password') new_password = request.forms.get('new_password') new_password_conf = request.forms.get('new_password_repeated') if new_password != new_password_conf: return stat_file("smth_wrong_pwd.html") global d if (UserDB.check(its_username) and (pbkdf2_sha256.verify(old_password, UserDB.get(its_username).pw))): # if the username exists and the old password is correct UserDB.set(its_username, 'pw', pbkdf2_sha256.hash(new_password, rounds=HRN)) # generate new pwd hash logout() return stat_file("pwd_changed.html") return stat_file("smth_wrong_pwd.html")
def run(self): try: #wait till the client push the push button if he/she doesn't push it through 5 min ignore the request print(' leave thread') t = time.time() dt = 0 state = True #wait the client press the pB if he don't through 5 min ignore his request while (dt < 300 and state == True): dt = time.time() - t state = GPIO.input(PB_SLOTS[self.slot - 1]) #open the slot if state == False: while GPIO.input(PB_SLOTS[self.slot - 1]) == False: time.sleep(0.2) print('client push the button') GPIO.output(SLOTS[self.slot - 1], True) #wait 10 min untill the user take his/her car t = time.time() dt = 0 dd = distance(self.slot - 1) print(dd) while ((dt < 600 and dd < 200) or (dd > 4 and dd < 12)): dt = time.time() - t dd = distance(self.slot - 1) print(dd) #close the slot lock GPIO.output(SLOTS[self.slot - 1], False) if dd > 200: #make slot empty UserDB.changestate(self.slot, 0) except Exception as e: print('error in leavethread : ', e) finally: activeThreads[self.slot - 1] = 0
def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] try: if UserDB.login(username,password): return json.dumps({'status':'OK','data':'login'}) return json.dumps({'status':'WR','data':'login'}) except: return json.dumps({'status':'RT','data':'login'})
def receive_sms(): """Receives an SMS message and replies with a simple greeting.""" number = request.values.get('From') response = request.values.get('Body') resp = MessagingResponse() number = number[1:] greeting = UserDB.check_user(number) result = responseAnalyze(response, number, greeting) resp.message(result) return str(resp)
def getHourEnv(sampleCount, factor, apiKey): sampleCount = int(sampleCount) factor = int(factor) if not UserDB.checkApiKey(apiKey): return jsonify(error = Constants.ERROR_INVALID_API_KEY_CODE, msg = Constants.ERROR_INVALID_API_KEY) lastHour = 0 # Get the min time to get samples from lastTimeStamp = time.time() // factor * factor - (sampleCount * factor) lastIdx = len(envMonitor.envData) - 1 # Get the last data timedData = {} while(lastIdx >= 0 and envMonitor.envData[lastIdx]["time"] >= lastTimeStamp): hourBound = envMonitor.envData[lastIdx]["time"] // factor * factor if hourBound in timedData: timedData[hourBound].append(envMonitor.envData[lastIdx]) else: if len(timedData) + 1 > sampleCount: break timedData[hourBound] = [envMonitor.envData[lastIdx]] lastIdx -= 1 if sampleCount != len(timedData): Logger.LOG_WARNING(MODULE_NAME, Constants.WARNING_SAMPLE_COUNT_MISSMATCH, None) Logger.LOG_WARNING(MODULE_NAME, "Samples count: " + str(sampleCount) + " | " + str(len(timedData)), None) # Average on the samples samples = [] for timeValue in sorted(timedData): avgTemp = 0 avgHum = 0 avgLum = 0 for data in timedData[timeValue]: avgTemp += data["t"] avgHum += data["h"] avgLum += data["l"] dataCount = len(timedData[timeValue]) avgTemp /= dataCount avgHum /= dataCount avgLum /= dataCount samples.append({ "t": avgTemp, "h": avgHum, "l": avgLum, "time": timeValue }) return jsonify(error = 0, data = samples)
def adduser_song(): if request.method == 'POST': userid = request.form['userid'] songname = request.form['songname'] songmid = request.form['songmid'] interval = request.form['interval'] singers = request.form['singers'] album = request.form['album'] albummid = request.form['albummid'] videoid = request.form['videoid'] songid = request.form['songid'] # print(request.form) # songname,songmid,interval,singers,album,videoid,songid 是要加入到 userid 用户的歌单里的歌曲信息 UserDB.add_song_to(songname, songmid, interval, singers, album, albummid, videoid, songid) if UserDB.add_to(userid, songmid): UserDB.add_count(songmid) return json.dumps({'status':'OK','data':'succ'}) return json.dumps({'status':'DP','data':'exist'}) else: pass
def chngaccs(): if access_is('admin'): his_username = request.forms.get('username') new_access_level = request.forms.get('access_level') if UserDB.check(his_username): cmnd = "UPDATE UserList SET access_level='%s' WHERE username='******';" % (new_access_level, his_username) db.query(cmnd) return ("Access level for "+his_username+" changed to "+ new_access_level) return "No such user"
def main(): #intialize the components of the project setupComponents() nfc = TwoRfid.Nfc522() #create object to read from 2 different rfid # This loop keeps checking for chips. If one is near it will get the UID and authenticate while continue_reading: #read RFID gid1, gid2 = nfc.obtem_nfc_rfid() Uid = str(gid1) if not Uid == '0': person = False # Print UID print("Card read UID: " + Uid) #alter the user that the card is read buzzer.beep(1) ok = UserDB.allowExit(Uid) if ok: ServoMotor.OpenGate() #open the gate #wait till the car pass the gate if (UltraSonicSensor.IsPassed()): time.sleep(2) ServoMotor.CloseGate() #close the gate #remove this user from the db of slots #and also from the db of car entrance UserDB.freeSlot(Uid) else: print("this tag doesn't have car inside the garage") print("enter the correct one")
def sign(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] # print(request.form) try: if UserDB.register(username,password): return json.dumps({'status':'OK','data':'sign'}) # print('failed sign up') return json.dumps({'status':'DP','data':'sign'}) except : # print('except') return json.dumps({'status':'RT','data':'sign'}) pass
def chngemail(): global d global email if access_is('admin'): his_username = request.forms.get('username') new_email = request.forms.get('new_mail') if UserDB.check(his_username): cmnd = "UPDATE UserList SET fio='%s' WHERE username='******';" % (new_email, his_username) db.query(cmnd) return ("FIO for "+his_username+" changed to "+ new_email) return "No such user"
def ask_stop(stop_number, bus_agency, bus_number, setting, list): if stop_number and bus_agency and list: response = bus_agency + " " + stop_number + " list" elif stop_number and bus_number and bus_agency: response = bus_agency + " " + stop_number + " " + bus_number elif stop_number and bus_agency: response = bus_agency + " " + stop_number elif stop_number and bus_number: response = stop_number + " " + bus_number elif stop_number: response = stop_number else: return ask("Please Try Again") result = responseAnalyze(response, "1", UserDB.check_user("1")) return ask(result)
def messaging_events(payload): """Generate tuples of (sender_id, message_text) from the provided payload. """ data = json.loads(payload) messaging_events = data["entry"][0]["messaging"] print data for event in messaging_events: if "message" in event and "text" in event["message"]: response = event["message"]["text"].encode('unicode_escape') number = event["sender"]["id"] greeting = UserDB.check_user(number) result = responseAnalyze(response, number, greeting) yield event["sender"]["id"], result else: yield event["sender"]["id"], "I can't echo this"
def createUser(): try: print "in making users" postData = request.body.read() jsonData = json.loads(postData) emailId=jsonData[Constants.EMAILID] print "Email Id is " +emailId if emailId is None or emailId=="": errorResponse = cust_error(Constants.BAD_DATA,Constants.EMAIL_VALIDATION) return errorResponse else: retData = UserDB.createUser(jsonData) return retData except: errorResponse = cust_error(Constants.BAD_DATA,Constants.REQUIRED_FIELD_MISSING) return errorResponse
def DeleteClient(): jsData = request.get_json(silent=True) if type(jsData) == 'str': jsData = json.loads(jsData) i = len(jsData["slot"]) j = 0 response = {"status": []} while j < i: slot = int(jsData["slot"][j]) print(slot) response["status"].append(UserDB.DeleteClient(slot)) j = j + 1 print(response) response = json.dumps(response).encode('utf-8') return response
def isInside(): jsData = request.get_json(silent=True) if type(jsData) == 'str': jsData = json.loads(jsData) i = len(jsData["slot"]) j = 0 response = {"status": []} print(jsData['slot']) while j < i: response["status"].append(UserDB.isInside(int(jsData["slot"][j]))) j = j + 1 print(response) response = json.dumps(response).encode('utf-8') return response
def doLogin(): if request.method == "POST": username = request.form["username"] passwd = request.form["passwd"] user = UserDB.getUserByUsername(username) if(user == None): return jsonify(error=Constants.ERROR_INCORRECT_CRED_CODE, message=Constants.ERROR_INCORRECT_CRED_MSG) # Hash given password strToHash = username + passwd + str(user.regtime) hash = hashlib.sha256(strToHash.encode("utf-8")) if hash.hexdigest() == user.password: # Add user to session and redirect to dashboard flask_login.login_user(user) return jsonify(error=0) else: return jsonify(error=Constants.ERROR_INCORRECT_CRED_CODE, message=Constants.ERROR_INCORRECT_CRED_MSG) else: print("Accessed doLogin with incorrect method.") return jsonify(error=Constants.ERROR_UNAUTHORIZED_CODE, message=Constants.ERROR_UNAUTHORIZED_MSG)
def send_joke_msg_to_all(): print("开始-----joke------向所有好友发送消息") user_db = UserDB.query_user_data() joke_data = JokeDB.query_joke_data_desc() jokes = joke_data['data'] joke = jokes[0] joke_content = joke['content'] joke_id = joke['id'] JokeDB.update_chat_state(joke_id) users = user_db['data'] for user in users: notify_we_chat_by_user(joke_content, user) JokeDB.update_chat_state(joke_id) print("结束-----joke------向所有好友发送消息")
def getNASStatus(apiKey): if not UserDB.checkApiKey(apiKey): return jsonify(error = Constants.ERROR_INVALID_API_KEY_CODE, msg = Constants.ERROR_INVALID_API_KEY) # Get services status isSAMBAEnabled = os.system('sudo systemctl is-active --quiet smbd') == 0 isFTPEnabled = os.system('sudo systemctl is-active --quiet proftpd') == 0 total, used, free = shutil.disk_usage(Config.NASMountPoint) usedUnitIdx = 0 totalUnitIdx = 0 while(used > 1024): used = used / 1024 usedUnitIdx += 1 while(total > 1024): total = total / 1024 totalUnitIdx += 1 return jsonify(error=0, ftpEnabled=isFTPEnabled, smbdEnabled=isSAMBAEnabled, diskUsed = "{:.2f}".format(used), diskTotal = "{:.2f}".format(total), diskUsedUnit = STORE_UNIT[usedUnitIdx], diskTotalUnit = STORE_UNIT[totalUnitIdx], diskPercent = "{:.2f}".format(used / total * 100))
def deluser_song(): if request.method == 'POST': userid = request.form['userid'] songmid = request.form['songmid'] UserDB.delete_from(userid, songmid) return json.dumps({'status':'OK','data':'succ'})
def get_songlist(username): return UserDB.songlist_test(username)
def get_toplisten(): num = request.args.get('num') num = int(num) return UserDB.get_top(num)
import CommandLine import File import UserDB if __name__ == "__main__": shell = CommandLine.CLI(File.FileManager(), UserDB.UserManager()) shell.main_loop()
def getByUserId(userId): retData = UserDB.getByUserId(userId) return retData