core/resolvers/reader.py

583 lines
22 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-31 15:28:09 +00:00
def query_shouts():
2024-08-07 08:35:59 +00:00
"""
2024-10-31 16:48:06 +00:00
Оптимизированный базовый запрос
2024-08-07 08:35:59 +00:00
"""
2024-10-31 16:48:06 +00:00
# Оптимизированный подзапрос статистики
stats_subquery = (
2024-10-31 16:06:58 +00:00
select(
2024-10-31 16:48:06 +00:00
Reaction.shout.label('shout_id'),
func.count(
case((Reaction.kind == ReactionKind.COMMENT.value, 1), else_=None)
).label('comments_count'),
2024-10-31 16:06:58 +00:00
func.sum(
case(
(Reaction.kind == ReactionKind.LIKE.value, 1),
(Reaction.kind == ReactionKind.DISLIKE.value, -1),
2024-10-31 16:48:06 +00:00
else_=0
2024-10-31 16:06:58 +00:00
)
2024-10-31 16:48:06 +00:00
).label('rating'),
func.max(
case((Reaction.reply_to.is_(None), Reaction.created_at), else_=None)
).label('last_reacted_at')
2024-10-31 16:06:58 +00:00
)
2024-10-31 16:48:06 +00:00
.where(Reaction.deleted_at.is_(None))
.group_by(Reaction.shout)
.subquery()
2024-10-31 16:11:41 +00:00
)
2024-08-07 09:38:15 +00:00
q = (
2024-10-31 16:48:06 +00:00
select(Shout, stats_subquery)
.outerjoin(stats_subquery, stats_subquery.c.shout_id == Shout.id)
.where(and_(
Shout.published_at.is_not(None),
Shout.deleted_at.is_(None)
))
2024-08-07 08:52:07 +00:00
)
2024-10-31 15:28:09 +00:00
return q
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-10-31 16:48:06 +00:00
Оптимизированное получение данных
2024-08-07 08:35:59 +00:00
"""
2024-10-31 16:06:58 +00:00
if author_id:
q = q.filter(Shout.created_by == author_id)
2024-10-31 11:09:33 +00:00
2024-10-31 16:06:58 +00:00
if limit:
q = q.limit(limit)
if offset:
q = q.offset(offset)
2024-10-31 10:39:38 +00:00
2024-10-31 11:14:54 +00:00
with local_session() as session:
2024-10-31 16:48:06 +00:00
# 1. Получаем шауты одним запросом
shouts_result = session.execute(q).all()
2024-10-31 16:57:09 +00:00
if not shouts_result:
2024-10-31 16:48:06 +00:00
return []
# 2. Получаем авторов и топики пакетным запросом
2024-10-31 16:57:09 +00:00
shout_ids = [row.Shout.id for row in shouts_result]
2024-10-31 16:48:06 +00:00
authors_and_topics = session.execute(
select(
ShoutAuthor.shout.label('shout_id'),
Author.id.label('author_id'),
Author.name.label('author_name'),
Author.slug.label('author_slug'),
Author.pic.label('author_pic'),
ShoutAuthor.caption.label('author_caption'),
Topic.id.label('topic_id'),
Topic.title.label('topic_title'),
Topic.slug.label('topic_slug'),
ShoutTopic.is_main.label('topic_is_main')
)
.outerjoin(Author, ShoutAuthor.author == Author.id)
.outerjoin(ShoutTopic, ShoutTopic.shout == ShoutAuthor.shout)
.outerjoin(Topic, ShoutTopic.topic == Topic.id)
.where(ShoutAuthor.shout.in_(shout_ids))
).all()
# 3. Группируем данные эффективно
shouts_data = {}
for row in shouts_result:
2024-10-31 16:57:09 +00:00
shout = row.shout
2024-10-31 16:48:06 +00:00
shout_id = shout['id']
2024-10-31 16:57:09 +00:00
viewed_stat = ViewedStorage.get_shout(shout_id=shout_id) or 0
2024-10-31 16:48:06 +00:00
shouts_data[shout_id] = {
**shout,
'stat': {
2024-10-31 16:57:09 +00:00
'viewed': viewed_stat,
2024-10-31 16:48:06 +00:00
'commented': row.comments_count or 0,
'rating': row.rating or 0,
'last_reacted_at': row.last_reacted_at
},
'authors': [],
'topics': set() # используем set для уникальности
}
# 4. Заполняем связанные данные
for row in authors_and_topics:
shout_data = shouts_data[row.shout_id]
# Добавляем автора
author = {
'id': row.author_id,
'name': row.author_name,
'slug': row.author_slug,
'pic': row.author_pic,
'caption': row.author_caption
}
if author not in shout_data['authors']:
shout_data['authors'].append(author)
# Добавляем топик если есть
if row.topic_id:
topic = {
'id': row.topic_id,
'title': row.topic_title,
'slug': row.topic_slug,
'is_main': row.topic_is_main
2024-10-31 16:06:58 +00:00
}
2024-10-31 16:48:06 +00:00
shout_data['topics'].add(tuple(topic.items()))
# 5. Финальная обработка и сортировка
result = []
for shout_data in shouts_data.values():
# Конвертируем topics обратно в список словарей и сортируем
shout_data['topics'] = sorted(
[dict(t) for t in shout_data['topics']],
key=lambda x: (not x['is_main'], x['id'])
2024-10-31 16:06:58 +00:00
)
2024-10-31 16:48:06 +00:00
result.append(shout_data)
2024-10-31 16:06:58 +00:00
2024-10-31 16:48:06 +00:00
return result
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
"""
2024-10-31 16:06:58 +00:00
Получение публикации по slug или id.
2024-08-07 08:35:59 +00:00
2024-10-31 16:06:58 +00:00
:param _: Корневой объект запроса (не используется)
:param _info: Информация о контексте GraphQL
:param slug: Уникальный идентификатор публикации
:param shout_id: ID публикации
:return: Данные публикации с включенной статистикой
2024-08-07 08:35:59 +00:00
"""
2024-04-26 08:43:22 +00:00
try:
2024-10-31 16:06:58 +00:00
# Получаем базовый запрос с подзапросами статистики
q = query_shouts()
# Применяем фильтр по slug или id
if slug:
q = q.where(Shout.slug == slug)
elif shout_id:
q = q.where(Shout.id == shout_id)
else:
return None
2024-08-12 08:00:01 +00:00
2024-10-31 16:06:58 +00:00
# Получаем результат через get_shouts_with_stats с limit=1
shouts = get_shouts_with_stats(q, limit=1)
2024-08-12 08:00:01 +00:00
2024-10-31 16:06:58 +00:00
# Возвращаем первую (и единственную) публикацию, если она найдена
return shouts[0] if shouts else None
2024-08-08 14:36:20 +00:00
2024-10-31 16:06:58 +00:00
except Exception as exc:
logger.error(f"Error in get_shout: {exc}", exc_info=True)
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-10-31 15:28:09 +00:00
q = 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:
2024-10-31 16:57:09 +00:00
q = q.order_by(Shout.published_at.desc())
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-10-31 15:28:09 +00:00
q = 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-10-31 15:28:09 +00:00
q = query_shouts()
2024-08-07 09:48:57 +00:00
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")
2024-10-31 16:57:09 +00:00
async def load_shouts_unrated(_, info, limit=50, offset=0):
2024-08-07 08:35:59 +00:00
"""
2024-10-31 16:57:09 +00:00
Загрузка публикаций с менее чем 3 реакциями типа LIKE/DISLIKE
2024-08-07 08:35:59 +00:00
"""
2024-10-31 16:57:09 +00:00
rated_shouts = (
select(Reaction.shout)
2024-10-31 14:47:07 +00:00
.where(
2023-12-16 15:24:30 +00:00
and_(
2024-10-31 16:57:09 +00:00
Reaction.deleted_at.is_(None),
Reaction.kind.in_([ReactionKind.LIKE.value, ReactionKind.DISLIKE.value])
2024-10-31 14:47:07 +00:00
)
2024-03-28 12:56:32 +00:00
)
2024-10-31 16:57:09 +00:00
.group_by(Reaction.shout)
.having(func.count('*') >= 3)
2024-10-31 14:47:07 +00:00
.scalar_subquery()
2024-03-28 12:56:32 +00:00
)
2023-12-16 15:24:30 +00:00
2024-10-31 16:57:09 +00:00
q = (
select(Shout)
.where(
and_(
Shout.published_at.is_not(None),
Shout.deleted_at.is_(None),
~Shout.id.in_(rated_shouts)
)
)
.order_by(desc(Shout.published_at))
)
2023-12-16 15:24:30 +00:00
2024-10-31 16:57:09 +00:00
return get_shouts_with_stats(q, limit, 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-10-31 15:28:09 +00:00
q = query_shouts()
2024-08-07 09:48:57 +00:00
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-10-31 15:28:09 +00:00
q = query_shouts()
2024-08-07 09:48:57 +00:00
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
"""
Загрузка публикаций, написанных в соавторстве с пользователем.
2024-10-31 16:48:06 +00:00
:param info: Информаци о контексте GraphQL.
2024-08-07 08:35:59 +00:00
:param limit: Максимальное количество публикаций.
:param offset: Смещение для пагинации.
2024-10-31 16:48:06 +00:00
:return: Список публикаций в соавтостве.
2024-08-07 08:35:59 +00:00
"""
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-10-31 15:28:09 +00:00
q = 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: Максимальное количество публикаций.
2024-10-31 16:48:06 +00:00
:param offset: Смещне для пагинации.
2024-08-07 08:35:59 +00:00
: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-10-31 15:28:09 +00:00
q = query_shouts()
2024-08-07 09:48:57 +00:00
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]:
"""
2024-10-31 16:48:06 +00:00
Обновляет публикации, на которые подписан автор, с учетом реакци.
2024-08-07 11:18:05 +00:00
: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:20:22 +00:00
# Публикации, где подписчик является автором
2024-10-31 15:28:09 +00:00
q1 = query_shouts()
2024-08-07 11:18:05 +00:00
q1 = q1.filter(Shout.authors.any(id=follower_id))
# Публикации, на которые подписчик реагировал
2024-10-31 15:28:09 +00:00
q2 = query_shouts()
2024-08-07 11:18:05 +00:00
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 []