Beispiel #1
0
def recursive_find_comment(comments):

    for comment in comments:
        comment = objid_to_str(
            comment, [
                "_id", "user_id", "audit_user_id", ""])
        comment["date"] = time_to_utcdate(
            time_stamp=comment["issue_time"],
            tformat="%Y-%m-%d %H:%M")
        if current_user.is_authenticated:
            r = mdbs["user"].db.user_like.find_one(
                {"user_id": current_user.str_id, "type": "comment", "values": comment["_id"]})
            if r:
                comment["like_it_already"] = True
        # 评论下面的所有回复
        query_conditions = {}
        query_conditions['issued'] = 1
        query_conditions['is_delete'] = 0
        query_conditions['audit_score'] = {
            "$lt": get_config(
                "content_inspection",
                "ALLEGED_ILLEGAL_SCORE")}
        query_conditions["reply_id"] = comment["_id"]
        reply_comments = mdbs["web"].db.comment.find(
            query_conditions).sort([("issue_time", -1)])
        if reply_comments.count(True):
            comment["reply"] = objid_to_str(
                list(reply_comments), [
                    "_id", "user_id", "audit_user_id"])
            comment["reply"] = recursive_find_comment(comment["reply"])

    return comments
Beispiel #2
0
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
Beispiel #3
0
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
Beispiel #4
0
def get_post_pr(post_id="",
                other_filter=None,
                is_admin=False,
                *args,
                **kwargs):
    """
    获取一个Post
    :param post_id:
    :param other_filter:
    :param is_admin: 是admin用户获取, 可以获取未公开的post
    :param args:
    :param kwargs:
    :return:
    """
    data = {}
    query_conditions = {}
    print("query_conditions:", query_conditions)
    if isinstance(other_filter, dict):
        query_conditions = deepcopy(other_filter)

    query_conditions["_id"] = ObjectId(post_id)

    post = mdbs["web"].db.post.find_one(query_conditions)
    if post:
        if not is_admin:
            if not post["issued"] or post[
                    "is_delete"] or post["audit_score"] >= get_config(
                        "content_inspection", "ALLEGED_ILLEGAL_SCORE"):
                # 未公开的
                if not current_user.is_authenticated or current_user.str_id != str(
                        post["user_id"]):
                    # 没有权限访问
                    abort(401)

        post = objid_to_str(post, ["_id", "user_id", "audit_user_id"])
        post["cover_url"] = get_file_url(post["cover_url"])
        imgs_l = len(post["imgs"])
        if imgs_l:
            for i, img in enumerate(post["imgs"]):
                post["imgs"][i] = get_file_url(img)

        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
        data["post"] = post
        if "category" in post and post["category"]:
            category = mdbs["web"].db.category.find_one(
                {"_id": ObjectId(str(post["category"]))})
            if category:
                data["post"]["category_name"] = category["name"]

        if current_user.is_authenticated and current_user.str_id in post[
                "like_user_id"]:
            post["like_it_already"] = True
    else:
        abort(404)
    return data
Beispiel #5
0
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
Beispiel #6
0
def sys_config_version():

    version_uses = mdb_sys.db.sys_config.find_one(
        {"new_version": {
            "$exists": True
        }}, {"_id": 0})
    hosts = objid_to_str(list(mdb_sys.db.sys_host.find({"type": "web"})))
    version_uses["used_versions"].reverse()
    data = {"version": version_uses, "hosts": hosts}
    return data
Beispiel #7
0
def get_global_site_data(req_type="api"):
    """
    获取全局的站点信息
    req_type:如果为"view"则不需要返回用户基本信息
    :return:
    """
    data = {}

    # 全局数据
    # theme
    data["theme_config"] = get_configs("theme_global_conf")
    theme_name = g.get_config("theme", "CURRENT_THEME_NAME")
    lang = g.site_global["language"]["current"]
    data["theme_config"]["navs"] = get_global_theme_navs(theme_name=theme_name,
                                                         lang=lang)

    # site
    data["site_config"] = get_configs("site_config")
    data["site_config"]["STATIC_FILE_VERSION"] = "{}_{}".format(
        data["site_config"]["STATIC_FILE_VERSION"], lang)
    data["site_config"] = dict(data["site_config"], **get_configs("seo"))
    data["site_config"]["sys_version"] = VERSION
    # msg
    if current_user.is_authenticated:
        msgs = mdbs["user"].db.message.find(
            {
                "user_id": current_user.str_id,
                "$or": [{
                    "status": "not_noticed"
                }, {
                    "status": {
                        "$exists": False
                    }
                }]
            }, {
                "_id": 0,
                "content": 0
            })
        msg_cnt = msgs.count(True)
        data["user_msg"] = {
            "msg_count": msg_cnt,
            "msgs": list(msgs.sort([("time", -1)]))
        }
    if req_type != "view":
        if current_user.is_authenticated:
            user_info = objid_to_str(current_user.user_info, ["id", "role_id"])
            data["is_authenticated"] = True
            data["user_info"] = user_info
        else:
            data["is_authenticated"] = False
            data["user_info"] = {}
    data['d_msg'] = gettext("Get the current user information successfully")
    data['d_msg_type'] = "s"
    return data
Beispiel #8
0
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
Beispiel #9
0
 def get_secret_tokens(self):
     token_info = mdbs["sys"].db.sys_token.find({"token_type": "secret_token"})
     if not token_info.count(True):
         s, r = self.create_secret_token()
         token_info = [r]
     else:
         token_info = objid_to_str(token_info)
     is_active_token = []
     for token in token_info:
         if token["is_active"]:
             is_active_token.append(token["token"])
     data = {"token_info": token_info, "is_active_token": is_active_token}
     return data
Beispiel #10
0
def categorys(user_id=None):

    if user_id is None:
        user_id = current_user.str_id
    data = {}
    ntype = request.argget.all('type')
    s, r = arg_verify([(gettext("category type"), ntype)], required=True)
    if not s:
        return r
    category = list(mdb_web.db.category.find(
        {"user_id": user_id, "type": ntype}))
    data["categorys"] = objid_to_str(category, ["_id", "user_id"])
    return data
Beispiel #11
0
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_businesses():

    '''
    获取所有厂家
    :return:
    '''
    goods_type_id = request.argget.all('goods_type_id')
    business = mdb_web.dbs["plug_warehouse_business"].find({"type_id":goods_type_id,
                                                          "user_id":current_user.str_id})
    business = objid_to_str(business)
    data = {"businesses":business, "msg_type": "s", "msg":gettext("Successful data acquisition"),
            "http_status": 200}

    return data
def get_categorys():

    '''
    获取一种商品的所有分类
    :return:
    '''
    goods_type_id = request.argget.all('goods_type_id')
    categorys = mdb_web.dbs["plug_warehouse_category"].find({"type_id":goods_type_id,
                                                          "user_id":current_user.str_id})
    categorys = objid_to_str(categorys)
    data = {"categorys":categorys, "msg_type": "s", "msg":gettext("Successful data acquisition"),
            "http_status": 200}

    return data
Beispiel #14
0
def get_navs():
    theme_name = request.argget.all("theme_name")
    lang = request.argget.all("language")
    s, r = arg_verify([(gettext("theme name"), theme_name),
                       (gettext("language"), lang)],
                      required=True)
    if not s:
        return r
    navs = mdbs["sys"].dbs["theme_nav_setting"].find({
        "language": lang,
        "theme_name": theme_name
    }).sort([("order", 1)])
    navs = objid_to_str(navs)
    data = {"navs": navs}
    return data
Beispiel #15
0
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 categorys(user_id=None):

    if user_id is None:
        user_id = current_user.str_id
    data = {}
    ntype = request.argget.all('type')
    theme_name = get_config("theme", "CURRENT_THEME_NAME")

    s, r = arg_verify([(gettext("category type"), ntype)], required=True)
    if not s:
        return r
    category = list(mdbs["web"].db.theme_category.find({"user_id": user_id,
                                                    "type": ntype,
                                                    "theme_name": theme_name}))
    data["categorys"] = objid_to_str(category, ["_id", "user_id"])
    data["theme_name"] = theme_name
    return data
def get_goods_types():
    '''
    获取商品所有分类
    :return:
    '''

    types = mdb_web.dbs["plug_warehouse_type"].find(
        {"user_id": current_user.str_id})
    types = objid_to_str(types)
    data = {
        "types": types,
        "msg_type": "s",
        "msg": gettext("Successful data acquisition"),
        "http_status": 200
    }

    return data
Beispiel #18
0
def get_global_site_data(req_type="api"):
    '''
    获取全局的站点信息
    req_type:如果为"view"则不需要返回用户基本信息
    :return:
    '''
    data = {}

    # 全局数据
    data["site_config"] = get_configs("site_config")
    data["site_config"] = dict(data["site_config"], **get_configs("seo"))
    data["site_config"]["sys_version"] = VERSION
    # msg
    if current_user.is_authenticated:
        msgs = mdb_user.db.message.find(
            {
                "user_id": current_user.str_id,
                "$or": [{
                    "status": "not_noticed"
                }, {
                    "status": {
                        "$exists": False
                    }
                }]
            }, {
                "_id": 0,
                "content": 0
            })
        msg_cnt = msgs.count(True)
        data["user_msg"] = {
            "msg_count": msg_cnt,
            "msgs": list(msgs.sort([("time", -1)]))
        }
    if req_type != "view":
        if current_user.is_authenticated:
            user_info = objid_to_str(current_user.user_info, ["id", "role_id"])
            data["is_authenticated"] = True
            data["user_info"] = user_info
        else:
            data["is_authenticated"] = False
            data["user_info"] = {}

    data['d_msg'] = gettext("Get the current user information successfully")
    data['d_msg_type'] = "s"
    return data
Beispiel #19
0
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
Beispiel #20
0
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
Beispiel #21
0
def get_plugin_setting():
    '''
    获取插件设置
    :return:
    '''

    plugin_name = request.argget.all('plugin_name')
    s, r = arg_verify(reqargs=[("plugin name", plugin_name)], required=True)
    if not s:
        return r
    data = {}
    configs = mdb_sys.db.plugin_config.find({"plugin_name": plugin_name})
    if configs.count(True):
        data["configs"] = objid_to_str(configs)

    plugin = mdb_sys.db.plugin.find_one({"plugin_name": plugin_name},
                                        {"_id": 0})
    if plugin:
        data["plugin_info"] = plugin
    else:
        data["plugin_info"] = None
    return data
Beispiel #22
0
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