core/resolvers/reader.py

719 lines
27 KiB
Python
Raw Normal View History

2024-08-07 11:18:05 +00:00
from typing import List
2024-08-09 06:37:06 +00:00
2024-10-31 10:39:38 +00:00
from sqlalchemy.orm import aliased, joinedload
2024-08-07 11:18:05 +00:00
from sqlalchemy.sql import union
2024-07-15 22:06:43 +00:00
from sqlalchemy.sql.expression import (
and_,
asc,
case,
desc,
distinct,
func,
nulls_last,
select,
text,
)
2024-08-09 06:37:06 +00:00
2023-12-17 20:30:20 +00:00
from orm.author import Author, AuthorFollower
from orm.reaction import Reaction, ReactionKind
2024-08-09 06:37:06 +00:00
from orm.shout import Shout, ShoutAuthor, ShoutReactionsFollower, ShoutTopic
2023-12-17 20:30:20 +00:00
from orm.topic import Topic, TopicFollower
2024-02-28 16:24:05 +00:00
from resolvers.topic import get_topics_random
2023-10-23 14:47:11 +00:00
from services.auth import login_required
2023-10-09 21:34:51 +00:00
from services.db import local_session
2023-11-23 23:00:28 +00:00
from services.schema import query
2024-01-29 01:41:46 +00:00
from services.search import search_text
2024-08-07 10:15:58 +00:00
from services.viewed import ViewedStorage
2024-08-09 06:37:06 +00:00
from utils.logger import root_logger as logger
2024-08-07 11:54:13 +00:00
2024-08-08 13:10:45 +00:00
2024-10-23 08:22:07 +00:00
def query_shouts(slug=None, shout_id=None):
2024-08-07 08:35:59 +00:00
"""
2024-08-07 14:45:22 +00:00
Базовый запрос для получения публикаций с подзапросами статистики, авторов и тем,
2024-10-31 09:49:18 +00:00
с агрегированием в JSON.
2024-08-07 08:35:59 +00:00
"""
2024-10-31 10:39:38 +00:00
comments_reaction = aliased(Reaction, name="comments_reaction")
ratings_reaction = aliased(Reaction, name="ratings_reaction")
last_reaction = aliased(Reaction, name="last_reaction")
2024-08-07 08:35:59 +00:00
2024-10-31 09:49:18 +00:00
# Подзапрос для уникальных авторов, агрегированных в JSON
2024-08-07 11:54:13 +00:00
authors_subquery = (
select(
2024-08-07 12:36:05 +00:00
ShoutAuthor.shout.label("shout_id"),
2024-10-31 09:49:18 +00:00
func.json_agg(
func.json_build_object(
"id",
Author.id,
"name",
Author.name,
"slug",
Author.slug,
"pic",
Author.pic,
"caption",
ShoutAuthor.caption,
)
).label("authors"),
2024-08-07 11:54:13 +00:00
)
2024-08-07 12:36:05 +00:00
.join(Author, ShoutAuthor.author == Author.id)
.group_by(ShoutAuthor.shout)
2024-08-07 11:54:13 +00:00
.subquery()
)
2024-08-07 11:41:22 +00:00
2024-10-31 09:49:18 +00:00
# Подзапрос для уникальных тем, агрегированных в JSON
2024-08-07 11:54:13 +00:00
topics_subquery = (
select(
2024-08-07 12:36:05 +00:00
ShoutTopic.shout.label("shout_id"),
2024-10-31 09:49:18 +00:00
func.json_agg(
func.json_build_object(
"id", Topic.id, "title", Topic.title, "slug", Topic.slug, "is_main", ShoutTopic.main
)
).label("topics"),
func.max(case((ShoutTopic.main.is_(True), Topic.slug))).label("main_topic_slug"),
2024-08-07 11:54:13 +00:00
)
2024-08-07 12:36:05 +00:00
.join(Topic, ShoutTopic.topic == Topic.id)
.group_by(ShoutTopic.shout)
2024-08-07 11:54:13 +00:00
.subquery()
)
2024-08-07 11:41:22 +00:00
2024-10-31 10:25:05 +00:00
# Подзапрос для комментариев
comments_subq = (
select(func.count(distinct(comments_reaction.id)))
.select_from(comments_reaction)
2024-10-14 09:19:30 +00:00
.where(
and_(
2024-10-31 10:25:05 +00:00
comments_reaction.shout == Shout.id,
comments_reaction.kind == ReactionKind.COMMENT.value,
2024-10-31 10:39:38 +00:00
comments_reaction.deleted_at.is_(None),
2024-10-14 09:19:30 +00:00
)
)
2024-10-14 06:37:40 +00:00
.scalar_subquery()
2024-10-31 10:39:38 +00:00
.label("comments_stat")
2024-10-14 06:37:40 +00:00
)
2024-10-14 09:19:30 +00:00
2024-10-31 10:25:05 +00:00
# Подзапрос для рейтинга
ratings_subq = (
2024-10-14 09:19:30 +00:00
select(
func.sum(
case(
2024-10-31 10:25:05 +00:00
(ratings_reaction.kind == ReactionKind.LIKE.value, 1),
(ratings_reaction.kind == ReactionKind.DISLIKE.value, -1),
2024-10-31 10:39:38 +00:00
else_=0,
2024-10-14 09:19:30 +00:00
)
2024-10-31 10:25:05 +00:00
)
2024-10-14 09:19:30 +00:00
)
2024-10-31 10:25:05 +00:00
.select_from(ratings_reaction)
2024-10-14 09:19:30 +00:00
.where(
and_(
2024-10-31 10:25:05 +00:00
ratings_reaction.shout == Shout.id,
ratings_reaction.reply_to.is_(None),
2024-10-31 10:39:38 +00:00
ratings_reaction.deleted_at.is_(None),
2024-10-14 06:37:40 +00:00
)
2024-10-14 09:19:30 +00:00
)
2024-10-14 06:37:40 +00:00
.scalar_subquery()
2024-10-31 10:39:38 +00:00
.label("rating_stat")
2024-10-14 06:37:40 +00:00
)
2024-10-14 09:19:30 +00:00
2024-08-07 11:49:15 +00:00
# Основной запрос с использованием подзапросов
2024-08-07 09:38:15 +00:00
q = (
2024-08-07 08:35:59 +00:00
select(
2024-08-07 09:38:15 +00:00
Shout,
2024-10-31 10:25:05 +00:00
comments_subq,
ratings_subq,
func.max(last_reaction.created_at).label("last_reacted_at"),
2024-08-07 12:36:05 +00:00
authors_subquery.c.authors.label("authors"),
topics_subquery.c.topics.label("topics"),
2024-08-08 15:57:03 +00:00
topics_subquery.c.main_topic_slug.label("main_topic_slug"),
2024-08-07 08:35:59 +00:00
)
2024-10-31 10:25:05 +00:00
.outerjoin(last_reaction, and_(last_reaction.shout == Shout.id, last_reaction.deleted_at.is_(None)))
2024-08-07 11:41:22 +00:00
.outerjoin(authors_subquery, authors_subquery.c.shout_id == Shout.id)
.outerjoin(topics_subquery, topics_subquery.c.shout_id == Shout.id)
2024-08-08 15:56:49 +00:00
.outerjoin(ShoutReactionsFollower, ShoutReactionsFollower.shout == Shout.id)
2024-03-28 12:56:32 +00:00
.where(and_(Shout.published_at.is_not(None), Shout.deleted_at.is_(None)))
2024-10-31 10:25:05 +00:00
.group_by(
Shout.id,
2024-10-31 10:39:38 +00:00
text("authors_subquery.authors::text"),
text("topics_subquery.topics::text"),
text("topics_subquery.main_topic_slug"),
2024-10-31 10:25:05 +00:00
)
2024-08-07 08:52:07 +00:00
)
2024-08-08 15:56:49 +00:00
if slug:
q = q.where(Shout.slug == slug)
2024-10-23 08:22:07 +00:00
elif shout_id:
q = q.where(Shout.id == shout_id)
2024-08-08 15:56:49 +00:00
2024-10-31 10:25:05 +00:00
return q, last_reaction
2024-08-07 08:35:59 +00:00
2024-08-08 14:36:20 +00:00
2024-10-31 11:09:33 +00:00
def get_shouts_with_stats(q, limit=20, offset=0, author_id=None):
2024-08-07 08:35:59 +00:00
"""
2024-08-07 09:29:51 +00:00
Получение публикаций со статистикой, и подзапросами авторов и тем.
2024-08-07 08:35:59 +00:00
:param q: Запрос
:param limit: Ограничение на количество результатов.
:param offset: Смещение для пагинации.
:return: Список публикаций с включенной статистикой.
"""
2024-10-31 11:09:33 +00:00
# Определение скалярного подзапроса для авторов
2024-10-31 10:39:38 +00:00
authors_subquery = (
2024-10-31 11:00:56 +00:00
select(
2024-10-31 10:39:38 +00:00
func.json_agg(
func.json_build_object(
2024-10-31 11:11:59 +00:00
"id", Author.id,
"name", Author.name,
"slug", Author.slug,
"pic", Author.pic,
"caption", ShoutAuthor.caption
2024-10-31 10:39:38 +00:00
)
2024-10-31 10:52:32 +00:00
).label("authors")
2024-10-31 10:39:38 +00:00
)
2024-10-31 11:09:33 +00:00
.select_from(ShoutAuthor)
2024-10-31 10:39:38 +00:00
.join(Author, ShoutAuthor.author == Author.id)
2024-10-31 11:09:33 +00:00
.where(ShoutAuthor.shout == Shout.id)
2024-10-31 11:11:59 +00:00
.correlate(Shout) # Явная корреляция с таблицей Shout
2024-10-31 11:09:33 +00:00
.scalar_subquery()
2024-10-31 10:39:38 +00:00
)
2024-10-31 11:09:33 +00:00
# Определение скалярного подзапроса для тем
2024-10-31 10:39:38 +00:00
topics_subquery = (
select(
func.json_agg(
func.json_build_object(
2024-10-31 11:11:59 +00:00
"id", Topic.id,
"title", Topic.title,
"slug", Topic.slug,
"is_main", ShoutTopic.main
2024-10-31 10:39:38 +00:00
)
).label("topics"),
2024-10-31 11:11:59 +00:00
func.max(
case(
(ShoutTopic.main, Topic.slug)
)
).label("main_topic_slug")
2024-10-31 10:39:38 +00:00
)
2024-10-31 11:09:33 +00:00
.select_from(ShoutTopic)
2024-10-31 10:39:38 +00:00
.join(Topic, ShoutTopic.topic == Topic.id)
2024-10-31 11:09:33 +00:00
.where(ShoutTopic.shout == Shout.id)
2024-10-31 10:39:38 +00:00
.group_by(ShoutTopic.shout)
2024-10-31 11:11:59 +00:00
.correlate(Shout) # Явная корреляция с таблицей Shout
2024-10-31 11:09:33 +00:00
.scalar_subquery()
2024-10-31 10:39:38 +00:00
)
2024-10-31 11:09:33 +00:00
# Определение скалярного подзапроса для последней реакции
2024-10-31 10:39:38 +00:00
last_reaction = (
2024-10-31 11:11:59 +00:00
select(
func.max(Reaction.created_at).label("last_reacted_at")
)
2024-10-31 11:09:33 +00:00
.where(Reaction.shout == Shout.id, Reaction.deleted_at.is_(None))
.scalar_subquery()
2024-10-31 10:39:38 +00:00
)
# Основной запрос
2024-10-31 11:11:59 +00:00
query = (
2024-10-31 10:39:38 +00:00
select(
Shout,
2024-10-31 11:11:59 +00:00
func.count(Reaction.id.distinct()).label("comments_stat"),
func.sum(
case(
(Reaction.kind == "LIKE", 1),
(Reaction.kind == "DISLIKE", -1),
else_=0
)
).label("rating_stat"),
last_reaction,
authors_subquery,
topics_subquery,
func.coalesce(
func.json_extract_path_text(topics_subquery, 'main_topic_slug'),
''
).label("main_topic_slug")
2024-08-07 10:15:58 +00:00
)
2024-10-31 10:39:38 +00:00
.outerjoin(Reaction, Reaction.shout == Shout.id)
2024-10-31 11:11:59 +00:00
.filter(
Shout.published_at.isnot(None),
Shout.deleted_at.is_(None),
Shout.featured_at.isnot(None)
)
.group_by(
Shout.id,
last_reaction
)
2024-10-31 10:39:38 +00:00
.order_by(Shout.published_at.desc().nullslast())
2024-08-07 10:15:58 +00:00
.limit(limit)
.offset(offset)
)
2024-08-07 08:35:59 +00:00
2024-10-31 10:59:18 +00:00
# Добавление фильтрации по author_id, если необходимо
if author_id:
2024-10-31 11:11:59 +00:00
query = query.filter(Shout.created_by == author_id)
2024-10-31 10:59:18 +00:00
2024-08-07 09:38:15 +00:00
# Выполнение запроса и обработка результатов
2024-10-31 11:11:59 +00:00
with q.session as session:
results = session.execute(query).all()
2024-08-07 08:35:59 +00:00
# Формирование списка публикаций с их данными
shouts = []
2024-10-14 06:23:11 +00:00
2024-10-31 11:11:59 +00:00
for row in results:
shout = row.Shout
comments_stat = row.comments_stat
rating_stat = row.rating_stat
last_reacted_at = row.last_reacted_at
authors_json = row.authors
topics_json = row.topics
main_topic_slug = row.main_topic_slug
2024-10-31 09:49:18 +00:00
# Преобразование JSON данных в объекты
shout.authors = [Author(**author) for author in authors_json] if authors_json else []
shout.topics = [Topic(**topic) for topic in topics_json] if topics_json else []
2024-08-07 08:35:59 +00:00
shout.stat = {
2024-08-07 10:15:58 +00:00
"viewed": ViewedStorage.get_shout(shout.id),
2024-08-07 08:35:59 +00:00
"rating": rating_stat or 0,
"commented": comments_stat or 0,
"last_reacted_at": last_reacted_at,
}
2024-08-08 15:56:49 +00:00
shout.main_topic = main_topic_slug # Присваиваем основной топик
2024-08-07 08:35:59 +00:00
shouts.append(shout)
return shouts
2024-03-25 17:28:58 +00:00
2024-08-08 13:10:45 +00:00
2024-03-25 17:28:58 +00:00
def filter_my(info, session, q):
2024-08-07 08:35:59 +00:00
"""
Фильтрация публикаций, основанная на подписках пользователя.
:param info: Информация о контексте GraphQL.
:param session: Сессия базы данных.
:param q: Исходный запрос для публикаций.
:return: Фильтрованный запрос.
"""
2024-04-19 15:22:07 +00:00
user_id = info.context.get("user_id")
reader_id = info.context.get("author", {}).get("id")
if user_id and reader_id:
2024-05-30 04:12:00 +00:00
reader_followed_authors = select(AuthorFollower.author).where(AuthorFollower.follower == reader_id)
reader_followed_topics = select(TopicFollower.topic).where(TopicFollower.follower == reader_id)
2024-08-07 08:35:59 +00:00
reader_followed_shouts = select(ShoutReactionsFollower.shout).where(
ShoutReactionsFollower.follower == reader_id
)
2024-04-19 15:22:07 +00:00
subquery = (
select(Shout.id)
2024-08-07 04:27:56 +00:00
.join(ShoutAuthor, ShoutAuthor.shout == Shout.id)
.join(ShoutTopic, ShoutTopic.shout == Shout.id)
2024-08-07 08:35:59 +00:00
.where(
ShoutAuthor.author.in_(reader_followed_authors)
| ShoutTopic.topic.in_(reader_followed_topics)
| Shout.id.in_(reader_followed_shouts)
)
2024-04-19 15:22:07 +00:00
)
q = q.filter(Shout.id.in_(subquery))
2024-03-25 17:28:58 +00:00
return q, reader_id
2024-08-08 13:10:45 +00:00
2024-01-25 19:41:27 +00:00
def apply_filters(q, filters, author_id=None):
2024-08-07 08:35:59 +00:00
"""
Применение фильтров к запросу.
:param q: Исходный запрос.
:param filters: Словарь фильтров.
:param author_id: Идентификатор автора (опционально).
:return: Запрос с примененными фильтрами.
"""
2024-03-25 17:41:28 +00:00
if isinstance(filters, dict):
2024-04-17 15:32:23 +00:00
if filters.get("reacted"):
2024-04-25 09:19:42 +00:00
q = q.join(
Reaction,
and_(
Reaction.shout == Shout.id,
Reaction.created_by == author_id,
),
)
2024-03-25 17:41:28 +00:00
2024-10-24 13:27:16 +00:00
if "featured" in filters:
featured_filter = filters.get("featured")
if featured_filter:
q = q.filter(Shout.featured_at.is_not(None))
else:
q = q.filter(Shout.featured_at.is_(None))
2024-05-01 02:08:54 +00:00
else:
pass
2024-04-17 15:32:23 +00:00
by_layouts = filters.get("layouts")
2024-05-01 02:02:35 +00:00
if by_layouts and isinstance(by_layouts, list):
2024-03-25 17:41:28 +00:00
q = q.filter(Shout.layout.in_(by_layouts))
2024-04-17 15:32:23 +00:00
by_author = filters.get("author")
2024-03-25 17:41:28 +00:00
if by_author:
q = q.filter(Shout.authors.any(slug=by_author))
2024-04-17 15:32:23 +00:00
by_topic = filters.get("topic")
2024-03-25 17:41:28 +00:00
if by_topic:
q = q.filter(Shout.topics.any(slug=by_topic))
2024-04-17 15:32:23 +00:00
by_after = filters.get("after")
2024-03-25 17:41:28 +00:00
if by_after:
ts = int(by_after)
q = q.filter(Shout.created_at > ts)
2022-11-21 08:13:57 +00:00
2022-11-25 18:31:53 +00:00
return q
2024-08-08 13:10:45 +00:00
2024-04-17 15:32:23 +00:00
@query.field("get_shout")
2024-10-23 21:01:09 +00:00
async def get_shout(_, _info, slug="", shout_id=0):
2024-08-07 08:35:59 +00:00
"""
Получение публикации по slug.
:param _: Корневой объект запроса (не используется).
:param info: Информация о контексте GraphQL.
:param slug: Уникальный идентификатор шута.
:return: Данные шута с включенной статистикой.
"""
2024-04-26 08:43:22 +00:00
try:
with local_session() as session:
2024-08-12 08:00:01 +00:00
# Отключение автосохранения
with session.no_autoflush:
2024-10-23 20:59:17 +00:00
q, _ = query_shouts(slug, shout_id)
2024-08-12 08:00:01 +00:00
results = session.execute(q).first()
if results:
[
shout,
commented_stat,
2024-10-14 06:23:11 +00:00
# followers_stat,
2024-08-12 08:00:01 +00:00
rating_stat,
last_reaction_at,
2024-10-31 09:49:18 +00:00
authors_json,
topics_json,
2024-08-12 08:00:01 +00:00
main_topic_slug,
] = results
shout.stat = {
"viewed": ViewedStorage.get_shout(shout.id),
"commented": commented_stat,
"rating": rating_stat,
"last_reacted_at": last_reaction_at,
}
# Преобразование строк в объекты Author без их создания
2024-10-31 09:49:18 +00:00
shout.authors = [Author(**author) for author in authors_json] if authors_json else []
2024-08-12 08:00:01 +00:00
# Преобразование строк в объекты Topic без их создания
2024-10-31 09:49:18 +00:00
shout.topics = [Topic(**topic) for topic in topics_json] if topics_json else []
2024-08-12 08:00:01 +00:00
# Добавляем основной топик, если он существует
shout.main_topic = main_topic_slug
return shout
2024-04-26 08:43:22 +00:00
except Exception as _exc:
import traceback
2024-08-08 14:36:20 +00:00
2024-04-26 08:43:22 +00:00
logger.error(traceback.format_exc())
2024-08-08 13:10:31 +00:00
return None
2022-11-23 21:53:53 +00:00
2024-08-08 13:10:45 +00:00
2024-04-17 15:32:23 +00:00
@query.field("load_shouts_by")
2023-12-02 22:14:36 +00:00
async def load_shouts_by(_, _info, options):
2022-11-15 02:36:30 +00:00
"""
2024-08-07 08:35:59 +00:00
Загрузка публикаций с фильтрацией, сортировкой и пагинацией.
2024-08-07 08:35:59 +00:00
:param options: Опции фильтрации и сортировки.
:return: Список публикаций, удовлетворяющих критериям.
2022-11-15 02:36:30 +00:00
"""
2024-08-07 08:35:59 +00:00
# Базовый запрос
2024-08-07 09:48:57 +00:00
q, aliased_reaction = query_shouts()
2023-12-02 06:25:08 +00:00
2024-08-07 08:35:59 +00:00
# Применение фильтров
2024-04-17 15:32:23 +00:00
filters = options.get("filters", {})
2024-02-02 12:03:44 +00:00
q = apply_filters(q, filters)
2022-11-25 18:31:53 +00:00
2024-08-07 08:35:59 +00:00
# Сортировка
2024-04-17 15:32:23 +00:00
order_by = Shout.featured_at if filters.get("featured") else Shout.published_at
order_str = options.get("order_by")
2024-08-07 07:22:37 +00:00
if order_str in ["rating", "followers", "comments", "last_reacted_at"]:
2024-04-17 15:32:23 +00:00
q = q.order_by(desc(text(f"{order_str}_stat")))
2024-08-07 08:35:59 +00:00
query_order_by = desc(order_by) if options.get("order_by_desc", True) else asc(order_by)
q = q.order_by(nulls_last(query_order_by))
else:
q = q.order_by(Shout.published_at.desc().nulls_last())
2023-12-02 06:25:08 +00:00
2024-08-07 08:35:59 +00:00
# Ограничение и смещение
2024-04-17 15:32:23 +00:00
offset = options.get("offset", 0)
limit = options.get("limit", 10)
2023-12-09 18:15:30 +00:00
2024-08-07 08:35:59 +00:00
return get_shouts_with_stats(q, limit, offset)
2023-02-06 14:27:23 +00:00
2024-03-05 13:59:55 +00:00
2024-04-17 15:32:23 +00:00
@query.field("load_shouts_feed")
2024-03-05 15:53:18 +00:00
@login_required
2023-11-28 07:53:48 +00:00
async def load_shouts_feed(_, info, options):
2024-08-07 08:35:59 +00:00
"""
Загрузка ленты публикаций для авторизованного пользователя.
2023-11-27 18:18:52 +00:00
2024-08-07 08:35:59 +00:00
:param info: Информация о контексте GraphQL.
:param options: Опции фильтрации и сортировки.
:return: Список публикаций для ленты.
"""
with local_session() as session:
2024-08-07 09:48:57 +00:00
q, aliased_reaction = query_shouts()
2023-11-27 18:18:52 +00:00
2024-08-07 08:35:59 +00:00
# Применение фильтров
2024-04-17 15:32:23 +00:00
filters = options.get("filters", {})
2024-03-25 17:28:58 +00:00
if filters:
q, reader_id = filter_my(info, session, q)
q = apply_filters(q, filters, reader_id)
2023-02-06 14:27:23 +00:00
2024-08-07 08:35:59 +00:00
# Сортировка
2024-06-06 08:06:18 +00:00
order_by = options.get("order_by")
order_by = text(order_by) if order_by else Shout.featured_at if filters.get("featured") else Shout.published_at
2024-05-30 04:12:00 +00:00
query_order_by = desc(order_by) if options.get("order_by_desc", True) else asc(order_by)
2024-08-07 08:52:07 +00:00
q = q.order_by(nulls_last(query_order_by))
2023-02-16 10:08:55 +00:00
2024-08-07 08:35:59 +00:00
# Пагинация
2024-04-17 15:32:23 +00:00
offset = options.get("offset", 0)
limit = options.get("limit", 10)
2023-02-16 10:08:55 +00:00
2024-08-07 08:35:59 +00:00
return get_shouts_with_stats(q, limit, offset)
2023-12-02 22:22:16 +00:00
2024-04-17 15:32:23 +00:00
@query.field("load_shouts_search")
2023-12-02 22:22:16 +00:00
async def load_shouts_search(_, _info, text, limit=50, offset=0):
2024-08-07 08:35:59 +00:00
"""
Поиск публикаций по тексту.
:param text: Строка поиска.
:param limit: Максимальное количество результатов.
:param offset: Смещение для пагинации.
:return: Список публикаций, найденных по тексту.
"""
2024-01-29 06:45:00 +00:00
if isinstance(text, str) and len(text) > 2:
2024-01-29 07:37:21 +00:00
results = await search_text(text, limit, offset)
2024-06-02 12:56:17 +00:00
scores = {}
hits_ids = []
2024-06-02 12:32:02 +00:00
for sr in results:
shout_id = sr.get("id")
if shout_id:
2024-06-02 14:36:34 +00:00
shout_id = str(shout_id)
2024-06-02 12:56:17 +00:00
scores[shout_id] = sr.get("score")
hits_ids.append(shout_id)
2024-06-02 16:19:30 +00:00
2024-08-07 09:48:57 +00:00
q, aliased_reaction = query_shouts()
q = q.filter(Shout.id.in_(hits_ids))
shouts = get_shouts_with_stats(q, limit, offset)
2024-08-07 08:35:59 +00:00
for shout in shouts:
shout.score = scores[f"{shout.id}"]
shouts.sort(key=lambda x: x.score, reverse=True)
2024-06-02 14:01:22 +00:00
return shouts
2024-01-28 21:28:04 +00:00
return []
2023-12-02 22:22:16 +00:00
2023-12-16 15:24:30 +00:00
2024-04-17 15:32:23 +00:00
@query.field("load_shouts_unrated")
2023-12-22 18:12:42 +00:00
async def load_shouts_unrated(_, info, limit: int = 50, offset: int = 0):
2024-08-07 08:35:59 +00:00
"""
Загрузка публикаций с наименьшим количеством оценок.
:param info: Информация о контексте GraphQL.
:param limit: Максимальное количество результатов.
:param offset: Смещение для пагинации.
:return: Список публикаций с минимальным количеством оценок.
"""
q, aliased_reaction = query_shouts()
2024-03-28 12:56:32 +00:00
q = (
q.outerjoin(
2024-07-18 09:13:30 +00:00
aliased_reaction,
2023-12-16 15:24:30 +00:00
and_(
2024-07-18 09:13:30 +00:00
aliased_reaction.shout == Shout.id,
aliased_reaction.reply_to.is_(None),
aliased_reaction.kind.in_([ReactionKind.LIKE.value, ReactionKind.DISLIKE.value]),
2023-12-16 15:24:30 +00:00
),
2024-03-28 12:56:32 +00:00
)
2024-07-18 09:07:53 +00:00
.filter(Shout.deleted_at.is_(None))
.filter(Shout.published_at.is_not(None))
2024-03-28 12:56:32 +00:00
)
2023-12-16 15:24:30 +00:00
2024-08-07 08:52:07 +00:00
q = q.having(func.count(distinct(aliased_reaction.id)) <= 4) # 3 или менее голосов
2024-08-07 08:35:59 +00:00
q = q.order_by(func.random())
2023-12-16 15:24:30 +00:00
2024-10-24 13:27:16 +00:00
return get_shouts_with_stats(q, limit, offset=offset)
2023-12-16 15:24:30 +00:00
2024-01-25 19:41:27 +00:00
2024-04-17 15:32:23 +00:00
@query.field("load_shouts_random_top")
2024-01-18 11:45:47 +00:00
async def load_shouts_random_top(_, _info, options):
2023-12-16 15:24:30 +00:00
"""
2024-08-07 08:35:59 +00:00
Загрузка случайных публикаций, упорядоченных по топовым реакциям.
:param _info: Информация о контексте GraphQL.
:param options: Опции фильтрации и сортировки.
:return: Список случайных публикаций.
2023-12-16 15:24:30 +00:00
"""
aliased_reaction = aliased(Reaction)
2024-02-21 07:27:16 +00:00
subquery = (
2024-05-30 04:12:00 +00:00
select(Shout.id).outerjoin(aliased_reaction).where(and_(Shout.deleted_at.is_(None), Shout.layout.is_not(None)))
2024-02-21 07:27:16 +00:00
)
2023-12-16 15:24:30 +00:00
2024-04-17 15:32:23 +00:00
subquery = apply_filters(subquery, options.get("filters", {}))
2024-03-25 12:03:03 +00:00
2024-01-25 19:41:27 +00:00
subquery = subquery.group_by(Shout.id).order_by(
desc(
2024-01-23 13:04:38 +00:00
func.sum(
case(
2024-08-07 08:35:59 +00:00
# не учитывать реакции на комментарии
2024-03-25 12:31:16 +00:00
(aliased_reaction.reply_to.is_not(None), 0),
2024-03-25 12:03:03 +00:00
(aliased_reaction.kind == ReactionKind.LIKE.value, 1),
(aliased_reaction.kind == ReactionKind.DISLIKE.value, -1),
2024-01-25 19:41:27 +00:00
else_=0,
2024-01-23 13:04:38 +00:00
)
)
2024-03-28 12:56:32 +00:00
)
2024-01-23 13:04:38 +00:00
)
2023-12-16 15:24:30 +00:00
2024-04-17 15:32:23 +00:00
random_limit = options.get("random_limit", 100)
2023-12-17 05:40:05 +00:00
if random_limit:
subquery = subquery.limit(random_limit)
2024-08-07 09:48:57 +00:00
q, aliased_reaction = query_shouts()
q = q.filter(Shout.id.in_(subquery))
2024-08-07 08:35:59 +00:00
q = q.order_by(func.random())
2024-04-17 15:32:23 +00:00
limit = options.get("limit", 10)
2024-08-07 08:35:59 +00:00
return get_shouts_with_stats(q, limit)
2023-12-22 18:08:37 +00:00
2023-12-23 19:00:22 +00:00
2024-04-17 15:32:23 +00:00
@query.field("load_shouts_random_topic")
2023-12-23 19:00:22 +00:00
async def load_shouts_random_topic(_, info, limit: int = 10):
2024-08-07 08:35:59 +00:00
"""
Загрузка случайной темы и связанных с ней публикаций.
:param info: Информация о контексте GraphQL.
:param limit: Максимальное количество публикаций.
:return: Тема и связанные публикации.
"""
2024-02-28 16:24:05 +00:00
[topic] = get_topics_random(None, None, 1)
if topic:
2024-08-07 09:48:57 +00:00
q, aliased_reaction = query_shouts()
q = q.filter(Shout.topics.any(slug=topic.slug))
2024-08-07 08:52:07 +00:00
q = q.order_by(desc(Shout.created_at))
2024-08-07 08:35:59 +00:00
shouts = get_shouts_with_stats(q, limit)
2024-02-28 16:24:05 +00:00
if shouts:
2024-04-17 15:32:23 +00:00
return {"topic": topic, "shouts": shouts}
2024-08-07 08:35:59 +00:00
return {"error": "failed to get random topic"}
2024-07-15 22:06:43 +00:00
@query.field("load_shouts_coauthored")
@login_required
async def load_shouts_coauthored(_, info, limit=50, offset=0):
2024-08-07 08:35:59 +00:00
"""
Загрузка публикаций, написанных в соавторстве с пользователем.
:param info: Информация о контексте GraphQL.
:param limit: Максимальное количество публикаций.
:param offset: Смещение для пагинации.
:return: Список публикаций в соавторстве.
"""
2024-07-15 22:06:43 +00:00
author_id = info.context.get("author", {}).get("id")
2024-07-18 09:07:53 +00:00
if not author_id:
return []
2024-08-08 13:10:31 +00:00
q, aliased_reaction = query_shouts()
2024-08-07 09:48:57 +00:00
q = q.filter(Shout.authors.any(id=author_id))
2024-08-07 08:35:59 +00:00
return get_shouts_with_stats(q, limit, offset=offset)
2024-07-15 22:06:43 +00:00
@query.field("load_shouts_discussed")
@login_required
async def load_shouts_discussed(_, info, limit=50, offset=0):
2024-08-07 08:35:59 +00:00
"""
Загрузка публикаций, которые обсуждались пользователем.
:param info: Информация о контексте GraphQL.
:param limit: Максимальное количество публикаций.
:param offset: Смещение для пагинации.
:return: Список публикаций, обсужденных пользователем.
"""
2024-07-15 22:06:43 +00:00
author_id = info.context.get("author", {}).get("id")
2024-07-18 09:07:53 +00:00
if not author_id:
return []
2024-08-08 13:10:31 +00:00
# Подзапрос для поиска идентификаторов публикаций, которые комментировал автор
2024-08-07 09:49:25 +00:00
reaction_subquery = (
select(Reaction.shout)
2024-08-08 13:10:31 +00:00
.distinct() # Убедитесь, что получены уникальные идентификаторы публикаций
2024-08-07 09:49:25 +00:00
.filter(and_(Reaction.created_by == author_id, Reaction.body.is_not(None)))
2024-08-08 13:10:31 +00:00
.correlate(Shout) # Убедитесь, что подзапрос правильно связан с основным запросом
2024-08-07 09:49:25 +00:00
)
2024-08-07 09:48:57 +00:00
q, aliased_reaction = query_shouts()
q = q.filter(Shout.id.in_(reaction_subquery))
return get_shouts_with_stats(q, limit, offset=offset)
2024-08-07 11:18:05 +00:00
2024-08-08 13:10:45 +00:00
2024-08-07 11:18:05 +00:00
async def reacted_shouts_updates(follower_id: int, limit=50, offset=0) -> List[Shout]:
"""
Обновляет публикации, на которые подписан автор, с учетом реакций.
:param follower_id: Идентификатор подписчика.
:param limit: Количество публикаций для загрузки.
:param offset: Смещение для пагинации.
:return: Список публикаций.
"""
shouts: List[Shout] = []
with local_session() as session:
author = session.query(Author).filter(Author.id == follower_id).first()
if author:
2024-10-31 11:11:59 +00:00
# Публикации, где подписчик <20><>вляется автором
2024-08-07 11:18:05 +00:00
q1, aliased_reaction1 = query_shouts()
q1 = q1.filter(Shout.authors.any(id=follower_id))
# Публикации, на которые подписчик реагировал
q2, aliased_reaction2 = query_shouts()
q2 = q2.options(joinedload(Shout.reactions))
q2 = q2.filter(Reaction.created_by == follower_id)
# Сортировка публикаций по полю `last_reacted_at`
combined_query = union(q1, q2).order_by(desc(text("last_reacted_at")))
# извлечение ожидаемой структуры данных
shouts = get_shouts_with_stats(combined_query, limit, offset=offset)
return shouts
2024-08-08 13:10:45 +00:00
2024-08-07 11:18:05 +00:00
@query.field("load_shouts_followed")
@login_required
async def load_shouts_followed(_, info, limit=50, offset=0) -> List[Shout]:
"""
Загружает публикации, на которые подписан пользователь.
:param info: Информация о контексте GraphQL.
:param limit: Количество публикаций для загрузки.
:param offset: Смещение для пагинации.
:return: Список публикаций.
"""
user_id = info.context["user_id"]
with local_session() as session:
author = session.query(Author).filter(Author.user == user_id).first()
if author:
try:
author_id: int = author.dict()["id"]
shouts = await reacted_shouts_updates(author_id, limit, offset)
return shouts
except Exception as error:
logger.debug(error)
return []
2024-08-08 13:10:45 +00:00
2024-08-07 11:18:05 +00:00
@query.field("load_shouts_followed_by")
async def load_shouts_followed_by(_, info, slug: str, limit=50, offset=0) -> List[Shout]:
"""
Загружает публикации, на которые подписан автор по slug.
:param info: Информация о контексте GraphQL.
:param slug: Slug автора.
:param limit: Количество публикаций для загрузки.
:param offset: Смещение для пагинации.
:return: Список публикаций.
"""
with local_session() as session:
author = session.query(Author).filter(Author.slug == slug).first()
if author:
try:
author_id: int = author.dict()["id"]
shouts = await reacted_shouts_updates(author_id, limit, offset)
return shouts
except Exception as error:
logger.debug(error)
return []