Example #1
0
def _get_post(post):
    if post is None:
        return errors.not_found()

    if post.is_draft:
        user = get_user_from_request()
        if user is None:
            return errors.no_access()

        if post.creator != user:
            return errors.no_access()

    user = get_user_from_request()

    if post.blog is not None:
        # workaround, delete later. Sometime in the past you can save post
        # without blog, so this check will fail.
        has_access = Blog.has_access(post.blog, user)
        if not has_access:
            return errors.no_access()

    post_dict = post.to_json()
    post_dict = Vote.add_votes_info(post_dict, 3, user)

    entries = JamEntry.get_entries_for_post(post)
    post_dict["jam_entries"] = [e.to_json() for e in entries]

    return jsonify({"success": 1, "post": post_dict})
Example #2
0
def _delete_post(post):
    if post is None:
        return errors.not_found()

    user = get_user_from_request()

    if post.creator == user or user.is_admin:
        Comment.delete().where((Comment.object_type == "post")
                               & (Comment.object_id == post.id)).execute()
        TagMark.delete().where(TagMark.post == post).execute()
        post.delete_instance()

        return jsonify({"success": 1})

    if post.blog is None:
        return errors.no_access()

    role = Blog.get_user_role(post.blog, user)
    # only blog owner can delete posts
    if role != 1:
        return errors.no_access()

    Comment.delete().where((Comment.object_type == "post")
                           & (Comment.object_id == post.id)).execute()
    TagMark.delete().where(TagMark.post == post).execute()
    post.delete_instance()

    return jsonify({"success": 1})
Example #3
0
def invites(url):
    """Пригласить пользователя или принять инвайт"""
    blog = Blog.get_or_none(Blog.url == url)
    if blog is None:
        return errors.not_found()

    user = get_user_from_request()

    json = request.get_json()

    if "invite" in json:
        invite = BlogInvite.get_or_none(BlogInvite.id == json["invite"])
        if invite is None:
            return errors.invite_not_found()

        if invite.user_to.id != user.id:
            return errors.no_access()

        invite.is_accepted = True
        invite.save()

        BlogParticipiation.create(blog=invite.blog, user=user, role=invite.role)

        return jsonify({"success": 1})
    elif "user" in json and "role" in json:
        user_to = User.get_or_none(User.id == json["user"])
        if user_to is None:
            return errors.not_found()

        role = Blog.get_user_role(blog, user)

        if role is None:
            return errors.no_access()

        role_to = json["role"]
        roles = {"owner": 1, "writer": 2, "reader": 3}

        if role_to not in roles:
            return errors.invite_wrong_role()

        role_to = roles[role_to]
        if role > role_to:
            return errors.no_access()

        invite = BlogInvite.create(
            blog=blog, user_from=user, user_to=user_to, role=role_to
        )

        Notification.create(
            user=user,
            created_date=datetime.datetime.now(),
            text='Вас пригласили в блог "{0}"'.format(blog.title),
            object_type="invite",
            object_id=invite.id,
        )

        return jsonify({"success": 1, "invite": invite.id})
Example #4
0
def unassign_achievement():
    user = get_user_from_request()

    if not user.is_admin:
        return errors.no_access()

    json = request.get_json()

    if "users" not in json or "achievement" not in json:
        return errors.wrong_payload("users", "achievement")

    if len(json["users"]) == 0:
        return errors.wrong_payload("users")

    achievement = Achievement.get_or_none(
        Achievement.id == json["achievement"])
    if achievement is None:
        return errors.wrong_payload("achievement")

    assign_errors = []
    for u in json["users"]:
        user_to_unassign = User.get_or_none(User.id == u)
        if user_to_unassign is None:
            assign_errors.append(f"Cannot unassign achievement from user {u}")
        else:
            assign = AchievementUser.get_or_none(achievement=achievement,
                                                 user=user_to_unassign)
            assign.delete_instance()

    return jsonify({"success": 1, "errors": assign_errors})
Example #5
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()},
        }
    )
Example #6
0
def _edit_post(post):
    if post is None:
        return errors.not_found()

    user = get_user_from_request()

    role = Blog.get_user_role(post.blog, user)

    if post.creator == user or role == 1 or user.is_admin:
        json = request.get_json()

        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)

        if not validate_url(post):
            return errors.post_url_already_taken()

        post.save()

        set_tags_for_post(post, json)

        manage_jam_entries(post, json)

        return jsonify({"success": 1, "post": post.to_json()})
    else:
        return errors.no_access()
Example #7
0
def get_feedback():
    """Получить список отзывов"""
    user = get_user_from_request()
    if user.is_admin:
        return jsonify(
            {"success": 1, "feedback": [f.to_json() for f in Feedback.select()]}
        )
    else:
        return errors.no_access()
Example #8
0
def _edit_comment(comment_id, user, text):
    comment = Comment.get_or_none(Comment.id == comment_id)
    if comment is None:
        return errors.not_found()

    is_accessible = user.is_admin or comment.creator == user
    if not is_accessible:
        return errors.no_access()

    comment.text = sanitize(text)
    comment.save()

    return comment
Example #9
0
def resolve(id):
    """Пометить отзыв как решенный"""
    user = get_user_from_request()
    if user.is_admin:
        f = Feedback.get_or_none(Feedback.id == id)
        if f is None:
            return errors.not_found()

        f.is_resolved = True
        f.save()

        return jsonify({"success": 1})
    else:
        return errors.no_access()
Example #10
0
def get_single_blog(url):
    """Получить блог по указанному 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()

    blog_dict = blog.to_json()
    blog_dict = Vote.add_votes_info(blog_dict, 2, user)
    return jsonify({"success": 1, "blog": blog_dict})
Example #11
0
def delete_blog(url):
    """Удалить блог"""
    blog = Blog.get_or_none(Blog.url == url)
    if blog is None:
        return errors.not_found()

    user = get_user_from_request()

    role = Blog.get_user_role(blog, user)
    if role != 1:
        return errors.no_access()

    blog.delete_instance()

    return jsonify({"success": 1})
Example #12
0
def finish(url):
    """Закончить джем"""
    user = get_user_from_request()
    jam = Jam.get_or_none(Jam.url == url)

    if jam is None:
        return errors.not_found()

    if jam.creator != user:
        return errors.no_access()

    jam.status = 2
    jam.save()

    return jsonify({"success": 1})
Example #13
0
def join(url):
    """Присоеденится к блогу. Работает только с открытми блогами"""
    blog = Blog.get_or_none(Blog.url == url)
    if blog is None:
        return errors.not_found()
    if blog.blog_type != 1:
        return errors.no_access()

    user = get_user_from_request()
    if user is None:
        return errors.not_authorized()
    if BlogParticipiation.get_or_none(blog=blog, user=user) is None:
        BlogParticipiation.create(blog=blog, user=user, role=3)

    return jsonify({"success": 1})
Example #14
0
def dashboard():
    """Получить статистику по сайту"""
    user = get_user_from_request()

    if not user.is_admin:
        return errors.no_access()

    users = User.select().count()

    d = datetime.datetime.now() - datetime.timedelta(days=7)
    active_users = User.select().where(User.last_active_date > d).count()
    return jsonify({
        "success": 1,
        "users": users,
        "active_users_7_days": active_users
    })
Example #15
0
def edit_jam(url):
    """Редактировать джем"""
    user = get_user_from_request()
    jam = Jam.get_or_none(Jam.url == url)

    if jam is None:
        return errors.not_found()

    if jam.creator != user:
        return errors.no_access()

    json = request.json

    title = json.get("title", jam.title)
    # url = json.get("url", jam.url)
    description = json.get("description", jam.description)
    short_description = json.get("short_description", jam.short_description)
    start_date = json.get("start_date", jam.start_date)
    end_date = json.get("end_date", jam.end_date)
    criterias = json.get("criterias", [])

    image = None
    if "image" in json:
        image = json["image"]

    edit_blog_for_jam(jam.blog, title, url, image)

    jam.title = title
    # jam.url = url
    jam.description = sanitize(description)
    jam.short_description = sanitize(short_description)
    jam.start_date = start_date
    jam.end_date = end_date

    if image:
        jam.logo = Content.get_or_none(Content.id == image)

    jam.updated_date = datetime.datetime.now()
    jam.save()

    JamCriteria.delete().where(JamCriteria.jam == jam).execute()
    for criteria in criterias:
        JamCriteria.create(jam=jam,
                           title=criteria["title"],
                           order=criteria["order"])

    return jsonify({"success": 1, "jam": jam.to_json()})
Example #16
0
def edit_blog(url):
    """Изменить блог"""
    blog = Blog.get_or_none(Blog.url == url)
    if blog is None:
        return errors.not_found()

    user = get_user_from_request()

    role = Blog.get_user_role(blog, user)
    if role != 1:
        return errors.no_access()

    fill_blog_from_json(blog, request.get_json())

    if not validate_url(blog):
        return errors.blog_url_already_taken()

    blog.save()

    return jsonify({"success": 1, "blog": blog.to_json()})
Example #17
0
def readers(url):
    """Получить список читателей блога"""
    blog = Blog.get_or_none(Blog.url == url)
    if blog is None:
        return errors.not_foun
    user = get_user_from_request()
    has_access = Blog.has_access(blog, user)
    if not has_access:
        return errors.no_access()

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

    return jsonify(
        {
            "success": 1,
            "readers": [u.to_json() for u in paginated_query.get_object_list()],
            "meta": {"page_count": paginated_query.get_page_count()},
        }
    )
Example #18
0
def assign_achievement():
    user = get_user_from_request()

    if not user.is_admin:
        return errors.no_access()

    json = request.get_json()

    if "users" not in json or "achievement" not in json:
        return errors.wrong_payload("users", "achievement")

    if len(json["users"]) == 0:
        return errors.wrong_payload("users")

    achievement = Achievement.get_or_none(
        Achievement.id == json["achievement"])
    if achievement is None:
        return errors.wrong_payload("achievement")

    assign_errors = []
    for u in json["users"]:
        user_to_assign = User.get_or_none(User.id == u)
        if user_to_assign is None:
            assign_errors.append(f"Cannot assign achievement to user {u}")
        else:
            AchievementUser.create(
                achievement=achievement,
                user=user_to_assign,
                comment=json.get("comment", None),
            )

            Notification.create(
                user=user_to_assign,
                created_date=datetime.datetime.now(),
                text=f"Новая награда: {achievement.title}",
                object_type="achievement",
                object_id=achievement.id,
            )

    return jsonify({"success": 1, "errors": assign_errors})
Example #19
0
def add_achievement():
    user = get_user_from_request()

    if not user.is_admin:
        return errors.no_access()

    json = request.get_json()

    if "title" not in json or "image" not in json:
        return errors.wrong_payload("title", "image")

    if len(json["title"]) == 0:
        return errors.wrong_payload("title")

    content = Content.get_or_none(Content.id == json["image"])
    if content:
        if not content.is_image:
            return errors.achievement_is_not_image()
        elif not content.is_small_image:
            return errors.achievement_too_large()

    achievement = Achievement.create(title=json["title"], image=content)

    return jsonify({"success": 1, "achievement": achievement.to_json()})
Example #20
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()})