core/resolvers/follower.py

274 lines
9.4 KiB
Python
Raw Normal View History

2024-02-21 14:37:58 +00:00
import json
2024-02-22 10:20:14 +00:00
import time
2024-01-25 19:41:27 +00:00
from typing import List
2023-11-28 07:53:48 +00:00
2024-02-23 16:35:40 +00:00
from sqlalchemy import select, or_
2024-02-02 12:03:44 +00:00
from sqlalchemy.sql import and_
2024-01-31 14:48:36 +00:00
2023-12-17 20:30:20 +00:00
from orm.author import Author, AuthorFollower
2024-03-11 13:12:28 +00:00
from orm.community import Community
2024-02-21 08:59:47 +00:00
# from orm.community import Community
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-03-11 09:03:41 +00:00
from resolvers.topic import topic_unfollow, topic_follow
2024-02-25 08:35:06 +00:00
from resolvers.stat import get_with_stat, author_follows_topics, author_follows_authors
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-03-06 09:25:55 +00:00
from services.cache import (
DEFAULT_FOLLOWS,
update_follows_for_author,
update_followers_for_author,
)
2023-10-25 18:33:53 +00:00
from services.notify import notify_follower
2023-11-28 07:53:48 +00:00
from services.schema import mutation, query
2024-02-20 16:19:46 +00:00
from services.logger import root_logger as logger
2024-02-21 07:27:16 +00:00
from services.rediscache import redis
2024-01-13 08:49:12 +00:00
2024-01-22 23:28:54 +00:00
2024-02-21 16:14:58 +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-03-11 08:59:20 +00:00
follows = []
2024-03-11 13:12:28 +00:00
error = None
user_id = info.context.get('user_id')
if not user_id:
return {"error": "unauthorized"}
[follower] = get_with_stat(select(Author).select_from(Author).filter(Author.user == user_id))
if not follower:
return {"error": "cant find follower"}
if what == 'AUTHOR':
if not author_follow(follower.id, slug):
return {"error": "cant follow author"}
logger.debug(f'@{follower.slug} followed @{slug}')
[author] = get_with_stat(select(Author).select_from(Author).where(Author.slug == slug))
if not author:
return {"error": "author is not found"}
follows = await update_follows_for_author(follower, 'author', author, True)
_followers = await update_followers_for_author(follower, author, True)
await notify_follower(follower.dict(), author.id, 'unfollow')
elif what == 'TOPIC':
if not topic_follow(follower.id, slug):
return {"error": "cant follow topic"}
2024-03-11 13:17:52 +00:00
[topic] = get_with_stat(select(Topic).where(Topic.slug == slug))
2024-03-11 13:12:28 +00:00
if not topic:
return {"error": "topic is not found"}
follows = await update_follows_for_author(follower, 'topic', topic, True)
elif what == 'COMMUNITY':
follows = local_session().execute(select(Community))
elif what == 'SHOUT':
if not reactions_follow(follower.id, slug):
return {"error": "cant follow shout"}
[shout] = local_session().execute(select(Shout).where(Shout.slug == slug))
if not shout:
return {"error": "cant find shout"}
follows = await update_follows_for_author(follower, 'shout', shout, True)
return {f'{what.lower()}s': follows, "error": error}
2023-10-23 14:47:11 +00:00
2024-02-21 16:14:58 +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-03-11 13:12:28 +00:00
follows = []
error = None
user_id = info.context.get('user_id')
if not user_id:
return {"error": "unauthorized"}
follower_query = select(Author).filter(Author.user == user_id)
[follower] = get_with_stat(follower_query)
if not follower:
return {"error": "follower profile is not found"}
if what == 'AUTHOR':
if not author_unfollow(follower.id, slug):
return {"error": "cant unfollow author"}
logger.info(f'@{follower.slug} unfollowing @{slug}')
[author] = get_with_stat(select(Author).where(Author.slug == slug))
if not author:
return {"error": "cant find author"}
_followers = await update_followers_for_author(follower, author, False)
await notify_follower(follower.dict(), author.id, 'unfollow')
follows = await update_follows_for_author(follower, 'author', author, False)
elif what == 'TOPIC':
if not topic_unfollow(follower.id, slug):
return {"error": "cant unfollow topic"}
logger.info(f'@{follower.slug} unfollowing §{slug}')
[topic] = get_with_stat(select(Topic).where(Topic.slug == slug))
if not topic:
return {"error": "cant find topic"}
follows = await update_follows_for_author(follower, 'topic', topic, False)
elif what == 'COMMUNITY':
follows = local_session().execute(select(Community))
elif what == 'SHOUT':
logger.info(f'@{follower.slug} unfollowing §{slug}')
[shout] = local_session().execute(select(Shout).where(Shout.slug == slug))
if not shout:
return {"error": "cant find shout"}
if not reactions_unfollow(follower.id, slug):
return {"error": "cant unfollow shout"}
follows = await update_follows_for_author(follower, 'shout', shout, False)
return {'error': error, f'{what.lower()}s': follows}
2023-11-28 07:53:48 +00:00
2024-02-21 07:27:16 +00:00
async def get_follows_by_user_id(user_id: str):
2024-03-11 08:56:14 +00:00
if not user_id:
return {"error": "unauthorized"}
author = await redis.execute('GET', f'user:{user_id}:author')
if isinstance(author, str):
author = json.loads(author)
if not author:
with local_session() as session:
author = session.query(Author).filter(Author.user == user_id).first()
if not author:
return {"error": "cant find author"}
author = author.dict()
last_seen = author.get('last_seen', 0) if isinstance(author, dict) else 0
follows = DEFAULT_FOLLOWS
day_old = int(time.time()) - last_seen > 24 * 60 * 60
if day_old:
author_id = json.loads(str(author)).get('id')
if author_id:
topics = author_follows_topics(author_id)
authors = author_follows_authors(author_id)
follows = {
'topics': topics,
'authors': authors,
'communities': [
{'id': 1, 'name': 'Дискурс', 'slug': 'discours', 'pic': ''}
],
}
else:
logger.debug(f'getting follows for {user_id} from redis')
res = await redis.execute('GET', f'user:{user_id}:follows')
if isinstance(res, str):
follows = json.loads(res)
return follows
2024-02-02 12:03:44 +00:00
def reactions_follow(author_id, shout_id, auto=False):
try:
with local_session() as session:
shout = session.query(Shout).where(Shout.id == shout_id).one()
following = (
session.query(ShoutReactionsFollower)
.where(
and_(
ShoutReactionsFollower.follower == author_id,
ShoutReactionsFollower.shout == shout.id,
)
)
.first()
)
if not following:
2024-02-21 07:27:16 +00:00
following = ShoutReactionsFollower(
follower=author_id, shout=shout.id, auto=auto
)
2024-02-02 12:03:44 +00:00
session.add(following)
session.commit()
return True
except Exception:
return False
def reactions_unfollow(author_id, shout_id: int):
try:
with local_session() as session:
shout = session.query(Shout).where(Shout.id == shout_id).one()
following = (
session.query(ShoutReactionsFollower)
.where(
and_(
ShoutReactionsFollower.follower == author_id,
ShoutReactionsFollower.shout == shout.id,
)
)
.first()
)
if following:
session.delete(following)
session.commit()
return True
except Exception as ex:
logger.debug(ex)
2024-03-11 12:41:24 +00:00
import traceback
traceback.print_exc()
2024-02-02 12:03:44 +00:00
return False
# for mutation.field("follow")
def author_follow(follower_id, slug):
try:
with local_session() as session:
author = session.query(Author).where(Author.slug == slug).one()
af = AuthorFollower(follower=follower_id, author=author.id)
session.add(af)
session.commit()
return True
2024-03-11 12:41:24 +00:00
except Exception as exc:
logger.error(exc)
import traceback
traceback.print_exc()
2024-02-02 12:03:44 +00:00
return False
# for mutation.field("unfollow")
def author_unfollow(follower_id, slug):
with local_session() as session:
flw = (
session.query(AuthorFollower)
.join(Author, Author.id == AuthorFollower.author)
.filter(and_(AuthorFollower.follower == follower_id, Author.slug == slug))
.first()
)
if flw:
session.delete(flw)
session.commit()
return True
return False
2024-02-21 08:52:57 +00:00
2024-02-21 16:14:58 +00:00
@query.field('get_topic_followers')
2024-02-22 23:08:43 +00:00
def get_topic_followers(_, _info, slug: str, topic_id: int) -> List[Author]:
2024-02-21 08:52:57 +00:00
q = select(Author)
q = (
2024-02-24 18:15:11 +00:00
q.join(TopicFollower, TopicFollower.follower == Author.id)
.join(Topic, Topic.id == TopicFollower.topic)
2024-02-21 08:52:57 +00:00
.filter(or_(Topic.slug == slug, Topic.id == topic_id))
)
2024-02-25 08:27:08 +00:00
return get_with_stat(q)
2024-02-21 08:52:57 +00:00
2024-02-21 16:14:58 +00:00
@query.field('get_shout_followers')
2024-02-21 08:52:57 +00:00
def get_shout_followers(
2024-02-21 16:14:58 +00:00
_, _info, slug: str = '', shout_id: int | None = None
2024-02-21 08:52:57 +00:00
) -> List[Author]:
followers = []
with local_session() as session:
shout = None
if slug:
shout = session.query(Shout).filter(Shout.slug == slug).first()
elif shout_id:
shout = session.query(Shout).filter(Shout.id == shout_id).first()
if shout:
reactions = session.query(Reaction).filter(Reaction.shout == shout.id).all()
for r in reactions:
followers.append(r.created_by)
return followers