reworked-feed+reader
All checks were successful
Deploy on push / deploy (push) Successful in 1m16s

This commit is contained in:
2024-11-01 13:50:47 +03:00
parent a01a3f1d7a
commit d88f905609
3 changed files with 177 additions and 249 deletions

View File

@@ -1,7 +1,6 @@
from typing import List
from sqlalchemy import and_, desc, select, text, union
from sqlalchemy.orm import joinedload
from sqlalchemy import and_, select
from orm.author import Author, AuthorFollower
from orm.reaction import Reaction
@@ -14,62 +13,36 @@ from services.schema import query
from utils.logger import root_logger as logger
def apply_options(q, options, author_id: int):
def apply_options(q, options, reactions_created_by=0):
"""
Применяет опции фильтрации и сортировки к запросу для данного автора.
Применяет опции фильтрации и сортировки
[опционально] выбирая те публикации, на которые есть реакции от указанного автора
:param q: Исходный запрос.
:param options: Опции фильтрации и сортировки.
:param author_id: Идентификатор автора.
:param reactions_created_by: Идентификатор автора.
:return: Запрос с примененными опциями.
"""
filters = options.get("filters")
if isinstance(filters, dict):
q = apply_filters(q, filters)
if author_id and "reacted" in filters:
reacted = filters.get("reacted")
q = q.join(Reaction, Reaction.shout == Shout.id)
if reacted:
q = q.filter(Reaction.created_by == author_id)
else:
q = q.filter(Reaction.created_by != author_id)
if reactions_created_by:
if "reacted" in filters or "commented" in filters:
commented = filters.get("commented")
reacted = filters.get("reacted") or commented
q = q.join(Reaction, Reaction.shout == Shout.id)
if commented:
q = q.filter(Reaction.body.is_not(None))
if reacted:
q = q.filter(Reaction.created_by == reactions_created_by)
else:
q = q.filter(Reaction.created_by != reactions_created_by)
q = apply_sorting(q, options)
limit = options.get("limit", 10)
offset = options.get("offset", 0)
return q, limit, offset
def filter_followed(info, q):
"""
Фильтрация публикаций, основанная на подписках пользователя.
:param info: Информация о контексте GraphQL.
:param q: Исходный запрос для публикаций.
:return: Фильтрованный запрос.
"""
user_id = info.context.get("user_id")
reader_id = info.context.get("author", {}).get("id")
if user_id and reader_id:
reader_followed_authors = select(AuthorFollower.author).where(AuthorFollower.follower == reader_id)
reader_followed_topics = select(TopicFollower.topic).where(TopicFollower.follower == reader_id)
reader_followed_shouts = select(ShoutReactionsFollower.shout).where(
ShoutReactionsFollower.follower == reader_id
)
subquery = (
select(Shout.id)
.join(ShoutAuthor, ShoutAuthor.shout == Shout.id)
.join(ShoutTopic, ShoutTopic.shout == Shout.id)
.where(
ShoutAuthor.author.in_(reader_followed_authors)
| ShoutTopic.topic.in_(reader_followed_topics)
| Shout.id.in_(reader_followed_shouts)
)
)
q = q.filter(Shout.id.in_(subquery))
return q, reader_id
@query.field("load_shouts_coauthored")
@login_required
async def load_shouts_coauthored(_, info, options):
@@ -83,27 +56,9 @@ async def load_shouts_coauthored(_, info, options):
author_id = info.context.get("author", {}).get("id")
if not author_id:
return []
q = (
query_with_stat()
if has_field(info, "stat")
else select(Shout).filter(and_(Shout.published_at.is_not(None), Shout.deleted_at.is_(None)))
)
q = query_with_stat(info)
q = q.filter(Shout.authors.any(id=author_id))
filters = options.get("filters")
if isinstance(filters, dict):
q = apply_filters(q, filters)
if filters.get("reacted"):
q = q.join(
Reaction,
and_(
Reaction.shout == Shout.id,
Reaction.created_by == author_id,
),
)
q = apply_sorting(q, options)
limit = options.get("limit", 10)
offset = options.get("offset", 0)
q, limit, offset = apply_options(q, options)
return get_shouts_with_links(info, q, limit, offset=offset)
@@ -120,19 +75,8 @@ async def load_shouts_discussed(_, info, options):
author_id = info.context.get("author", {}).get("id")
if not author_id:
return []
# Подзапрос для поиска идентификаторов публикаций, которые комментировал автор
reaction_subquery = (
select(Reaction.shout)
.distinct() # Убедитесь, что получены уникальные идентификаторы публикаций
.filter(and_(Reaction.created_by == author_id, Reaction.body.is_not(None)))
.correlate(Shout) # Убедитесь, что подзапрос правильно связан с основным запросом
)
q = (
query_with_stat()
if has_field(info, "stat")
else select(Shout).filter(and_(Shout.published_at.is_not(None), Shout.deleted_at.is_(None)))
)
q = q.filter(Shout.id.in_(reaction_subquery))
q = query_with_stat(info)
options["filters"]["commented"] = True
q, limit, offset = apply_options(q, options, author_id)
return get_shouts_with_links(info, q, limit, offset=offset)
@@ -141,33 +85,32 @@ def shouts_by_follower(info, follower_id: int, options):
"""
Загружает публикации, на которые подписан автор.
- по авторам
- по темам
- по реакциям
:param info: Информация о контексте GraphQL.
:param follower_id: Идентификатор автора.
:param options: Опции фильтрации и сортировки.
:return: Список публикаций.
"""
# Публикации, где подписчик является автором
q1 = (
query_with_stat()
if has_field(info, "stat")
else select(Shout).filter(and_(Shout.published_at.is_not(None), Shout.deleted_at.is_(None)))
q = query_with_stat(info)
reader_followed_authors = select(AuthorFollower.author).where(AuthorFollower.follower == follower_id)
reader_followed_topics = select(TopicFollower.topic).where(TopicFollower.follower == follower_id)
reader_followed_shouts = select(ShoutReactionsFollower.shout).where(ShoutReactionsFollower.follower == follower_id)
followed_subquery = (
select(Shout.id)
.join(ShoutAuthor, ShoutAuthor.shout == Shout.id)
.join(ShoutTopic, ShoutTopic.shout == Shout.id)
.where(
ShoutAuthor.author.in_(reader_followed_authors)
| ShoutTopic.topic.in_(reader_followed_topics)
| Shout.id.in_(reader_followed_shouts)
)
)
q1 = q1.filter(Shout.authors.any(id=follower_id))
# Публикации, на которые подписчик реагировал
q2 = (
query_with_stat()
if has_field(info, "stat")
else select(Shout).filter(and_(Shout.published_at.is_not(None), Shout.deleted_at.is_(None)))
)
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")))
# извлечение ожидаемой структуры данных
q, limit, offset = apply_options(combined_query, options, follower_id)
q = q.filter(Shout.id.in_(followed_subquery))
q, limit, offset = apply_options(q, options)
shouts = get_shouts_with_links(info, q, limit, offset=offset)
return shouts
@@ -216,7 +159,7 @@ async def load_shouts_authored_by(_, info, slug: str, options) -> List[Shout]:
try:
author_id: int = author.dict()["id"]
q = (
query_with_stat()
query_with_stat(info)
if has_field(info, "stat")
else select(Shout).filter(and_(Shout.published_at.is_not(None), Shout.deleted_at.is_(None)))
)
@@ -240,7 +183,7 @@ async def load_shouts_with_topic(_, info, slug: str, options) -> List[Shout]:
try:
topic_id: int = topic.dict()["id"]
q = (
query_with_stat()
query_with_stat(info)
if has_field(info, "stat")
else select(Shout).filter(and_(Shout.published_at.is_not(None), Shout.deleted_at.is_(None)))
)