예제 #1
0
def test_edit_post_wrong_user(client, post, user_not_in_blog_with_token):
    rv = client.put(
        "/posts/" + post.url + "/",
        json={"title": "new title"},
        headers={"Authorization": user_not_in_blog_with_token[1].token},
    )
    assert rv.json["success"] == 0
    assert rv.json["error"]["code"] == 3

    assert Post.get().title == post.title, "Post title changed"
    assert Post.get().title != "new title"
예제 #2
0
def test_edit_post_with_cut(client, post, user_token):
    rv = client.put(
        "/posts/" + post.url + "/",
        json={"text": '<p>Some text</p><cut name="it\'s cut"></cut><p>More text</p>"'},
        headers={"Authorization": user_token[1].token},
    )
    assert rv.json["success"] == 1

    assert Post.get().cut_text == "<p>Some text</p>"
    assert Post.get().cut_name == "it's cut"
    assert (
        Post.get().text
        == '<p>Some text</p><cut name="it\'s cut"></cut><p>More text</p>"'
    )
예제 #3
0
def test_delete_post(client, post, user_token):
    rv = client.delete(
        "/posts/" + post.url + "/", headers={"Authorization": user_token[1].token}
    )
    assert rv.json["success"] == 1

    assert Post.select().count() == 0, "Post not deleted"
예제 #4
0
def posts(url):
    """Получить список постов для блога"""
    blog = Blog.get_or_none(Blog.url == url)
    if blog is None:
        return errors.not_found()

    user = get_user_from_request()
    has_access = Blog.has_access(blog, user)
    if not has_access:
        return errors.no_access()

    query = Post.get_posts_for_blog(blog)
    limit = max(1, min(int(request.args.get("limit") or 20), 100))
    paginated_query = PaginatedQuery(query, paginate_by=limit)

    posts = [p.to_json() for p in paginated_query.get_object_list()]
    posts = [Vote.add_votes_info(p, 3, user) for p in posts]

    return jsonify(
        {
            "success": 1,
            "posts": posts,
            "meta": {"page_count": paginated_query.get_page_count()},
        }
    )
예제 #5
0
def test_delete_post_reader(client, post, reader_token):
    rv = client.delete(
        "/posts/" + post.url + "/", headers={"Authorization": reader_token[1].token}
    )
    assert rv.json["success"] == 0
    assert rv.json["error"]["code"] == 3

    assert Post.select().count() == 1, "Post was deleted"
예제 #6
0
def validate_url(post):
    new_url = post.url

    posts_with_url = Post.select().where(Post.url == new_url)
    for p in posts_with_url:
        if p.url == new_url and p.id != post.id:
            return False

    return True
예제 #7
0
def test_edit_post(client, post, user_token):
    rv = client.put(
        "/posts/" + post.url + "/",
        json={"title": "new title"},
        headers={"Authorization": user_token[1].token},
    )
    assert rv.json["success"] == 1

    assert Post.get().title == "new title", "Post title not chaged"
예제 #8
0
def test_delete_post_wrong_user(client, post, user_not_in_blog_with_token):
    rv = client.delete(
        "/posts/" + post.url + "/",
        headers={"Authorization": user_not_in_blog_with_token[1].token},
    )
    assert rv.json["success"] == 0
    assert rv.json["error"]["code"] == 3

    assert Post.select().count() == 1, "Post was deleted"
예제 #9
0
def test_create_post(client, user_token):
    rv = client.post(
        "/posts/",
        headers={"Authorization": user_token[1].token},
        json={"url": "sample-url"},
    )
    assert rv.json["success"] == 1
    assert "post" in rv.json, "No post in response"

    post = Post.get()
    assert post.creator == user_token[0], "Wrong creator"
    assert post.id == rv.json["post"]["id"]
예제 #10
0
def create_post():
    """Создать пост"""
    user = get_user_from_request()

    post = Post(
        created_date=datetime.datetime.now(),
        updated_date=datetime.datetime.now(),
        creator=user,
    )

    json = request.get_json()

    url = json["url"]
    if Post.get_or_none(Post.url == url) is not None:
        return errors.post_url_already_taken()

    error = set_blog(post, json, user)
    if error is not None:
        error_response = {
            BlogError.NoBlog: errors.blog_not_found(),
            BlogError.NoAccess: errors.blog_no_access(),
        }[error]
        return error_response

    fill_post_from_json(post, json)

    post.save()

    set_tags_for_post(post, json)

    manage_jam_entries(post, json)

    return jsonify({"success": 1, "post": post.to_json()})
예제 #11
0
def convert():
    create_app()

    for post in Post.select():
        if not post.text:
            continue
        post.text = process_text(post.text)

        cut_info = process_cut(post.text)
        post.has_cut = cut_info["has_cut"]
        post.cut_text = cut_info["text_before_cut"]
        post.cut_name = cut_info["cut_name"]

        post.save()
예제 #12
0
def convert():
    create_app()

    for p in Post.select():
        if not p.text:
            continue
        p.text = process_text(p.text)
        p.save()

    for c in Comment.select():
        if not c.text:
            continue
        c.text = process_text(c.text)
        c.save()
예제 #13
0
def migration_v1(db, migrator: SchemaMigrator):
    from src.model.models import Post

    with db.atomic():
        migrate(
            migrator.add_column("post", "has_cut",
                                BooleanField(default=False)),
            migrator.add_column("post", "cut_name",
                                CharField(default=None, null=True)),
        )

    query = Post.select()

    for p in query:
        p.has_cut = "<cut>" in p.text
        p.save()
예제 #14
0
def get_posts():
    """Получить список публичных постов"""
    query = Post.get_public_posts()
    limit = max(1, min(int(request.args.get("limit") or 20), 100))
    paginated_query = PaginatedQuery(query, paginate_by=limit)

    posts = [p.to_json() for p in paginated_query.get_object_list()]
    posts = [Vote.add_votes_info(p, 3, get_user_from_request()) for p in posts]

    return jsonify({
        "success": 1,
        "posts": posts,
        "meta": {
            "page_count": paginated_query.get_page_count()
        },
    })
예제 #15
0
def convert():
    create_app()

    print("Replacing stickers")

    stickers_set = set()

    def replace_sticker(text):
        if text:
            pattern = r'<img src="\/common\/templates\/skin\/start-kit\/assets\/images\/(.*?)\..*?">'
            items = re.findall(pattern, text)
            for i in items:
                stickers_set.add(i)
            text = re.sub(pattern, r":\1:", text)

            pattern = r'<img src="\/common\/templates\/skin\/start-kit\/assets\/images\/(.*?)\..*?" />'
            items = re.findall(pattern, text)
            for i in items:
                stickers_set.add(i)
            text = re.sub(pattern, r":\1:", text)

            pattern = r'<img src="http:\/\/k\.faisu\.net\/kreguzda\/images\/smilies\/(.*?)\..*?" />'
            items = re.findall(pattern, text)
            for i in items:
                stickers_set.add(i)
            return re.sub(pattern, r":\1:", text)
        return None

    for p in Post.select():
        p.text = replace_sticker(p.text)
        p.cut_text = replace_sticker(p.cut_text)
        p.save()

    for p in Comment.select():
        p.text = replace_sticker(p.text)
        p.save()

    for p in Message.select():
        p.text = replace_sticker(p.text)
        p.save()

    for p in User.select():
        p.about = replace_sticker(p.about)
        p.save()

    print(stickers_set)
예제 #16
0
def convert():
    create_app()

    for t in TuTopic.select():
        creator = User.get_or_none(User.id == t.user)
        if not creator:
            print("Skipped post. Owner:" +
                  TuUser.get(TuUser.user == t.user).user_login)
            continue

        updated = t.topic_date_edit
        if not updated:
            updated = t.topic_date_add

        topic_content = TuTopicContent.get(TuTopicContent.topic == t.topic)
        text = topic_content.topic_text_source

        text = content.replace_uploads_in_text(creator, text)
        # TODO convert questions and photosets

        cut = text.split("<cut>")[0]
        post = Post.create(
            id=t.topic,
            blog=Blog.get(Blog.id == t.blog),
            creator=creator,
            created_date=t.topic_date_add,
            updated_date=updated,
            title=t.topic_title,
            cut_text=cut,
            has_cut="<cut>" in text,
            text=text,
            rating=0,
            is_draft=t.topic_publish == 0,
            is_on_main=t.topic_publish_index == 1,
            reads=0,
            url=t.topic_url,
        )

        tags = t.topic_tags.split(",")
        for tag in tags:
            tag_obj = Tag.get_or_none(title=tag)
            if tag_obj is None:
                tag_obj = Tag.create(title=tag, created_date=t.topic_date_add)
            TagMark.create(tag=tag_obj, post=post)
예제 #17
0
def convert():
    create_app()

    for c in TuComment.select():
        if c.target_type != "topic":
            continue

        creator = User.get_or_none(User.id == c.user)
        if not creator:
            print(
                "Skipped comment. Owner:" + TuUser.get(TuUser.user == c.user).user_login
            )
            continue

        updated = c.comment_date
        if not updated:
            updated = c.comment_date_edit

        text = content.replace_uploads_in_text(creator, c.comment_text)

        post = Post.get_or_none(Post.id == c.target)
        if post is None:
            print("Skipped comment " + str(c.comment) + ". No post" + str(c.target))
            continue

        parent = None
        if c.comment_pid:
            parent = Comment.get_or_none(Comment.id == c.comment_pid)
            if parent is None:
                print("Skipped comment " + str(c.comment) + ". No parent")

        Comment.create(
            id=c.comment,
            post=post,
            creator=creator,
            parent=parent,
            level=c.comment_level,
            created_date=c.comment_date,
            updated_date=updated,
            text=text,
            rating=0,
        )
예제 #18
0
def tag(title):
    """Получить посты с указанным тегом"""
    tag = Tag.get_or_none(Tag.title == title)
    if tag is None:
        return errors.not_found()

    query = Post.get_public_posts_with_tag(tag)
    limit = max(1, min(int(request.args.get("limit") or 20), 100))
    paginated_query = PaginatedQuery(query, paginate_by=limit)

    posts = [p.to_json() for p in paginated_query.get_object_list()]
    posts = [Vote.add_votes_info(p, 3, get_user_from_request()) for p in posts]

    return jsonify(
        {
            "success": 1,
            "posts": posts,
            "meta": {"page_count": paginated_query.get_page_count()},
        }
    )
예제 #19
0
def draft_post(user, blog):
    post = Post.create(
        blog=blog,
        creator=user,
        created_date=datetime.datetime.now(),
        updated_date=datetime.datetime.now(),
        title="Some post title",
        text="Some text",
        cut_text="Cut text",
        rating=0,
        is_draft=True,
        is_on_main=False,
        url="url-for-draft-post",
    )

    from src.model import db

    db.db_wrapper.database.close()

    return post
예제 #20
0
def get():
    search_type = request.args.get("type")
    search_query = request.args.get("q")
    limit = max(1, min(int(request.args.get("limit") or 20), 100))

    type = 0

    if not search_query or len(search_query) == 0:
        return errors.wrong_payload("q")

    if search_type == "post":
        query = Post.get_public_posts().where(
            Post.title.contains(search_query)
            | Post.text.contains(search_query))
        type = 3
    elif search_type == "blog":
        query = Blog.get_public_blogs().where(
            Blog.title.contains(search_query)
            | Blog.description.contains(search_query))
        type = 2
    elif search_type == "user":
        query = User.select().where(
            User.username.contains(search_query)
            | User.name.contains(search_query))
        type = 1
    else:
        return errors.wrong_payload("type")

    paginated_query = PaginatedQuery(query, paginate_by=limit)
    items = [item.to_json() for item in paginated_query.get_object_list()]
    items = [
        Vote.add_votes_info(i, type, get_user_from_request()) for i in items
    ]

    return jsonify({
        "success": 1,
        "result": items,
        "meta": {
            "page_count": paginated_query.get_page_count()
        },
    })
예제 #21
0
def user_posts(username):
    """Получить список постов пользователя"""
    user = User.get_or_none(User.username == username)

    if user is None:
        return errors.not_found()

    query = Post.get_user_posts(user)
    limit = max(1, min(int(request.args.get("limit") or 20), 100))
    paginated_query = PaginatedQuery(query, paginate_by=limit)

    posts = [p.to_json() for p in paginated_query.get_object_list()]
    posts = [Vote.add_votes_info(p, 3, get_user_from_request()) for p in posts]

    return jsonify({
        "success": 1,
        "posts": posts,
        "meta": {
            "page_count": paginated_query.get_page_count()
        },
    })
예제 #22
0
def edit_comment(url, comment_id):
    """Редактировать комментарий"""
    post = Post.get_or_none(Post.url == url)
    if post is None:
        return errors.not_found()

    user = get_user_from_request()
    if user is None:
        return errors.not_authorized()

    json = request.get_json()

    text = None
    if "text" in json:
        text = sanitize(json.get("text"))
    else:
        return errors.wrong_payload("text")

    comment = _edit_comment(comment_id, user, text)

    return jsonify({"success": 1, "comment": comment.to_json()})
예제 #23
0
def get_post_by_id(id):
    """Получить пост по id"""
    post = Post.get_or_none(Post.id == id)
    return _get_post(post)
예제 #24
0
def get_post(url):
    """Получить пост по url"""
    post = Post.get_or_none(Post.url == url)
    return _get_post(post)
예제 #25
0
def edit_post_by_id(id):
    """Изменить пост"""
    post = Post.get_or_none(Post.id == id)
    return _edit_post(post)
예제 #26
0
def delete_post(url):
    """Удалить пост"""
    post = Post.get_or_none(Post.url == url)
    return _delete_post(post)
예제 #27
0
def delete_post_by_id(id):
    """Удалить пост"""
    post = Post.get_or_none(Post.id == id)
    return _delete_post(post)
예제 #28
0
def comments(url):
    """Получить список комментариев для поста или добавить новый комментарий"""
    post = Post.get_or_none(Post.url == url)
    if post is None:
        return errors.not_found()

    if request.method == "GET":
        user = get_user_from_request()
        if post.is_draft:

            if user is None:
                return errors.no_access()

            if post.creator != user:
                return errors.no_access()
        return _get_comments("post", post.id, user)
    elif request.method == "POST":
        user = get_user_from_request()
        if user is None:
            return errors.not_authorized()

        json = request.get_json()

        if "text" in json:
            text = sanitize(json.get("text"))
        else:
            return errors.wrong_payload("text")

        parent_id = None
        if "parent" in json:
            parent_id = json["parent"]
        parent = None
        if parent_id:
            parent = Comment.get_or_none(Comment.id == parent_id)

        comment = _add_comment("post", post.id, user, text, parent_id)

        if user.id != post.creator.id:
            t = "Пользователь {0} оставил комментарий к вашему посту {1}: {2}"
            notification_text = t.format(user.visible_name, post.title, text)

            Notification.create(
                user=post.creator,
                created_date=datetime.datetime.now(),
                text=notification_text,
                object_type="comment",
                object_id=comment.id,
            )

        if parent is not None:
            if user.id != parent.creator.id:
                t = "Пользователь {0} ответил на ваш комментарий {1}: {2}"
                notification_text = t.format(user.visible_name, parent.text,
                                             text)

                Notification.create(
                    user=parent.creator,
                    created_date=datetime.datetime.now(),
                    text=notification_text,
                    object_type="comment",
                    object_id=comment.id,
                )

        return jsonify({"success": 1, "comment": comment.to_json()})
예제 #29
0
def vote():
    """
    Добавить голос.
    """
    user = get_user_from_request()

    json = request.get_json()

    t_id = json["target_id"]
    t_type = 0

    notification_str_type = ""
    notification_to_whom = None
    notification_object_type = ""

    if json["target_type"] == "user":
        user_to = User.get_or_none(User.id == t_id)
        if user_to is None:
            return errors.vote_no_target()
        t_type = 1

        notification_str_type = "профиль"
        notification_to_whom = user_to
        notification_object_type = "user"

    elif json["target_type"] == "blog":
        blog = Blog.get_or_none(Blog.id == t_id)
        if blog is None:
            return errors.vote_no_target()
        t_type = 2

        notification_str_type = "блог"
        notification_to_whom = blog.creator
        notification_object_type = "blog"

    elif json["target_type"] == "post":
        post = Post.get_or_none(Post.id == t_id)
        if post is None:
            return errors.vote_no_target()
        t_type = 3

        notification_str_type = "пост"
        notification_to_whom = post.creator
        notification_object_type = "post"

    elif json["target_type"] == "comment":
        comment = Comment.get_or_none(Comment.id == t_id)
        if comment is None:
            return errors.vote_no_target()
        t_type = 4

        notification_str_type = "комментарий"
        notification_to_whom = comment.creator
        notification_object_type = "comment"
    else:
        return errors.vote_no_target_type()

    value = json["value"]
    if value > 0:
        value = 1
    elif value < 0:
        value = -1
    else:
        value = 0

    vote = Vote.get_or_none(Vote.voter == user,
                            target_id=t_id,
                            target_type=t_type)
    if vote:
        vote.vote_value = value
        vote.updated_date = datetime.datetime.now()
    else:
        vote = Vote(
            created_date=datetime.datetime.now(),
            updated_date=datetime.datetime.now(),
            voter=user,
            target_id=t_id,
            target_type=t_type,
            vote_value=value,
        )

    notification_str_val = "+1" if value > 0 else "-1"
    notification_text = "{0}: Пользователь {1} оценил ваш {2}".format(
        notification_str_val, user.visible_name, notification_str_type)

    Notification.create(
        user=notification_to_whom,
        created_date=datetime.datetime.now(),
        text=notification_text,
        object_type=notification_object_type,
        object_id=t_id,
    )

    vote.save()

    return jsonify({"success": 1, "vote": vote.to_json()})
예제 #30
0
def edit_post(url):
    """Изменить пост"""
    post = Post.get_or_none(Post.url == url)
    return _edit_post(post)