core/resolvers/follower.py

220 lines
9.8 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-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
2024-08-09 06:37:06 +00:00
from cache.cache import (
cache_author,
cache_topic,
get_cached_follower_authors,
get_cached_follower_topics,
)
2023-12-17 20:30:20 +00:00
from orm.author import Author, AuthorFollower
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
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
2023-10-23 14:47:11 +00:00
async def follow(_, info, what, slug):
2024-11-02 08:35:02 +00:00
logger.debug("Начало выполнения функции 'follow'")
2024-04-17 15:32:23 +00:00
user_id = info.context.get("user_id")
2024-05-20 13:23:49 +00:00
follower_dict = info.context.get("author")
2024-11-02 08:35:02 +00:00
logger.debug(f"user_id: {user_id}, follower_dict: {follower_dict}")
2024-05-20 13:23:49 +00:00
if not user_id or not follower_dict:
2024-11-02 08:35:02 +00:00
logger.warning("Неавторизованный доступ при попытке следования")
2024-04-17 15:32:23 +00:00
return {"error": "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), # Нет методов кэша для сообщества
"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()
2024-11-02 08:35:02 +00:00
logger.debug(f"entity_class: {entity_class}, follower_class: {follower_class}, entity_type: {entity_type}")
2024-06-05 14:45:55 +00:00
entity_id = None
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)
logger.debug(f"Полученные сущности: {entities}")
[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"}
entity_id = entity.id
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 08:35:02 +00:00
logger.debug("Попытка добавить запись в базу данных")
2024-06-05 14:45:55 +00:00
with local_session() as session:
sub = follower_class(follower=follower_id, **{entity_type: entity_id})
2024-11-02 08:35:02 +00:00
logger.debug(f"Создан объект подписки: {sub}")
2024-06-05 14:45:55 +00:00
session.add(sub)
session.commit()
2024-11-02 08:35:02 +00:00
logger.info(f"Пользователь {follower_id} подписался на {what.lower()} с ID {entity_id}")
2024-06-05 14:45:55 +00:00
follows = None
2024-11-02 08:35:02 +00:00
# Обновление кэша
2024-06-05 14:45:55 +00:00
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 08:35:02 +00:00
logger.debug("Получение обновленных подписок из кэша")
2024-06-05 14:45:55 +00:00
follows = await get_cached_follows_method(follower_id)
2024-11-02 08:35:02 +00:00
logger.debug(f"Текущие подписки: {follows}")
2024-06-05 14:45:55 +00:00
2024-11-02 08:35:02 +00:00
# Уведомление автора (только для типа AUTHOR)
2024-06-05 14:45:55 +00:00
if what == "AUTHOR":
2024-11-02 08:35:02 +00:00
logger.debug("Отправка уведомления автору о подписке")
2024-06-05 14:45:55 +00:00
await notify_follower(follower=follower_dict, author=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-11-02 08:35:02 +00:00
logger.debug(f"Функция 'follow' завершена успешно с результатом: {what.lower()}s={follows}")
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
2023-10-23 14:47:11 +00:00
async def unfollow(_, info, what, slug):
2024-11-02 08:35:02 +00:00
logger.debug("Начало выполнения функции 'unfollow'")
2024-04-17 15:32:23 +00:00
user_id = info.context.get("user_id")
2024-05-20 13:23:49 +00:00
follower_dict = info.context.get("author")
2024-11-02 08:35:02 +00:00
logger.debug(f"user_id: {user_id}, follower_dict: {follower_dict}")
2024-05-20 13:23:49 +00:00
if not user_id or not follower_dict:
2024-11-02 08:35:02 +00:00
logger.warning("Неавторизованный доступ при попытке отписаться")
2024-04-17 15:32:23 +00:00
return {"error": "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-06-05 14:45:55 +00:00
"SHOUT": (
Shout,
ShoutReactionsFollower,
None,
2024-11-02 08:35:02 +00:00
), # Нет методов кэша для 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()
2024-11-02 08:35:02 +00:00
logger.debug(f"entity_class: {entity_class}, follower_class: {follower_class}, entity_type: {entity_type}")
2024-06-05 14:45:55 +00:00
entity_id = None
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"}
entity_id = entity.id
2024-11-02 08:35:02 +00:00
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
2024-06-05 14:45:55 +00:00
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 08:35:02 +00:00
logger.debug("Получение обновленных подписок из кэша")
2024-06-05 14:45:55 +00:00
follows = await get_cached_follows_method(follower_id)
2024-11-02 08:35:02 +00:00
logger.debug(f"Текущие подписки: {follows}")
2024-02-02 12:03:44 +00:00
2024-06-05 14:45:55 +00:00
if what == "AUTHOR":
2024-11-02 08:35:02 +00:00
logger.debug("Отправка уведомления автору об отписке")
2024-06-05 14:45:55 +00:00
await notify_follower(follower=follower_dict, author=entity_id, action="unfollow")
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
traceback.print_exc()
2024-06-05 14:45:55 +00:00
return {"error": str(exc)}
2024-02-02 12:03:44 +00:00
2024-11-02 08:35:02 +00:00
logger.debug(f"Функция 'unfollow' завершена успешно с результатом: {entity_type}s={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
traceback.print_exc()
logger.exception("Произошла ошибка в функции 'get_shout_followers'")
return []
logger.debug(f"Функция 'get_shout_followers' завершена с {len(followers)} подписчиками")
2024-02-21 08:52:57 +00:00
return followers