core/resolvers/zine/profile.py

265 lines
8.1 KiB
Python
Raw Normal View History

from typing import List
2022-11-23 14:09:35 +00:00
from datetime import datetime, timedelta, timezone
2022-11-29 16:37:40 +00:00
from sqlalchemy import and_, func, distinct, select, literal
2022-11-28 22:16:39 +00:00
from sqlalchemy.orm import aliased, joinedload
from auth.authenticate import login_required
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
2022-11-28 20:29:02 +00:00
from orm.shout import ShoutAuthor, ShoutTopic
2022-11-28 22:16:39 +00:00
from orm.topic import Topic
2022-11-13 15:24:29 +00:00
from orm.user import AuthorFollower, Role, User, UserRating, UserRole
2022-11-15 02:36:30 +00:00
# from .community import followed_communities
2022-11-21 08:13:57 +00:00
from resolvers.inbox.unread import get_total_unread_counter
2022-11-28 20:29:02 +00:00
from resolvers.zine.topics import followed_by_user
2022-09-03 10:50:14 +00:00
2022-11-28 22:16:39 +00:00
def add_author_stat_columns(q):
author_followers = aliased(AuthorFollower)
author_following = aliased(AuthorFollower)
2022-11-29 12:36:46 +00:00
shout_author_aliased = aliased(ShoutAuthor)
2022-12-01 08:12:48 +00:00
# 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
)
2022-11-29 16:37:40 +00:00
q = q.add_columns(literal(0).label('rating_stat'))
# FIXME
2022-11-30 06:27:12 +00:00
# q = q.outerjoin(user_rating_aliased, user_rating_aliased.user == User.id).add_columns(
2022-11-29 16:37:40 +00:00
# # TODO: check
# func.sum(user_rating_aliased.value).label('rating_stat')
# )
2022-12-01 13:24:05 +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,
"commented": commented_stat
}
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
2022-10-23 09:33:28 +00:00
async def user_subscriptions(slug: str):
2022-09-19 13:50:43 +00:00
return {
2022-11-28 20:29:02 +00:00
"unread": await get_total_unread_counter(slug), # unread inbox messages counter
2022-10-23 09:33:28 +00:00
"topics": [t.slug for t in await followed_topics(slug)], # followed topics slugs
"authors": [a.slug for a in await followed_authors(slug)], # followed authors slugs
2022-11-26 00:55:45 +00:00
"reactions": await followed_reactions(slug)
2022-11-15 02:36:30 +00:00
# "communities": [c.slug for c in followed_communities(slug)], # communities
2022-09-19 13:50:43 +00:00
}
2022-11-26 00:55:45 +00:00
# @query.field("userFollowedDiscussions")
@login_required
async def followed_discussions(_, info, slug) -> List[Topic]:
return await followed_reactions(slug)
async def followed_reactions(slug):
with local_session() as session:
user = session.query(User).where(User.slug == slug).first()
return session.query(
Reaction.shout
).where(
2022-11-29 12:36:46 +00:00
Reaction.createdBy == user.id
2022-11-26 00:55:45 +00:00
).filter(
Reaction.createdAt > user.lastSeen
).all()
@query.field("userFollowedTopics")
@login_required
2022-10-04 12:07:41 +00:00
async def get_followed_topics(_, info, slug) -> List[Topic]:
2022-10-23 09:33:28 +00:00
return await followed_topics(slug)
async def followed_topics(slug):
2022-11-28 20:29:02 +00:00
return followed_by_user(slug)
@query.field("userFollowedAuthors")
2022-10-04 12:07:41 +00:00
async def get_followed_authors(_, _info, slug) -> List[User]:
2022-10-23 09:33:28 +00:00
return await followed_authors(slug)
2022-12-01 08:12:48 +00:00
async def followed_authors(slug):
with local_session() as session:
user = session.query(User).where(User.slug == slug).first()
q = select(User)
q = add_author_stat_columns(q)
aliased_user = aliased(User)
q = q.join(AuthorFollower, AuthorFollower.author == user.id).join(
aliased_user, aliased_user.id == AuthorFollower.follower
).where(
aliased_user.slug == slug
)
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)
q = q.join(AuthorFollower).join(
2022-11-30 06:27:12 +00:00
aliased_user, aliased_user.id == AuthorFollower.author
2022-11-29 12:36:46 +00:00
).where(
aliased_user.slug == slug
)
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-01 10:05:02 +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:
user = session.query(User).filter(User.id == user_id).first()
if user:
User.update(user, **profile)
session.add(user)
session.commit()
2022-09-03 10:50:14 +00:00
return {}
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-09-03 10:50:14 +00:00
user = info.context["request"].user
with local_session() as session:
rating = (
session.query(UserRating)
2022-12-01 08:12:48 +00:00
.filter(and_(UserRating.rater == user.slug, UserRating.user == rated_userslug))
.first()
2022-09-03 10:50:14 +00:00
)
if rating:
rating.value = value
session.commit()
return {}
try:
2022-10-04 12:07:41 +00:00
UserRating.create(rater=user.slug, 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")
def author_follow(user, slug):
2022-09-18 14:29:21 +00:00
with local_session() as session:
2022-11-29 12:36:46 +00:00
author = session.query(User).where(User.slug == slug).one()
2022-11-30 06:27:12 +00:00
af = AuthorFollower.create(follower=user.id, author=author.id)
2022-09-18 14:29:21 +00:00
session.add(af)
session.commit()
2022-09-03 10:50:14 +00:00
# for mutation.field("unfollow")
def author_unfollow(user, slug):
2022-09-03 10:50:14 +00:00
with local_session() as session:
flw = (
2022-11-29 12:36:46 +00:00
session.query(
AuthorFollower
2022-11-30 06:27:12 +00:00
).join(User, User.id == AuthorFollower.author).filter(
2022-09-03 10:50:14 +00:00
and_(
2022-11-30 06:27:12 +00:00
AuthorFollower.follower == user.id, User.slug == slug
2022-09-03 10:50:14 +00:00
)
2022-11-29 12:36:46 +00:00
).first()
2022-09-03 10:50:14 +00:00
)
if not flw:
raise Exception("[resolvers.profile] follower not exist, cant unfollow")
else:
session.delete(flw)
session.commit()
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)
authors = get_authors_from_query(q)
return authors[0]
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)
q = q.order_by(
by.get("order", User.createdAt)
).limit(limit).offset(offset)
return get_authors_from_query(q)