core/resolvers/reaction.py

655 lines
26 KiB
Python
Raw Normal View History

2023-11-03 10:10:22 +00:00
import time
2023-11-22 16:38:39 +00:00
2024-08-07 11:18:05 +00:00
from sqlalchemy import and_, asc, case, desc, func, select
from sqlalchemy.orm import aliased
2023-12-17 20:30:20 +00:00
from orm.author import Author
2024-04-24 07:42:33 +00:00
from orm.rating import PROPOSAL_REACTIONS, RATING_REACTIONS, is_negative, is_positive
2024-02-19 11:45:55 +00:00
from orm.reaction import Reaction, ReactionKind
2024-02-02 16:36:30 +00:00
from orm.shout import Shout
2024-02-02 12:03:44 +00:00
from resolvers.editor import handle_proposing
2024-06-05 15:29:15 +00:00
from resolvers.follower import follow
2024-04-19 15:22:07 +00:00
from resolvers.stat import update_author_stat
2024-01-25 19:41:27 +00:00
from services.auth import add_user_role, login_required
2023-10-23 14:51:13 +00:00
from services.db import local_session
2024-08-07 05:57:56 +00:00
from utils.logger import root_logger as logger
2023-12-17 20:30:20 +00:00
from services.notify import notify_reaction
2023-10-23 14:51:13 +00:00
from services.schema import mutation, query
2024-01-13 08:49:12 +00:00
2023-01-17 21:07:44 +00:00
2024-02-22 23:08:43 +00:00
def add_reaction_stat_columns(q, aliased_reaction):
2024-08-07 11:18:05 +00:00
"""
Добавляет статистические колонки к запросу реакций.
:param q: SQL-запрос для реакций.
:param aliased_reaction: Алиас для таблицы реакций.
:return: Запрос с добавленными колонками статистики.
"""
# Присоединение реакций и добавление статистических колонок
2024-08-07 07:22:37 +00:00
q = q.outerjoin(aliased_reaction, aliased_reaction.deleted_at.is_(None)).add_columns(
2024-08-07 11:18:05 +00:00
# Подсчет комментариев
2024-08-07 07:22:37 +00:00
func.count(case((aliased_reaction.body.is_not(None), 1), else_=0)).label("comments_stat"),
2024-08-07 11:18:05 +00:00
# Вычисление рейтинга как разница между лайками и дизлайками
2024-08-07 07:22:37 +00:00
func.sum(
case(
(aliased_reaction.kind == ReactionKind.LIKE.value, 1),
(aliased_reaction.kind == ReactionKind.DISLIKE.value, -1),
else_=0,
)
).label("rating_stat"),
2024-08-06 15:53:25 +00:00
)
2024-08-07 07:22:37 +00:00
return q
2024-08-07 11:18:05 +00:00
def is_featured_author(session, author_id) -> bool:
"""
Проверяет, есть ли у автора хотя бы одна опубликованная статья.
:param session: Сессия базы данных.
:param author_id: Идентификатор автора.
:return: True, если у автора есть хотя бы одна опубликованная статья, иначе False.
"""
2023-10-05 18:46:18 +00:00
return (
session.query(Shout)
2024-01-22 22:21:01 +00:00
.where(Shout.authors.any(id=author_id))
2024-02-02 12:03:44 +00:00
.filter(and_(Shout.featured_at.is_not(None), Shout.deleted_at.is_(None)))
2023-10-05 18:46:18 +00:00
.count()
> 0
)
2022-11-13 15:24:29 +00:00
2024-02-02 12:59:22 +00:00
2024-08-07 11:18:05 +00:00
def check_to_feature(session, approver_id, reaction) -> bool:
"""
Устанавливает публикацию в открытый доступ, если количество голосов превышает 4.
:param session: Сессия базы данных.
:param approver_id: Идентификатор утверждающего автора.
:param reaction: Объект реакции.
:return: True, если нужно установить публикацию в открытый доступ, иначе False.
"""
2024-01-23 13:04:38 +00:00
if not reaction.reply_to and is_positive(reaction.kind):
2024-02-02 12:03:44 +00:00
if is_featured_author(session, approver_id):
2024-02-24 18:45:38 +00:00
approvers = [approver_id]
2024-08-07 11:18:05 +00:00
# Подсчет количества голосующих утверждающих
2024-05-30 04:12:00 +00:00
reacted_readers = session.query(Reaction).where(Reaction.shout == reaction.shout).all()
2024-02-02 12:03:44 +00:00
for reacted_reader in reacted_readers:
if is_featured_author(session, reacted_reader.id):
approvers.append(reacted_reader.id)
2022-11-13 15:24:29 +00:00
if len(approvers) > 4:
return True
return False
2024-08-07 11:18:05 +00:00
def check_to_unfeature(session, rejecter_id, reaction) -> bool:
"""
Убирает публикацию из открытого доступа, если 20% реакций негативные.
:param session: Сессия базы данных.
:param rejecter_id: Идентификатор отклоняющего автора.
:param reaction: Объект реакции.
:return: True, если нужно убрать публикацию из открытого доступа, иначе False.
"""
2024-01-23 13:04:38 +00:00
if not reaction.reply_to and is_negative(reaction.kind):
2024-02-02 12:03:44 +00:00
if is_featured_author(session, rejecter_id):
2024-02-02 12:59:22 +00:00
reactions = (
session.query(Reaction)
2024-02-21 07:27:16 +00:00
.where(
and_(
Reaction.shout == reaction.shout,
Reaction.kind.in_(RATING_REACTIONS),
)
)
2024-02-02 12:59:22 +00:00
.all()
)
2024-02-02 12:03:44 +00:00
rejects = 0
for r in reactions:
2024-05-30 04:12:00 +00:00
approver = session.query(Author).filter(Author.id == r.created_by).first()
2024-02-02 12:03:44 +00:00
if is_featured_author(session, approver):
if is_negative(r.kind):
rejects += 1
if len(reactions) / rejects < 5:
return True
2022-11-13 15:24:29 +00:00
return False
2024-02-02 12:03:44 +00:00
async def set_featured(session, shout_id):
2024-08-07 11:18:05 +00:00
"""
Устанавливает публикацию в открытый доступ и обновляет роль автора.
:param session: Сессия базы данных.
:param shout_id: Идентификатор публикации.
"""
2022-12-01 14:45:19 +00:00
s = session.query(Shout).where(Shout.id == shout_id).first()
2024-02-02 12:03:44 +00:00
s.featured_at = int(time.time())
2024-04-17 15:32:23 +00:00
Shout.update(s, {"featured_at": int(time.time())})
2024-01-10 13:29:49 +00:00
author = session.query(Author).filter(Author.id == s.created_by).first()
if author:
await add_user_role(str(author.user))
2022-11-13 15:24:29 +00:00
session.add(s)
session.commit()
2024-02-02 12:03:44 +00:00
def set_unfeatured(session, shout_id):
2024-08-07 11:18:05 +00:00
"""
Убирает публикацию из открытого доступа.
:param session: Сессия базы данных.
:param shout_id: Идентификатор публикации.
"""
2022-12-01 14:45:19 +00:00
s = session.query(Shout).where(Shout.id == shout_id).first()
2024-04-17 15:32:23 +00:00
Shout.update(s, {"featured_at": None})
2022-11-13 15:24:29 +00:00
session.add(s)
session.commit()
2024-01-23 13:04:38 +00:00
2024-08-07 11:18:05 +00:00
async def _create_reaction(session, info, shout, author_id: int, reaction) -> dict:
"""
Создает новую реакцию и выполняет связанные с этим действия, такие как обновление счетчиков и уведомление.
:param session: Сессия базы данных.
:param info: Информация о контексте GraphQL.
:param shout: Объект публикации.
:param author_id: Идентификатор автора.
:param reaction: Словарь с данными реакции.
:return: Словарь с данными о созданной реакции.
"""
2024-01-23 13:04:38 +00:00
r = Reaction(**reaction)
session.add(r)
session.commit()
2024-01-31 00:09:58 +00:00
rdict = r.dict()
2024-01-23 13:04:38 +00:00
2024-08-07 11:18:05 +00:00
# Пересчет счетчика комментариев
2024-04-18 09:34:04 +00:00
if str(r.kind) == ReactionKind.COMMENT.value:
2024-06-11 19:46:35 +00:00
update_author_stat(author_id)
2024-04-09 13:43:06 +00:00
2024-08-07 11:18:05 +00:00
# Совместное редактирование
2024-05-30 04:12:00 +00:00
if rdict.get("reply_to") and r.kind in PROPOSAL_REACTIONS and author_id in shout.authors:
2024-02-02 12:03:44 +00:00
handle_proposing(session, r, shout)
2024-08-07 11:18:05 +00:00
# Рейтинг и саморегуляция
2024-04-09 11:03:50 +00:00
if r.kind in RATING_REACTIONS:
2024-08-07 11:18:05 +00:00
# Механизм саморегуляции
2024-04-19 15:22:07 +00:00
if check_to_unfeature(session, author_id, r):
2024-04-09 11:03:50 +00:00
set_unfeatured(session, shout.id)
2024-04-19 15:22:07 +00:00
elif check_to_feature(session, author_id, r):
2024-04-09 11:03:50 +00:00
await set_featured(session, shout.id)
2024-08-07 11:18:05 +00:00
# Подписка, если понравилось
2024-04-09 11:03:50 +00:00
if r.kind == ReactionKind.LIKE.value:
try:
2024-08-07 11:18:05 +00:00
# Автоподписка при реакции
2024-06-05 15:29:15 +00:00
follow(None, info, "shout", shout.slug)
2024-04-09 11:03:50 +00:00
except Exception:
pass
2024-01-23 13:04:38 +00:00
2024-08-07 11:18:05 +00:00
# Обновление счетчика комментариев в кэше
2024-04-18 09:34:04 +00:00
if str(r.kind) == ReactionKind.COMMENT.value:
2024-06-11 19:46:35 +00:00
update_author_stat(author_id)
2024-04-09 13:43:06 +00:00
2024-04-17 15:32:23 +00:00
rdict["shout"] = shout.dict()
rdict["stat"] = {"commented": 0, "reacted": 0, "rating": 0}
2024-01-23 13:04:38 +00:00
2024-08-07 11:18:05 +00:00
# Уведомление о создании
2024-04-17 15:32:23 +00:00
await notify_reaction(rdict, "create")
2024-01-23 13:04:38 +00:00
return rdict
2024-01-25 19:41:27 +00:00
2024-04-19 15:22:07 +00:00
def prepare_new_rating(reaction: dict, shout_id: int, session, author_id: int):
2024-08-07 11:18:05 +00:00
"""
Проверяет возможность выставления новой оценки для публикации.
:param reaction: Словарь с данными реакции.
:param shout_id: Идентификатор публикации.
:param session: Сессия базы данных.
:param author_id: Идентификатор автора.
:return: Словарь с ошибкой или None.
"""
2024-04-17 15:32:23 +00:00
kind = reaction.get("kind")
2024-05-30 04:12:00 +00:00
opposite_kind = ReactionKind.DISLIKE.value if is_positive(kind) else ReactionKind.LIKE.value
2024-02-24 18:45:38 +00:00
2024-08-07 11:18:05 +00:00
# Формирование запроса для проверки существующих оценок
2024-02-24 18:45:38 +00:00
q = select(Reaction).filter(
and_(
Reaction.shout == shout_id,
2024-04-19 15:22:07 +00:00
Reaction.created_by == author_id,
2024-02-24 18:45:38 +00:00
Reaction.kind.in_(RATING_REACTIONS),
2024-05-04 21:00:58 +00:00
Reaction.deleted_at.is_not(None),
2024-02-24 18:45:38 +00:00
)
)
2024-04-17 15:32:23 +00:00
reply_to = reaction.get("reply_to")
2024-02-24 18:45:38 +00:00
if reply_to and isinstance(reply_to, int):
q = q.filter(Reaction.reply_to == reply_to)
rating_reactions = session.execute(q).all()
2024-08-07 11:18:05 +00:00
# Проверка условий для выставления новой оценки
2024-05-04 21:00:58 +00:00
if rating_reactions:
same_rating = filter(
lambda r: r.created_by == author_id and r.kind == kind,
rating_reactions,
)
opposite_rating = filter(
lambda r: r.created_by == author_id and r.kind == opposite_kind,
rating_reactions,
)
if same_rating:
return {"error": "You can't rate the same thing twice"}
elif opposite_rating:
return {"error": "Remove opposite vote first"}
elif filter(lambda r: r.created_by == author_id, rating_reactions):
return {"error": "You can't rate your own thing"}
2024-02-24 18:45:38 +00:00
return
2024-04-17 15:32:23 +00:00
@mutation.field("create_reaction")
@login_required
2023-02-26 21:23:25 +00:00
async def create_reaction(_, info, reaction):
2024-08-07 11:18:05 +00:00
"""
Создает новую реакцию через GraphQL запрос.
:param info: Информация о контексте GraphQL.
:param reaction: Словарь с данными реакции.
:return: Словарь с информацией о созданной реакции или ошибкой.
"""
2024-05-18 14:41:04 +00:00
# logger.debug(f"{info.context} for {reaction}")
2024-04-19 15:22:07 +00:00
info.context.get("user_id")
2024-05-18 14:41:04 +00:00
author_dict = info.context.get("author", {})
if not isinstance(author_dict, dict):
2024-05-18 09:38:46 +00:00
return {"error": "Unauthorized"}
2024-05-18 14:41:04 +00:00
author_id = author_dict.get("id")
shout_id = reaction.get("shout")
2024-01-22 20:54:02 +00:00
if not shout_id:
2024-04-17 15:32:23 +00:00
return {"error": "Shout ID is required to create a reaction."}
2024-01-22 20:54:02 +00:00
try:
with local_session() as session:
2024-02-02 12:03:44 +00:00
shout = session.query(Shout).filter(Shout.id == shout_id).first()
2024-04-19 15:22:07 +00:00
if shout and author_id:
reaction["created_by"] = int(author_id)
2024-04-17 15:32:23 +00:00
kind = reaction.get("kind")
2024-01-23 13:04:38 +00:00
2024-04-17 15:32:23 +00:00
if not kind and isinstance(reaction.get("body"), str):
2024-01-22 22:11:34 +00:00
kind = ReactionKind.COMMENT.value
2024-01-23 13:04:38 +00:00
2024-01-22 22:11:34 +00:00
if not kind:
2024-04-17 15:32:23 +00:00
return {"error": "cannot create reaction without a kind"}
2024-01-23 13:04:38 +00:00
2024-02-07 13:41:17 +00:00
if kind in RATING_REACTIONS:
2024-05-30 04:12:00 +00:00
error_result = prepare_new_rating(reaction, shout_id, session, author_id)
2024-03-06 09:15:26 +00:00
if error_result:
return error_result
2024-02-07 13:41:17 +00:00
2024-06-05 15:29:15 +00:00
rdict = await _create_reaction(session, info, shout, author_id, reaction)
2024-03-06 09:15:26 +00:00
# TODO: call recount ratings periodically
2024-05-18 14:41:04 +00:00
rdict["created_by"] = author_dict
2024-04-17 15:32:23 +00:00
return {"reaction": rdict}
2024-01-22 20:54:02 +00:00
except Exception as e:
2024-01-22 21:27:57 +00:00
import traceback
2024-01-25 19:41:27 +00:00
traceback.print_exc()
2024-04-17 15:32:23 +00:00
logger.error(f"{type(e).__name__}: {e}")
2023-10-23 14:47:11 +00:00
2024-04-17 15:32:23 +00:00
return {"error": "Cannot create reaction."}
2024-04-17 15:32:23 +00:00
@mutation.field("update_reaction")
@login_required
2024-02-16 16:46:57 +00:00
async def update_reaction(_, info, reaction):
2024-08-07 11:18:05 +00:00
"""
Обновляет существующую реакцию через GraphQL запрос.
:param info: Информация о контексте GraphQL.
:param reaction: Словарь с данными реакции.
:return: Словарь с информацией об обновленной реакции или ошибкой.
"""
2024-04-17 15:32:23 +00:00
logger.debug(f"{info.context} for {reaction}")
user_id = info.context.get("user_id")
roles = info.context.get("roles")
rid = reaction.get("id")
2024-02-24 18:30:19 +00:00
if rid and isinstance(rid, int) and user_id and roles:
2024-04-17 15:32:23 +00:00
del reaction["id"]
2024-02-05 09:47:26 +00:00
with local_session() as session:
2024-02-24 18:30:19 +00:00
reaction_query = select(Reaction).filter(Reaction.id == rid)
2024-02-05 09:47:26 +00:00
aliased_reaction = aliased(Reaction)
2024-02-22 23:08:43 +00:00
reaction_query = add_reaction_stat_columns(reaction_query, aliased_reaction)
2024-02-16 16:46:57 +00:00
reaction_query = reaction_query.group_by(Reaction.id)
2022-11-28 08:47:39 +00:00
2024-02-16 16:46:57 +00:00
try:
2024-04-18 09:34:04 +00:00
result = session.execute(reaction_query).unique().first()
if result:
2024-08-07 11:18:05 +00:00
[r, commented_stat, rating_stat] = result
2024-04-18 09:34:04 +00:00
if not r:
return {"error": "invalid reaction id"}
2024-05-30 04:12:00 +00:00
author = session.query(Author).filter(Author.user == user_id).first()
2024-04-18 09:34:04 +00:00
if author:
if r.created_by != author.id and "editor" not in roles:
return {"error": "access denied"}
body = reaction.get("body")
if body:
r.body = body
r.updated_at = int(time.time())
if r.kind != reaction["kind"]:
# Определение изменения мнения может быть реализовано здесь
pass
Reaction.update(r, reaction)
session.add(r)
session.commit()
r.stat = {
"commented": commented_stat,
2024-08-07 07:22:37 +00:00
"rating": rating_stat,
2024-04-18 09:34:04 +00:00
}
await notify_reaction(r.dict(), "update")
return {"reaction": r}
else:
return {"error": "not authorized"}
2024-02-16 16:46:57 +00:00
except Exception:
import traceback
traceback.print_exc()
2024-04-17 15:32:23 +00:00
return {"error": "cannot create reaction"}
2024-01-25 19:41:27 +00:00
2024-04-17 15:32:23 +00:00
@mutation.field("delete_reaction")
@login_required
2024-02-07 13:41:17 +00:00
async def delete_reaction(_, info, reaction_id: int):
2024-08-07 11:18:05 +00:00
"""
Удаляет существующую реакцию через GraphQL запрос.
:param info: Информация о контексте GraphQL.
:param reaction_id: Идентификатор удаляемой реакции.
:return: Словарь с информацией об удаленной реакции или ошибкой.
"""
2024-04-17 15:32:23 +00:00
logger.debug(f"{info.context} for {reaction_id}")
user_id = info.context.get("user_id")
2024-04-19 15:22:07 +00:00
author_id = info.context.get("author", {}).get("id")
2024-04-17 15:32:23 +00:00
roles = info.context.get("roles", [])
2024-03-06 09:09:46 +00:00
if user_id:
2024-02-07 13:41:17 +00:00
with local_session() as session:
try:
author = session.query(Author).filter(Author.user == user_id).one()
r = session.query(Reaction).filter(Reaction.id == reaction_id).one()
2024-04-19 15:22:07 +00:00
if r.created_by != author_id and "editor" not in roles:
2024-04-17 15:32:23 +00:00
return {"error": "access denied"}
2024-02-07 13:41:17 +00:00
2024-04-17 15:32:23 +00:00
logger.debug(f"{user_id} user removing his #{reaction_id} reaction")
2024-04-09 13:43:06 +00:00
reaction_dict = r.dict()
session.delete(r)
session.commit()
2024-08-07 11:18:05 +00:00
# Обновление счетчика комментариев в кэше
2024-04-18 09:34:04 +00:00
if str(r.kind) == ReactionKind.COMMENT.value:
2024-06-11 19:46:35 +00:00
update_author_stat(author.id)
2024-04-17 15:32:23 +00:00
await notify_reaction(reaction_dict, "delete")
2024-04-08 18:33:47 +00:00
2024-04-17 15:32:23 +00:00
return {"error": None, "reaction": reaction_dict}
2024-02-07 13:41:17 +00:00
except Exception as exc:
2024-04-17 15:32:23 +00:00
return {"error": f"cannot delete reaction: {exc}"}
return {"error": "cannot delete reaction"}
2022-11-28 20:29:02 +00:00
2023-11-29 09:59:00 +00:00
def apply_reaction_filters(by, q):
2024-08-07 11:18:05 +00:00
"""
Применяет фильтры к запросу реакций.
:param by: Словарь с параметрами фильтрации.
:param q: SQL-запрос.
:return: Запрос с примененными фильтрами.
"""
2024-04-17 15:32:23 +00:00
shout_slug = by.get("shout", None)
2024-02-02 22:39:57 +00:00
if shout_slug:
q = q.filter(Shout.slug == shout_slug)
2023-11-29 09:59:00 +00:00
2024-04-17 15:32:23 +00:00
elif by.get("shouts"):
q = q.filter(Shout.slug.in_(by.get("shouts", [])))
2023-11-29 09:59:00 +00:00
2024-04-17 15:32:23 +00:00
created_by = by.get("created_by", None)
2024-02-02 22:39:57 +00:00
if created_by:
q = q.filter(Author.id == created_by)
2023-11-29 09:59:00 +00:00
2024-07-18 06:05:10 +00:00
author_slug = by.get("author", None)
if author_slug:
q = q.filter(Author.slug == author_slug)
2024-04-17 15:32:23 +00:00
topic = by.get("topic", None)
2024-04-09 19:24:47 +00:00
if isinstance(topic, int):
2024-04-09 19:09:26 +00:00
q = q.filter(Shout.topics.any(id=topic))
2023-11-29 09:59:00 +00:00
2024-04-17 15:32:23 +00:00
if by.get("comment", False):
2024-02-03 09:10:38 +00:00
q = q.filter(Reaction.kind == ReactionKind.COMMENT.value)
2024-07-15 22:06:43 +00:00
2024-04-17 15:32:23 +00:00
if by.get("rating", False):
2024-02-07 15:39:55 +00:00
q = q.filter(Reaction.kind.in_(RATING_REACTIONS))
2023-11-29 09:59:00 +00:00
2024-04-17 15:32:23 +00:00
by_search = by.get("search", "")
2023-11-29 09:59:00 +00:00
if len(by_search) > 2:
2024-04-17 15:32:23 +00:00
q = q.filter(Reaction.body.ilike(f"%{by_search}%"))
2023-11-29 09:59:00 +00:00
2024-04-17 15:32:23 +00:00
after = by.get("after", None)
2024-02-07 16:50:01 +00:00
if isinstance(after, int):
q = q.filter(Reaction.created_at > after)
2023-11-29 09:59:00 +00:00
return q
2024-04-17 15:32:23 +00:00
@query.field("load_reactions_by")
2023-10-23 14:47:11 +00:00
async def load_reactions_by(_, info, by, limit=50, offset=0):
2022-11-23 02:05:34 +00:00
"""
2024-08-07 11:18:05 +00:00
Загружает реакции по указанным параметрам.
:param info: Информация о контексте GraphQL.
2022-11-23 02:05:34 +00:00
:param by: {
2024-08-07 11:18:05 +00:00
:shout - фильтрация по slug публикации
:shouts - фильтрация по списку slug публикаций
:created_by - фильтрация по идентификатору автора
:author - фильтрация по slug автора
:topic - фильтрация по теме
:search - поиск по тексту реакций
:comment - фильтрация комментариев
:rating - фильтрация реакций с рейтингом
:after - фильтрация по времени создания
:sort - поле для сортировки (по убыванию по умолчанию)
2022-11-23 02:05:34 +00:00
}
2024-08-07 11:18:05 +00:00
:param limit: Количество реакций для загрузки.
:param offset: Смещение для пагинации.
:return: Список реакций.
2022-11-23 02:05:34 +00:00
"""
2023-10-05 18:46:18 +00:00
q = (
2024-02-29 12:39:55 +00:00
select(Reaction, Author, Shout)
2024-02-29 12:21:46 +00:00
.select_from(Reaction)
2024-02-29 12:39:55 +00:00
.join(Author, Reaction.created_by == Author.id)
.join(Shout, Reaction.shout == Shout.id)
2022-11-27 08:19:38 +00:00
)
2022-09-03 10:50:14 +00:00
2024-08-07 11:18:05 +00:00
# Подсчет статистики
2024-02-29 12:21:46 +00:00
aliased_reaction = aliased(Reaction)
q = add_reaction_stat_columns(q, aliased_reaction)
2023-11-29 11:16:09 +00:00
2024-08-07 11:18:05 +00:00
# Применение фильтров
2023-11-29 09:59:00 +00:00
q = apply_reaction_filters(by, q)
2024-02-29 12:21:46 +00:00
q = q.where(Reaction.deleted_at.is_(None))
2023-11-29 11:16:09 +00:00
2024-08-07 11:18:05 +00:00
# Группировка
2024-02-29 12:21:46 +00:00
q = q.group_by(Reaction.id, Author.id, Shout.id, aliased_reaction.id)
2024-01-13 08:15:45 +00:00
2024-08-07 11:18:05 +00:00
# Сортировка
2024-04-17 15:32:23 +00:00
order_stat = by.get("sort", "").lower() # 'like' | 'dislike' | 'newest' | 'oldest'
2024-02-29 12:39:55 +00:00
order_by_stmt = desc(Reaction.created_at)
2024-04-17 15:32:23 +00:00
if order_stat == "oldest":
2024-02-29 12:39:55 +00:00
order_by_stmt = asc(Reaction.created_at)
2024-04-17 15:32:23 +00:00
elif order_stat.endswith("like"):
2024-08-07 11:18:05 +00:00
order_by_stmt = desc("rating_stat")
2024-02-29 12:39:55 +00:00
q = q.order_by(order_by_stmt)
2023-11-29 11:16:09 +00:00
2024-08-07 11:18:05 +00:00
# Пагинация
2022-11-22 07:29:54 +00:00
q = q.limit(limit).offset(offset)
2023-11-30 07:38:41 +00:00
2024-02-26 17:07:42 +00:00
reactions = set()
2023-11-29 10:50:20 +00:00
with local_session() as session:
result_rows = session.execute(q)
for [
reaction,
author,
shout,
commented_stat,
2024-08-07 11:02:36 +00:00
rating_stat,
2024-08-06 15:18:51 +00:00
last_reacted_at,
2023-11-29 10:50:20 +00:00
] in result_rows:
reaction.created_by = author
reaction.shout = shout
2024-08-07 11:18:05 +00:00
reaction.stat = {"rating": rating_stat, "commented": commented_stat}
2024-07-22 07:42:41 +00:00
reactions.add(reaction)
2024-02-26 17:07:42 +00:00
2022-11-23 02:05:34 +00:00
return reactions
2023-10-23 14:47:11 +00:00
2024-07-22 07:42:41 +00:00
@query.field("load_shout_ratings")
async def load_shout_ratings(_, info, shout: int, limit=100, offset=0):
"""
2024-08-07 11:18:05 +00:00
Получает оценки для указанной публикации с пагинацией.
2024-07-22 07:42:41 +00:00
2024-08-07 11:18:05 +00:00
:param info: Информация о контексте GraphQL.
:param shout: Идентификатор публикации.
:param limit: Количество реакций для загрузки.
:param offset: Смещение для пагинации.
:return: Список реакций.
"""
2024-07-22 07:42:41 +00:00
q = (
select(Reaction, Author, Shout)
.select_from(Reaction)
.join(Author, Reaction.created_by == Author.id)
.join(Shout, Reaction.shout == Shout.id)
)
2024-08-07 11:18:05 +00:00
# Фильтрация, группировка, сортировка, лимит, офсет
2024-07-22 07:42:41 +00:00
q = q.filter(and_(Reaction.deleted_at.is_(None), Reaction.shout == shout, Reaction.kind.in_(RATING_REACTIONS)))
q = q.group_by(Reaction.id)
q = q.order_by(desc(Reaction.created_at))
q = q.limit(limit).offset(offset)
reactions = set()
with local_session() as session:
result_rows = session.execute(q)
for [
reaction,
author,
shout,
] in result_rows:
reaction.created_by = author
reaction.shout = shout
reactions.add(reaction)
return reactions
@query.field("load_shout_comments")
async def load_shout_comments(_, info, shout: int, limit=50, offset=0):
"""
2024-08-07 11:18:05 +00:00
Получает комментарии для указанной публикации с пагинацией и статистикой.
:param info: Информация о контексте GraphQL.
:param shout: Идентификатор публикации.
:param limit: Количество комментариев для загрузки.
:param offset: Смещение для пагинации.
:return: Список реакций.
2024-07-22 07:42:41 +00:00
"""
2024-07-26 13:56:30 +00:00
aliased_reaction = aliased(Reaction)
2024-07-22 07:42:41 +00:00
q = (
2024-07-26 13:56:30 +00:00
select(
Reaction,
Author,
Shout,
func.count(aliased_reaction.id).label("reacted_stat"),
func.count(aliased_reaction.body).label("commented_stat"),
2024-07-30 02:19:16 +00:00
func.sum(case((aliased_reaction.kind == str(ReactionKind.LIKE.value), 1), else_=0)).label("likes_stat"),
2024-08-06 11:34:12 +00:00
func.sum(case((aliased_reaction.kind == str(ReactionKind.DISLIKE.value), 1), else_=0)).label(
"dislikes_stat"
),
2024-07-26 13:56:30 +00:00
)
2024-07-22 07:42:41 +00:00
.select_from(Reaction)
.join(Author, Reaction.created_by == Author.id)
.join(Shout, Reaction.shout == Shout.id)
)
2024-08-07 11:18:05 +00:00
# Фильтрация, группировка, сортировка, лимит, офсет
2024-07-22 07:42:41 +00:00
q = q.filter(and_(Reaction.deleted_at.is_(None), Reaction.shout == shout, Reaction.body.is_not(None)))
2024-07-26 13:56:30 +00:00
q = q.group_by(Reaction.id, Author.id, Shout.id)
2024-07-22 07:42:41 +00:00
q = q.order_by(desc(Reaction.created_at))
q = q.limit(limit).offset(offset)
reactions = set()
with local_session() as session:
result_rows = session.execute(q)
2024-07-26 13:56:30 +00:00
for row in result_rows:
reaction, author, shout, reacted_stat, commented_stat, likes_stat, dislikes_stat = row
2024-07-22 07:42:41 +00:00
reaction.created_by = author
reaction.shout = shout
reaction.stat = {
"rating": int(likes_stat or 0) - int(dislikes_stat or 0),
"reacted": reacted_stat,
"commented": commented_stat,
}
reactions.add(reaction)
2024-07-26 13:56:30 +00:00
return list(reactions)
2024-07-26 16:04:40 +00:00
2024-08-06 11:34:12 +00:00
2024-07-26 16:04:40 +00:00
@query.field("load_comment_ratings")
async def load_comment_ratings(_, info, comment: int, limit=50, offset=0):
"""
2024-08-07 11:18:05 +00:00
Получает оценки для указанного комментария с пагинацией и статистикой.
:param info: Информация о контексте GraphQL.
:param comment: Идентификатор комментария.
:param limit: Количество оценок для загрузки.
:param offset: Смещение для пагинации.
:return: Список реакций.
2024-07-26 16:04:40 +00:00
"""
aliased_reaction = aliased(Reaction)
q = (
select(
Reaction,
Author,
Shout,
func.count(aliased_reaction.id).label("reacted_stat"),
func.count(aliased_reaction.body).label("commented_stat"),
2024-07-30 02:19:16 +00:00
func.sum(case((aliased_reaction.kind == str(ReactionKind.LIKE.value), 1), else_=0)).label("likes_stat"),
2024-08-06 11:34:12 +00:00
func.sum(case((aliased_reaction.kind == str(ReactionKind.DISLIKE.value), 1), else_=0)).label(
"dislikes_stat"
),
2024-07-26 16:04:40 +00:00
)
.select_from(Reaction)
.join(Author, Reaction.created_by == Author.id)
.join(Shout, Reaction.shout == Shout.id)
)
2024-08-07 11:18:05 +00:00
# Фильтрация, группировка, сортировка, лимит, офсет
2024-07-26 16:04:40 +00:00
q = q.filter(and_(Reaction.deleted_at.is_(None), Reaction.reply_to == comment, Reaction.body.is_not(None)))
q = q.group_by(Reaction.id, Author.id, Shout.id)
q = q.order_by(desc(Reaction.created_at))
q = q.limit(limit).offset(offset)
reactions = set()
with local_session() as session:
result_rows = session.execute(q)
for row in result_rows:
reaction, author, shout, reacted_stat, commented_stat, likes_stat, dislikes_stat = row
reaction.created_by = author
reaction.shout = shout
reaction.stat = {
"rating": int(likes_stat or 0) - int(dislikes_stat or 0),
"reacted": reacted_stat,
"commented": commented_stat,
}
reactions.add(reaction)
return list(reactions)