Files
core/resolvers/follower.py

302 lines
13 KiB
Python
Raw Normal View History

from __future__ import annotations
2023-11-28 10:53:48 +03:00
2025-07-31 18:55:59 +03:00
from typing import Any
from graphql import GraphQLResolveInfo
2024-02-02 15:03:44 +03:00
from sqlalchemy.sql import and_
2024-01-31 17:48:36 +03:00
2025-05-29 12:37:39 +03:00
from auth.orm import Author, AuthorFollower
2024-06-05 17:45:55 +03:00
from orm.community import Community, CommunityFollower
2024-02-23 19:35:40 +03:00
from orm.shout import Shout, ShoutReactionsFollower
2023-11-28 10:53:48 +03:00
from orm.topic import Topic, TopicFollower
2023-12-17 23:30:20 +03:00
from services.auth import login_required
2023-10-23 17:47:11 +03:00
from services.db import local_session
2024-04-08 10:38:58 +03:00
from services.notify import notify_follower
2025-05-31 17:18:31 +03:00
from services.redis import redis
2024-04-08 10:38:58 +03:00
from services.schema import mutation, query
2024-11-02 11:35:02 +03:00
from utils.logger import root_logger as logger
2024-01-13 11:49:12 +03:00
2024-01-23 02:28:54 +03:00
2024-04-17 18:32:23 +03:00
@mutation.field("follow")
2024-01-23 02:28:54 +03:00
@login_required
2025-07-31 18:55:59 +03:00
async def follow(
_: None, info: GraphQLResolveInfo, what: str, slug: str = "", entity_id: int | None = None
) -> dict[str, Any]:
2024-11-02 11:35:02 +03:00
logger.debug("Начало выполнения функции 'follow'")
2025-05-22 04:34:30 +03:00
viewer_id = info.context.get("author", {}).get("id")
2025-07-31 18:55:59 +03:00
if not viewer_id:
return {"error": "Access denied"}
2025-05-29 17:09:32 +03:00
follower_dict = info.context.get("author") or {}
2024-11-02 11:49:30 +03:00
logger.debug(f"follower: {follower_dict}")
2024-11-02 11:35:02 +03:00
2025-05-22 04:34:30 +03:00
if not viewer_id or not follower_dict:
2025-07-31 18:55:59 +03:00
logger.warning("Неавторизованный доступ при попытке подписаться")
return {"error": "UnauthorizedError"}
2024-11-02 11:35:02 +03:00
2024-05-20 16:23:49 +03:00
follower_id = follower_dict.get("id")
2024-11-02 11:35:02 +03:00
logger.debug(f"follower_id: {follower_id}")
2024-04-18 12:34:04 +03:00
2025-07-31 18:55:59 +03:00
# Поздние импорты для избежания циклических зависимостей
from cache.cache import (
cache_author,
cache_topic,
get_cached_follower_authors,
get_cached_follower_topics,
)
2024-06-05 17:45:55 +03:00
entity_classes = {
"AUTHOR": (Author, AuthorFollower, get_cached_follower_authors, cache_author),
"TOPIC": (Topic, TopicFollower, get_cached_follower_topics, cache_topic),
2024-11-02 11:35:02 +03:00
"COMMUNITY": (Community, CommunityFollower, None, None), # Нет методов кэша для сообщества
"SHOUT": (Shout, ShoutReactionsFollower, None, None), # Нет методов кэша для shout
2024-06-05 17:45:55 +03:00
}
2024-03-11 16:12:28 +03:00
2024-06-05 17:45:55 +03:00
if what not in entity_classes:
2024-11-02 11:35:02 +03:00
logger.error(f"Неверный тип для следования: {what}")
2024-06-05 17:45:55 +03:00
return {"error": "invalid follow type"}
2024-03-11 16:12:28 +03:00
2024-06-05 17:45:55 +03:00
entity_class, follower_class, get_cached_follows_method, cache_method = entity_classes[what]
entity_type = what.lower()
2025-07-31 18:55:59 +03:00
follows: list[dict[str, Any]] = []
error: str | None = None
2024-06-05 17:45:55 +03:00
try:
2024-11-02 11:35:02 +03:00
logger.debug("Попытка получить сущность из базы данных")
2024-05-26 02:17:45 +03:00
with local_session() as session:
2025-07-31 18:55:59 +03:00
# Используем query для получения сущности
entity_query = session.query(entity_class)
# Проверяем наличие slug перед фильтрацией
if hasattr(entity_class, "slug"):
entity_query = entity_query.where(entity_class.slug == slug)
entity = entity_query.first()
2024-06-05 17:45:55 +03:00
if not entity:
2024-11-02 11:35:02 +03:00
logger.warning(f"{what.lower()} не найден по slug: {slug}")
2024-06-05 17:45:55 +03:00
return {"error": f"{what.lower()} not found"}
2025-07-31 18:55:59 +03:00
# Получаем ID сущности
if entity_id is None:
entity_id = getattr(entity, "id", None)
if not entity_id:
logger.warning(f"Не удалось получить ID для {what.lower()}")
return {"error": f"Cannot get ID for {what.lower()}"}
2025-05-29 12:37:39 +03:00
2025-05-21 01:34:02 +03:00
# Если это автор, учитываем фильтрацию данных
2025-07-31 18:55:59 +03:00
entity_dict = entity.dict() if hasattr(entity, "dict") else {}
2025-05-29 12:37:39 +03:00
2024-11-02 11:35:02 +03:00
logger.debug(f"entity_id: {entity_id}, entity_dict: {entity_dict}")
2024-06-05 17:45:55 +03:00
2025-07-31 18:55:59 +03:00
if entity_id is not None and isinstance(entity_id, int):
2024-11-02 12:33:52 +03:00
existing_sub = (
session.query(follower_class)
2025-07-31 18:55:59 +03:00
.where(
follower_class.follower == follower_id, # type: ignore[attr-defined]
getattr(follower_class, entity_type) == entity_id, # type: ignore[attr-defined]
2025-05-16 09:23:48 +03:00
)
2024-11-02 12:33:52 +03:00
.first()
)
2024-11-02 12:33:35 +03:00
if existing_sub:
2025-05-29 12:37:39 +03:00
logger.info(f"Пользователь {follower_id} уже подписан на {what.lower()} с ID {entity_id}")
2025-05-31 17:21:14 +03:00
error = "already following"
2024-11-02 12:33:35 +03:00
else:
logger.debug("Добавление новой записи в базу данных")
sub = follower_class(follower=follower_id, **{entity_type: entity_id})
logger.debug(f"Создан объект подписки: {sub}")
session.add(sub)
session.commit()
logger.info(f"Пользователь {follower_id} подписался на {what.lower()} с ID {entity_id}")
2024-06-05 17:45:55 +03:00
2025-05-31 17:21:14 +03:00
# Инвалидируем кэш подписок пользователя после любой операции
cache_key_pattern = f"author:follows-{entity_type}s:{follower_id}"
await redis.execute("DEL", cache_key_pattern)
logger.debug(f"Инвалидирован кэш подписок: {cache_key_pattern}")
if cache_method:
logger.debug("Обновление кэша сущности")
await cache_method(entity_dict)
if what == "AUTHOR" and not existing_sub:
logger.debug("Отправка уведомления автору о подписке")
if isinstance(follower_dict, dict) and isinstance(entity_id, int):
await notify_follower(follower=follower_dict, author_id=entity_id, action="follow")
2025-05-29 12:37:39 +03:00
2025-05-31 17:21:14 +03:00
# Всегда получаем актуальный список подписок для возврата клиенту
if get_cached_follows_method and isinstance(follower_id, int):
2025-05-31 17:21:14 +03:00
logger.debug("Получение актуального списка подписок из кэша")
existing_follows = await get_cached_follows_method(follower_id)
# Если это авторы, получаем безопасную версию
if what == "AUTHOR":
follows_filtered = []
for author_data in existing_follows:
# Создаем объект автора для использования метода dict
temp_author = Author()
for key, value in author_data.items():
if hasattr(temp_author, key):
setattr(temp_author, key, value)
# Добавляем отфильтрованную версию
2025-07-31 18:55:59 +03:00
follows_filtered.append(temp_author.dict())
2025-05-31 17:21:14 +03:00
follows = follows_filtered
else:
follows = existing_follows
2024-06-05 17:45:55 +03:00
2025-05-31 17:21:14 +03:00
logger.debug(f"Актуальный список подписок получен: {len(follows)} элементов")
2024-03-11 16:12:28 +03:00
2025-07-31 18:55:59 +03:00
return {f"{entity_type}s": follows, "error": error}
2024-06-05 17:45:55 +03:00
except Exception as exc:
2024-11-02 11:35:02 +03:00
logger.exception("Произошла ошибка в функции 'follow'")
2024-06-05 17:45:55 +03:00
return {"error": str(exc)}
2024-03-11 16:12:28 +03:00
2023-10-23 17:47:11 +03:00
2024-04-17 18:32:23 +03:00
@mutation.field("unfollow")
2024-01-23 02:28:54 +03:00
@login_required
2025-07-31 18:55:59 +03:00
async def unfollow(
_: None, info: GraphQLResolveInfo, what: str, slug: str = "", entity_id: int | None = None
) -> dict[str, Any]:
2024-11-02 11:35:02 +03:00
logger.debug("Начало выполнения функции 'unfollow'")
2025-05-22 04:34:30 +03:00
viewer_id = info.context.get("author", {}).get("id")
if not viewer_id:
return {"error": "Access denied"}
2025-05-29 17:09:32 +03:00
follower_dict = info.context.get("author") or {}
2024-11-02 11:49:30 +03:00
logger.debug(f"follower: {follower_dict}")
2024-11-02 11:35:02 +03:00
2025-05-22 04:34:30 +03:00
if not viewer_id or not follower_dict:
2024-11-02 11:35:02 +03:00
logger.warning("Неавторизованный доступ при попытке отписаться")
2025-07-31 18:55:59 +03:00
return {"error": "UnauthorizedError"}
2024-11-02 11:35:02 +03:00
2024-05-20 16:23:49 +03:00
follower_id = follower_dict.get("id")
2024-11-02 11:35:02 +03:00
logger.debug(f"follower_id: {follower_id}")
2024-04-18 12:34:04 +03:00
2025-07-31 18:55:59 +03:00
# Поздние импорты для избежания циклических зависимостей
from cache.cache import (
cache_author,
cache_topic,
get_cached_follower_authors,
get_cached_follower_topics,
)
2024-06-05 17:45:55 +03:00
entity_classes = {
"AUTHOR": (Author, AuthorFollower, get_cached_follower_authors, cache_author),
"TOPIC": (Topic, TopicFollower, get_cached_follower_topics, cache_topic),
2024-11-02 11:35:02 +03:00
"COMMUNITY": (Community, CommunityFollower, None, None), # Нет методов кэша для сообщества
2024-11-02 12:09:24 +03:00
"SHOUT": (Shout, ShoutReactionsFollower, None, None), # Нет методов кэша для shout
2024-05-21 01:40:57 +03:00
}
2024-02-02 15:03:44 +03:00
2024-06-05 17:45:55 +03:00
if what not in entity_classes:
2024-11-02 11:35:02 +03:00
logger.error(f"Неверный тип для отписки: {what}")
2024-06-05 17:45:55 +03:00
return {"error": "invalid unfollow type"}
2024-02-02 15:03:44 +03:00
2024-06-05 17:45:55 +03:00
entity_class, follower_class, get_cached_follows_method, cache_method = entity_classes[what]
entity_type = what.lower()
2025-07-31 18:55:59 +03:00
follows: list[dict[str, Any]] = []
2024-03-12 10:35:33 +03:00
2024-02-02 15:03:44 +03:00
try:
2024-11-02 11:35:02 +03:00
logger.debug("Попытка получить сущность из базы данных")
2024-02-02 15:03:44 +03:00
with local_session() as session:
2025-07-31 18:55:59 +03:00
# Используем query для получения сущности
entity_query = session.query(entity_class)
if hasattr(entity_class, "slug"):
entity_query = entity_query.where(entity_class.slug == slug)
entity = entity_query.first()
2024-11-02 11:35:02 +03:00
logger.debug(f"Полученная сущность: {entity}")
2024-06-05 17:45:55 +03:00
if not entity:
2024-11-02 11:35:02 +03:00
logger.warning(f"{what.lower()} не найден по slug: {slug}")
2024-06-05 17:45:55 +03:00
return {"error": f"{what.lower()} not found"}
2024-02-02 15:03:44 +03:00
2025-07-31 18:55:59 +03:00
if not entity_id:
entity_id = getattr(entity, "id", None)
if not entity_id:
logger.warning(f"Не удалось получить ID для {what.lower()}")
return {"error": f"Cannot get ID for {what.lower()}"}
logger.debug(f"entity_id: {entity_id}")
2024-06-05 17:45:55 +03:00
sub = (
session.query(follower_class)
2025-07-31 18:55:59 +03:00
.where(
2024-02-02 15:03:44 +03:00
and_(
follower_class.follower == follower_id, # type: ignore[attr-defined]
getattr(follower_class, entity_type) == entity_id, # type: ignore[attr-defined]
2024-02-02 15:03:44 +03:00
)
)
.first()
)
2025-07-31 18:55:59 +03:00
if not sub:
logger.warning(f"Подписка не найдена для {what.lower()} с ID {entity_id}")
return {"error": "Not following"}
2025-05-31 17:18:31 +03:00
2025-07-31 18:55:59 +03:00
logger.debug(f"Найдена подписка для удаления: {sub}")
session.delete(sub)
session.commit()
logger.info(f"Пользователь {follower_id} отписался от {what.lower()} с ID {entity_id}")
# Инвалидируем кэш подписок пользователя
cache_key_pattern = f"author:follows-{entity_type}s:{follower_id}"
await redis.execute("DEL", cache_key_pattern)
logger.debug(f"Инвалидирован кэш подписок: {cache_key_pattern}")
if get_cached_follows_method and isinstance(follower_id, int):
logger.debug("Получение актуального списка подписок из кэша")
follows = await get_cached_follows_method(follower_id)
logger.debug(f"Актуальный список подписок получен: {len(follows)} элементов")
2024-11-22 20:19:56 +03:00
else:
2025-07-31 18:55:59 +03:00
follows = []
2025-05-31 17:18:31 +03:00
2025-07-31 18:55:59 +03:00
if what == "AUTHOR" and isinstance(follower_dict, dict):
await notify_follower(follower=follower_dict, author_id=entity_id, action="unfollow")
2025-05-31 17:18:31 +03:00
2025-07-31 18:55:59 +03:00
return {f"{entity_type}s": follows, "error": None}
2024-02-02 15:03:44 +03:00
2024-06-05 17:45:55 +03:00
except Exception as exc:
2024-11-02 11:35:02 +03:00
logger.exception("Произошла ошибка в функции 'unfollow'")
2024-06-05 17:45:55 +03:00
return {"error": str(exc)}
2024-02-02 15:03:44 +03:00
2024-02-21 11:52:57 +03:00
2024-04-17 18:32:23 +03:00
@query.field("get_shout_followers")
2025-07-31 18:55:59 +03:00
def get_shout_followers(
_: None, _info: GraphQLResolveInfo, slug: str = "", shout_id: int | None = None
) -> list[dict[str, Any]]:
"""
Получает список подписчиков для шаута по slug или ID
Args:
_: GraphQL root
_info: GraphQL context info
slug: Slug шаута (опционально)
shout_id: ID шаута (опционально)
Returns:
Список подписчиков шаута
"""
if not slug and not shout_id:
return []
2025-07-31 18:55:59 +03:00
with local_session() as session:
# Если slug не указан, ищем шаут по ID
if not slug and shout_id is not None:
shout = session.query(Shout).where(Shout.id == shout_id).first()
else:
# Ищем шаут по slug
shout = session.query(Shout).where(Shout.slug == slug).first()
2024-11-02 11:35:02 +03:00
2025-07-31 18:55:59 +03:00
if not shout:
return []
2024-11-02 12:09:24 +03:00
2025-07-31 18:55:59 +03:00
# Получаем подписчиков шаута
followers_query = (
session.query(Author)
.join(ShoutReactionsFollower, Author.id == ShoutReactionsFollower.follower)
.where(ShoutReactionsFollower.shout == shout.id)
)
followers = followers_query.all()
2024-11-02 11:35:02 +03:00
2025-07-31 18:55:59 +03:00
# Возвращаем безопасную версию данных
return [follower.dict() for follower in followers]