core/resolvers/zine/profile.py

285 lines
8.6 KiB
Python
Raw Normal View History

2022-11-23 14:09:35 +00:00
from datetime import datetime, timedelta, timezone
2023-10-26 17:56:42 +00:00
from typing import List
from sqlalchemy import and_, distinct, func, literal, select
2022-11-28 22:16:39 +00:00
from sqlalchemy.orm import aliased, joinedload
from auth.authenticate import login_required
2022-12-01 14:45:19 +00:00
from auth.credentials import AuthCredentials
2022-08-11 05:53:14 +00:00
from base.orm import local_session
from base.resolvers import mutation, query
from orm.reaction import Reaction, ReactionKind
2022-11-28 20:29:02 +00:00
from orm.shout import ShoutAuthor, ShoutTopic
from orm.topic import Topic, TopicFollower
2022-11-13 15:24:29 +00:00
from orm.user import AuthorFollower, Role, User, UserRating, UserRole
2022-11-28 20:29:02 +00:00
from resolvers.zine.topics import followed_by_user
2022-09-03 10:50:14 +00:00
def add_author_stat_columns(q):
2022-11-28 22:16:39 +00:00
author_followers = aliased(AuthorFollower)
author_following = aliased(AuthorFollower)
2022-11-29 12:36:46 +00:00
shout_author_aliased = aliased(ShoutAuthor)
# user_rating_aliased = aliased(UserRating)
2022-11-29 12:36:46 +00:00
q = q.outerjoin(shout_author_aliased).add_columns(
2022-11-30 06:27:12 +00:00
func.count(distinct(shout_author_aliased.shout)).label('shouts_stat')
2022-11-29 16:37:40 +00:00
)
2022-11-30 06:27:12 +00:00
q = q.outerjoin(author_followers, author_followers.author == User.id).add_columns(
func.count(distinct(author_followers.follower)).label('followers_stat')
2022-11-29 16:37:40 +00:00
)
2022-11-30 06:27:12 +00:00
q = q.outerjoin(author_following, author_following.follower == User.id).add_columns(
func.count(distinct(author_following.author)).label('followings_stat')
2022-11-28 22:16:39 +00:00
)
q = q.add_columns(literal(0).label('rating_stat'))
# FIXME
# q = q.outerjoin(user_rating_aliased, user_rating_aliased.user == User.id).add_columns(
# # TODO: check
# func.sum(user_rating_aliased.value).label('rating_stat')
# )
2022-11-29 16:37:40 +00:00
q = q.add_columns(literal(0).label('commented_stat'))
# q = q.outerjoin(Reaction, and_(Reaction.createdBy == User.id, Reaction.body.is_not(None))).add_columns(
# func.count(distinct(Reaction.id)).label('commented_stat')
# )
2022-11-29 16:37:40 +00:00
2022-11-28 22:16:39 +00:00
q = q.group_by(User.id)
return q
def add_stat(author, stat_columns):
[shouts_stat, followers_stat, followings_stat, rating_stat, commented_stat] = stat_columns
author.stat = {
"shouts": shouts_stat,
"followers": followers_stat,
"followings": followings_stat,
"rating": rating_stat,
2023-10-26 17:56:42 +00:00
"commented": commented_stat,
2022-11-28 22:16:39 +00:00
}
return author
def get_authors_from_query(q):
authors = []
with local_session() as session:
for [author, *stat_columns] in session.execute(q):
author = add_stat(author, stat_columns)
authors.append(author)
return authors
2023-04-22 08:22:24 +00:00
# dufok mod (^*^') :
@query.field("userFollowedTopics")
2023-04-22 08:22:24 +00:00
async def get_followed_topics(_, info, slug) -> List[Topic]:
user_id_query = select(User.id).where(User.slug == slug)
with local_session() as session:
user_id = session.execute(user_id_query).scalar()
if user_id is None:
raise ValueError("User not found")
2022-12-01 14:45:19 +00:00
return await followed_topics(user_id)
2022-10-23 09:33:28 +00:00
2022-12-01 14:45:19 +00:00
async def followed_topics(user_id):
return followed_by_user(user_id)
2023-04-22 08:22:24 +00:00
# dufok mod (^*^') :
@query.field("userFollowedAuthors")
2023-04-22 08:22:24 +00:00
async def get_followed_authors(_, _info, slug) -> List[User]:
# 1. First, we need to get the user_id for the given slug
user_id_query = select(User.id).where(User.slug == slug)
with local_session() as session:
user_id = session.execute(user_id_query).scalar()
2022-10-23 09:33:28 +00:00
2023-04-22 08:22:24 +00:00
if user_id is None:
raise ValueError("User not found")
return await followed_authors(user_id)
2022-10-23 09:33:28 +00:00
2023-04-22 08:22:24 +00:00
# 2. Now, we can use the user_id to get the followed authors
2022-12-01 14:45:19 +00:00
async def followed_authors(user_id):
q = select(User)
q = add_author_stat_columns(q)
2022-12-01 18:42:13 +00:00
q = q.join(AuthorFollower, AuthorFollower.author == User.id).where(
AuthorFollower.follower == user_id
2022-12-01 14:45:19 +00:00
)
2023-04-22 08:22:24 +00:00
# 3. Pass the query to the get_authors_from_query function and return the results
2022-12-01 14:45:19 +00:00
return get_authors_from_query(q)
@query.field("userFollowers")
2022-10-04 12:07:41 +00:00
async def user_followers(_, _info, slug) -> List[User]:
2022-11-28 22:16:39 +00:00
q = select(User)
q = add_author_stat_columns(q)
2022-11-29 12:36:46 +00:00
aliased_user = aliased(User)
2023-10-26 17:56:42 +00:00
q = (
q.join(AuthorFollower, AuthorFollower.follower == User.id)
.join(aliased_user, aliased_user.id == AuthorFollower.author)
.where(aliased_user.slug == slug)
2022-11-29 12:36:46 +00:00
)
2022-11-28 22:16:39 +00:00
return get_authors_from_query(q)
2022-09-03 10:50:14 +00:00
2022-08-12 08:13:18 +00:00
2022-11-15 02:36:30 +00:00
async def get_user_roles(slug):
2022-09-03 10:50:14 +00:00
with local_session() as session:
user = session.query(User).where(User.slug == slug).first()
roles = (
session.query(Role)
2022-12-01 08:12:48 +00:00
.options(joinedload(Role.permissions))
.join(UserRole)
.where(UserRole.user == user.id)
.all()
2022-09-03 10:50:14 +00:00
)
2022-11-28 22:16:39 +00:00
2022-12-06 07:53:23 +00:00
return roles
2021-11-24 09:09:47 +00:00
@mutation.field("updateProfile")
@login_required
async def update_profile(_, info, profile):
2022-09-03 10:50:14 +00:00
auth = info.context["request"].auth
user_id = auth.user_id
with local_session() as session:
2022-12-06 07:53:23 +00:00
user = session.query(User).filter(User.id == user_id).one()
if not user:
2023-10-26 17:56:42 +00:00
return {"error": "canoot find user"}
2022-12-06 07:53:23 +00:00
user.update(profile)
2022-12-02 08:47:55 +00:00
session.commit()
2023-10-26 17:56:42 +00:00
return {"error": None, "author": user}
2022-02-22 09:55:02 +00:00
2022-02-16 12:38:05 +00:00
@mutation.field("rateUser")
@login_required
2022-10-04 12:07:41 +00:00
async def rate_user(_, info, rated_userslug, value):
2022-12-01 14:45:19 +00:00
auth: AuthCredentials = info.context["request"].auth
2022-09-03 10:50:14 +00:00
with local_session() as session:
rating = (
session.query(UserRating)
2022-12-02 08:51:53 +00:00
.filter(and_(UserRating.rater == auth.user_id, UserRating.user == rated_userslug))
2022-12-01 08:12:48 +00:00
.first()
2022-09-03 10:50:14 +00:00
)
if rating:
rating.value = value
session.commit()
return {}
try:
2022-12-01 15:55:37 +00:00
UserRating.create(rater=auth.user_id, user=rated_userslug, value=value)
2022-09-03 10:50:14 +00:00
except Exception as err:
return {"error": err}
return {}
# for mutation.field("follow")
2022-12-01 14:45:19 +00:00
def author_follow(user_id, slug):
2023-02-20 17:38:20 +00:00
try:
with local_session() as session:
author = session.query(User).where(User.slug == slug).one()
af = AuthorFollower.create(follower=user_id, author=author.id)
session.add(af)
session.commit()
return True
except:
return False
2022-09-03 10:50:14 +00:00
# for mutation.field("unfollow")
2022-12-01 14:45:19 +00:00
def author_unfollow(user_id, slug):
2022-09-03 10:50:14 +00:00
with local_session() as session:
flw = (
2023-10-26 17:56:42 +00:00
session.query(AuthorFollower)
.join(User, User.id == AuthorFollower.author)
.filter(and_(AuthorFollower.follower == user_id, User.slug == slug))
.first()
2022-09-03 10:50:14 +00:00
)
2023-02-20 17:38:20 +00:00
if flw:
2022-09-03 10:50:14 +00:00
session.delete(flw)
session.commit()
2023-02-20 17:38:20 +00:00
return True
return False
2022-09-03 10:50:14 +00:00
2022-07-28 03:44:56 +00:00
@query.field("authorsAll")
2022-09-30 08:48:38 +00:00
async def get_authors_all(_, _info):
2022-11-28 22:16:39 +00:00
q = select(User)
q = add_author_stat_columns(q)
2022-11-30 06:27:12 +00:00
q = q.join(ShoutAuthor, User.id == ShoutAuthor.user)
2022-11-28 22:16:39 +00:00
return get_authors_from_query(q)
2022-09-14 08:27:44 +00:00
2022-09-30 08:48:38 +00:00
2022-11-21 04:36:40 +00:00
@query.field("getAuthor")
async def get_author(_, _info, slug):
2022-11-28 22:16:39 +00:00
q = select(User).where(User.slug == slug)
q = add_author_stat_columns(q)
2022-11-28 22:16:39 +00:00
[author] = get_authors_from_query(q)
with local_session() as session:
2023-10-26 17:56:42 +00:00
comments_count = (
session.query(Reaction)
.where(and_(Reaction.createdBy == author.id, Reaction.kind == ReactionKind.COMMENT))
.count()
)
author.stat["commented"] = comments_count
return author
2022-11-21 04:36:40 +00:00
2022-11-15 02:36:30 +00:00
@query.field("loadAuthorsBy")
2022-11-16 07:32:24 +00:00
async def load_authors_by(_, info, by, limit, offset):
2022-11-28 22:16:39 +00:00
q = select(User)
q = add_author_stat_columns(q)
if by.get("slug"):
q = q.filter(User.slug.ilike(f"%{by['slug']}%"))
elif by.get("name"):
q = q.filter(User.name.ilike(f"%{by['name']}%"))
elif by.get("topic"):
2022-11-29 12:36:46 +00:00
q = q.join(ShoutAuthor).join(ShoutTopic).join(Topic).where(Topic.slug == by["topic"])
2022-11-28 22:16:39 +00:00
if by.get("lastSeen"): # in days
days_before = datetime.now(tz=timezone.utc) - timedelta(days=by["lastSeen"])
q = q.filter(User.lastSeen > days_before)
elif by.get("createdAt"): # in days
days_before = datetime.now(tz=timezone.utc) - timedelta(days=by["createdAt"])
q = q.filter(User.createdAt > days_before)
2023-10-26 17:56:42 +00:00
q = q.order_by(by.get("order", User.createdAt)).limit(limit).offset(offset)
2022-11-28 22:16:39 +00:00
return get_authors_from_query(q)
@query.field("loadMySubscriptions")
@login_required
async def load_my_subscriptions(_, info):
auth = info.context["request"].auth
user_id = auth.user_id
2023-10-26 17:56:42 +00:00
authors_query = (
select(User)
.join(AuthorFollower, AuthorFollower.author == User.id)
.where(AuthorFollower.follower == user_id)
)
2023-10-26 17:56:42 +00:00
topics_query = select(Topic).join(TopicFollower).where(TopicFollower.follower == user_id)
topics = []
authors = []
with local_session() as session:
for [author] in session.execute(authors_query):
authors.append(author)
for [topic] in session.execute(topics_query):
topics.append(topic)
2023-10-26 17:56:42 +00:00
return {"topics": topics, "authors": authors}