def func_enquiry_qrcode(self): """ web 询问接口 :return: """ qrcode = self.extra_data.get('qrcode', '') if qrcode == "": raise response_code.ParamERR(errmsg='qrcode can not be empty!') try: qr_state = (redis_conn.get('{}'.format(qrcode))) except Exception as e: raise response_code.DatabaseERR(errmsg='{}'.format(e)) if qr_state == "0": resp = set_resjson(err=1, errmsg='未扫描') elif qr_state == "1": resp = set_resjson(err=-2, errmsg='已扫描未登录') elif qr_state is None: resp = set_resjson(err=-4, errmsg='验证码已过期') else: try: user_info = mongo.db.user.find_one({"_id": qr_state}, { "name": 1, "headshot": 1, "_id": 0 }) except Exception as e: raise response_code.DatabaseERR(errmsg="{}".format(e)) resp = make_response(set_resjson(res_array=[user_info])) resp.headers["Authorization"] = encode_auth_token(qr_state) return resp
def func_read_message(self): """ 阅读消息 @return: """ user = g.user if not user: raise response_code.UserERR(errmsg='用户未登录') message_id_list = self.extra_data.get("message_id") date_type = self.extra_data.get("type") if type(message_id_list) != list: raise response_code.ParamERR(errmsg="message_id must be list") elif date_type not in ["like", "subscription", "system"]: raise response_code.ParamERR(errmsg="type is Incorrect") if date_type == "like": mongo.db.like.update({"_id": { "$in": message_id_list }}, {"$set": { "read_state": 1 }}, multi=True) elif date_type == "subscription": mongo.db.subscription.update({"_id": { "$in": message_id_list }}, {"$set": { "read_state": 1 }}, multi=True) else: return set_resjson(errmsg="这个功能暂时没做") return set_resjson(errmsg="200")
def raise_info(error): """ capture all exception information :param error: :return: """ if isinstance(error, response_code.ApiException): return set_resjson(error.err_code, error.errmsg, []) current_app.logger.error(error) return set_resjson(error.err_code, errmsg=error)
def func_view_file(self): """ 查看课件 """ video_id = self.extra_data.get('video_id') video_document = {} res_list = [] try: video_document_cursor = mongo.db.document.find( {"video_id": video_id}) except Exception as e: raise response_code.DatabaseERR(errmsg="{}".format(e)) for document in video_document_cursor: video_document["file_id"] = document["_id"] video_document["file_name"] = document["file_name"] video_document["file_path"] = document["file_path"] video_document["image_path"] = document["image_path"] video_document["price"] = document["price"] video_document["time"] = document["time"] res_list.append(deepcopy(video_document)) if not video_document: raise response_code.RoleERR(errmsg="这个视频没有课件") return set_resjson(res_array=res_list)
def qq_login(code): """ QQ 登录 :param code: :return: """ oauth_qq = OAuthQQ() access_token = oauth_qq.get_access_token(code) unionid, openid = oauth_qq.get_unionid(access_token) try: user_info = mongo.db.user.find_one({"qq_unionid": unionid}) except Exception as e: raise response_code.DatabaseERR(errmsg="{}".format(e)) if not user_info: # 第一次登录 user_info = oauth_qq.get_user_info(access_token, openid) try: pl = redis_conn.pipeline() pl.set("unionid_name_%s" % unionid, user_info['nickname'], constants.SMS_CODE_REDIS_EXPIRES) pl.set("unionid_photo_url_%s" % unionid, user_info['figureurl_qq_1'], constants.SMS_CODE_REDIS_EXPIRES) pl.execute() except Exception as e: raise response_code.DatabaseERR(errmsg="{}".format(e)) access_token = generate_save_user_token(unionid, 'qq') return set_resjson(res_array=[{"access_token": access_token}]) else: response = not_first_login(user_info) return response
def upload_file(): """ 上传图片 @return: """ user = g.user if not user: raise response_code.UserERR(errmsg='用户未登录') image_type = request.form.get('type', "") try: file = request.files['file'] except Exception as e: raise response_code.ParamERR(errmsg="{}".format(e)) if not all([image_type, file]): raise response_code.ParamERR(errmsg="Parameter is not complete") elif not allowed_image_file(file): raise response_code.ParamERR(errmsg="The image type is incorrect") if image_type == "background": file_path = 'static/background/{}'.format(allowed_image_file(file)) res_url = "http://api.haetek.com:8181/" + file_path elif image_type == "headshot": file_path = 'static/headershot/{}'.format(allowed_image_file(file)) res_url = "http://api.haetek.com:8181/" + file_path elif image_type in ["video_image", "series_image"]: file_path = 'static/image/{}'.format(allowed_image_file(file)) res_url = file_path elif image_type == "document": file_path = 'static/document/{}'.format(allowed_image_file(file)) res_url = file_path else: raise response_code.ParamERR(errmsg="type is incorrect") file.save(file_path) return set_resjson(res_array=[res_url])
def func_change_mobile(self): """ 修改手机号码时更改手机号 @return: """ user = g.user if not user: raise response_code.UserERR(errmsg='用户未登录') mobile = self.extra_data.get("new_mobile", "") code = self.extra_data.get('code', "") token = self.extra_data.get('token', "") if mobile == "" or code == "" or token == "": raise response_code.ParamERR(errmsg="Parameter is not complete") elif not mobile_re.match('{}'.format(mobile)): raise response_code.ParamERR(errmsg="手机号码不正确") elif mobile == user['mobile']: raise response_code.ParamERR( errmsg="The phone number hasn't changed") # 手机验证码验证 sms_verify(mobile, code) real_token = redis_conn.get("verify_mobile_%s" % mobile) if token != real_token: raise response_code.ParamERR(errmsg="token is incorrect ") else: mongo.db.user.update_one(user, {"$set": {"mobile": mobile}}) return set_resjson()
def func_end_watch_history(self): """ 观看播放历史 """ user = g.user if not user: raise response_code.ParamERR(errmsg="用户未登陆") user_id = user["_id"] video_id = self.extra_data.get("video_id", "") end_time = self.extra_data.get("end_time", "") if end_time == "" or video_id == "": raise response_code.ParamERR( errmsg="video_id, end_time must be provide") try: time.strptime(end_time, "%H:%M:%S") except Exception as e: raise response_code.ParamERR("end_time format incorrect") video_info = mongo.db.video.find_one({"_id": video_id}) if not video_info: raise response_code.ParamERR(errmsg="video_id 不存在") else: mongo.db.video_history.insert_one({ "_id": create_uuid(), "time": time.time(), "video_id": video_id, "user_id": user_id, "record": { "action": "end_watch", "end_time": end_time } }) return set_resjson()
def func_get_like(self): """ 查看点赞 @return: """ user = g.user if not user: raise response_code.UserERR(errmsg='用户未登录') res_list = [] try: for like in mongo.db.like.find( {"user_id": user["_id"], "type": "video"}).sort("time", -1): video_info = mongo.db.video.find_one( {"_id": like["relation_id"]}, {"title": 1, "upload_time": 1, "video_time": 1, "image_path": 1}) if not video_info: continue video_id = video_info.pop("_id") video_info["video_id"] = video_id video_info["like_counts"] = mongo.db.like.find( {"relation_id": video_id}).count() res_list.append(deepcopy(video_info)) except Exception as e: current_app.log.error(e) raise response_code.ParamERR(errmsg="{}".format(e)) return set_resjson(res_array=res_list)
def upload_document(): """ 上传课件 @return: """ user = g.user if not user: raise response_code.UserERR(errmsg='用户未登录') document_type = request.form.get('type', "") try: file = request.files['file'] except Exception as e: raise response_code.ParamERR(errmsg="{}".format(e)) if not all([document_type, file]): raise response_code.ParamERR(errmsg="Parameter is not complete") elif not allowed_document_file(file): raise response_code.ParamERR(errmsg="The document type is incorrect") filename = file.filename.rsplit(".")[0] file_path = 'static/document/{}'.format(allowed_document_file(file)) file.save(file_path) return set_resjson(res_array={ "file_path": file_path, "file_name": filename })
def func_generate_qrcode(self): """ 生成二维码 :return: """ qrcode = str(uuid1()) redis_conn.set(qrcode, 0, constants.QR_CODE_REDIS_EXPIRES) return set_resjson(res_array=[{"qrcode": qrcode}])
def func_code_login(self): """ login :return: """ _id = None mobile = self.extra_data.get("mobile", "") code = self.extra_data.get('code', "") if not mobile_re.match('{}'.format(mobile)): raise response_code.ParamERR(errmsg="手机号码不正确") # 手机验证码验证 sms_verify(mobile, code) try: user_info = mongo.db.user.find_one({"mobile": '{}'.format(mobile)}, { "headshot": 1, "name": 1 }) except Exception as error: current_app.logger.error(error) raise response_code.DatabaseERR(errmsg='{}'.format(error)) now_time = time.time() if not user_info: _id = get_user_id("id") try: mongo.db.user.insert_one({ "gender": "男", "birthday": str(datetime.date.today()), "name": ranstr(16), "mobile": '{}'.format(mobile), "_id": _id, "headshot": self.head_shot_path, "create_time": now_time, "login_time": now_time, "background": self.background_path, "introduction": self.introduction }) except Exception as error: current_app.logger.error(error) raise response_code.DatabaseERR(errmsg='{}'.format(error)) user_info = {"name": ranstr(16), "headshot": self.head_shot_path} else: _id = user_info.pop("_id") try: mongo.db.user.update_one({"mobile": '{}'.format(mobile)}, {"$set": { "login_time": now_time }}) except Exception as err: current_app.logger.error(err) raise response_code.DatabaseERR(errmsg='{}'.format(err)) # set the token information in the response response = make_response(set_resjson(res_array=[user_info])) response.headers["Authorization"] = encode_auth_token(_id) return response
def func_add_subscription(self): """ 订阅 @return: """ user = g.user if not user: raise response_code.UserERR(errmsg='用户未登录') sub_type = self.extra_data.get("type", "") relation_id = self.extra_data.get("relation_id", "") value = self.extra_data.get("value", "") if value not in [0, 1]: raise response_code.ParamERR(errmsg="value must be 1 or 0") elif relation_id == "": raise response_code.ParamERR(errmsg="relation_id must be provide") elif sub_type != "author": raise response_code.ParamERR(errmsg="mode must be author") author_info = mongo.db.user.find_one({"_id": relation_id}) if not author_info: raise response_code.ParamERR(errmsg="relation_id 不存在") else: sub_info = mongo.db.subscription.find_one({ "relation_id": relation_id, "user_id": user["_id"] }) if value == 1: if not sub_info: mongo.db.subscription.insert_one({ "_id": create_uuid(), "user_id": user["_id"], "relation_id": relation_id, "read_state": 0, "time": time.time(), "type": sub_type, "state": 0 }) elif sub_info["state"] == -1: mongo.db.subscription.update_one({"_id": sub_info["_id"]}, {"$set": { "state": 0 }}) else: raise response_code.ParamERR(errmsg="此作者已经订阅") else: if sub_info: if sub_info["state"] == 0: mongo.db.subscription.update_one( {"_id": sub_info["_id"]}, {"$set": { "state": -1 }}) else: raise response_code.ParamERR(errmsg="此作者还没有订阅") else: raise response_code.ParamERR(errmsg="此作者还没有订阅") return set_resjson()
def func_change_color(self): """ 字体改变颜色 @return: """ start_RGB = self.extra_data.get("start_RGB") middle_RGB = self.extra_data.get("middle_RGB") end_RGB = self.extra_data.get("end_RGB") result_data = demo_display(start_RGB, middle_RGB, end_RGB) return set_resjson(res_array=result_data)
def func_is_login(self): """ 判断登陆 """ user = None try: authorization = request.headers.get("Authorization") if authorization: token = authorization.strip()[7:] payload = jwt.decode(token, current_app.config['JWT_SECRET'], algorithm=['HS256']) if payload: _id = payload["data"].get("_id") user = mongo.db.user.find_one({"_id": _id}) except Exception as e: return set_resjson(err=-1, errmsg="ERROR") if user: return set_resjson()
def func_check_mobile(self): """ 查看手机号码重复 @return: """ mobile = self.extra_data.get('mobile', '') if not mobile_re.match('{}'.format(mobile)): raise response_code.ParamERR(errmsg="手机号码不正确") try: user_info = mongo.db.user.find_one({"mobile": '{}'.format(mobile)}) except Exception as error: current_app.logger.error(error) raise response_code.DatabaseERR(errmsg='{}'.format(error)) if user_info: resp = set_resjson(err=-1, errmsg='This mobile is already exist!') else: resp = set_resjson(err=0, errmsg="This mobile can be registered!") return resp
def func_quick_login(self): """ 手机一键登陆 """ login_token = self.extra_data.get("login_token", "") if login_token == "": raise response_code.ParamERR( errmsg="[ login_token ] must be provided") curl = 'https://api.verification.jpush.cn/v1/web/loginTokenVerify' dict_body = {"loginToken": login_token} json_body = json.dumps(dict_body) encrypt_phone = get_phone(curl, json_body) if not encrypt_phone: raise response_code.ParamERR(errmsg="登陆失败") phone = get_num(encrypt_phone, config.JI_GUANG_PRIKEY) user_info = mongo.db.user.find_one({"mobile": phone}, { "headshot": 1, "name": 1 }) now_time = time.time() if not user_info: _id = get_user_id("id") try: mongo.db.user.insert_one({ "gender": "男", "birthday": str(datetime.date.today()), "name": ranstr(16), "mobile": '{}'.format(phone), "_id": _id, "headershot": self.head_shot_path, "create_time": now_time, "login_time": now_time, "background": self.background_path, "introduction": self.introduction }) except Exception as error: current_app.logger.error(error) raise response_code.DatabaseERR(errmsg='{}'.format(error)) user_info = {"name": ranstr(16), "headshot": self.head_shot_path} else: _id = user_info.pop("_id") try: mongo.db.user.update_one({"mobile": '{}'.format(phone)}, {"$set": { "login_time": now_time }}) except Exception as err: current_app.logger.error(err) raise response_code.DatabaseERR(errmsg='{}'.format(err)) # set the token information in the response response = make_response(set_resjson(res_array=[user_info])) response.headers["Authorization"] = encode_auth_token(_id) return response
def func_get_information(self): """ 获取个人信息 @return: """ user = g.user res_dict = {} if not user: raise response_code.ParamERR(errmsg="用户未登陆") try: subscription_counts = mongo.db.subscription.find({ "user_id": user["_id"], "state": 0 }).count() fans_counts = mongo.db.subscription.find({ "relation_id": user["_id"], "state": 0 }).count() video_id_list = [ video.get("_id") for video in mongo.db.video.find( {"user_id": user["_id"]}, {"_id": 1}) ] like_counts = mongo.db.like.find({ "user_id": user["_id"], "relation_id": { "$in": video_id_list } }).count() except Exception as e: raise response_code.DatabaseERR(errmsg="{}".format(e)) res_dict["user_name"] = user["name"] res_dict["user_id"] = user["_id"] res_dict["birthday"] = user.get( "birthday", time.strftime("%Y-%m-%d", time.localtime(user["create_time"]))) res_dict["gender"] = user.get("gender", "男") res_dict["introduction"] = user["introduction"] res_dict["headshot"] = user["headshot"] res_dict["background"] = user["background"] res_dict["like_counts"] = like_counts res_dict["video_counts"] = len(video_id_list) res_dict["user_name"] = user["name"] res_dict["binding_webchat"] = 1 if user.get("wechat_unionid", None) else 0 res_dict["binding_qq"] = 1 if user.get("qq_unionid", None) else 0 res_dict["binding_microblog"] = 1 if user.get("microblog_unionid", None) else 0 res_dict["subscription_counts"] = subscription_counts res_dict["fans_counts"] = fans_counts return set_resjson(res_array=[res_dict])
def func_get_category(self): """ 查看标签信息 """ try: category_info = mongo.db.tool.find_one({ "type": "category" }).get("data") except Exception as e: raise response_code.DatabaseERR(errmsg="{}".format(e)) return set_resjson(res_array=category_info)
def handle_model(self): func_name = 'func_{}'.format(self.model_action) func_name = func_name.lower() try: handle_function = getattr(DocumentHandler, func_name) resp = handle_function(self) except AttributeError as e: resp = set_resjson(err=-4, errmsg="{} is incorrect !".format( self.model_action)) return resp
def func_generate_code(self): """ Send SMS verification code :return: """ mobile = self.extra_data.get("mobile", "") if not mobile_re.match('{}'.format(mobile)): raise response_code.ParamERR(errmsg="手机号码不正确") send_flag = redis_conn.get("send_flag_{}".format(mobile)) if send_flag: raise response_code.ReqERR(errmsg="请求次数过于频繁") # sms_code = "%04d" % random.randint(0, 9999) sms_code = "6666" # encrypted message hash1 = hashlib.sha256() hash1.update(bytes(sms_code, encoding="utf-8")) hash_sms_code = hash1.hexdigest() # Using redis transactions, save SMS and flag to redis, # SMS expiration time is 300 seconds, flag expiration time is 60 seconds try: pl = redis_conn.pipeline() pl.set("sms_code_%s" % mobile, sms_code, constants.SMS_CODE_REDIS_EXPIRES) pl.set("send_flag_%s" % mobile, sms_code, constants.SEND_SMS_CODE_INTERVAL) pl.execute() except Exception as error: current_app.logger.error(error) raise response_code.DatabaseERR(errmsg='{}'.format(error)) # try: # # resp = send_sms(mobile, constants.SMS_LOGIN_TEMPLATE_ID, constants.SMS_SIGN, sms_code) # except Exception as e: # current_app.logger.error('[send_verification_code] {}'.format(e)) # raise response_code.ThirdERR(errmsg='{}'.format(e)) # resp_dict = json.loads(resp.decode('utf-8')) # resp_code = resp_dict.get('Code', 'OK') # if resp_code != 'OK': # redis_conn.delete("send_flag_{}".format(mobile)) # message = resp_dict.get('Message', '') # current_app.logger.error(message) # raise response_code.ThirdERR(errmsg=message) response = make_response( set_resjson(res_array=[{ "code": hash_sms_code, 'real_code': sms_code }])) return response
def handle_model(self): func_name = 'func_{}'.format(self.model_action) func_name = func_name.lower() try: handle_function = getattr(SeriesHandler, func_name) if self.model_action not in ["get_series"]: if self.extra_data == '': raise response_code.ParamERR( errmsg="[ extra_data ] must be provided ") resp = handle_function(self) except AttributeError as e: resp = set_resjson(err=-4, errmsg="{} is incorrect !".format( self.model_action)) return resp
def not_first_login(user_info, refresh_token=None): """ 已经登陆过 """ _id = user_info['_id'] login_time = time.time() try: mongo.db.user.update_one({"_id": '{}'.format(_id)}, {"$set": { "login_time": login_time }}) except Exception as e: raise response_code.DatabaseERR(errmsg="{}".format(e)) response = make_response( set_resjson(res_array=[{ "name": user_info['name'], 'headshot': user_info.get('headshot', "") }])) response.headers["Authorization"] = encode_auth_token(_id, refresh_token) return response
def func_generate_third_qrcode(self): """ 生成 url 连接 """ mode = self.extra_data.get('type', "") next1 = self.extra_data.get('next', "") display = self.extra_data.get('display', "") log_url = None if mode not in ["microblog", "qq", "wechat"]: raise response_code.ParamERR(errmsg="type is incorrect") elif mode == "qq": oauth_qq = OAuthQQ(state=next1, display=display) log_url = oauth_qq.get_qq_login_url() elif mode == "wechat": wechat = WeChat(state=next1) log_url = wechat.get_wechat_url() elif mode == "microblog": weibo = WeiBo(state=next1) log_url = weibo.get_weibo_login_url() return set_resjson(res_array=[{"url": log_url}])
def func_verify_mobile(self): """ 修改手机号码时验证手机号 @return: """ user = g.user if not user: raise response_code.UserERR(errmsg='用户未登录') mobile = self.extra_data.get("mobile", "") code = self.extra_data.get('code', "") if '{}'.format(mobile) != user["mobile"]: raise response_code.ParamERR(errmsg="不是原手机号码") # 手机验证码验证 sms_verify(mobile, code) token = str(uuid1()) redis_conn.set("verify_mobile_%s" % mobile, token, constants.VERIFY_MOBILE_REDIS_EXPIRES) res_dict = {"token": token} return set_resjson(res_array=[res_dict])
def func_get_series(self): """ 获得系列信息 """ user = g.user if not user: raise response_code.UserERR(errmsg='用户未登录') try: series_cursor = mongo.db.series.find({'user_id': user["_id"]}, { "title": 1, "_id": 0 }) except Exception as e: raise response_code.ParamERR(errmsg="{}".format(e)) # res_data = [] # for result in results: # data_dict = {'title': result['title']} # res_data.append(data_dict) res_list = [i for i in series_cursor] return set_resjson(res_array=res_list)
def func_logout(self): """ logout :return: """ user = g.user if not user: raise response_code.UserERR(errmsg='用户未登录') response = make_response(set_resjson()) logout_time = time.time() try: del response.headers["Authorization"] mongo.db.user.update_one({"_id": user['_id']}, {"$set": { "logout_time": logout_time }}) except Exception as error: current_app.logger.error(error) raise response_code.RoleERR(errmsg="{}".format(error)) return response
def func_remove_binding(self): """ 解除第三方绑定 @return: """ user = g.user if not user: raise response_code.UserERR(errmsg='用户未登录') third_type = self.extra_data.get("type", "") if third_type not in ["microblog", "wechat", "qq"]: raise response_code.ParamERR(errmsg="type is incorrect") elif third_type.lower() == "microblog": mongo.db.user.update_one(user, {"$unset": {"wechat_unionid": ""}}) elif third_type.lower() == "wechat": mongo.db.user.update_one(user, {"$unset": { "microblog_unionid": "" }}) elif third_type.lower() == "qq": mongo.db.user.update_one(user, {"$unset": {"qq_unionid": ""}}) raise set_resjson()
def func_scan_qrcode(self): """ 移动端扫描二维码 :return: """ user = g.user if not user: raise response_code.UserERR(errmsg='用户未登录') qrcode = self.extra_data.get('qrcode', '') try: qr_state_byte = redis_conn.get('{}'.format(qrcode)) except Exception as e: raise response_code.DatabaseERR(errmsg='{}'.format(e)) if not qr_state_byte: raise response_code.ParamERR(errmsg='验证码过期') try: redis_conn.set(qrcode, user['_id'], constants.QR_CODE_REDIS_EXPIRES) except Exception as e: raise response_code.DatabaseERR(errmsg='{}'.format(e)) return set_resjson()
def wehcat_login(code): """ 微信登陆 :param code: :return: """ wechatlogin = WeChat(state='') access_token, openid, unionid, refresh_token = wechatlogin.get_access_token( code) try: user_info = mongo.db.user.find_one({"wechat_unionid": unionid}) except Exception as e: raise response_code.DatabaseERR(errmsg="{}".format(e)) if not user_info: # 第一次登录 nickname, headimgurl, _, gender = wechatlogin.get_user_info( access_token, openid) try: pl = redis_conn.pipeline() pl.set("unionid_name_%s" % unionid, nickname, constants.SMS_CODE_REDIS_EXPIRES) pl.set("unionid_gender_%s" % unionid, gender, constants.SMS_CODE_REDIS_EXPIRES) pl.set("unionid_refresh_token_%s" % unionid, refresh_token, constants.SMS_CODE_REDIS_EXPIRES) pl.set("unionid_photo_url_%s" % unionid, headimgurl, constants.SMS_CODE_REDIS_EXPIRES) pl.execute() except Exception as e: raise response_code.DatabaseERR(errmsg="{}".format(e)) access_token = generate_save_user_token(unionid, 'wechat') return set_resjson(res_array=[{"access_token": access_token}]) else: response = not_first_login(user_info, refresh_token) return response