async def send_notify_multiple(list_user_id, title, content, id_datkham): if(title is None or title == ""): title = "Thông báo đặt khám" notify_record = Notify() notify_record.title = title notify_record.content = content notify_record.type = "text" notify_record.action = {"datkham_id":str(id_datkham)} db.session.add(notify_record) db.session.flush() notify_record.url = app.config.get("DOMAIN_URL") + "/#dangkykham/model?id="+str(id_datkham) notify_user_list = [] for uid in list_user_id: notify_user = NotifyUser() notify_user.user_id = uid notify_user.notify_id = notify_record.id notify_user.notify_at = floor(time.time()) db.session.add(notify_user) # notify user user_notify_token = redisdb.get("notify_token:" + str(uid)) if user_notify_token is not None: user_notify_token = user_notify_token.decode('utf8') notify_user_list.append(user_notify_token) db.session.commit() await send_firebase_notify(notify_user_list, title, to_dict(notify_record))
async def reset_password(request): if request.method == 'GET': token = request.args.get("token", None) static_url = app.config.get("DOMAIN_URL")+"/"+app.config.get("STATIC_URL", "") return jinja.render('email/reset_password.html', request, static_url = static_url, token=token) if request.method == 'POST': token = request.form.get("token", None) password = request.form.get("password", None) confirm_password = request.form.get("confirm_password", None) if token is None or password is None: return json({"error_code": "PARAM_ERROR", "error_message": "Tham số không hợp lệ, vui lòng thực hiện lại"}, status=520) uid_current = redisdb.get("sessions:" + token) if uid_current is None: return json({"error_code": "SESSION_EXPIRED", "error_message": "Hết thời gian thay đổi mật khẩu, vui lòng thực hiện lại"}, status=520) redisdb.delete("sessions:" + token) user = User.query.filter(User.id == str(uid_current.decode('ascii'))).first() if (user is not None): user.password = auth.encrypt_password(password) auth.login_user(request, user) db.session.commit() return text(u'bạn đã lấy lại mật khẩu thành công. mời bạn đăng nhập lại để sử dụng!') else: return text('Không tìm thấy tài khoản trong hệ thống, vui lòng thử lại sau!')
async def reset_password(request): if request.method == 'GET': token = request.args.get("token", None) static_url = app.config.get("DOMAIN_URL")+"/"+app.config.get("STATIC_URL", "") return jinja.render('email/reset_password.html', request, static_url = static_url, token=token) if request.method == 'POST': token = request.form.get("token", None) password = request.form.get("password", None) confirm_password = request.form.get("confirm_password", None) if token is None or password is None: return json({"error_code": "PARAM_ERROR", "error_message": "Invalid value, please check again"}, status=520) uid_current = redisdb.get("sessions:" + token) if uid_current is None: return json({"error_code": "SESSION_EXPIRED", "error_message": "Timeout to change password, please select again"}, status=520) redisdb.delete("sessions:" + token) user = User.query.filter(User.id == str(uid_current.decode('ascii'))).first() if (user is not None): user.password = auth.encrypt_password(password) auth.login_user(request, user) db.session.commit() return text(u'Password change was successful.') else: return text('User account not found, please select again!')
async def send_notify_single(user_id, title, content, notify_type ,url, iteminfo): try: if(title is None or title == ""): title = "Thông báo kết quả" notify_record = Notify() notify_record.title = title notify_record.content = content notify_record.type = notify_type notify_record.iteminfo = iteminfo notify_record.url = url db.session.add(notify_record) db.session.flush() notify_user = NotifyUser() notify_user.user_id = user_id notify_user.notify_id = notify_record.id notify_user.notify_at = floor(time.time()) db.session.add(notify_user) db.session.commit() iteminfo["url"] = url iteminfo["content"] = content iteminfo["title"] = title data_notify = iteminfo firebase_token = redisdb.get("notify_token:" + str(user_id)) print("send_notify_single.token===",firebase_token) if firebase_token is not None: firebase_token = firebase_token.decode('utf8') await send_firebase_notify(firebase_token, content, data_notify) firebase_token_web = redisdb.get("notify_token_web:" + str(user_id)) print("firebase_token_web=====",firebase_token_web) if firebase_token_web is not None: firebase_token_web = firebase_token_web.decode('utf8') data_notify_web = {"title":title, "content":content, "url":url} webpush_message(firebase_token_web,title,content, data_notify_web) # await send_firebase_notify(firebase_token_web, content, to_dict(notify_record)) except Exception as error: print(error) pass
def current_uid(request): user_token = request.headers.get("X-USER-TOKEN", request.args.get("access_token", None)) if user_token is None: return None uid = redisdb.get("sessions:" + user_token) if uid is not None: return uid.decode('utf8') return None
async def send_notify_single(user_id, notify_data): # title = db.Column(String, index=True) # content = db.Column(String) # type = db.Column(String(20)) # text/image/video # url = db.Column(String) # action = db.Column(JSONB()) # notify_condition = db.Column(JSONB()) data = request.json firebase_token = redisdb.get("notify_token:" + user_id) if firebase_token is not None: firebase_token = firebase_token.decode('utf8')
def current_uid(request): user_token = request.headers.get("X-USER-TOKEN", None) print("user_token=======================", user_token) if user_token is None: return None uid = redisdb.get("sessions:" + user_token) if uid is not None: p = redisdb.pipeline() p.set("sessions:" + user_token, uid) p.expire("sessions:" + user_token, app.config.get('SESSION_EXPIRED', 86400)) p.execute() return uid.decode('utf8') return None
async def send_notify(request): data = request.json phone_number = data.get("phone_number", None) if phone_number is not None: user = db.session.query(User).filter( User.phone_number == phone_number).first() print("user: "******"notify_token:" + str(user.id)) print("firebase_token: ", firebase_token) if firebase_token is not None: firebase_token = firebase_token.decode('utf8') await send_firebase_notify([firebase_token], data.get("title", "Test"), data) return json({})
async def test_notify(request): # uid_current = current_uid(request) # if uid_current is None: # return json({ # "error_code": "USER_NOT_LOGIN", # "error_message": None # }, status=520) data = request.json uid_current = data.get("uid",None) firebase_token = redisdb.get("notify_token:" + str(uid_current)) if firebase_token is not None: firebase_token = firebase_token.decode('utf8') await send_firebase_notify([firebase_token], data.get("content", ""), data) return json({}) else: return json({"error_code": "KEY_NOT_SET", "error_message": ""}, status=520)
async def register_active(request): data = request.json uid = data.get('uid', None) active = data.get('active', None) check_token = redisdb.get("session-reset-password:"******"session-reset-password:"******"active====" + active) if check_token is not None: str_active = check_token.decode('utf8') print("str_active==" + str_active) if active != str_active: return json( { "error_code": "ACTIVE_FAILED", "error_message": "Mã số không hợp lệ" }, status=520) else: user = db.session.query(User).filter( and_(User.id == uid, User.deleted == False)).first() if user is None: return json( { "error_code": "ACTIVE_FAILED", "error_message": "Tham số không hợp lệ" }, status=520) # user.active = 1 # db.session.commit() result = response_current_user(user) return json(result, status=200) else: return json( { "error_code": "ACTIVE_FAILED", "error_message": "Mã số hết hạn sử dụng, vui lòng thử lại" }, status=520)
async def test_notify(request): currentUser = await current_user(request) if currentUser is None: return json({ "error_code": "USER_NOT_LOGIN", "error_message": None }, status=520) data = request.json firebase_token = redisdb.get("notify_token:" + str(currentUser.id)) if firebase_token is not None: firebase_token = firebase_token.decode('utf8') # data = { # "data": { # "push_type": "UPDATE_TRANSACTION", # "transaction_hash": transaction_hash, # "title": body # }, # "notification" : { # "body": body, # "sound": "bell.mp3" # }, # "registration_ids": [from_token] # } await send_firebase_notify([firebase_token], data.get("title", "Thông báo"), data) return json({}) else: return json( { "error_code": "KEY_NOT_SET", "error_message": "KEY_NOT_SET" }, status=520)
async def postprocess_send_notify_cosoKCB(request=None, Model=None, result=None, **kw): notify_condition = result["notify_condition"] if notify_condition is not None: notify_user_list = [] for condition in notify_condition: user = [] if condition.get("notify_type", "") == "TO_ALL": user = db.session.query(User).has_role("CoSoKCB").all() if condition.get("notify_type", "") == "TO_PHONE": phone_list = condition.get("notify_phone_number", []) for phone in phone_list: user = db.session.query(User).filter( User.phone_number == phone).first() user = user.append(user) for user in user: notify_user = NotifyUser() notify_user['user_id'] = str(user.id) notify_user['notify_id'] = result["id"] notify_user['notify_at'] = floor(time.time()) db.session.add(notify_user) # notify user user_notify_token = redisdb.get("notify_token:" + str(user.id)) if user_notify_token is not None: user_notify_token = user_notify_token.decode('utf8') notify_user_list.append(user_notify_token) db.session.commit() noti_data = {"push_type": "NORMAL", "notify_id": result["id"]} await send_firebase_notify(notify_user_list, result["title"], noti_data)
def check_token_app(token): uid = redisdb.get("sessions:" + user_token) if uid is not None: return uid.decode('utf8') return None
async def dmoss_upload_dengue_notification_module(request): data = request.headers uid = redisdb.get("sessions:" + data['X-Auth-Token']) if uid is not None: redisdb.delete("sessions:" + data['X-Auth-Token']) url = app.config['FILE_SERVICE_URL'] fsroot = app.config['FS_ROOT'] if request.method == 'POST': file = request.files.get('file', None) if file : print ('____________________yes file_____') rand = ''.join(random.choice(string.digits) for _ in range(15)) file_name = os.path.splitext(file.name)[0] extname = os.path.splitext(file.name)[1] newfilename = file_name + "-" + rand + extname new_filename = newfilename.replace(" ", "_") async with aiofiles.open(fsroot + new_filename, 'wb+') as f: await f.write(file.body) title = pandas.read_excel("static/uploads/"+new_filename,header=0) df = pandas.read_excel("static/uploads/"+new_filename,header=1) count = df.Province.count() i = 0 arr = [] while i < count: obj = {} obj['Province'] = df.Province[i] obj['Month'] = df.Month[i] obj['ThresholdDescription'] = df.ThresholdDescription[i] obj['ThresholdValue'] = df.ThresholdValue[i] obj['ExceedanceProbability'] = df.ExceedanceProbability[i] obj['Title'] = title.columns.ravel()[0] obj['Date'] = date.today() arr.append(obj) i += 1 j = 0 date_string = str(arr[j]['Date'])[5:7]+'/'+str(arr[j]['Date'])[8:10]+'/'+str(arr[j]['Date'])[0:4] datesend = datetime.datetime.strptime(date_string, "%m/%d/%Y") ngaygui = int(datetime.datetime.timestamp(datesend)) arr2 = [] while j < count: obj = {} obj['Province'] = str(arr[j]['Province']) obj['Month'] = str(arr[j]['Month']) obj['ThresholdValue'] = str(arr[j]['ThresholdValue']) obj['ExceedanceProbability'] = str(arr[j]['ExceedanceProbability']) obj['ThresholdDescription'] = str(arr[j]['ThresholdDescription']) arr2.append(obj) if j % 6 == 0: dataDMoss = DataDMoss() dataDMoss.tieude = str(arr[j]['Title']) +' '+str(arr[j]['Province']) dataDMoss.ngaygui = ngaygui dataDMoss.type = "excel" dataDMoss.nguoigui = "Dmoss system" dataDMoss.data = arr2 arr2 = [] db.session.add(dataDMoss) db.session.commit() j += 1 return json({"error_code":0,"error_message":"successful"}) else: print ('____________________no file_____') title = pandas.read_excel("static/uploads/D-MOSS_Vietnam_Dengue_Forecast.xlsx",header=0) df = pandas.read_excel("static/uploads/D-MOSS_Vietnam_Dengue_Forecast.xlsx",header=1) count = df.Province.count() i = 0 arr = [] while i < count: obj = {} obj['Province'] = df.Province[i] obj['Month'] = df.Month[i] obj['ThresholdDescription'] = df.ThresholdDescription[i] obj['ThresholdValue'] = df.ThresholdValue[i] obj['ExceedanceProbability'] = df.ExceedanceProbability[i] obj['Title'] = title.columns.ravel()[0] obj['Date'] = date.today() arr.append(obj) i += 1 j = 0 date_string = str(arr[j]['Date'])[5:7]+'/'+str(arr[j]['Date'])[8:10]+'/'+str(arr[j]['Date'])[0:4] datesend = datetime.datetime.strptime(date_string, "%m/%d/%Y") ngaygui = int(datetime.datetime.timestamp(datesend)) arr2 = [] while j < count: obj = {} obj['Province'] = str(arr[j]['Province']) obj['Month'] = str(arr[j]['Month']) obj['ThresholdValue'] = str(arr[j]['ThresholdValue']) obj['ExceedanceProbability'] = str(arr[j]['ExceedanceProbability']) obj['ThresholdDescription'] = str(arr[j]['ThresholdDescription']) arr2.append(obj) if j % 6 == 0: dataDMoss = DataDMoss() dataDMoss.tieude = str(arr[j]['Title']) +' '+str(arr[j]['Province']) dataDMoss.ngaygui = ngaygui dataDMoss.type = "excel" dataDMoss.nguoigui = "Dmoss system" dataDMoss.data = arr2 arr2 = [] db.session.add(dataDMoss) db.session.commit() j += 1 return json({"error_code":0,"error_message":"successful"}) return json({ "error_code": "Upload Error", "error_message": "Could not upload file to store" }, status=520) else: return json({ "error_code": "Upload Error", "error_message": "Incorrect token" }, status=520) # @app.route('/api/v1/dmoss_upload_dengue_notification_module', methods=['POST']) # async def dmoss_upload_dengue_notification_module(request): # data = request.headers # uid = redisdb.get("sessions:" + data['X-Auth-Token']) # if uid is not None: # url = app.config['FILE_SERVICE_URL'] # fsroot = app.config['FS_ROOT'] # if request.method == 'POST': # file = request.files.get('file', None) # if file : # rand = ''.join(random.choice(string.digits) for _ in range(15)) # file_name = os.path.splitext(file.name)[0] # extname = os.path.splitext(file.name)[1] # newfilename = file_name + "-" + rand + extname # new_filename = newfilename.replace(" ", "_") # async with aiofiles.open(fsroot + new_filename, 'wb+') as f: # await f.write(file.body) # title = pandas.read_excel("static/uploads/D-MOSS_Vietnam_Dengue_Forecast.xlsx",header=0) # df = pandas.read_excel("static/uploads/D-MOSS_Vietnam_Dengue_Forecast.xlsx",header=1) # count = df.Province.count() # i = 0 # arr = [] # while i < count: # obj = {} # obj['Province'] = df.Province[i] # obj['Month'] = df.Month[i] # obj['ThresholdDescription'] = df.ThresholdDescription[i] # obj['ThresholdValue'] = df.ThresholdValue[i] # obj['ExceedanceProbability'] = df.ExceedanceProbability[i] # obj['Title'] = title.columns.ravel()[0] # obj['Date'] = date.today() # arr.append(obj) # i += 1 # j = 0 # date_string = str(arr[j]['Date'])[5:7]+'/'+str(arr[j]['Date'])[8:10]+'/'+str(arr[j]['Date'])[0:4] # datesend = datetime.datetime.strptime(date_string, "%m/%d/%Y") # ngaygui = int(datetime.datetime.timestamp(datesend)) # arr2 = [] # while j < count: # obj = {} # obj['Province'] = str(arr[j]['Province']) # obj['Month'] = str(arr[j]['Month']) # obj['ThresholdValue'] = str(arr[j]['ThresholdValue']) # obj['ExceedanceProbability'] = str(arr[j]['ExceedanceProbability']) # obj['ThresholdDescription'] = str(arr[j]['ThresholdDescription']) # arr2.append(obj) # if j % 6 == 0: # dataDMoss = DataDMoss() # dataDMoss.tieude = str(arr[j]['Title']) +' '+str(arr[j]['Province']) # dataDMoss.ngaygui = ngaygui # dataDMoss.type = "excel" # dataDMoss.nguoigui = "Dmoss system" # dataDMoss.data = arr2 # arr2 = [] # db.session.add(dataDMoss) # db.session.commit() # j += 1 # return json({"error_code":0,"error_message":"successful"}) # return json({ # "error_code": "Upload Error", # "error_message": "Could not upload file to store" # }, status=520) # # else: # # return json({ # # "error_code": "Upload Error", # # "error_message": "Incorrect token" # # }, status=520)