Ejemplo n.º 1
0
def post_issue():

    tid = request.argget.all('id')
    title = request.argget.all('title', "").strip()
    content = request.argget.all('content', "")
    content_text = request.argget.all('content_text', "")
    editor = request.argget.all('editor')
    category = request.argget.all('category')
    tags = json_to_pyseq(request.argget.all('tags', []))
    issue_way = request.argget.all('issue_way', 'issue')
    cover_url = request.argget.all('cover_url')

    # 标签处理验证
    tag_max_num = get_config("post", "TAG_MAX_NUM")
    if len(tags) > tag_max_num:
        data = {
            "msg": gettext("Up to {} tags are used").format(tag_max_num),
            "msg_type": "w",
            "custom_status": 403
        }
        return data

    tags = list(set(tags))
    temp_tags = ""
    for tag in tags:
        s, r = arg_verify(reqargs=[(gettext("tag"), tag)],
                          max_len=get_config("post", "TAG_MAX_LEN"))
        if not s:
            return r
        temp_tags = "{} {}".format(tag, temp_tags)

    # 分类验证
    try:
        ObjectId(category)
    except BaseException:
        category = None
    # Title 处理
    s, r = arg_verify(reqargs=[(gettext("title"), title.strip())],
                      max_len=get_config("post", "TITLE_MAX_LEN"),
                      required=True)
    if not s:
        return r
    # content
    s, r = arg_verify(reqargs=[(gettext("content"), content.strip()),
                               ("editor", editor)],
                      required=True)
    if not s:
        return r

    text_l = len(content_text)
    if text_l > get_config("post", "BRIEF_LEN"):
        brief_content = content_text[0:get_config("post", "BRIEF_LEN")]
    else:
        brief_content = content_text
    s, r = arg_verify(reqargs=[(gettext("content"), content_text)],
                      max_len=int(get_config("post", "MAX_LEN")))
    if not s:
        data = r
    else:
        if issue_way == "issue":
            issue_way = 1
        else:
            issue_way = 0
        # 获取已上传的文章图片
        old_imgs = []
        if tid:
            # 文章更新
            post = mdbs["web"].db.post.find_one({
                "_id": ObjectId(tid),
                "user_id": current_user.str_id
            })
            if post["issue_time"]:
                # 有发布时间,则发布时间不改变
                issue_time = post["issue_time"]
            elif issue_way:
                # 第一次发布
                issue_time = time.time()
            else:
                # 不发布
                issue_time = 0

            old_imgs = post["imgs"]

        elif issue_way:
            # 发布时间
            issue_time = time.time()
        else:
            # 不发布就不需要发布时间
            issue_time = 0

        # 获取文章中使用的图片
        # 如果是markdown
        if editor == "markdown":
            srcs = richtext_extract_img(richtext=markdown.markdown(content))
        else:
            srcs = richtext_extract_img(richtext=content)
        imgs = clean_tempfile(user_id=current_user.str_id,
                              type="image",
                              old_file=old_imgs,
                              keey_file=srcs)

        if not cover_url and len(imgs) > 0:
            cover_url = imgs[0]

        if issue_way:
            r = content_inspection_text("{} {} {}".format(
                title, content, temp_tags))
            audit_score = r["score"]
            audit_label = r["label"]
            if r["label"] == "detection_off" or ("suggestion" in r and
                                                 r["suggestion"] == "review"):
                # 未开启审核或无法自动鉴别, 等待人工审核
                audited = 0
                audit_way = "artificial"

            elif r["label"] == "no_plugin":
                # 没有检查插件
                audited = 0
                audit_way = "artificial"

            else:
                audit_label = r["label"]
                audited = 1
                audit_way = "auto"
        else:
            # 草稿
            audit_label = None
            audited = audit_score = 0
            audit_way = "auto"
        content = content_attack_defense(content)["content"]
        brief_content = content_attack_defense(brief_content)["content"]
        post = {
            "title": title.strip(),
            "content": content.strip(),
            "brief_content": brief_content,
            "category": category,
            "tags": tags,
            "issued": issue_way,
            "issue_time": issue_time,
            "update_time": time.time(),
            "audited": audited,
            "audit_score": audit_score,
            "audit_user_id": None,
            "audit_way": audit_way,
            "audit_label": audit_label,
            "word_num": text_l,
            "is_delete": 0,
            "imgs": imgs,
            "cover_url": cover_url
        }

        if tid:
            mdbs["web"].db.post.update_one(
                {
                    "_id": ObjectId(tid),
                    "user_id": current_user.str_id
                }, {"$set": post},
                upsert=True)
        else:
            post["comment_num"] = 0
            post["like"] = 0
            post["like_user_id"] = []
            post["user_id"] = current_user.str_id
            post["editor"] = editor
            r = mdbs["web"].db.post.insert_one(post)
            tid = r.inserted_id

        # 如果已审核, 并且分数高于最高检查违规分, 给用户通知
        if audited and issue_way and audit_score >= get_config(
                "content_inspection", "ALLEGED_ILLEGAL_SCORE"):
            insert_user_msg(
                user_id=post["user_id"],
                ctype="notice",
                label="audit_failure",
                title=gettext("[Label:{}]Post allegedly violated").format(
                    audit_label),
                content={"text": post["brief_content"]},
                target_id=str(tid),
                target_type="post")
        if issue_way:
            data = {
                "msg": gettext("Issue success"),
                "msg_type": "s",
                "custom_status": 201
            }
        else:
            data = {
                "msg": gettext("Save success"),
                "msg_type": "s",
                "custom_status": 201
            }
    return data
Ejemplo n.º 2
0
def profile_update():
    """
    用户信息更新
    :return:
    """
    gender = request.argget.all('gender', 'secret')
    birthday = request.argget.all('birthday')
    homepage = request.argget.all('homepage')
    address = json_to_pyseq(request.argget.all('address', {}))
    info = request.argget.all('info')
    if len(birthday) != 8:
        data = {
            'msg':
            gettext("The date of birth requires an 8-digit date,Such as '{}'").
            format(time_to_utcdate(tformat="%Y%m%d")),
            'msg_type':
            "e",
            "custom_status":
            400
        }
        return data
    birthday = int(birthday)
    s, r = arg_verify(reqargs=[(gettext("gender"), gender)],
                      only=["secret", "m", "f"])
    if not s:
        return r
    addr_keys = ['countries', 'provinces', 'city', 'district', 'detailed']
    for k, v in address.items():
        if not (k in addr_keys) or not isinstance(v, str):
            data = {
                'msg':
                gettext(
                    "Address format is not in conformity with the requirements"
                ),
                'msg_type':
                "e",
                "custom_status":
                400
            }
            return data
    if homepage:
        s, r = url_format_ver(homepage)
        if not s:
            return {"msg": r, "msg_type": "w", "custom_status": 403}

    r = content_attack_defense(info)
    if r["security"] < 100:
        data = {
            'msg': gettext("User profile information is illegal"),
            'msg_type': "e",
            "custom_status": 400
        }
        return data
    update_data = {
        'gender': gender,
        'homepage': homepage,
        'introduction': info,
        'birthday': birthday,
        'address': address
    }
    r = update_one_user(user_id=current_user.str_id,
                        updata={"$set": update_data})

    if r.modified_count:
        # 清理user信息数据缓存
        delete_user_info_cache(user_id=current_user.str_id)
        data = {
            'msg': gettext("Update succeed"),
            'msg_type': "s",
            "custom_status": 201
        }
    else:
        data = {
            'msg': gettext("No changes"),
            'msg_type': "w",
            "custom_status": 201
        }
    return data
Ejemplo n.º 3
0
def comment_issue():

    if not get_config("comment", "OPEN_COMMENT"):
        data = {
            "msg": gettext("Comment feature is not open"),
            "msg_type": "w",
            "custom_status": 401
        }
        return data

    target_id = request.argget.all('target_id')  # 目标ID指的是什么事件的评论
    target_type = request.argget.all('target_type', "post")
    content = request.argget.all('content')
    reply_id = request.argget.all('reply_id')  # 回复哪条评论
    reply_user_id = request.argget.all('reply_user_id')  # 回复的评论的用户ID
    reply_username = request.argget.all('reply_username')  # 回复的评论的用户名

    s, r = arg_verify(reqargs=[(gettext("comment"), content)],
                      min_len=1,
                      max_len=int(get_config("comment", "MAX_LEN")))
    if not s:
        return r
    s, r = arg_verify(reqargs=[("target_id", target_id),
                               ("target_type", target_type)],
                      required=True)
    if not s:
        return r

    if reply_id:
        s, r = arg_verify(reqargs=[("reply_user_id", reply_user_id),
                                   ("reply_username", reply_username)],
                          required=True)
        if not s:
            return r
    """
    查看最后一次评论时间
    """
    tquery = {
        "issue_time": {
            "$gt": time.time() - int(get_config("comment", "INTERVAL"))
        }
    }
    if current_user.is_authenticated:
        user_id = current_user.str_id
        username = current_user.username
        email = None
        tquery["user_id"] = user_id

    elif get_config("comment", "TRAVELER_COMMENT"):
        user_id = None
        username = request.argget.all('username')
        email = request.argget.all('email')
        # 用户名格式验证
        r, s = short_str_verifi(username)
        if not r:
            data = {'msg': s, 'msg_type': "e", "custom_status": 422}
            return data

        # 邮箱格式验证
        r, s = email_format_ver(email)
        if not r:
            data = {'msg': s, 'msg_type': "e", "custom_status": 422}
            return data
        tquery["email"] = email

    else:
        data = {
            "msg":
            gettext(
                "Guest reviews feature is not open, please login account comments"
            ),
            "msg_type":
            "w",
            "custom_status":
            401
        }
        return data

    if mdbs["web"].db.comment.find(tquery).count(True) >= int(
            get_config("comment", "NUM_OF_INTERVAL")):
        # 频繁评论
        data = {
            "msg": gettext("You comment too often and come back later"),
            "msg_type": "e",
            "custom_status": 400
        }
        return data

    target = None
    if target_type == "post":
        target = mdbs["web"].db.post.find_one({
            "_id": ObjectId(target_id),
            "issued": {
                "$in": [1, True]
            }
        })
        if not target:
            data = {
                "msg":
                gettext("Articles do not exist or have not been published"),
                "msg_type": "w",
                "custom_status": 400
            }
            return data

        target_user_id = str(target["user_id"])
        target_brief_info = target["title"]

    if not target:
        data = {
            "msg": gettext("Your comment goal does not exist"),
            "msg_type": "w",
            "custom_status": 400
        }
        return data

    issue_time = time.time()
    # 自动审核内容
    r = content_inspection_text(content)

    audit_score = r["score"]
    audit_label = r["label"]
    if r["label"] == "detection_off" or ("suggestion" in r
                                         and r["suggestion"] == "review"):
        # 未开启审核或无法自动鉴别, 等待人工审核
        audited = 0
        audit_way = "artificial"
    elif r["label"] == "no_plugin":
        # 没有检查插件
        audited = 0
        audit_way = "artificial"

    else:
        audit_label = r["label"]
        audited = 1
        audit_way = "auto"
        # 加强审核

    cad = content_attack_defense(content)
    content = cad["content"]
    if cad["security"] < 100:
        audit_label = "attack"
        audited = 1
        audit_way = "auto"
        audit_score = 100

    comment = {
        "target_id": str(target_id),
        "target_user_id": target_user_id,
        "target_brief_info": target_brief_info,
        "type": target_type,
        "user_id": user_id,
        "username": username,
        "email": email,
        "content": content,
        "issued": 1,
        "audited": audited,
        "audit_score": audit_score,
        "audit_label": audit_label,
        "audit_way": audit_way,
        "audit_user_id": None,
        "issue_time": issue_time,
        "word_num": len(content),
        "is_delete": 0,
        "like_user_id": [],
        "like": 0
    }

    if reply_id:
        comment["reply_id"] = reply_id
        comment["reply_user_id"] = reply_user_id
        comment["reply_username"] = reply_username

    r = mdbs["web"].db.comment.insert_one(comment)

    # 如果已审核, 并且违规分数高于正常
    if (audited and audit_score >= get_config("content_inspection",
                                              "ALLEGED_ILLEGAL_SCORE")
        ) or cad["security"] < 100:
        # 通知评论不通过
        msg_content = {"text": content}
        insert_user_msg(
            user_id=user_id,
            ctype="notice",
            label="audit_failure",
            title=gettext("[Label:{}]Comment on alleged violations").format(
                audit_label),
            content=msg_content,
            target_id=str(r.inserted_id),
            target_type="comment")

    elif audit_score < get_config("content_inspection",
                                  "ALLEGED_ILLEGAL_SCORE"):
        # 更新文章中的评论数目
        if target_type == "post":
            mdbs["web"].db.post.update_one({"_id": ObjectId(target_id)},
                                           {"$inc": {
                                               "comment_num": 1
                                           }})

        if current_user.is_authenticated:
            # 评论正常才通知被评论用户
            user_ids = [target_user_id]
            if reply_id:
                user_ids.append(reply_user_id)
            user_ids = list(set(user_ids))
            if user_id in user_ids:
                user_ids.remove(user_id)

            msg_content = {
                "id": str(r.inserted_id),
                "reply_id": reply_id,
                "reply_user_id": reply_user_id,
                "reply_username": reply_username,
                "user_id": user_id,
                "username": username,
                "text": content
            }
            insert_user_msg(user_id=user_ids,
                            ctype="notice",
                            label="comment",
                            title=target_brief_info,
                            content=msg_content,
                            target_id=target_id,
                            target_type=target_type)

    if current_user.is_authenticated:
        data = {
            "msg": gettext("Successful reviews"),
            "msg_type": "s",
            "custom_status": 201
        }
    else:
        data = {
            "msg": gettext("Success back, waiting for the system audit."),
            "msg_type": "s",
            "custom_status": 201
        }

    return data