def add_votes(url, entry_url): """Получить оценки для заявки на джем""" jam = Jam.get_or_none(Jam.url == url) if jam is None: return errors.not_found() entry = JamEntry.get_or_none(JamEntry.url == entry_url) if entry is None: return errors.not_found() JamEntryVote.delete().where((JamEntryVote.entry == entry) & ( JamEntryVote.voter == get_user_from_request())).execute() json = request.json json_criterias = json for criteria_id, vote in json_criterias.items(): JamEntryVote.create( entry=entry, voter=get_user_from_request(), vote=vote, criteria=criteria_id, ) return jsonify({"success": 1})
def edit_comment_in_entry(url, entry_url, comment_id): """Редактировать комментарий""" jam = Jam.get_or_none(Jam.url == url) if jam is None: return errors.not_found() entry = JamEntry.get_or_none(JamEntry.url == entry_url) if entry 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()})
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})
def edit_my_entry(url): """Редактировать заявку на джем от текущего пользователя""" user = get_user_from_request() jam = Jam.get_or_none(Jam.url == url) if jam is None: return errors.not_found() entry = JamEntry.get_or_none(jam=jam, creator=user) if entry is None: return errors.not_found() json = request.json title = json.get("title", entry.title) url = json.get("url", entry.url) description = json.get("info", entry.info) short_description = json.get("short_info", entry.short_info) links = json.get("links", []) has_entry_with_same_url = False entries_with_same_url = JamEntry.select().where((JamEntry.url == url) & (JamEntry.jam == jam)) for e in entries_with_same_url: if e.id != entry.id: has_entry_with_same_url = True if has_entry_with_same_url: return errors.jam_entry_url_already_taken() image = None if "logo" in json: image = json["logo"] entry.title = title entry.url = url entry.info = sanitize(description) entry.short_info = sanitize(short_description) if image: entry.logo = Content.get_or_none(Content.id == image) JamEntryLink.delete().where(JamEntryLink.entry == entry).execute() for link in links: JamEntryLink.create( entry=entry, title=link["title"], href=link["href"], order=link["order"], ) entry.save() return jsonify({"success": 1, "entry": _entry_to_json(entry)})
def jam_entry(url, entry_url): """Получить заявку на джем по ссылке""" jam = Jam.get_or_none(Jam.url == url) if jam is None: return errors.not_found() entry = JamEntry.get_or_none(JamEntry.url == entry_url) if entry is None: return errors.not_found() return jsonify({"success": 1, "entry": _entry_to_json(entry)})
def get_criterias(url, entry_url): """Получить оценки для заявки на джем""" jam = Jam.get_or_none(Jam.url == url) if jam is None: return errors.not_found() entry = JamEntry.get_or_none(JamEntry.url == entry_url) if entry is None: return errors.not_found() criterias = JamEntryVote.select().where((JamEntryVote.entry == entry) & ( JamEntryVote.voter == get_user_from_request())) return jsonify({"success": 1, "criterias": _criterias_to_json(criterias)})
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})
def get(id): """Получить файл по id""" content = Content.get_or_none(Content.id == id) if content is not None: return send_file(content.path, add_etags=False, conditional=True) else: return errors.not_found()
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()}, } )
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})
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()
def get_jam(url): """Получить джем по указанному url""" jam = Jam.get_or_none(Jam.url == url) if jam is None: return errors.not_found() jam_dict = _jam_to_json(jam) return jsonify({"success": 1, "jam": jam_dict})
def jam_entries(url): """Получить список заявок на джем""" jam = Jam.get_or_none(Jam.url == url) if jam is None: return errors.not_found() entries = JamEntry.select().where(JamEntry.jam == jam) entries = [_entry_to_json(entry) for entry in entries] return jsonify({"success": 1, "entries": entries})
def my_entry(url): """Получить заявку на джем от текущего пользователя""" user = get_user_from_request() jam = Jam.get_or_none(Jam.url == url) if jam is None: return errors.not_found() entry = JamEntry.get_or_none(jam=jam, creator=user) return jsonify({"success": 1, "entry": _entry_to_json(entry)})
def user_jams(username): """Получить список джемов, которые пользователь организовал""" user = User.get_or_none(User.username == username) if user is None: return errors.not_found() query = Jam.get_jams_organized_by_user(user) jams = [e.to_json() for e in query] return jsonify({"success": 1, "jams": jams})
def user(username): """Получить подробную информацию о пользователе""" user = User.get_or_none(User.username == username) if user is None: return errors.not_found() user_dict = user.to_json() user_dict = Vote.add_votes_info(user_dict, 1, get_user_from_request()) user_dict = Achievement.add_achievements(user_dict) return jsonify({"success": 1, "user": user_dict})
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
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()
def leave(url): """Не участвовать в джеме""" user = get_user_from_request() jam = Jam.get_or_none(Jam.url == url) if jam is None: return errors.not_found() entry = JamEntry.get_or_none(jam=jam, creator=user) if entry: entry.is_archived = True entry.save() return jsonify({"success": 1})
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})
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})
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})
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})
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()})
def participiate(url): """Участвовать в джеме""" user = get_user_from_request() jam = Jam.get_or_none(Jam.url == url) if jam is None: return errors.not_found() entry = JamEntry.get_or_none(jam=jam, creator=user) if not entry: JamEntry.create( jam=jam, creator=user, created_date=datetime.datetime.now(), url=uuid.uuid4(), ) else: entry.is_archived = False entry.save() return jsonify({"success": 1})
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()})
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()}, } )
def user_jam_entries(username): """Получить список заявок на джем для данного пользователя""" user = User.get_or_none(User.username == username) if user is None: return errors.not_found() query = JamEntry.get_user_entries(user) limit = max(1, min(int(request.args.get("limit") or 100), 100)) paginated_query = PaginatedQuery(query, paginate_by=limit) entries = [e.to_json() for e in paginated_query.get_object_list()] return jsonify({ "success": 1, "entries": entries, "meta": { "page_count": paginated_query.get_page_count() }, })
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() }, })
def user_blogs(username): """Получить список блогов пользователя""" user = User.get_or_none(User.username == username) if user is None: return errors.not_found() query = Blog.get_blogs_for_user(user) limit = max(1, min(int(request.args.get("limit") or 20), 100)) paginated_query = PaginatedQuery(query, paginate_by=limit) blogs = [b.to_json() for b in paginated_query.get_object_list()] blogs = [Vote.add_votes_info(b, 2, get_user_from_request()) for b in blogs] return jsonify({ "success": 1, "blogs": blogs, "meta": { "page_count": paginated_query.get_page_count() }, })