예제 #1
0
    def login_user(self, username: str, password: str, ip: str,
                   browser: str) -> dict:
        data = self.db["users"].find_one({"username": username})
        returned_value = {"status_code": 0, "message": ""}

        if data:
            # try to login
            stored_password = data["password"]
            if pbkdf2_sha256.verify(password, stored_password):
                returned_value["status_code"] = HTTPStatus.OK
            else:
                returned_value["status_code"] = HTTPStatus.FORBIDDEN
                returned_value["message"] = "用户名或密码错误"

        else:
            hash_value = pbkdf2_sha256.hash(password)
            try:
                self.db["users"].insert_one(
                    dict(username=username,
                         password=hash_value,
                         date=ts_date(),
                         ip=ip,
                         browser=browser))
                returned_value["status_code"] = HTTPStatus.CREATED

            except Exception as e:
                returned_value[
                    "status_code"] = HTTPStatus.INTERNAL_SERVER_ERROR
                returned_value["message"] = str(e)

        return returned_value
예제 #2
0
 def update_user_last(self, username: str, now_ip: str) -> None:
     self.db["users"].update_one(
         {"username": username},
         {"$set": {
             "lastDate": (ts_date()),
             "lastIP": now_ip
         }})
예제 #3
0
    def login_user(self, username: str, password: str, captcha: str,
                   captcha_id: str, ip: str, browser: str) -> dict:
        # verify captcha in the first place.
        redis = Redis().r
        correct_captcha = redis.get(captcha_id)
        if correct_captcha is None:
            return {
                "status_code": HTTPStatus.BAD_REQUEST,
                "message": "验证码已过期",
                "status": False
            }
        elif correct_captcha.lower() == captcha.lower():
            redis.expire(captcha_id, 0)
        else:
            return {
                "status_code": HTTPStatus.FORBIDDEN,
                "message": "验证码错误",
                "status": False
            }
        # check user account is locked.

        data = self.db["users"].find_one({"username": username}) or {}
        if data.get("status", {}).get("disable"):
            return {
                "status_code": HTTPStatus.FORBIDDEN,
                "status": False,
                "message": data.get("status", {}).get("reason")
            }

        returned_value = {"status_code": 0, "message": ""}

        if data:
            # try to login
            stored_password = data["password"]
            if pbkdf2_sha256.verify(password, stored_password):
                returned_value["status_code"] = HTTPStatus.OK
            else:
                returned_value["status_code"] = HTTPStatus.FORBIDDEN
                returned_value["message"] = "用户名或密码错误"

        else:
            # register
            hash_value = pbkdf2_sha256.hash(password)
            try:
                self.db["users"].insert_one(
                    dict(username=username,
                         password=hash_value,
                         date=ts_date(),
                         ip=ip,
                         browser=browser))
                returned_value["status_code"] = HTTPStatus.CREATED

            except Exception as e:
                returned_value[
                    "status_code"] = HTTPStatus.INTERNAL_SERVER_ERROR
                returned_value["message"] = str(e)

        returned_value["username"] = data.get("username")
        returned_value["group"] = data.get("group", ["user"])
        return returned_value
예제 #4
0
    def query_db(self) -> dict:
        col = self.db["yyets"]
        projection = {"_id": False, "status": False, "info": False}
        episode_data = {}
        for res in tqdm(col.find(projection=projection), total=col.count()):
            for season in res["data"].get("list", []):
                for item in season["items"].values():
                    for single in item:
                        ts = single["dateline"]
                        res_name = res["data"]["info"]["cnname"]
                        name = "{}-{}".format(res_name, single["name"])
                        size = single["size"]
                        episode_data[name] = {
                            "timestamp": ts,
                            "size": size,
                            "resource_id": res["data"]["info"]["id"],
                            "res_name": res_name,
                            "date": ts_date(int(ts))
                        }

        sorted_res: list = sorted(episode_data.items(),
                                  key=lambda x: x[1]["timestamp"],
                                  reverse=True)
        limited_res = dict(sorted_res[:100])
        ok = []
        for k, v in limited_res.items():
            t = {"name": k}
            t.update(v)
            ok.append(t)
        return dict(data=ok)
예제 #5
0
 def add_announcement(self, username, content, ip, browser):
     construct = {
         "username": username,
         "ip": ip,
         "date": ts_date(),
         "browser": browser,
         "content": content,
     }
     self.db["announcement"].insert_one(construct)
예제 #6
0
    def delete_comment(self, comment_id):
        current_time = ts_date()
        count = self.db["comment"].update_one(
            {
                "_id": ObjectId(comment_id),
                "deleted_at": {
                    "$exists": False
                }
            }, {
                "$set": {
                    "deleted_at": current_time
                }
            }).modified_count
        # 找到子评论,全部标记删除
        parent_data = self.db["comment"].find_one(
            {"_id": ObjectId(comment_id)})
        if parent_data:
            child_ids = parent_data.get("children", [])
        else:
            child_ids = []
        count += self.db["comment"].update_many(
            {
                "_id": {
                    "$in": child_ids
                },
                "deleted_at": {
                    "$exists": False
                }
            }, {
                "$set": {
                    "deleted_at": current_time
                }
            }).modified_count

        returned = {"status_code": 0, "message": "", "count": -1}
        if count == 0:
            returned["status_code"] = HTTPStatus.NOT_FOUND
            returned["count"] = 0
        else:
            returned["status_code"] = HTTPStatus.OK
            returned["count"] = count

        return returned
예제 #7
0
    "resource_id": 234,
    "type": "parent"
}
col = Mongo().db["comment"]
share_doc = {
    "status": 1.0,
    "info": "OK",
    "data": {
        "info": {
            "id": 234,
            "cnname": "网友分享",
            "enname": "",
            "aliasname": "",
            "channel": "share",
            "channel_cn": "",
            "area": "",
            "show_type": "",
            "expire": "1610401225",
            "views": 0
        },
        "list": []
    }
}

Mongo().db["yyets"].update_one({"data.info.id": 234}, {"$set": share_doc}, upsert=True)

for name, link in tqdm(data.items()):
    template["content"] = f"{name}\n{link}"
    template["date"] = ts_date()
    col.insert_one(template.copy())
예제 #8
0
    def add_comment(self,
                    captcha: str,
                    captcha_id: int,
                    content: str,
                    resource_id: int,
                    ip: str,
                    username: str,
                    browser: str,
                    parent_comment_id=None) -> dict:
        returned = {"status_code": 0, "message": ""}
        verify_result = CaptchaResource().verify_code(captcha, captcha_id)
        verify_result["status"] = 1
        if not verify_result["status"]:
            returned["status_code"] = HTTPStatus.BAD_REQUEST
            returned["message"] = verify_result["message"]
            return returned

        exists = self.db["yyets"].find_one({"data.info.id": resource_id})
        if not exists:
            returned["status_code"] = HTTPStatus.NOT_FOUND
            returned["message"] = "资源不存在"
            return returned

        if parent_comment_id:
            exists = self.db["comment"].find_one(
                {"_id": ObjectId(parent_comment_id)})
            if not exists:
                returned["status_code"] = HTTPStatus.NOT_FOUND
                returned["message"] = "评论不存在"
                return returned

        basic_comment = {
            "username": username,
            "ip": ip,
            "date": ts_date(),
            "browser": browser,
            "content": content,
            "resource_id": resource_id
        }
        if parent_comment_id is None:
            basic_comment["type"] = "parent"
        else:
            basic_comment["type"] = "child"
        # 无论什么评论,都要插入一个新的document
        inserted_id: str = self.db["comment"].insert_one(
            basic_comment).inserted_id

        if parent_comment_id is not None:
            # 对父评论的子评论,需要给父评论加children id
            self.db["comment"].find_one_and_update(
                {"_id": ObjectId(parent_comment_id)},
                {"$push": {
                    "children": inserted_id
                }})
            self.db["comment"].find_one_and_update(
                {"_id": ObjectId(inserted_id)},
                {"$set": {
                    "parent_id": ObjectId(parent_comment_id)
                }})
        returned["status_code"] = HTTPStatus.CREATED
        returned["message"] = "评论成功"
        return returned
예제 #9
0
    def add_comment(self, captcha: str, captcha_id: int, content: str, resource_id: int,
                    ip: str, username: str, browser: str, parent_comment_id=None) -> dict:
        returned = {"status_code": 0, "message": ""}
        # check if this user is blocked
        reason = self.is_user_blocked(username)
        if reason:
            return {"status_code": HTTPStatus.FORBIDDEN, "message": reason}
        if check_spam(ip, browser, username, content) != 0:
            document = {
                "username": username,
                "ip": ip,
                "date": ts_date(),
                "browser": browser,
                "content": content,
                "resource_id": resource_id
            }
            inserted_id = self.db["spam"].insert_one(document).inserted_id
            document["_id"] = str(inserted_id)
            SpamProcessMongoResource.request_approval(document)
            return {"status_code": HTTPStatus.FORBIDDEN, "message": f"possible spam, reference id: {inserted_id}"}

        user_group = self.db["users"].find_one(
            {"username": username},
            projection={"group": True, "_id": False}
        )
        if not user_group:
            # admin don't have to verify code
            verify_result = CaptchaResource().verify_code(captcha, captcha_id)
            if not verify_result["status"]:
                returned["status_code"] = HTTPStatus.BAD_REQUEST
                returned["message"] = verify_result["message"]
                return returned

        exists = self.db["yyets"].find_one({"data.info.id": resource_id})
        if not exists:
            returned["status_code"] = HTTPStatus.NOT_FOUND
            returned["message"] = "资源不存在"
            return returned

        if parent_comment_id:
            exists = self.db["comment"].find_one({"_id": ObjectId(parent_comment_id)})
            if not exists:
                returned["status_code"] = HTTPStatus.NOT_FOUND
                returned["message"] = "评论不存在"
                return returned

        basic_comment = {
            "username": username,
            "ip": ip,
            "date": ts_date(),
            "browser": browser,
            "content": content,
            "resource_id": resource_id
        }
        if parent_comment_id is None:
            basic_comment["type"] = "parent"
        else:
            basic_comment["type"] = "child"
        # 无论什么评论,都要插入一个新的document
        inserted_id: str = self.db["comment"].insert_one(basic_comment).inserted_id

        if parent_comment_id is not None:
            # 对父评论的子评论,需要给父评论加children id
            self.db["comment"].find_one_and_update({"_id": ObjectId(parent_comment_id)},
                                                   {"$push": {"children": inserted_id}}
                                                   )
            self.db["comment"].find_one_and_update({"_id": ObjectId(inserted_id)},
                                                   {"$set": {"parent_id": ObjectId(parent_comment_id)}}
                                                   )
        returned["status_code"] = HTTPStatus.CREATED
        returned["message"] = "评论成功"

        # notification
        if parent_comment_id:
            # find username

            self.db["notification"].find_one_and_update(
                {"username": exists["username"]},
                {"$push": {"unread": inserted_id}},
                upsert=True
            )
            # send email
            # TODO unsubscribe
            parent_comment = self.db["comment"].find_one({"_id": ObjectId(parent_comment_id)})
            if resource_id == 233:
                link = f"https://yyets.dmesg.app/discuss#{parent_comment_id}"
            else:
                link = f"https://yyets.dmesg.app/resource?id={resource_id}#{parent_comment_id}"
            user_info = self.db["users"].find_one({"username": parent_comment["username"], "email.verified": True})
            if user_info:
                subject = "[人人影视下载分享站] 你的评论有了新的回复"
                pt_content = content.split("</reply>")[-1]
                body = f"{username} 您好,<br>你的评论 {parent_comment['content']} 有了新的回复:<br>{pt_content}" \
                       f"<br>你可以<a href='{link}'>点此链接</a>查看<br><br>请勿回复此邮件"
                send_mail(user_info["email"]["address"], subject, body)
        return returned