core/resolvers/follower.py

300 lines
14 KiB
Python
Raw Normal View History

2024-01-25 19:41:27 +00:00
from typing import List
2023-11-28 07:53:48 +00:00
2024-11-02 08:49:30 +00:00
from graphql import GraphQLError
2024-05-18 16:30:25 +00:00
from sqlalchemy import select
2024-02-02 12:03:44 +00:00
from sqlalchemy.sql import and_
2024-01-31 14:48:36 +00:00
2025-05-29 09:37:39 +00:00
from auth.orm import Author, AuthorFollower
2024-08-09 06:37:06 +00:00
from cache.cache import (
cache_author,
cache_topic,
get_cached_follower_authors,
get_cached_follower_topics,
)
2024-06-05 14:45:55 +00:00
from orm.community import Community, CommunityFollower
2023-11-28 09:11:45 +00:00
from orm.reaction import Reaction
2024-02-23 16:35:40 +00:00
from orm.shout import Shout, ShoutReactionsFollower
2023-11-28 07:53:48 +00:00
from orm.topic import Topic, TopicFollower
2024-05-20 22:40:57 +00:00
from resolvers.stat import get_with_stat
2023-12-17 20:30:20 +00:00
from services.auth import login_required
2023-10-23 14:47:11 +00:00
from services.db import local_session
2024-04-08 07:38:58 +00:00
from services.notify import notify_follower
2025-05-31 14:18:31 +00:00
from services.redis import redis
2024-04-08 07:38:58 +00:00
from services.schema import mutation, query
2024-11-02 08:35:02 +00:00
from utils.logger import root_logger as logger
2024-01-13 08:49:12 +00:00
2024-01-22 23:28:54 +00:00
2024-04-17 15:32:23 +00:00
@mutation.field("follow")
2024-01-22 23:28:54 +00:00
@login_required
2024-11-02 19:34:20 +00:00
async def follow(_, info, what, slug="", entity_id=0):
2024-11-02 08:35:02 +00:00
logger.debug("Начало выполнения функции 'follow'")
2025-05-22 01:34:30 +00:00
viewer_id = info.context.get("author", {}).get("id")
if not viewer_id:
return {"error": "Access denied"}
2025-05-29 14:09:32 +00:00
follower_dict = info.context.get("author") or {}
2024-11-02 08:49:30 +00:00
logger.debug(f"follower: {follower_dict}")
2024-11-02 08:35:02 +00:00
2025-05-22 01:34:30 +00:00
if not viewer_id or not follower_dict:
return GraphQLError("Access denied")
2024-11-02 08:35:02 +00:00
2024-05-20 13:23:49 +00:00
follower_id = follower_dict.get("id")
2024-11-02 08:35:02 +00:00
logger.debug(f"follower_id: {follower_id}")
2024-04-18 09:34:04 +00:00
2024-06-05 14:45:55 +00:00
entity_classes = {
"AUTHOR": (Author, AuthorFollower, get_cached_follower_authors, cache_author),
"TOPIC": (Topic, TopicFollower, get_cached_follower_topics, cache_topic),
2024-11-02 08:35:02 +00:00
"COMMUNITY": (Community, CommunityFollower, None, None), # Нет методов кэша для сообщества
"SHOUT": (Shout, ShoutReactionsFollower, None, None), # Нет методов кэша для shout
2024-06-05 14:45:55 +00:00
}
2024-03-11 13:12:28 +00:00
2024-06-05 14:45:55 +00:00
if what not in entity_classes:
2024-11-02 08:35:02 +00:00
logger.error(f"Неверный тип для следования: {what}")
2024-06-05 14:45:55 +00:00
return {"error": "invalid follow type"}
2024-03-11 13:12:28 +00:00
2024-06-05 14:45:55 +00:00
entity_class, follower_class, get_cached_follows_method, cache_method = entity_classes[what]
entity_type = what.lower()
entity_dict = None
try:
2024-11-02 08:35:02 +00:00
logger.debug("Попытка получить сущность из базы данных")
2024-05-25 23:17:45 +00:00
with local_session() as session:
2024-06-05 14:45:55 +00:00
entity_query = select(entity_class).filter(entity_class.slug == slug)
2024-11-02 08:35:02 +00:00
entities = get_with_stat(entity_query)
[entity] = entities
2024-06-05 14:45:55 +00:00
if not entity:
2024-11-02 08:35:02 +00:00
logger.warning(f"{what.lower()} не найден по slug: {slug}")
2024-06-05 14:45:55 +00:00
return {"error": f"{what.lower()} not found"}
2024-11-02 19:34:20 +00:00
if not entity_id and entity:
entity_id = entity.id
2025-05-29 09:37:39 +00:00
2025-05-20 22:34:02 +00:00
# Если это автор, учитываем фильтрацию данных
if what == "AUTHOR":
# Полная версия для кэширования
2025-05-30 10:48:02 +00:00
entity_dict = entity.dict(access=True)
2025-05-20 22:34:02 +00:00
else:
2025-05-29 09:37:39 +00:00
entity_dict = entity.dict()
2024-11-02 08:35:02 +00:00
logger.debug(f"entity_id: {entity_id}, entity_dict: {entity_dict}")
2024-06-05 14:45:55 +00:00
if entity_id:
2024-11-02 09:33:35 +00:00
logger.debug("Проверка существующей подписки")
2024-06-05 14:45:55 +00:00
with local_session() as session:
2024-11-02 09:33:52 +00:00
existing_sub = (
session.query(follower_class)
2025-05-16 06:23:48 +00:00
.filter(
follower_class.follower == follower_id,
getattr(follower_class, entity_type) == entity_id,
)
2024-11-02 09:33:52 +00:00
.first()
)
2024-11-02 09:33:35 +00:00
if existing_sub:
2025-05-29 09:37:39 +00:00
logger.info(f"Пользователь {follower_id} уже подписан на {what.lower()} с ID {entity_id}")
2024-11-02 09:33:35 +00: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 14:45:55 +00:00
2025-05-31 14:18:31 +00: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}")
2024-06-05 14:45:55 +00:00
follows = None
if cache_method:
2024-11-02 08:35:02 +00:00
logger.debug("Обновление кэша")
2024-06-05 14:45:55 +00:00
await cache_method(entity_dict)
if get_cached_follows_method:
2024-11-02 09:09:24 +00:00
logger.debug("Получение подписок из кэша")
existing_follows = await get_cached_follows_method(follower_id)
2025-05-29 09:37:39 +00:00
2025-05-20 22:34:02 +00:00
# Если это авторы, получаем безопасную версию
if what == "AUTHOR":
# Получаем ID текущего пользователя и фильтруем данные
follows_filtered = []
2025-05-29 09:37:39 +00:00
2025-05-20 22:34:02 +00:00
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-05-30 10:48:02 +00:00
follows_filtered.append(temp_author.dict(access=False))
2025-05-29 09:37:39 +00:00
2025-05-20 22:34:02 +00:00
if not existing_sub:
# Создаем объект автора для entity_dict
temp_author = Author()
for key, value in entity_dict.items():
if hasattr(temp_author, key):
setattr(temp_author, key, value)
# Добавляем отфильтрованную версию
2025-05-30 10:48:02 +00:00
follows = [*follows_filtered, temp_author.dict(access=False)]
2025-05-20 22:34:02 +00:00
else:
follows = follows_filtered
else:
follows = [*existing_follows, entity_dict] if not existing_sub else existing_follows
2025-05-29 09:37:39 +00:00
2024-11-02 09:09:24 +00:00
logger.debug("Обновлен список подписок")
2024-06-05 14:45:55 +00:00
2024-11-02 09:33:35 +00:00
if what == "AUTHOR" and not existing_sub:
2024-11-02 08:35:02 +00:00
logger.debug("Отправка уведомления автору о подписке")
2024-11-02 08:42:24 +00:00
await notify_follower(follower=follower_dict, author_id=entity_id, action="follow")
2024-03-11 13:12:28 +00:00
2024-06-05 14:45:55 +00:00
except Exception as exc:
2024-11-02 08:35:02 +00:00
logger.exception("Произошла ошибка в функции 'follow'")
2024-06-05 14:45:55 +00:00
return {"error": str(exc)}
2024-03-11 13:12:28 +00:00
2024-06-05 14:45:55 +00:00
return {f"{what.lower()}s": follows}
2023-10-23 14:47:11 +00:00
2024-04-17 15:32:23 +00:00
@mutation.field("unfollow")
2024-01-22 23:28:54 +00:00
@login_required
2024-11-02 19:34:20 +00:00
async def unfollow(_, info, what, slug="", entity_id=0):
2024-11-02 08:35:02 +00:00
logger.debug("Начало выполнения функции 'unfollow'")
2025-05-22 01:34:30 +00:00
viewer_id = info.context.get("author", {}).get("id")
if not viewer_id:
return GraphQLError("Access denied")
2025-05-29 14:09:32 +00:00
follower_dict = info.context.get("author") or {}
2024-11-02 08:49:30 +00:00
logger.debug(f"follower: {follower_dict}")
2024-11-02 08:35:02 +00:00
2025-05-22 01:34:30 +00:00
if not viewer_id or not follower_dict:
2024-11-02 08:35:02 +00:00
logger.warning("Неавторизованный доступ при попытке отписаться")
2025-05-22 01:34:30 +00:00
return GraphQLError("Unauthorized")
2024-11-02 08:35:02 +00:00
2024-05-20 13:23:49 +00:00
follower_id = follower_dict.get("id")
2024-11-02 08:35:02 +00:00
logger.debug(f"follower_id: {follower_id}")
2024-04-18 09:34:04 +00:00
2024-06-05 14:45:55 +00:00
entity_classes = {
"AUTHOR": (Author, AuthorFollower, get_cached_follower_authors, cache_author),
"TOPIC": (Topic, TopicFollower, get_cached_follower_topics, cache_topic),
2024-11-02 08:35:02 +00:00
"COMMUNITY": (Community, CommunityFollower, None, None), # Нет методов кэша для сообщества
2024-11-02 09:09:24 +00:00
"SHOUT": (Shout, ShoutReactionsFollower, None, None), # Нет методов кэша для shout
2024-05-20 22:40:57 +00:00
}
2024-02-02 12:03:44 +00:00
2024-06-05 14:45:55 +00:00
if what not in entity_classes:
2024-11-02 08:35:02 +00:00
logger.error(f"Неверный тип для отписки: {what}")
2024-06-05 14:45:55 +00:00
return {"error": "invalid unfollow type"}
2024-02-02 12:03:44 +00:00
2024-06-05 14:45:55 +00:00
entity_class, follower_class, get_cached_follows_method, cache_method = entity_classes[what]
entity_type = what.lower()
follows = []
error = None
2024-03-12 07:35:33 +00:00
2024-02-02 12:03:44 +00:00
try:
2024-11-02 08:35:02 +00:00
logger.debug("Попытка получить сущность из базы данных")
2024-02-02 12:03:44 +00:00
with local_session() as session:
2024-06-05 14:45:55 +00:00
entity = session.query(entity_class).filter(entity_class.slug == slug).first()
2024-11-02 08:35:02 +00:00
logger.debug(f"Полученная сущность: {entity}")
2024-06-05 14:45:55 +00:00
if not entity:
2024-11-02 08:35:02 +00:00
logger.warning(f"{what.lower()} не найден по slug: {slug}")
2024-06-05 14:45:55 +00:00
return {"error": f"{what.lower()} not found"}
2024-11-02 19:34:20 +00:00
if entity and not entity_id:
entity_id = entity.id
logger.debug(f"entity_id: {entity_id}")
2024-02-02 12:03:44 +00:00
2024-06-05 14:45:55 +00:00
sub = (
session.query(follower_class)
.filter(
2024-02-02 12:03:44 +00:00
and_(
2024-06-05 14:45:55 +00:00
getattr(follower_class, "follower") == follower_id,
getattr(follower_class, entity_type) == entity_id,
2024-02-02 12:03:44 +00:00
)
)
.first()
)
2024-11-02 08:35:02 +00:00
logger.debug(f"Найдена подписка для удаления: {sub}")
2024-06-05 14:45:55 +00:00
if sub:
session.delete(sub)
2024-02-02 12:03:44 +00:00
session.commit()
2024-11-02 08:35:02 +00:00
logger.info(f"Пользователь {follower_id} отписался от {what.lower()} с ID {entity_id}")
2024-02-02 12:03:44 +00:00
2025-05-31 14:18:31 +00: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}")
2024-06-05 14:45:55 +00:00
if cache_method:
2024-11-02 08:35:02 +00:00
logger.debug("Обновление кэша после отписки")
2025-05-20 22:34:02 +00:00
# Если это автор, кэшируем полную версию
if what == "AUTHOR":
2025-05-30 10:48:02 +00:00
await cache_method(entity.dict(access=True))
2025-05-20 22:34:02 +00:00
else:
await cache_method(entity.dict())
2025-05-29 09:37:39 +00:00
2024-06-05 14:45:55 +00:00
if what == "AUTHOR":
2024-11-02 08:35:02 +00:00
logger.debug("Отправка уведомления автору об отписке")
2024-11-02 08:42:24 +00:00
await notify_follower(follower=follower_dict, author_id=entity_id, action="unfollow")
2024-11-22 17:19:56 +00:00
else:
2025-05-31 14:18:31 +00:00
# Подписка не найдена, но это не критическая ошибка
logger.warning(f"Подписка не найдена: follower_id={follower_id}, {entity_type}_id={entity_id}")
error = "following was not found"
# Всегда получаем актуальный список подписок для возврата клиенту
if get_cached_follows_method:
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)
# Добавляем отфильтрованную версию
follows_filtered.append(temp_author.dict(access=False))
follows = follows_filtered
else:
follows = existing_follows
logger.debug(f"Актуальный список подписок получен: {len(follows)} элементов")
2024-02-02 12:03:44 +00:00
2024-06-05 14:45:55 +00:00
except Exception as exc:
2024-11-02 08:35:02 +00:00
logger.exception("Произошла ошибка в функции 'unfollow'")
import traceback
2024-11-02 09:09:24 +00:00
2024-11-02 08:35:02 +00:00
traceback.print_exc()
2024-06-05 14:45:55 +00:00
return {"error": str(exc)}
2024-02-02 12:03:44 +00:00
2025-05-31 14:18:31 +00:00
logger.debug(f"Функция 'unfollow' завершена: {entity_type}s={len(follows)}, error={error}")
2024-06-05 14:45:55 +00:00
return {f"{entity_type}s": follows, "error": error}
2024-02-21 08:52:57 +00:00
2024-04-17 15:32:23 +00:00
@query.field("get_shout_followers")
2024-05-30 04:12:00 +00:00
def get_shout_followers(_, _info, slug: str = "", shout_id: int | None = None) -> List[Author]:
2024-11-02 08:35:02 +00:00
logger.debug("Начало выполнения функции 'get_shout_followers'")
2024-02-21 08:52:57 +00:00
followers = []
2024-11-02 08:35:02 +00:00
try:
with local_session() as session:
shout = None
if slug:
shout = session.query(Shout).filter(Shout.slug == slug).first()
logger.debug(f"Найден shout по slug: {slug} -> {shout}")
elif shout_id:
shout = session.query(Shout).filter(Shout.id == shout_id).first()
logger.debug(f"Найден shout по ID: {shout_id} -> {shout}")
if shout:
reactions = session.query(Reaction).filter(Reaction.shout == shout.id).all()
logger.debug(f"Полученные реакции для shout ID {shout.id}: {reactions}")
for r in reactions:
followers.append(r.created_by)
logger.debug(f"Добавлен follower: {r.created_by}")
except Exception as _exc:
import traceback
2024-11-02 09:09:24 +00:00
2024-11-02 08:35:02 +00:00
traceback.print_exc()
logger.exception("Произошла ошибка в функции 'get_shout_followers'")
return []
2024-11-02 09:09:24 +00:00
# logger.debug(f"Функция 'get_shout_followers' завершена с {len(followers)} подписчиками")
2024-02-21 08:52:57 +00:00
return followers