def leave_feedback(): """Оставить отзыв""" json = request.get_json() if "text" in json: Feedback.create(text=json["text"], user=get_user_from_request()) Telegram(current_app.config).notify_admin_channel( "Пользователь %s оставил отзыв: %s" % (get_user_from_request().username, json["text"]) ) success = Trello(current_app.config).create_card(json["text"]) if not success: return errors.feedback_trello_error() for user in User.get_admins(): Notification.create( user=user, created_date=datetime.datetime.now(), text="Пользователь %s оставил отзыв: %s" % (get_user_from_request().username, json["text"]), object_type="feedback", ) return jsonify({"success": 1}) else: return errors.wrong_payload("text")
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 mark_as_read(): """Пометить уведомления как прочитанные""" user = get_user_from_request() json = request.get_json() if "ids" in json: for i in json["ids"]: Notification.mark_notification_as_readed(user, i) else: return errors.wrong_payload("ids") return jsonify({"success": 1})
def test_notifications(client, user_token): rv = client.get("/notifications/", headers={"Authorization": user_token[1].token}) assert rv.json["success"] == 1 assert len(rv.json["notifications"]) == 0 rv = client.get( "/notifications/test", headers={"Authorization": user_token[1].token} ) assert rv.json["success"] == 1 assert Notification.select().count() == 1 from src.model import db db.db_wrapper.database.close() rv = client.get("/notifications/", headers={"Authorization": user_token[1].token}) assert rv.json["success"] == 1 assert len(rv.json["notifications"]) == 1 assert "text" in rv.json["notifications"][0] assert rv.json["notifications"][0]["is_new"] rv = client.put( "/notifications/", headers={"Authorization": user_token[1].token}, json={"ids": [rv.json["notifications"][0]["id"]]}, ) assert rv.json["success"] == 1 rv = client.get("/notifications/", headers={"Authorization": user_token[1].token}) assert rv.json["success"] == 1 assert len(rv.json["notifications"]) == 1 assert "text" in rv.json["notifications"][0] assert not rv.json["notifications"][0]["is_new"] rv = client.get( "/notifications/test", headers={"Authorization": user_token[1].token} ) assert rv.json["success"] == 1 assert Notification.select().count() == 2 from src.model import db db.db_wrapper.database.close() rv = client.get( "/notifications/new", headers={"Authorization": user_token[1].token} ) assert rv.json["success"] == 1 assert len(rv.json["notifications"]) == 1 assert "text" in rv.json["notifications"][0] assert rv.json["notifications"][0]["is_new"] rv = client.get("/notifications/", headers={"Authorization": user_token[1].token}) assert rv.json["success"] == 1 assert len(rv.json["notifications"]) == 2
def test_notification(): """Создать тестовое уведомление""" user = get_user_from_request() n = Notification.create(user=user, created_date=datetime.datetime.now(), text="Это тестовое уведомление") return jsonify({"success": 1, "notification": n.to_json()})
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})
def get_new(): """Получить список новых уведомлений""" query = Notification.get_user_unread_notifications(get_user_from_request()) limit = max(1, min(int(request.args.get("limit") or 20), 100)) paginated = PaginatedQuery(query, paginate_by=limit) return jsonify({ "success": 1, "notifications": [p.to_json() for p in paginated.get_object_list()], "meta": { "page_count": paginated.get_page_count() }, })
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()})
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()})