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_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_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_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_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 audit_rules(): data = {} project = request.argget.all('project', 'username') keyword = request.argget.all('keyword') page = int(request.argget.all('page', 1)) pre = int(request.argget.all('pre', 10)) q = {} if project: q["project"] = project if keyword: keyword = {"$regex": keyword, "$options": "$i"} q["$or"] = [ {"rule": keyword} ] rules = mdb_sys.db.audit_rules.find(q) data_cnt = rules.count(True) rules = objid_to_str( list(rules.sort([("time", -1)]).skip(pre * (page - 1)).limit(pre))) data["rules"] = datas_paging( pre=pre, page_num=page, data_cnt=data_cnt, datas=rules) 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 users(): ''' Admin获取用户数据 :return: ''' data = {} status = request.argget.all('status') page = int(request.argget.all('page', 1)) pre = int(request.argget.all('pre', 10)) keyword = request.argget.all('keyword', '').strip() if status == "normal" or not status: status = "normal" query_conditions = {"is_delete": {"$in": [False, 0]}, "active": {"$in": [True, 1]}} elif status == "inactive": query_conditions = {"is_delete": {"$in": [False, 0]}, "active": {"$in": [False, 0]}} elif status == "cancelled": query_conditions = {"is_delete": {"$in": [True, 1]}} if keyword: keyword = {"$regex":keyword, "$options":"$i"} query_conditions["$or"] = [{"username": keyword}, {"email": keyword}, {"custom_domain": keyword} ] us = mdb_user.db.user.find(query_conditions, {"password": 0}) data_cnt = us.count(True) users = list(us.sort([("create_at",-1)]).skip(pre * (page - 1)).limit(pre)) roles = list(mdb_user.db.role.find({})) for user in users: user['_id'] = str(user['_id']) for role in roles: if ObjectId(user["role_id"]) == role["_id"]: user["role_name"] = role["name"] user_login_log = mdb_user.db.user_login_log.find_one({"user_id": user["_id"]}, {"user_id": 0}) user["user_login_log"] = [] if user_login_log: user_login_log["_id"] = str(user_login_log["_id"]) user_login_log["login_info"] = sorted(user_login_log["login_info"], key=lambda x:x["time"], reverse=True) user["user_login_log"] = user_login_log user_op_log = mdb_user.db.user_op_log.find_one({'user_id': user["_id"]}, {"user_id": 0}) user["user_op_log"] = [] if user_op_log: user_op_log["_id"] = str(user_op_log["_id"]) user_op_log["logs"] = sorted(user_op_log["logs"], key=lambda x:x["time"], reverse=True) user["user_op_log"] = user_op_log user["role_id"] = str(user["role_id"]) user["avatar_url"]["url"] = get_avatar_url(user["avatar_url"]) data["users"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=users) data["status"] = status return data
def get_posts_query(query_conditions, field, sort, pre, page, get_userinfo): """ 提供查询条件等获取文章 :param query_conditions: :param field: :param sort: :param pre: :param page: :param get_userinfo: :return: """ data = {} if field: ps = mdbs["web"].db.post.find(query_conditions, field) else: ps = mdbs["web"].db.post.find(query_conditions) data_cnt = ps.count(True) posts = list(ps.sort(sort).skip(pre * (page - 1)).limit(pre)) for post in posts: post = objid_to_str(post, ["_id", "user_id", "audit_user_id"]) # image if "cover_url" in post and post["cover_url"]: post["cover_url"] = get_file_url(post["cover_url"]) if "imgs" in post and len(post["imgs"]): for i, img in enumerate(post["imgs"]): post["imgs"][i] = get_file_url(img) if "user_id" not in query_conditions.keys() and get_userinfo: s, r = get_user_public_info( user_id=post["user_id"], is_basic=False, current_user_isauth=current_user.is_authenticated) if s: post["user"] = r else: post['user'] = {} # category if "category" in post and post["category"]: post["category"] = str(post["category"]) category = mdbs["web"].db.category.find_one( {"_id": ObjectId(post["category"])}) if category: post["category_name"] = category["name"] data["posts"] = datas_paging( pre=pre, page_num=page, data_cnt=data_cnt, datas=posts) return data
def roles(): data = {} page = int(request.argget.all('page', 1)) pre = int(request.argget.all('pre', 10)) rs = mdb_user.db.role.find({}) data_cnt = rs.count(True) roles = list(rs.skip(pre * (page - 1)).limit(pre)) roles = sorted(roles, key=lambda x: x["permissions"]) data["roles"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=objid_to_str(roles)) 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 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 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 roles(): data = {} page = int(request.argget.all('page', 1)) pre = int(request.argget.all('pre', 10)) rs = mdbs["user"].db.role.find({}) data_cnt = rs.count(True) roles = list(rs.skip(pre * (page - 1)).limit(pre)) roles = sorted(roles, key=lambda x: x["permissions"]) pers = permissions() for i, role in enumerate(roles): roles[i]["permission_names"] = [] for per in pers["permissions"]: if int(role["permissions"]) & int(per[1]): roles[i]["permission_names"].append(per[0]) data["roles"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=objid_to_str(roles)) return data
def permissions_details(): """ 获取多个权限的详情 :return: """ data = {} page = int(request.argget.all('page', 1)) pre = int(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 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 get_sys_configs(): data = {} project = json_to_pyseq(request.argget.all('project', [])) keyword = request.argget.all('keyword', "") project_info = str_to_num(request.argget.all('project_info', 0)) project_info_page = str_to_num(request.argget.all('project_info_page', 1)) project_info_pre = str_to_num(request.argget.all('project_info_pre', 10)) new_version = mdb_sys.db.sys_config.find_one( {"new_version": { "$exists": True }}, {"_id": 0})["new_version"] query = { "conf_version": new_version, "__sort__": { "$exists": True, "$ne": "" } } if project: query["project"] = {"$in": project} if keyword: keyword = {"$regex": keyword, "$options": "$i"} query["$or"] = [{ "project": keyword }, { "key": keyword }, { "value": keyword }, { "info": keyword }] if project_info: temp_projects = mdb_sys.db.sys_config.find( query, { "project": 1, "__info__": 1, "__restart__": 1, "__sort__": 1, "update_time": 1, "_id": 0 }) data["projects"] = [] exist_project = [] for pr in temp_projects: if pr["project"] not in exist_project: data["projects"].append(pr) exist_project.append(pr["project"]) data_cnt = len(data["projects"]) data["projects"] = sorted(data["projects"], key=lambda x: x["__sort__"]) data["projects"] = data["projects"][ (project_info_page - 1) * project_info_pre:(project_info_page - 1) * project_info_pre + project_info_pre] data["projects"] = datas_paging(pre=project_info_pre, page_num=project_info_page, data_cnt=data_cnt, datas=data["projects"]) return data confs = mdb_sys.db.sys_config.find(query).sort([("__sort__", 1), ("sort", 1)]) if confs.count(True): confs = confs temp_list_other = [] temp_list_json = [] # 将值是list和dict的配置放发哦数组后面 key_hiding = get_config("system", "KEY_HIDING") for conf in confs: conf["_id"] = str(conf["_id"]) if key_hiding and conf["type"] == "password": conf["value"] = "Has been hidden" if conf["type"] in ["list", "dict"]: temp_list_json.append(conf) else: temp_list_other.append(conf) temp_list_other.extend(temp_list_json) data["configs"] = temp_list_other if key_hiding: data["msg_type"] = "w" data["msg"] = gettext( "The KEY_HIDING switch in the system configuration has been enabled." " The value of the password type has been replaced.") else: data = { "msg": gettext("There is no such data"), "msg_type": "warning", "http_status": 400 } return data
def get_more_goods(): ''' 获取多个货物信息 :return: ''' goods_type_id = request.argget.all('goods_type_id') category_id = request.argget.all('category_id') business_id = request.argget.all('business_id') keyword = request.argget.all('keyword') sort = json_to_pyseq(request.argget.all('sort', [("update_time", -1)])) page = str_to_num(request.argget.all('page', 1)) pre = str_to_num(request.argget.all('pre', 15)) query = {"goods_type_id": goods_type_id, "user_id": current_user.str_id} if category_id: query["category_id"] = category_id if business_id: query["business_id"] = business_id if keyword: keyword = {"$regex": r".*{}.*".find(keyword)} query["$or"] = [ { "customize_id": keyword }, { "introduction": keyword }, { "property.color": keyword }, ] goods = mdb_web.dbs["plug_warehouse_goods"].find(query) data_cnt = goods.count(True) if data_cnt: goods = list(goods.sort(sort).skip(pre * (page - 1)).limit(pre)) goods = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=goods) for gd in goods["datas"]: sizes = [] colors = [] cloths = [] total = 0 shortcoming = 0 total_sales = 0 inventory_warning = 0 property = gd["property"] for v in property.values(): if v["size"]: sizes.append(v["size"]) if v["color"]: colors.append(v["color"]) if v["quantity"] > 0: total += v["quantity"] elif v["quantity"] < 0: shortcoming += -v["quantity"] total_sales += v["sales"] if v["quantity"] < 10: inventory_warning += 1 for k, v in gd['cloth'].items(): cloths.append({"name": k, "per": v}) sizes = list(set(sizes)) colors = list(set(colors)) gd["sizes"] = sizes gd["colors"] = colors gd["cloths"] = cloths gd["total"] = total gd["total_sales"] = total_sales gd["_id"] = str(gd["_id"]) gd["inventory_warning"] = inventory_warning gd["shortcoming"] = shortcoming data = {"goods": goods, "msg_type": "s", "http_status": 200} else: data = { "msg": gettext("No related data found"), "msg_type": "w", "http_status": 404 } return data
def find_comments( query_conditions={}, page=1, pre=10, sort=None, keyword="", status="is_issued", *args, **kwargs): data = {} if pre > get_config("comment", "NUM_PAGE_MAX"): data = {"msg": gettext('The "pre" must not exceed the maximum amount'), "msg_type": "e", "custom_status": 400} return data query_conditions = deepcopy(query_conditions) if status == "not_audit": query_conditions['issued'] = 1 query_conditions['is_delete'] = 0 # 没有审核, 而且默认评分涉嫌违规的 query_conditions['audited'] = 0 query_conditions['audit_score'] = { "$gte": get_config( "content_inspection", "ALLEGED_ILLEGAL_SCORE")} elif status == "unqualified": query_conditions['issued'] = 1 query_conditions['is_delete'] = 0 query_conditions['audited'] = 1 query_conditions['audit_score'] = { "$gte": get_config( "content_inspection", "ALLEGED_ILLEGAL_SCORE")} elif status == "user_remove": query_conditions['is_delete'] = {"$in": [1, 2]} else: query_conditions['issued'] = 1 query_conditions['is_delete'] = 0 query_conditions['audit_score'] = { "$lt": get_config( "content_inspection", "ALLEGED_ILLEGAL_SCORE")} if keyword: keyword = {"$regex": keyword, "$options": "$i"} query_conditions["content"] = keyword cs = mdbs["web"].db.comment.find(query_conditions) data_cnt = cs.count(True) # sort if sort: for i, srt in enumerate(sort): sort[i] = (list(srt.keys())[0], list(srt.values())[0]) else: sort = [("issue_time", -1)] comments = list(cs.sort(sort).skip(pre * (page - 1)).limit(pre)) comments = recursive_find_comment(comments) data["comments"] = datas_paging( pre=pre, page_num=page, data_cnt=data_cnt, datas=comments) return data
def get_global_media(): ''' 根据conditions获取category_name获取media :return: ''' 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 media_id: media = mdb_web.db.media.find_one({"_id": ObjectId(media_id)}) media["_id"] = str(media["_id"]) media["url"] = get_file_url(media["url"]) data = {"media": media} return data elif category_name: # 获取指定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 = mdb_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)] medias = mdb_web.db.media.find({"category_id": {"$in": category_ids}}) 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"]: temp_media = list( mdb_web.db.media.find({ "type": condition["type"], "name": { "$regex": condition["name_regex"], "$options": "$i" } }).sort([("name", 1)])) else: temp_media = list( mdb_web.db.media.find({ "type": condition["type"], "name": { "$in": condition["names"] } }).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 get_posts_pr(field=None, page=1, pre=10, status="is_issued", sort=None, time_range=None, matching_rec=None, keyword=None, other_filter=None, is_admin=False, *args, **kwargs): ''' 获取一些指定的post :param field: :param page: :param pre: :param status: :param sort: :param time_range: :param matching_rec: :param keyword: :param other_filter: :param is_admin: 是admin用户获取, 可以获取未公开的post :param args: :param kwargs: :return: ''' data = {} if pre > get_config("post", "NUM_PAGE_MAX"): data = { "msg": gettext('The "pre" must not exceed the maximum amount'), "msg_type": "e", "http_status": 400 } return data query_conditions = {} if other_filter: query_conditions = deepcopy(other_filter) if status and status != "is_issued" and not is_admin: # 非admin用户获取未公开post, 需要认证 if not current_user.is_authenticated: # 未登录用户 abort(401) elif "user_id" in query_conditions: if query_conditions["user_id"] != current_user.str_id: # 要获取的user_id不是当前用户 abort(401) else: # 默认获取当前用户 query_conditions["user_id"] = current_user.str_id if status == "no_issued": query_conditions['$or'] = [ { 'issued': 0 }, { 'is_delete': 1 }, { 'audited': 1, 'audit_score': { "$gte": get_config("content_inspection", "ALLEGED_ILLEGAL_SCORE") } }, ] elif status == "draft": query_conditions['issued'] = 0 query_conditions['is_delete'] = 0 elif status == "not_audit": query_conditions['issued'] = 1 query_conditions['is_delete'] = 0 # 没有审核, 而且默认评分涉嫌违规的 query_conditions['audited'] = 0 query_conditions['audit_score'] = { "$gte": get_config("content_inspection", "ALLEGED_ILLEGAL_SCORE") } elif status == "unqualified": query_conditions['issued'] = 1 query_conditions['is_delete'] = 0 query_conditions['audited'] = 1 query_conditions['audit_score'] = { "$gte": get_config("content_inspection", "ALLEGED_ILLEGAL_SCORE") } elif status == "recycle": query_conditions['is_delete'] = 1 elif status == "user_remove": query_conditions['is_delete'] = {"$in": [2, 3]} else: query_conditions['issued'] = 1 query_conditions['is_delete'] = 0 query_conditions['audit_score'] = { "$lt": get_config("content_inspection", "ALLEGED_ILLEGAL_SCORE") } if keyword: keyword = {"$regex": keyword, "$options": "$i"} query_conditions["$or"] = [{ "title": keyword }, { "content": keyword }, { "category": keyword }, { "tag": keyword }] # sort if sort: for i in range(0, len(sort)): sort[i] = (list(sort[i].keys())[0], list(sort[i].values())[0]) else: sort = [("issue_time", -1), ("update_time", -1)] # time_range if time_range: now_time = time.time() gt_time = (now_time - 86400 * (time_range - 1)) - now_time % 86400 query_conditions["issue_time"] = {'$gt': gt_time} if field: ps = mdb_web.db.post.find(query_conditions, field) else: ps = mdb_web.db.post.find(query_conditions) data_cnt = ps.count(True) posts = list(ps.sort(sort).skip(pre * (page - 1)).limit(pre)) get_userinfo = kwargs.get("get_userinfo", True) for post in posts: post = objid_to_str(post, ["_id", "user_id", "audit_user_id"]) # image if "cover_url" in post and post["cover_url"]: post["cover_url"] = get_file_url(post["cover_url"]) if "imgs" in post and len(post["imgs"]): for i in range(0, len(post["imgs"])): post["imgs"][i] = get_file_url(post["imgs"][i]) if not "user_id" in query_conditions.keys() and get_userinfo: s, r = get_user_public_info(user_id=post["user_id"], is_basic=False) if s: post["user"] = r # category if "category" in post and post["category"]: post["category"] = str(post["category"]) category = mdb_web.db.category.find_one( {"_id": ObjectId(post["category"])}) if category: post["category_name"] = category["name"] data["posts"] = datas_paging(pre=pre, page_num=page, data_cnt=data_cnt, datas=posts) return data
def get_static_files(): page = int(request.argget.all('page', 1)) pre = int(request.argget.all('pre', 15)) keyword = request.argget.all('keyword', "") ntype = request.argget.all('type', "all") regex_filter = r".+\.(html|js|css)$" path = os.path.join(THEME_TEMPLATE_FOLDER, get_config("theme", "CURRENT_THEME_NAME")) temp_files = file_traversal(path, regex_filter=regex_filter) if ntype == "custom": theme_custom = mdbs["sys"].db.theme.find_one( {"theme_name": get_config("theme", "CURRENT_THEME_NAME")}) if not theme_custom or not theme_custom["custom_pages"]: theme_custom = False else: theme_custom = False if ntype != "custom": if theme_custom: for file in temp_files[:]: if file["name"] in theme_custom["custom_pages"]: temp_files.remove(file) else: if keyword: if keyword in file["path"] or keyword in file["name"]: file["is_custom_page"] = False file["relative_path"] = file["path"].replace( path, "").strip("/") else: temp_files.remove(file) else: file["is_custom_page"] = False file["relative_path"] = file["path"].replace( path, "").strip("/") else: for file in temp_files[:]: if keyword: if keyword in file["path"] or keyword in file["name"]: file["is_custom_page"] = False file["relative_path"] = file["path"].replace( path, "").strip("/") else: temp_files.remove(file) else: file["is_custom_page"] = False file["relative_path"] = file["path"].replace(path, "").strip("/") elif ntype == "custom": if theme_custom: for file in temp_files[:]: if file["name"] in theme_custom["custom_pages"]: if keyword: if keyword in file["path"] or keyword in file["name"]: file["is_custom_page"] = True file["relative_path"] = file["path"].replace( path, "").strip("/") else: temp_files.remove(file) else: file["is_custom_page"] = True file["relative_path"] = file["path"].replace( path, "").strip("/") else: temp_files.remove(file) else: temp_files = [] data = {"files": temp_files[(page - 1) * pre:(page - 1) * pre + pre]} data["files"] = datas_paging(pre=pre, page_num=page, data_cnt=len(temp_files), datas=data["files"]) data["files"]["current_theme"] = get_config("theme", "CURRENT_THEME_NAME") return data
def sys_log(): name = request.argget.all('name') ip = request.argget.all('ip') page = int(request.argget.all('page', 1)) host = mdbs["sys"].db.sys_host.find_one({"host_info.local_ip": ip}) if host: host_info = host["host_info"] s, v = audit_host_info(host_info) if not s: return v else: ssh = MySSH(ip, port=host_info["port"], username=host_info["username"], password=host_info["password"]) if not ssh: data = { "msg": gettext( "Connection host[{}] failed,Check the host Settings"). format(ip), "msg_type": "e", "custom_status": 400 } return data sftp = ssh.client.open_sftp() remote_file = "{}/logs/{}".format(PROJECT_PATH, name) local_temp_log_dir = '{}/logs/remote_file'.format(PROJECT_PATH) if not os.path.exists(local_temp_log_dir): os.makedirs(local_temp_log_dir) local_file = '{}/{}_{}'.format(local_temp_log_dir, ip, name) sftp.get(remote_file, local_file) ssh.close() pre = 50 rf = open(local_file) count = 0 while True: buffer = rf.read(8192 * 1024) if not buffer: break count += buffer.count('\n') rf.close() logs = [] n = 1 with open(local_file) as f: for line in f: if n > (page - 1) * pre: logs.append(line) if n >= page * pre: break n += 1 f.close() logs = datas_paging(pre=pre, page_num=page, data_cnt=count, datas=logs) logs["datas"] = "".join(logs["datas"]) logs["datas"] = logs["datas"].replace("\n", "<br>") data = {"logs": logs} os.remove(local_file) else: data = { "msg": gettext("There is no host {}").format(ip), "msg_type": "e", "custom_status": 400 } return data