def get_user_msgs(is_admin=None): """ api获取消息 :return: """ data = {} ctype = json_to_pyseq( request.argget.all("type", ["notice", "private_letter"])) label = json_to_pyseq(request.argget.all("label")) pre = str_to_num(request.argget.all("pre", 10)) page = str_to_num(request.argget.all("page", 1)) status_update = request.argget.all("status_update") # admin api才有效的参数 is_sys_msg = str_to_num(request.argget.all("is_sys_msg", 1)) keyword = request.argget.all("keyword", "") q = {"type": {"$in": ctype}} if not is_admin: q["user_id"] = current_user.str_id else: if is_sys_msg: q["is_sys_msg"] = True else: q["is_sys_msg"] = False if keyword: keyword = {"$regex": keyword} q["$or"] = [{ "title": keyword }, { "link": keyword }, { "content": keyword }] if label: q["label"] = {"$in": label} msgs = mdb_user.db.message.find(q) data_cnt = msgs.count(True) msgs = list(msgs.sort([("time", -1)]).skip(pre * (page - 1)).limit(pre)) ids = [msg["_id"] for msg in msgs] data["msgs"] = objid_to_str(msgs) data["msgs"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=data["msgs"]) if not is_admin: # user_id为真,表示非管理端获取消息. 标记为已通知 q = {"user_id": current_user.str_id, "status": {"$ne": "have_read"}} data["msgs"]["more"] = get_unread_num(q) mdb_user.db.message.update_many(q, {"$set": {"status": "notified"}}) if status_update: mdb_user.db.message.update_many({"_id": { "$in": ids }}, {"$set": { "status": status_update }}) return data
def get_followed_users(): """ 获取一个用户已经关注的用户 :return: """ user_id = request.argget.all("user_id") page = str_to_num(request.argget.all("page", 1)) pre = str_to_num(request.argget.all("pre", 20)) s, r = arg_verify(reqargs=[("user id", user_id)], required=True) if not s: return r data = {"users": []} follow_user = mdb_user.db.user_follow.find_one({ "user_id": user_id, "type": "account" }) if follow_user: data_cnt = len(follow_user["follow"]) for tid in follow_user["follow"][(page - 1) * pre:page * pre]: s, r = get_user_public_info( user_id=str(tid), is_basic=False, determine_following=False, current_user_isauth=current_user.is_authenticated) if s: data["users"].append(r) else: data_cnt = 0 data["users"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=data["users"]) return data
def get_fans_users(): """ 获取用户的粉丝 :return: """ user_id = request.argget.all("user_id") page = str_to_num(request.argget.all("page", 1)) pre = str_to_num(request.argget.all("pre", 20)) s, r = arg_verify(reqargs=[("user id", user_id)], required=True) if not s: return r data = {"users": []} fans = mdb_user.db.user_follow.find({"type": "account", "follow": user_id}) data_cnt = fans.count(True) for user in fans.skip(pre * (page - 1)).limit(pre): s, r = get_user_public_info( user_id=user["user_id"], is_basic=False, current_user_isauth=current_user.is_authenticated) if s: data["users"].append(r) data["users"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=data["users"]) return data
def get_tags(): """ 根据条件获取post tags :return: """ last_days = str_to_num(request.argget.all('last_days', 360)) user_id = request.argget.all('user_id') tlimit = str_to_num(request.argget.all('limit', 20)) tsort = json_to_pyseq(request.argget.all('sort', [{"tag_cnt": -1}, {"like": -1}, {"comment_num": -1}])) # sort sort = {} for s in tsort: sort = dict(sort, **s) # 查看是否存在缓存 cache_key = cache.get_autokey( fun="_get_tags", key_base64=False, db_type="redis", user_id=user_id, last_days=last_days, tlimit=tlimit, sort=sort) data = cache.get(key=cache_key, db_type="redis") if data != cache.cache_none: return data else: # 调用生成缓存程序生成新缓存 async_get_tags(user_id, last_days, tlimit, sort) # 然后返回最后一次的长期缓存 data = cache.get(key="LAST_POST_TAGS_CACHE", db_type="mongodb") return data
def get_medias(user_id=None): """ :param user_id: 媒体为管理端(系统)所有时需要传入user_id = 0 :return: """ if user_id is None: user_id = current_user.str_id keyword = request.argget.all("keyword") category_id = request.argget.all("category_id") ctype = request.argget.all("ctype") page = str_to_num(request.argget.all("page", 1)) pre = str_to_num(request.argget.all("pre", 12)) sort = json_to_pyseq(request.argget.all('sort')) s, r = arg_verify([(gettext("type"), ctype)], only=get_config("category", "CATEGORY_TYPE").values()) if not s: return r data = {} if category_id: if category_id == "default": category_id = {"$in": [None, ""]} query = {"category_id": category_id, "type": ctype} else: query = {"type": ctype} if keyword: k_rule = {"$regex": keyword, "$options": "$i"} query["$or"] = [{ "name": k_rule }, { "title": k_rule }, { "link": k_rule }, { "text": k_rule }] query["user_id"] = user_id # sort if sort: for i, srt in enumerate(sort): sort[i] = (list(srt.keys())[0], list(srt.values())[0]) else: sort = [("time", -1)] medias = mdb_web.db.media.find(query) data_cnt = medias.count(True) medias = list(medias.sort(sort).skip(pre * (page - 1)).limit(pre)) for d in medias: d["_id"] = str(d["_id"]) if "url" in d and d["url"]: d["url"] = get_file_url(d["url"]) data["medias"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=medias) return data
def get_plugins(): """ 获取插件信息 :return: """ data = {} pre = str_to_num(request.argget.all('pre', 10)) page = str_to_num(request.argget.all('page', 1)) keyword = request.argget.all('keyword') plugin_manager.load_all_plugin() query = {"is_deleted": {"$nin": [1, True]}} if keyword: keyword = {"$regex": keyword, "$options": "$i"} query["$or"] = [{ "plugin_name": keyword }, { "alias_name": keyword }, { "introduce": keyword }, { "license": keyword }, { "author": keyword }] plugins = mdbs["sys"].db.plugin.find(query) data_cnt = plugins.count(True) plugins = list(plugins.skip(pre * (page - 1)).limit(pre)) data["plugins"] = objid_to_str(plugins) data["plugins"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=data["plugins"]) return data
def get_display_settings(): """ :return: """ keyword = request.argget.all("keyword") category_id = request.argget.all("category_id") ctype = request.argget.all("ctype") page = str_to_num(request.argget.all("page", 1)) pre = str_to_num(request.argget.all("pre", 12)) sort = json_to_pyseq(request.argget.all('sort')) s, r = arg_verify([(gettext("type"), ctype)], only=get_config("category", "CATEGORY_TYPE").values()) if not s: return r data = {} if category_id: if category_id == "default": category_id = {"$in": [None, ""]} query = {"category_id": category_id, "type": ctype} else: query = {"type": ctype} if keyword: k_rule = {"$regex": keyword, "$options": "$i"} query["$or"] = [{ "name": k_rule }, { "title": k_rule }, { "link": k_rule }, { "text": k_rule }] theme_name = get_config("theme", "CURRENT_THEME_NAME") query["theme_name"] = theme_name # sort if sort: for i, srt in enumerate(sort): sort[i] = (list(srt.keys())[0], list(srt.values())[0]) else: sort = [("time", -1)] display_settings = mdbs["sys"].db.theme_display_setting.find(query) data_cnt = display_settings.count(True) display_settings = list( display_settings.sort(sort).skip(pre * (page - 1)).limit(pre)) for d in display_settings: d["_id"] = str(d["_id"]) if "url" in d and d["url"]: d["url"] = get_file_url(d["url"]) data["medias"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=display_settings) data["theme_name"] = theme_name return data
def theme_static_file(path): """ 获取主题下静态文件 注意: theme主题图片获取路由 (目录themes/<theme name>/static下图片) 1.对于图片,本路由只能获取目录themes/<theme name>/static下定义尺寸图片 参数w,h可指定图片大小 :param path:原图片路径 :param w:获取的宽 :param h:获取的高 :return:w和h都大于0则返回相应尺寸图片; w和h都等于0则返回原图; 其中一个值大于0则返回以这个值为基础等比缩放图片 """ w = str_to_num(request.args.get("w", 0)) h = str_to_num(request.args.get("h", 0)) if w or h: path_list = os.path.splitext(path.rstrip().rstrip("/")) absolute_path = os.path.abspath( "{}/{}/static/{}_w_{}_h_{}{}".format( theme_view.template_folder, get_config( "theme", "CURRENT_THEME_NAME"), path_list[0], w, h, path_list[1])) if not os.path.isfile(absolute_path): img_path = os.path.abspath( "{}/{}/static/{}".format( theme_view.template_folder, get_config( "theme", "CURRENT_THEME_NAME"), path)) try: imgcs = ImageCompression(img_path, absolute_path) except BaseException: abort(404) if w and h: # 自定义长宽 imgcs.custom_pixels(w, h) else: # 等比缩放 imgcs.isometric(w, h) else: absolute_path = os.path.abspath( "{}/{}/static/{}".format( theme_view.template_folder, get_config( "theme", "CURRENT_THEME_NAME"), path)) if not os.path.isfile(absolute_path): abort(404) return send_file(filename_or_fp=absolute_path, conditional=True, last_modified=True)
def get_posts(): page = str_to_num(request.argget.all('page', 1)) pre = str_to_num(request.argget.all('pre', get_config("post", "NUM_PAGE"))) sort = json_to_pyseq(request.argget.all('sort')) status = request.argget.all('status', 'is_issued') matching_rec = request.argget.all('matching_rec') time_range = int(request.argget.all('time_range', 0)) keyword = request.argget.all('keyword', '').strip() fields = json_to_pyseq(request.argget.all('fields')) unwanted_fields = json_to_pyseq(request.argget.all('unwanted_fields')) user_id = request.argget.all('user_id') category_id = request.argget.all('category_id') tag = request.argget.all('tag') # 不能同时使用fields 和 unwanted_fields temp_field = {} if fields: for f in fields: temp_field[f] = 1 elif unwanted_fields: for f in unwanted_fields: temp_field[f] = 0 other_filter = {} if user_id: # 获取指定用户的post other_filter["user_id"] = user_id # 如果category_id为None, 则获取全部分类文章 if category_id: try: ObjectId(category_id) # 指定分类 other_filter["category"] = category_id except BaseException: # 默认文集 other_filter["category"] = None if tag: other_filter["tags"] = tag data = get_posts_pr(page=page, field=temp_field, pre=pre, sort=sort, status=status, time_range=time_range, matching_rec=matching_rec, keyword=keyword, other_filter=other_filter) return data
def get_urls(): ''' 获取web url :return: ''' data = {} ctype = request.argget.all("type") keyword = request.argget.all("keyword") pre = str_to_num(request.argget.all("pre", 10)) page = str_to_num(request.argget.all("page", 1)) q = {} if ctype: q["type"] = ctype if keyword: keyword = {"$regex": keyword, "$options": "$i"} q["$or"] = [{ "url": keyword }, { "endpoint": keyword }, { "custom_permission": keyword }, { "methods": keyword }] urls = mdb_sys.db.sys_urls.find(q) data_cnt = urls.count(True) urls = list(urls.sort([("url", 1)]).skip(pre * (page - 1)).limit(pre)) for url in urls: url["_id"] = str(url["_id"]) if "OPTIONS" in url["methods"]: url["methods"].remove("OPTIONS") if "HEAD" in url["methods"]: url["methods"].remove("HEAD") # 判断是否不存在自定义权限 if not url["custom_permission"]: url["custom_permission"] = None else: no_custom = True for v in url["custom_permission"].values(): if v: no_custom = False break if no_custom: url["custom_permission"] = None data["urls"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=urls) return data
def get_sys_message(): """ 管理端获取消息 :return: """ data = {} msg_type = request.argget.all("msg_type") ctype = request.argget.all("type") status = request.argget.all("status", "successful") keyword = request.argget.all("keyword", "") pre = str_to_num(request.argget.all("pre", 10)) page = str_to_num(request.argget.all("page", 1)) if status == "normal": status = "successful" q = {"status": status, "type": ctype} if msg_type: q["msg_type"] = msg_type if keyword: keyword = {"$regex": keyword, "$options": "$i"} q["$or"] = [ { "subject": keyword }, { "from": keyword }, { "to": keyword }, { "body": keyword }, { "html": keyword }, ] emails = mdbs["sys"].db.sys_message.find(q) data_cnt = emails.count(True) emails = list( emails.sort([("time", -1)]).skip(pre * (page - 1)).limit(pre)) data["msgs"] = objid_to_str(emails) data["msgs"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=data["msgs"]) return data
def search_process(): ''' 搜索(暂不支持全文搜索) 只能搜索文章, 用户 :return: ''' keyword = request.argget.all('keyword') target = request.argget.all('target') page = str_to_num(request.argget.all('page', 1)) pre = str_to_num(request.argget.all('pre', 10)) s, r = arg_verify(reqargs=[(gettext("keyword"), keyword)], required=True) if not s: return r data = {"posts":{}, "users":{}} # post if not target or target == "post": data["posts"] = {} data["posts"]["items"] = get_posts_pr(field={"title":1, "issue_time":1, "brief_content":1}, page=page, pre=pre, status="is_issued", sort=None, time_range=None, matching_rec=None, keyword=keyword, other_filter=None, is_admin=False, get_userinfo=False)["posts"] data["posts"]["kw"] = keyword if not target or target == "user": # user data["users"] = {"kw": keyword, "items": []} query_conditions = {"is_delete": {"$in": [False, 0]}, "active": {"$in": [True, 1]}} keyword = {"$regex":keyword, "$options":"$i"} query_conditions["$or"] = [{"username": keyword}, {"email": keyword}, {"custom_domain": keyword} ] us = mdb_user.db.user.find(query_conditions, {"_id": 1, "username":1, "avatar_url":1, "custom_domain":1, "gender":1, }) data_cnt = us.count(True) users = list(us.skip(pre * (page - 1)).limit(pre)) for user in users: user['_id'] = str(user['_id']) user["avatar_url"]["url"] = get_avatar_url(user["avatar_url"]) data["users"]["items"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=users) return data
def sign_out(): ''' GET or PUT: 用户登出api use_jwt_auth:<int>, 是否使用jwt验证. 0 或 1,默认为0不使用. 如果是jwt验证登录信息的客户端use_jwt_auth应为1 :param adm: :return: ''' use_jwt_auth = str_to_num(request.argget.all('use_jwt_auth', 0)) if use_jwt_auth: # 使用jwt验证的客户端登出 jwt_auth = JwtAuth() s, r = jwt_auth.clean_login() if s: data = { "msg": gettext("Successfully logged out"), "msg_type": "s", "http_status": 201, "to_url": get_config("login_manager", "LOGIN_OUT_TO") } else: data = {"msg": r, "msg_type": "s", "http_status": 400} else: logout_user() data = { "msg": gettext("Successfully logged out"), "msg_type": "s", "http_status": 201, "to_url": get_config("login_manager", "LOGIN_OUT_TO") } return response_format(data)
def public_profile(): """ 获取用户公开信息 :return: """ data = {} user_id = request.argget.all('user_id') is_basic = str_to_num(request.argget.all('is_basic', 1)) if not user_id or user_id == "None": data = { 'd_msg': gettext('Lack of parameters "user_id"'), 'd_msg_type': "e", "custom_status": 400 } return data try: ObjectId(user_id) except BaseException: data = { 'd_msg': gettext('This may be a visitor"'), 'd_msg_type': "e", "custom_status": 400 } return data s, r = get_user_public_info( user_id=user_id, is_basic=is_basic, current_user_isauth=current_user.is_authenticated) if not s: data = {'msg': r, 'msg_type': "w", "custom_status": 400} else: data["user"] = r return data
def public_profile(): ''' 获取用户公开信息 :return: ''' data = {} user_id = request.argget.all('user_id') is_basic = str_to_num(request.argget.all('is_basic', 1)) if not user_id or user_id == "None": data = { 'd_msg': gettext('Lack of parameters "user_id"'), 'd_msg_type': "e", "http_status": 400 } return data try: ObjectId(user_id) except: data = { 'd_msg': gettext('This may be a visitor"'), 'd_msg_type': "e", "http_status": 400 } return data s, r = get_user_public_info(user_id=user_id, is_basic=is_basic) if not s: data = {'msg': r, 'msg_type': "w", "http_status": 400} else: data["user"] = r return data
def user_edit(): ''' 用户编辑 :return: ''' id = request.argget.all('id') role_id = request.argget.all('role_id') active = str_to_num(request.argget.all('active', 0)) s, r = arg_verify(reqargs=[("id", id), ("role_id", role_id)], required=True) if not s: return r data = {'msg': gettext("Update success"), 'msg_type': "s", "http_status":201} update_data = { 'role_id': role_id, 'active': active, } user = mdb_user.db.user.find_one({"_id": ObjectId(id)}) if user: # 权限检查 current_user_role = mdb_user.db.role.find_one({"_id": ObjectId(current_user.role_id)}) edit_user_role = mdb_user.db.role.find_one({"_id": ObjectId(user["role_id"])}) if edit_user_role \ and get_num_digits(current_user_role["permissions"]) \ <= get_num_digits(edit_user_role["permissions"]): # 没有权限修改 data = {"msg_type": "w", "msg": gettext("No permission modification"), "http_status":401} return data r = mdb_user.db.user.update_one({"_id": ObjectId(id)}, {"$set": update_data}) if not r.modified_count: data = {'msg': gettext("No changes"), 'msg_type': "w", "http_status":201} return data
def sign_in(): username = request.argget.all('username', '').strip() password = request.argget.all('password', '').strip() code = request.argget.all('code', '').strip() code_url_obj = json_to_pyseq(request.argget.all('code_url_obj', {})) remember_me = request.argget.all('remember_me', 0) use_jwt_auth = str_to_num(request.argget.all('use_jwt_auth', 0)) try: remember_me = int(remember_me) except BaseException: data = { "d_msg": gettext("remember_me requires an integer"), "d_msg_type": "e", "custom_status": 400 } return data data = p_sign_in(username=username, password=password, code_url_obj=code_url_obj, code=code, remember_me=remember_me, use_jwt_auth=use_jwt_auth) return data
def static_file(path): """ apps/static下静态文件获取(本视图函数只针对apps/static下的图片),apps/static下其他可以直接哟你flask默认的 注意:图片获取路由(apps/static下) 参数w,h可指定图片大小 :param path:原图片路径 :param w:获取的宽 :param h:获取的高 :return:w和h都大于0则返回相应尺寸图片; w和h都等于0则返回原图; 其中一个值大于0则返回以这个值为基础等比缩放图片 """ w = str_to_num(request.args.get("w", 0)) h = str_to_num(request.args.get("h", 0)) if w or h: path_list = os.path.splitext(path.rstrip().rstrip("/")) absolute_path = os.path.abspath("{}/{}_w_{}_h_{}{}".format( static.template_folder, path_list[0], w, h, path_list[1])) if not os.path.isfile(absolute_path): img_path = os.path.abspath("{}/{}".format(static.template_folder, path)) try: imgcs = ImageCompression(img_path, absolute_path) except BaseException: abort(404) if w and h: # 自定义长宽 imgcs.custom_pixels(w, h) else: # 等比缩放 imgcs.isometric(w, h) else: absolute_path = os.path.abspath("{}/{}".format(static.template_folder, path)) if not os.path.isfile(absolute_path): abort(404) absolute_path = banel_translate_js_files(prefix="static", route_relative_path=path, absolute_path=absolute_path) return send_file(filename_or_fp=absolute_path, conditional=True, last_modified=True)
def add_per(): name = request.argget.all('name', '').strip() explain = request.argget.all('explain') default = int(request.argget.all('is_default', 0).strip()) position = str_to_num(request.argget.all('position', 0)) data = { 'msg': gettext("Add a success"), 'msg_type': "s", "custom_status": 201} s, r = arg_verify( reqargs=[ (gettext("name"), name), (gettext("position"), position)], required=True) if not s: return r hightest_pos = get_num_digits(SUPER_PER) permissions = int(math.pow(2, position - 1)) if hightest_pos > hightest_pos and position < 1: data = { 'msg': gettext( "Must be an integer greater than 0," " less than or equal to {}".format(hightest_pos)), 'msg_type': "w", "custom_status": 403} elif mdbs["user"].db.permission.find_one({"name": name}): data = {'msg': gettext("Permission name or valready exists"), 'msg_type': "w", "custom_status": 403} elif mdbs["user"].db.permission.find_one({"value": permissions}): data = {'msg': gettext('Location has been used'), 'msg_type': "w", "custom_status": 403} else: user_role = mdbs["user"].db.role.find_one( {"_id": ObjectId(current_user.role_id)}) if get_num_digits(user_role["permissions"] ) <= get_num_digits(permissions): data = { "msg": gettext( "The current user permissions are lower than the permissions that you want to add," " without permission to add"), "msg_type": "w", "custom_status": 401} return data mdbs["user"].db.permission.insert_one({"name": name, "explain": explain, 'value': permissions, "is_default": default}) cache.delete(key=GET_DEFAULT_SYS_PER_CACHE_KEY, db_type="redis") cache.delete(key=GET_ALL_PERS_CACHE_KEY, db_type="redis") return data
def permissions_details(): """ 获取多个权限的详情 :return: """ data = {} page = str_to_num(request.argget.all('page', 1)) pre = str_to_num(request.argget.all('pre', 10)) rs = mdbs["user"].db.permission.find({}) data_cnt = rs.count(True) roles = list(rs.skip(pre * (page - 1)).limit(pre)) roles = sorted(roles, key=lambda x: x["value"]) for role in roles: role["pos"] = get_num_digits(role["value"]) data["pers"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=objid_to_str(roles)) return data
def all_profile(): ''' 获取用户信息 :return: ''' is_basic = str_to_num(request.argget.all('is_basic', 1)) data = {} s, r = get_user_all_info(user_id=current_user.str_id, is_basic=is_basic) if not s: data = {'msg': r, 'msg_type': "w", "http_status": 400} else: data["user"] = r return data
def all_profile(): """ 获取用户信息 :return: """ is_basic = str_to_num(request.argget.all('is_basic', 1)) data = {} s, r = get_user_all_info(user_id=current_user.str_id, is_basic=is_basic, current_user_isauth=current_user.is_authenticated) if not s: data = {'msg': r, 'msg_type': "w", "custom_status": 400} else: data["user"] = r return data
def sign_up(): if not get_config("login_manager", "OPEN_REGISTER"): data = { "msg": gettext('Sorry, temporarily unregistered function'), "msy_type": "w", "http_status": 401} else: email = request.argget.all('email', '').strip() mobile_phone_number = str_to_num( request.argget.all( 'mobile_phone_number', 0)) username = request.argget.all('username', '').strip() password = request.argget.all('password', '').strip() password2 = request.argget.all('password2', '').strip() code = request.argget.all('code', '').strip() data = p_sign_up(email=email, mobile_phone_number=mobile_phone_number, username=username, password=password, password2=password2, code=code) return data
def get_search_logs(): number = str_to_num(request.argget.all('number', 10)) if not number: number = 10 if number > 20: number = 20 user_logs = [] if current_user.is_authenticated: user_id = current_user.str_id user_logs = mdbs["web"].dbs["search_logs"].find( { "user_id": user_id, "status": "normal" }, { "_id": 0 } ).sort([("lasted_time", -1)]).limit(number) user_logs = list(user_logs) user_logs = sorted(user_logs, key=lambda x: -x["lasted_time"]) return { "logs": user_logs }
def send_code(): """ 发送验证码 :return: """ data = {} account_type = request.argget.all('account_type', "email").strip() account = request.argget.all('account') exist_account = str_to_num(request.argget.all('exist_account', 0)) code = request.argget.all('code', '').strip() code_url_obj = json_to_pyseq(request.argget.all('code_url_obj', {})) s, r = arg_verify(reqargs=[("account_type", account_type)], only=["email", "mobile_phone"]) if not s: return r if account_type == "email": s, r = arg_verify(reqargs=[(gettext("Email"), account)], required=True) if not s: return r # 邮箱格式验证 r, s = email_format_ver(account) if not r: data = {'msg': s, 'msg_type': "e", "custom_status": 422} return data if exist_account: if not get_one_user(email=account): data = { 'msg': gettext("This account is not registered on this platform"), 'msg_type': "w", "custom_status": 400 } return data r, s = call_verification(code_url_obj, code) if not r: return s data = create_code_send(account=account, account_type=account_type) elif account_type == "mobile_phone": s, r = arg_verify(reqargs=[(gettext("Telephone number"), account)], required=True) if not s: return r # 移动号码格式格式验证 r, s = mobile_phone_format_ver(account) if not r: data = {'msg': s, 'msg_type': "e", "custom_status": 422} return data if exist_account: user_query = {"mphone_num": account} if not get_one_user(mphone_num=account): data = { 'msg': gettext("This account is not registered on this platform"), 'msg_type': "w", "custom_status": 400 } return data r, s = call_verification(code_url_obj, code) if not r: return s data = create_code_send(account=account, account_type=account_type) return data
def get_global_media(dbname, collname): """ 根据conditions, category_name 获取media或theme_display_setting中的数据 :param dbname: :param collname: :return: """ mdb = mdbs[dbname] conditions = json_to_pyseq(request.argget.all("conditions", [])) category_name = json_to_pyseq(request.argget.all("category_name", [])) media_id = request.argget.all("media_id") medias = {} if collname == "theme_display_setting": q = {"theme_name": get_config("theme", "CURRENT_THEME_NAME")} else: q = {} if media_id: q["_id"] = ObjectId(media_id) media = mdb.dbs[collname].find_one(q) media["_id"] = str(media["_id"]) media["url"] = get_file_url(media["url"]) data = {"media": media} return data elif category_name and collname == "media": # collname == "media" 的时候 # 获取指定category_name user_id type的media category_user_id = request.argget.all("category_user_id", 0) category_type = request.argget.all("category_type") page = str_to_num(request.argget.all("page", 1)) pre = str_to_num(request.argget.all("pre", 8)) categorys = mdbs["web"].db.category.find( { "type": category_type, "user_id": category_user_id, "name": { "$in": category_name } }, {"_id": 1}) category_ids = [] for category in categorys: category_ids.append(str(category["_id"])) sort = [("time", -1)] q["category_id"] = {"$in": category_ids} medias = mdb.dbs[collname].find(q) data_cnt = medias.count(True) medias = list(medias.sort(sort).skip(pre * (page - 1)).limit(pre)) for d in medias: d["_id"] = str(d["_id"]) if "url" in d and d["url"]: d["url"] = get_file_url(d["url"]) medias = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=medias) else: for condition in conditions: if "name_regex" in condition and condition["name_regex"]: q["type"] = condition["type"] q["name"] = { "$regex": condition["name_regex"], "$options": "$i" } temp_media = list(mdb.dbs[collname].find(q).sort([("name", 1) ])) else: q["type"] = condition["type"] q["name"] = {"$in": condition["names"]} temp_media = list(mdb.dbs[collname].find(q).sort([("name", 1) ])) for d in temp_media: d["_id"] = str(d["_id"]) if "url" in d and d["url"]: d["url"] = get_file_url(d["url"]) medias[condition["result_key"]] = temp_media data = {"medias": medias} return data
def edit_per(): tid = request.argget.all('id').strip() name = request.argget.all('name', '').strip() explain = request.argget.all('explain', '') default = int(request.argget.all('is_default', 0).strip()) position = str_to_num(request.argget.all('position', 0)) s, r = arg_verify(reqargs=[(gettext("name"), name), (gettext("position"), position)], required=True) if not s: return r hightest_pos = get_num_digits(SUPER_PER) if position > hightest_pos and position < 1: data = { 'msg': gettext("Must be an integer greater than 0," " less than or equal to {}".format(hightest_pos)), 'msg_type': "w", "custom_status": 403 } return data data = { "msg": gettext( "The current user permissions are lower than the permissions you want to modify," " without permission to modify"), "msg_type": "w", "custom_status": 401 } user_role = mdbs["user"].db.role.find_one( {"_id": ObjectId(current_user.role_id)}) # 如果当前用户的权限最高位 小于 要修改成的这个角色权重的最高位,是不可以的 permissions = int(math.pow(2, position - 1)) if get_num_digits(user_role["permissions"]) <= get_num_digits(permissions): return data per = { "name": name, "explain": explain, 'value': permissions, "is_default": default } if mdbs["user"].db.permission.find_one({ "name": name, "_id": { "$ne": ObjectId(tid) } }): data = { 'msg': gettext("Permission name already exists"), 'msg_type': "w", "custom_status": 403 } elif mdbs["user"].db.permission.find_one({ "value": permissions, "_id": { "$ne": ObjectId(tid) } }): data = { 'msg': gettext('Location has been used'), 'msg_type': "w", "custom_status": 403 } else: old_per = mdbs["user"].db.permission.find_one({ "_id": ObjectId(tid), "value": { "$exists": True } }) if old_per: old_per_value = old_per["value"] r = mdbs["user"].db.permission.update_one({"_id": ObjectId(tid)}, {"$set": per}) if not r.modified_count: data = { 'msg': gettext("No changes"), 'msg_type': "w", "custom_status": 201 } else: r = update_role_and_api_per(old_per_value, new_per_value=0) updated_rolename = r["updated_rolename"] msg_updated_rolename = gettext( "The role of the chain reaction is: \n") if updated_rolename: for ur in updated_rolename: msg_updated_rolename = '{}, "{}"'.format( msg_updated_rolename, ur) else: msg_updated_rolename = '{} 0'.format(msg_updated_rolename) # 刷新缓存 cache.delete(key=GET_DEFAULT_SYS_PER_CACHE_KEY, db_type="redis") cache.delete(key=GET_ALL_PERS_CACHE_KEY, db_type="redis") data = { 'msg': gettext("The update is successful. {}".format( msg_updated_rolename)), 'msg_type': "s", "custom_status": 201 } else: data = { 'msg': gettext("Update failed"), 'msg_type': "w", "custom_status": 400 } return data
def nav_setting(): """ Update :RETURN: """ cid = request.argget.all("id") theme_name = request.argget.all("theme_name") lang = request.argget.all("language") display_name = request.argget.all("display_name") order = str_to_num(request.argget.all("order", 99)) json_data = json_to_pyseq(request.argget.all("json_data")) s, r = arg_verify([(gettext("Display name"), display_name), (gettext("theme name"), theme_name), (gettext("language"), lang), (gettext("Json data"), json_data)], required=True) if not s: return r if not isinstance(json_data, dict): data = { "msg": gettext('Value must be of type json'), "msg_type": "e", "custom_status": 400 } return data if not cid: updata = { 'theme_name': theme_name, 'display_name': display_name, 'language': lang, 'json_data': json_data, "order": order } r = mdbs["sys"].dbs["theme_nav_setting"].insert_one(updata) if r.inserted_id: data = { "msg": gettext("Navigation added successfully"), "msg_type": "s", "custom_status": 200 } else: data = { "msg": gettext("Failed to add navigation"), "msg_type": "w", "custom_status": 400 } else: updata = { 'theme_name': theme_name, 'display_name': display_name, 'language': lang, 'json_data': json_data, "order": order } r = mdbs["sys"].dbs["theme_nav_setting"].update_one( {"_id": ObjectId(cid)}, {"$set": updata}) if r.modified_count: data = { "msg": gettext("Updated successfully"), "msg_type": "s", "custom_status": 200 } elif r.matched_count: data = { "msg": gettext("Unmodified"), "msg_type": "w", "custom_status": 200 } else: data = { "msg": gettext("Update failed"), "msg_type": "w", "custom_status": 400 } cache.delete_autokey(fun="get_global_theme_navs", theme_name=".*", lang=".*", db_type="redis", key_regex=True) return data
def add_display_setting(): """ :return: """ batch = request.argget.all("batch", False) name = request.argget.all("name") link = request.argget.all("link") link_open_new_tab = str_to_num(request.argget.all("link_open_new_tab", 1)) link_name = request.argget.all("link_name") title = request.argget.all("title") text = request.argget.all("text", "") text_html = request.argget.all("text_html", "") code = request.argget.all("code", "") code_type = request.argget.all("code_type") ctype = request.argget.all("ctype") category_id = request.argget.all("category_id") data = {} category = "Default" if code_type == "json": code = json_to_pyseq(code) if category_id and category_id.lower() != "default": display_setting_category = mdbs["web"].db.category.find_one( {"_id": ObjectId(category_id)}) if display_setting_category: category = display_setting_category["name"] elif not category_id or category_id.lower() == "default": category_id = "" s, r = arg_verify([(gettext("type"), ctype)], only=get_config("category", "CATEGORY_TYPE").values()) if not s: return r s, r = arg_verify([(gettext("name"), name)], required=True) if not s and not batch: return r # 如果有上传文件 if request.files: data = file_upload(return_key=True, prefix="multidisplay_setting/{}/".format(ctype)) if data["msg_type"] != "s": return data theme_name = get_config("theme", "CURRENT_THEME_NAME") if not batch and mdbs["sys"].db.theme_display_setting.find_one( { "name": name, "type": ctype, "theme_name": theme_name }): type_alias = ctype for k, v in get_config("category", "CATEGORY_TYPE").items(): if v == ctype: type_alias = k break data = { "msg": gettext('The type "{}" exists in the name "{}"').format( type_alias, name), "msg_type": "w", "custom_status": 403 } else: # 获取text_html使用的图片 if text_html: srcs = richtext_extract_img(richtext=text_html) else: srcs = [] text_imgs = clean_tempfile(user_id=current_user.str_id, type="image", keey_file=srcs) info = { "theme_name": theme_name, "category": category, "category_id": category_id, "link": link, "link_open_new_tab": link_open_new_tab, "link_name": link_name, "title": title, "text": text, "text_html": text_html, "code": code, "code_type": code_type, "switch": 0, "text_imgs": text_imgs, "type": ctype, "time": time.time() } if "keys" in data: for key in data["keys"]: rand_name = "{}_{}".format(name, uuid1()) info["name"] = rand_name info["url"] = key mdbs["sys"].db.theme_display_setting.insert_one(info) data["msg"] = gettext("{} uploaded successfully").format( ctype.capitalize()) else: info["name"] = name info["url"] = None mdbs["sys"].db.theme_display_setting.insert_one(info) data["msg"] = gettext("Added successfully").format( ctype.capitalize()) data["msg_type"] = "s" data["custom_status"] = 201 return data
def edit_display_setting(): """ :return: """ display_setting_id = request.argget.all("id") name = request.argget.all("name") link = request.argget.all("link") link_name = request.argget.all("link_name") link_open_new_tab = str_to_num(request.argget.all("link_open_new_tab", 1)) title = request.argget.all("title") text = request.argget.all("text", "") text_html = request.argget.all("text_html", "") code = request.argget.all("code", "") code_type = request.argget.all("code_type") switch = request.argget.all("switch") category_id = request.argget.all("category_id") s, r = arg_verify([("id", display_setting_id)], required=True) if not s: return r s, r = arg_verify([(gettext("name"), name)], required=True) if not s: return r if code_type == "json": code = json_to_pyseq(code) theme_name = get_config("theme", "CURRENT_THEME_NAME") old_display_setting = mdbs["sys"].db.theme_display_setting.find_one({ "_id": ObjectId(display_setting_id), "theme_name": theme_name }) # 如果只是更新图片, 则保存上传图片 if request.files: data = file_upload(return_key=True, prefix="multidisplay_setting/{}/".format( old_display_setting["type"])) if data["msg_type"] != "s": return data else: # 删除旧的图片 if "url" in old_display_setting: file_del(old_display_setting["url"]) temp_url = None if "keys" in data: for key in data["keys"]: temp_url = key if temp_url: mdbs["sys"].db.theme_display_setting.update_one( { "_id": ObjectId(display_setting_id), "theme_name": theme_name }, {"$set": { "url": temp_url }}) data = { "msg": gettext("Update picture successfully"), "msg_type": "s", "custom_status": 201 } else: data = { "msg": gettext("Failed to update"), "msg_type": "e", "custom_status": 400 } return data category = "Default" not_updated_category = False if category_id is None: # 不更新category not_updated_category = True elif category_id and category_id.lower() != "default": display_setting_category = mdbs["web"].db.category.find_one( {"_id": ObjectId(category_id)}) if display_setting_category: category = display_setting_category["name"] elif category_id.lower() == "default": category_id = "" # 处理其他字段更新 query = { "name": name, "type": old_display_setting["type"], "_id": { "$ne": ObjectId(display_setting_id) }, "theme_name": theme_name } if mdbs["sys"].db.theme_display_setting.find_one(query): type_alias = old_display_setting["type"] for k, v in get_config("category", "CATEGORY_TYPE").items(): if v == old_display_setting["type"]: type_alias = k break data = { "msg": gettext('The type "{}" exists in the name "{}"').format( type_alias, name), "msg_type": "w", "custom_status": 403 } else: # 获取text_html使用的图片 old_imgs = old_display_setting.get("text_imgs", []) if text_html: srcs = richtext_extract_img(richtext=text_html) else: srcs = [] text_imgs = clean_tempfile(user_id=current_user.str_id, type="image", old_file=old_imgs, keey_file=srcs) info = { "name": name, "link": link, "link_name": link_name, "link_open_new_tab": link_open_new_tab, "title": title, "text": text, "text_html": text_html, "code": code, "code_type": code_type, "text_imgs": text_imgs, } if switch is not None and switch.isdigit(): info["switch"] = int(switch) if not not_updated_category: info["category_id"] = category_id info["category"] = category r = mdbs["sys"].db.theme_display_setting.update_one( { "_id": ObjectId(display_setting_id), "theme_name": theme_name }, {"$set": info}) if r.modified_count: data = { "msg": gettext("Modify the success"), "msg_type": "s", "custom_status": 201 } else: data = { "msg": gettext("The content is not modified"), "msg_type": "w", "custom_status": 400 } return data