restructured,inbox-removed
This commit is contained in:
@@ -1,147 +0,0 @@
|
||||
import asyncio
|
||||
from base.orm import local_session
|
||||
from base.resolvers import mutation, subscription
|
||||
from auth.authenticate import login_required
|
||||
from auth.credentials import AuthCredentials
|
||||
# from resolvers.community import community_follow, community_unfollow
|
||||
from orm.user import AuthorFollower
|
||||
from orm.topic import TopicFollower
|
||||
from orm.shout import ShoutReactionsFollower
|
||||
from resolvers.zine.profile import author_follow, author_unfollow
|
||||
from resolvers.zine.reactions import reactions_follow, reactions_unfollow
|
||||
from resolvers.zine.topics import topic_follow, topic_unfollow
|
||||
from services.following import Following, FollowingManager, FollowingResult
|
||||
from graphql.type import GraphQLResolveInfo
|
||||
|
||||
|
||||
@mutation.field("follow")
|
||||
@login_required
|
||||
async def follow(_, info, what, slug):
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
|
||||
try:
|
||||
if what == "AUTHOR":
|
||||
if author_follow(auth.user_id, slug):
|
||||
result = FollowingResult("NEW", 'author', slug)
|
||||
await FollowingManager.push('author', result)
|
||||
elif what == "TOPIC":
|
||||
if topic_follow(auth.user_id, slug):
|
||||
result = FollowingResult("NEW", 'topic', slug)
|
||||
await FollowingManager.push('topic', result)
|
||||
elif what == "COMMUNITY":
|
||||
if False: # TODO: use community_follow(auth.user_id, slug):
|
||||
result = FollowingResult("NEW", 'community', slug)
|
||||
await FollowingManager.push('community', result)
|
||||
elif what == "REACTIONS":
|
||||
if reactions_follow(auth.user_id, slug):
|
||||
result = FollowingResult("NEW", 'shout', slug)
|
||||
await FollowingManager.push('shout', result)
|
||||
except Exception as e:
|
||||
print(Exception(e))
|
||||
return {"error": str(e)}
|
||||
|
||||
return {}
|
||||
|
||||
|
||||
@mutation.field("unfollow")
|
||||
@login_required
|
||||
async def unfollow(_, info, what, slug):
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
|
||||
try:
|
||||
if what == "AUTHOR":
|
||||
if author_unfollow(auth.user_id, slug):
|
||||
result = FollowingResult("DELETED", 'author', slug)
|
||||
await FollowingManager.push('author', result)
|
||||
elif what == "TOPIC":
|
||||
if topic_unfollow(auth.user_id, slug):
|
||||
result = FollowingResult("DELETED", 'topic', slug)
|
||||
await FollowingManager.push('topic', result)
|
||||
elif what == "COMMUNITY":
|
||||
if False: # TODO: use community_unfollow(auth.user_id, slug):
|
||||
result = FollowingResult("DELETED", 'community', slug)
|
||||
await FollowingManager.push('community', result)
|
||||
elif what == "REACTIONS":
|
||||
if reactions_unfollow(auth.user_id, slug):
|
||||
result = FollowingResult("DELETED", 'shout', slug)
|
||||
await FollowingManager.push('shout', result)
|
||||
except Exception as e:
|
||||
return {"error": str(e)}
|
||||
|
||||
return {}
|
||||
|
||||
|
||||
# by author and by topic
|
||||
@subscription.source("newShout")
|
||||
@login_required
|
||||
async def shout_generator(_, info: GraphQLResolveInfo):
|
||||
print(f"[resolvers.zine] shouts generator {info}")
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
user_id = auth.user_id
|
||||
try:
|
||||
tasks = []
|
||||
|
||||
with local_session() as session:
|
||||
|
||||
# notify new shout by followed authors
|
||||
following_topics = session.query(TopicFollower).where(TopicFollower.follower == user_id).all()
|
||||
|
||||
for topic_id in following_topics:
|
||||
following_topic = Following('topic', topic_id)
|
||||
await FollowingManager.register('topic', following_topic)
|
||||
following_topic_task = following_topic.queue.get()
|
||||
tasks.append(following_topic_task)
|
||||
|
||||
# by followed topics
|
||||
following_authors = session.query(AuthorFollower).where(
|
||||
AuthorFollower.follower == user_id).all()
|
||||
|
||||
for author_id in following_authors:
|
||||
following_author = Following('author', author_id)
|
||||
await FollowingManager.register('author', following_author)
|
||||
following_author_task = following_author.queue.get()
|
||||
tasks.append(following_author_task)
|
||||
|
||||
# TODO: use communities
|
||||
# by followed communities
|
||||
# following_communities = session.query(CommunityFollower).where(
|
||||
# CommunityFollower.follower == user_id).all()
|
||||
|
||||
# for community_id in following_communities:
|
||||
# following_community = Following('community', author_id)
|
||||
# await FollowingManager.register('community', following_community)
|
||||
# following_community_task = following_community.queue.get()
|
||||
# tasks.append(following_community_task)
|
||||
|
||||
while True:
|
||||
shout = await asyncio.gather(*tasks)
|
||||
yield shout
|
||||
finally:
|
||||
pass
|
||||
|
||||
|
||||
@subscription.source("newReaction")
|
||||
@login_required
|
||||
async def reaction_generator(_, info):
|
||||
print(f"[resolvers.zine] reactions generator {info}")
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
user_id = auth.user_id
|
||||
try:
|
||||
with local_session() as session:
|
||||
followings = session.query(ShoutReactionsFollower.shout).where(
|
||||
ShoutReactionsFollower.follower == user_id).unique()
|
||||
|
||||
# notify new reaction
|
||||
|
||||
tasks = []
|
||||
for shout_id in followings:
|
||||
following_shout = Following('shout', shout_id)
|
||||
await FollowingManager.register('shout', following_shout)
|
||||
following_author_task = following_shout.queue.get()
|
||||
tasks.append(following_author_task)
|
||||
|
||||
while True:
|
||||
reaction = await asyncio.gather(*tasks)
|
||||
yield reaction
|
||||
finally:
|
||||
pass
|
@@ -1,258 +0,0 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy.orm import joinedload, aliased
|
||||
from sqlalchemy.sql.expression import desc, asc, select, func, case, and_, text, nulls_last
|
||||
|
||||
from auth.authenticate import login_required
|
||||
from auth.credentials import AuthCredentials
|
||||
from base.exceptions import ObjectNotExist, OperationNotAllowed
|
||||
from base.orm import local_session
|
||||
from base.resolvers import query
|
||||
from orm import TopicFollower
|
||||
from orm.reaction import Reaction, ReactionKind
|
||||
from orm.shout import Shout, ShoutAuthor, ShoutTopic
|
||||
from orm.user import AuthorFollower
|
||||
|
||||
|
||||
def add_stat_columns(q):
|
||||
aliased_reaction = aliased(Reaction)
|
||||
|
||||
q = q.outerjoin(aliased_reaction).add_columns(
|
||||
func.sum(
|
||||
aliased_reaction.id
|
||||
).label('reacted_stat'),
|
||||
func.sum(
|
||||
case(
|
||||
(aliased_reaction.kind == ReactionKind.COMMENT, 1),
|
||||
else_=0
|
||||
)
|
||||
).label('commented_stat'),
|
||||
func.sum(case(
|
||||
# do not count comments' reactions
|
||||
(aliased_reaction.replyTo.is_not(None), 0),
|
||||
(aliased_reaction.kind == ReactionKind.AGREE, 1),
|
||||
(aliased_reaction.kind == ReactionKind.DISAGREE, -1),
|
||||
(aliased_reaction.kind == ReactionKind.PROOF, 1),
|
||||
(aliased_reaction.kind == ReactionKind.DISPROOF, -1),
|
||||
(aliased_reaction.kind == ReactionKind.ACCEPT, 1),
|
||||
(aliased_reaction.kind == ReactionKind.REJECT, -1),
|
||||
(aliased_reaction.kind == ReactionKind.LIKE, 1),
|
||||
(aliased_reaction.kind == ReactionKind.DISLIKE, -1),
|
||||
else_=0)
|
||||
).label('rating_stat'),
|
||||
func.max(case(
|
||||
(aliased_reaction.kind != ReactionKind.COMMENT, None),
|
||||
else_=aliased_reaction.createdAt
|
||||
)).label('last_comment'))
|
||||
|
||||
return q
|
||||
|
||||
|
||||
def apply_filters(q, filters, user_id=None):
|
||||
if filters.get("reacted") and user_id:
|
||||
q.join(Reaction, Reaction.createdBy == user_id)
|
||||
|
||||
v = filters.get("visibility")
|
||||
if v == "public":
|
||||
q = q.filter(Shout.visibility == filters.get("visibility"))
|
||||
if v == "community":
|
||||
q = q.filter(Shout.visibility.in_(["public", "community"]))
|
||||
|
||||
if filters.get("layout"):
|
||||
q = q.filter(Shout.layout == filters.get("layout"))
|
||||
if filters.get('excludeLayout'):
|
||||
q = q.filter(Shout.layout != filters.get("excludeLayout"))
|
||||
if filters.get("author"):
|
||||
q = q.filter(Shout.authors.any(slug=filters.get("author")))
|
||||
if filters.get("topic"):
|
||||
q = q.filter(Shout.topics.any(slug=filters.get("topic")))
|
||||
if filters.get("title"):
|
||||
q = q.filter(Shout.title.ilike(f'%{filters.get("title")}%'))
|
||||
if filters.get("body"):
|
||||
q = q.filter(Shout.body.ilike(f'%{filters.get("body")}%s'))
|
||||
if filters.get("days"):
|
||||
before = datetime.now(tz=timezone.utc) - timedelta(days=int(filters.get("days")) or 30)
|
||||
q = q.filter(Shout.createdAt > before)
|
||||
|
||||
return q
|
||||
|
||||
|
||||
@query.field("loadShout")
|
||||
async def load_shout(_, info, slug=None, shout_id=None):
|
||||
with local_session() as session:
|
||||
q = select(Shout).options(
|
||||
joinedload(Shout.authors),
|
||||
joinedload(Shout.topics),
|
||||
)
|
||||
q = add_stat_columns(q)
|
||||
|
||||
if slug is not None:
|
||||
q = q.filter(
|
||||
Shout.slug == slug
|
||||
)
|
||||
|
||||
if shout_id is not None:
|
||||
q = q.filter(
|
||||
Shout.id == shout_id
|
||||
)
|
||||
|
||||
q = q.filter(
|
||||
Shout.deletedAt.is_(None)
|
||||
).group_by(Shout.id)
|
||||
|
||||
try:
|
||||
[shout, reacted_stat, commented_stat, rating_stat, last_comment] = session.execute(q).first()
|
||||
|
||||
shout.stat = {
|
||||
"viewed": shout.views,
|
||||
"reacted": reacted_stat,
|
||||
"commented": commented_stat,
|
||||
"rating": rating_stat
|
||||
}
|
||||
|
||||
for author_caption in session.query(ShoutAuthor).join(Shout).where(Shout.slug == slug):
|
||||
for author in shout.authors:
|
||||
if author.id == author_caption.user:
|
||||
author.caption = author_caption.caption
|
||||
return shout
|
||||
except Exception:
|
||||
raise ObjectNotExist("Slug was not found: %s" % slug)
|
||||
|
||||
|
||||
@query.field("loadShouts")
|
||||
async def load_shouts_by(_, info, options):
|
||||
"""
|
||||
:param options: {
|
||||
filters: {
|
||||
layout: 'audio',
|
||||
excludeLayout: 'article',
|
||||
visibility: "public",
|
||||
author: 'discours',
|
||||
topic: 'culture',
|
||||
title: 'something',
|
||||
body: 'something else',
|
||||
days: 30
|
||||
}
|
||||
offset: 0
|
||||
limit: 50
|
||||
order_by: 'createdAt' | 'commented' | 'reacted' | 'rating'
|
||||
order_by_desc: true
|
||||
|
||||
}
|
||||
:return: Shout[]
|
||||
"""
|
||||
|
||||
q = select(Shout).options(
|
||||
joinedload(Shout.authors),
|
||||
joinedload(Shout.topics),
|
||||
).where(
|
||||
and_(
|
||||
Shout.deletedAt.is_(None),
|
||||
Shout.layout.is_not(None)
|
||||
)
|
||||
)
|
||||
|
||||
q = add_stat_columns(q)
|
||||
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
q = apply_filters(q, options.get("filters", {}), auth.user_id)
|
||||
|
||||
order_by = options.get("order_by", Shout.publishedAt)
|
||||
|
||||
query_order_by = desc(order_by) if options.get('order_by_desc', True) else asc(order_by)
|
||||
offset = options.get("offset", 0)
|
||||
limit = options.get("limit", 10)
|
||||
|
||||
q = q.group_by(Shout.id).order_by(nulls_last(query_order_by)).limit(limit).offset(offset)
|
||||
|
||||
shouts = []
|
||||
with local_session() as session:
|
||||
shouts_map = {}
|
||||
|
||||
for [shout, reacted_stat, commented_stat, rating_stat, last_comment] in session.execute(q).unique():
|
||||
shouts.append(shout)
|
||||
shout.stat = {
|
||||
"viewed": shout.views,
|
||||
"reacted": reacted_stat,
|
||||
"commented": commented_stat,
|
||||
"rating": rating_stat
|
||||
}
|
||||
shouts_map[shout.id] = shout
|
||||
|
||||
return shouts
|
||||
|
||||
|
||||
@query.field("loadDrafts")
|
||||
async def get_drafts(_, info):
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
user_id = auth.user_id
|
||||
|
||||
q = select(Shout).options(
|
||||
joinedload(Shout.authors),
|
||||
joinedload(Shout.topics),
|
||||
).where(
|
||||
and_(Shout.deletedAt.is_(None), Shout.createdBy == user_id)
|
||||
)
|
||||
|
||||
q = q.group_by(Shout.id)
|
||||
|
||||
shouts = []
|
||||
with local_session() as session:
|
||||
for [shout] in session.execute(q).unique():
|
||||
shouts.append(shout)
|
||||
|
||||
return shouts
|
||||
|
||||
|
||||
@query.field("myFeed")
|
||||
@login_required
|
||||
async def get_my_feed(_, info, options):
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
user_id = auth.user_id
|
||||
|
||||
subquery = select(Shout.id).join(
|
||||
ShoutAuthor
|
||||
).join(
|
||||
AuthorFollower, AuthorFollower.follower == user_id
|
||||
).join(
|
||||
ShoutTopic
|
||||
).join(
|
||||
TopicFollower, TopicFollower.follower == user_id
|
||||
)
|
||||
|
||||
q = select(Shout).options(
|
||||
joinedload(Shout.authors),
|
||||
joinedload(Shout.topics),
|
||||
).where(
|
||||
and_(
|
||||
Shout.publishedAt.is_not(None),
|
||||
Shout.deletedAt.is_(None),
|
||||
Shout.id.in_(subquery)
|
||||
)
|
||||
)
|
||||
|
||||
q = add_stat_columns(q)
|
||||
q = apply_filters(q, options.get("filters", {}), user_id)
|
||||
|
||||
order_by = options.get("order_by", Shout.publishedAt)
|
||||
|
||||
query_order_by = desc(order_by) if options.get('order_by_desc', True) else asc(order_by)
|
||||
offset = options.get("offset", 0)
|
||||
limit = options.get("limit", 10)
|
||||
|
||||
q = q.group_by(Shout.id).order_by(nulls_last(query_order_by)).limit(limit).offset(offset)
|
||||
|
||||
shouts = []
|
||||
with local_session() as session:
|
||||
shouts_map = {}
|
||||
for [shout, reacted_stat, commented_stat, rating_stat, last_comment] in session.execute(q).unique():
|
||||
shouts.append(shout)
|
||||
shout.stat = {
|
||||
"viewed": shout.views,
|
||||
"reacted": reacted_stat,
|
||||
"commented": commented_stat,
|
||||
"rating": rating_stat
|
||||
}
|
||||
shouts_map[shout.id] = shout
|
||||
|
||||
return shouts
|
@@ -1,296 +0,0 @@
|
||||
from typing import List
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from sqlalchemy import and_, func, distinct, select, literal
|
||||
from sqlalchemy.orm import aliased, joinedload
|
||||
|
||||
from auth.authenticate import login_required
|
||||
from auth.credentials import AuthCredentials
|
||||
from base.orm import local_session
|
||||
from base.resolvers import mutation, query
|
||||
from orm.reaction import Reaction
|
||||
from orm.shout import ShoutAuthor, ShoutTopic
|
||||
from orm.topic import Topic
|
||||
from orm.user import AuthorFollower, Role, User, UserRating, UserRole
|
||||
|
||||
# from .community import followed_communities
|
||||
from resolvers.inbox.unread import get_total_unread_counter
|
||||
from resolvers.zine.topics import followed_by_user
|
||||
|
||||
|
||||
def add_author_stat_columns(q, include_heavy_stat=False):
|
||||
author_followers = aliased(AuthorFollower)
|
||||
author_following = aliased(AuthorFollower)
|
||||
shout_author_aliased = aliased(ShoutAuthor)
|
||||
|
||||
q = q.outerjoin(shout_author_aliased).add_columns(
|
||||
func.count(distinct(shout_author_aliased.shout)).label('shouts_stat')
|
||||
)
|
||||
q = q.outerjoin(author_followers, author_followers.author == User.id).add_columns(
|
||||
func.count(distinct(author_followers.follower)).label('followers_stat')
|
||||
)
|
||||
|
||||
q = q.outerjoin(author_following, author_following.follower == User.id).add_columns(
|
||||
func.count(distinct(author_following.author)).label('followings_stat')
|
||||
)
|
||||
|
||||
if include_heavy_stat:
|
||||
user_rating_aliased = aliased(UserRating)
|
||||
q = q.outerjoin(user_rating_aliased, user_rating_aliased.user == User.id).add_columns(
|
||||
func.sum(user_rating_aliased.value).label('rating_stat')
|
||||
)
|
||||
|
||||
else:
|
||||
q = q.add_columns(literal(-1).label('rating_stat'))
|
||||
|
||||
if include_heavy_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')
|
||||
)
|
||||
else:
|
||||
q = q.add_columns(literal(-1).label('commented_stat'))
|
||||
|
||||
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
|
||||
|
||||
|
||||
async def user_subscriptions(user_id: int):
|
||||
return {
|
||||
"unread": await get_total_unread_counter(user_id), # unread inbox messages counter
|
||||
"topics": [t.slug for t in await followed_topics(user_id)], # followed topics slugs
|
||||
"authors": [a.slug for a in await followed_authors(user_id)], # followed authors slugs
|
||||
"reactions": await followed_reactions(user_id)
|
||||
# "communities": [c.slug for c in followed_communities(slug)], # communities
|
||||
}
|
||||
|
||||
|
||||
# @query.field("userFollowedDiscussions")
|
||||
# @login_required
|
||||
async def followed_discussions(_, info, user_id) -> List[Topic]:
|
||||
return await followed_reactions(user_id)
|
||||
|
||||
|
||||
async def followed_reactions(user_id):
|
||||
with local_session() as session:
|
||||
user = session.query(User).where(User.id == user_id).first()
|
||||
return session.query(
|
||||
Reaction.shout
|
||||
).where(
|
||||
Reaction.createdBy == user.id
|
||||
).filter(
|
||||
Reaction.createdAt > user.lastSeen
|
||||
).all()
|
||||
|
||||
|
||||
# dufok mod (^*^') :
|
||||
@query.field("userFollowedTopics")
|
||||
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")
|
||||
|
||||
return await followed_topics(user_id)
|
||||
|
||||
|
||||
async def followed_topics(user_id):
|
||||
return followed_by_user(user_id)
|
||||
|
||||
|
||||
# dufok mod (^*^') :
|
||||
@query.field("userFollowedAuthors")
|
||||
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()
|
||||
|
||||
if user_id is None:
|
||||
raise ValueError("User not found")
|
||||
|
||||
return await followed_authors(user_id)
|
||||
|
||||
|
||||
# 2. Now, we can use the user_id to get the followed authors
|
||||
async def followed_authors(user_id):
|
||||
q = select(User)
|
||||
q = add_author_stat_columns(q)
|
||||
q = q.join(AuthorFollower, AuthorFollower.author == User.id).where(
|
||||
AuthorFollower.follower == user_id
|
||||
)
|
||||
# 3. Pass the query to the get_authors_from_query function and return the results
|
||||
return get_authors_from_query(q)
|
||||
|
||||
|
||||
@query.field("userFollowers")
|
||||
async def user_followers(_, _info, slug) -> List[User]:
|
||||
q = select(User)
|
||||
q = add_author_stat_columns(q)
|
||||
|
||||
aliased_user = aliased(User)
|
||||
q = q.join(AuthorFollower, AuthorFollower.follower == User.id).join(
|
||||
aliased_user, aliased_user.id == AuthorFollower.author
|
||||
).where(
|
||||
aliased_user.slug == slug
|
||||
)
|
||||
|
||||
return get_authors_from_query(q)
|
||||
|
||||
|
||||
async def get_user_roles(slug):
|
||||
with local_session() as session:
|
||||
user = session.query(User).where(User.slug == slug).first()
|
||||
roles = (
|
||||
session.query(Role)
|
||||
.options(joinedload(Role.permissions))
|
||||
.join(UserRole)
|
||||
.where(UserRole.user == user.id)
|
||||
.all()
|
||||
)
|
||||
|
||||
return roles
|
||||
|
||||
|
||||
@mutation.field("updateProfile")
|
||||
@login_required
|
||||
async def update_profile(_, info, profile):
|
||||
auth = info.context["request"].auth
|
||||
user_id = auth.user_id
|
||||
with local_session() as session:
|
||||
user = session.query(User).filter(User.id == user_id).one()
|
||||
if not user:
|
||||
return {
|
||||
"error": "canoot find user"
|
||||
}
|
||||
user.update(profile)
|
||||
session.commit()
|
||||
return {
|
||||
"error": None,
|
||||
"author": user
|
||||
}
|
||||
|
||||
|
||||
@mutation.field("rateUser")
|
||||
@login_required
|
||||
async def rate_user(_, info, rated_userslug, value):
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
|
||||
with local_session() as session:
|
||||
rating = (
|
||||
session.query(UserRating)
|
||||
.filter(and_(UserRating.rater == auth.user_id, UserRating.user == rated_userslug))
|
||||
.first()
|
||||
)
|
||||
if rating:
|
||||
rating.value = value
|
||||
session.commit()
|
||||
return {}
|
||||
try:
|
||||
UserRating.create(rater=auth.user_id, user=rated_userslug, value=value)
|
||||
except Exception as err:
|
||||
return {"error": err}
|
||||
return {}
|
||||
|
||||
|
||||
# for mutation.field("follow")
|
||||
def author_follow(user_id, slug):
|
||||
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
|
||||
|
||||
|
||||
# for mutation.field("unfollow")
|
||||
def author_unfollow(user_id, slug):
|
||||
with local_session() as session:
|
||||
flw = (
|
||||
session.query(
|
||||
AuthorFollower
|
||||
).join(User, User.id == AuthorFollower.author).filter(
|
||||
and_(
|
||||
AuthorFollower.follower == user_id, User.slug == slug
|
||||
)
|
||||
).first()
|
||||
)
|
||||
if flw:
|
||||
session.delete(flw)
|
||||
session.commit()
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
@query.field("authorsAll")
|
||||
async def get_authors_all(_, _info):
|
||||
q = select(User)
|
||||
q = add_author_stat_columns(q)
|
||||
q = q.join(ShoutAuthor, User.id == ShoutAuthor.user)
|
||||
|
||||
return get_authors_from_query(q)
|
||||
|
||||
|
||||
@query.field("getAuthor")
|
||||
async def get_author(_, _info, slug):
|
||||
q = select(User).where(User.slug == slug)
|
||||
q = add_author_stat_columns(q, True)
|
||||
|
||||
authors = get_authors_from_query(q)
|
||||
return authors[0]
|
||||
|
||||
|
||||
@query.field("loadAuthorsBy")
|
||||
async def load_authors_by(_, info, by, limit, offset):
|
||||
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"):
|
||||
q = q.join(ShoutAuthor).join(ShoutTopic).join(Topic).where(Topic.slug == by["topic"])
|
||||
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)
|
@@ -1,383 +0,0 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from sqlalchemy import and_, asc, desc, select, text, func, case
|
||||
from sqlalchemy.orm import aliased
|
||||
|
||||
from auth.authenticate import login_required
|
||||
from auth.credentials import AuthCredentials
|
||||
from base.exceptions import OperationNotAllowed
|
||||
from base.orm import local_session
|
||||
from base.resolvers import mutation, query
|
||||
from orm.reaction import Reaction, ReactionKind
|
||||
from orm.shout import Shout, ShoutReactionsFollower
|
||||
from orm.user import User
|
||||
|
||||
|
||||
def add_reaction_stat_columns(q):
|
||||
aliased_reaction = aliased(Reaction)
|
||||
|
||||
q = q.outerjoin(aliased_reaction, Reaction.id == aliased_reaction.replyTo).add_columns(
|
||||
func.sum(
|
||||
aliased_reaction.id
|
||||
).label('reacted_stat'),
|
||||
func.sum(
|
||||
case(
|
||||
(aliased_reaction.body.is_not(None), 1),
|
||||
else_=0
|
||||
)
|
||||
).label('commented_stat'),
|
||||
func.sum(case(
|
||||
(aliased_reaction.kind == ReactionKind.AGREE, 1),
|
||||
(aliased_reaction.kind == ReactionKind.DISAGREE, -1),
|
||||
(aliased_reaction.kind == ReactionKind.PROOF, 1),
|
||||
(aliased_reaction.kind == ReactionKind.DISPROOF, -1),
|
||||
(aliased_reaction.kind == ReactionKind.ACCEPT, 1),
|
||||
(aliased_reaction.kind == ReactionKind.REJECT, -1),
|
||||
(aliased_reaction.kind == ReactionKind.LIKE, 1),
|
||||
(aliased_reaction.kind == ReactionKind.DISLIKE, -1),
|
||||
else_=0)
|
||||
).label('rating_stat'))
|
||||
|
||||
return q
|
||||
|
||||
|
||||
def reactions_follow(user_id, shout_id: int, 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 == user_id,
|
||||
ShoutReactionsFollower.shout == shout.id,
|
||||
)).first()
|
||||
)
|
||||
|
||||
if not following:
|
||||
following = ShoutReactionsFollower.create(
|
||||
follower=user_id,
|
||||
shout=shout.id,
|
||||
auto=auto
|
||||
)
|
||||
session.add(following)
|
||||
session.commit()
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
def reactions_unfollow(user_id: int, 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 == user_id,
|
||||
ShoutReactionsFollower.shout == shout.id
|
||||
)).first()
|
||||
)
|
||||
|
||||
if following:
|
||||
session.delete(following)
|
||||
session.commit()
|
||||
return True
|
||||
except:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def is_published_author(session, user_id):
|
||||
''' checks if user has at least one publication '''
|
||||
return session.query(
|
||||
Shout
|
||||
).where(
|
||||
Shout.authors.contains(user_id)
|
||||
).filter(
|
||||
and_(
|
||||
Shout.publishedAt.is_not(None),
|
||||
Shout.deletedAt.is_(None)
|
||||
)
|
||||
).count() > 0
|
||||
|
||||
|
||||
def check_to_publish(session, user_id, reaction):
|
||||
''' set shout to public if publicated approvers amount > 4 '''
|
||||
if not reaction.replyTo and reaction.kind in [
|
||||
ReactionKind.ACCEPT,
|
||||
ReactionKind.LIKE,
|
||||
ReactionKind.PROOF
|
||||
]:
|
||||
if is_published_author(user_id):
|
||||
# now count how many approvers are voted already
|
||||
approvers_reactions = session.query(Reaction).where(Reaction.shout == reaction.shout).all()
|
||||
approvers = [user_id, ]
|
||||
for ar in approvers_reactions:
|
||||
a = ar.createdBy
|
||||
if is_published_author(session, a):
|
||||
approvers.append(a)
|
||||
if len(approvers) > 4:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def check_to_hide(session, user_id, reaction):
|
||||
''' hides any shout if 20% of reactions are negative '''
|
||||
if not reaction.replyTo and reaction.kind in [
|
||||
ReactionKind.REJECT,
|
||||
ReactionKind.DISLIKE,
|
||||
ReactionKind.DISPROOF
|
||||
]:
|
||||
# if is_published_author(user):
|
||||
approvers_reactions = session.query(Reaction).where(Reaction.shout == reaction.shout).all()
|
||||
rejects = 0
|
||||
for r in approvers_reactions:
|
||||
if r.kind in [
|
||||
ReactionKind.REJECT,
|
||||
ReactionKind.DISLIKE,
|
||||
ReactionKind.DISPROOF
|
||||
]:
|
||||
rejects += 1
|
||||
if len(approvers_reactions) / rejects < 5:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def set_published(session, shout_id):
|
||||
s = session.query(Shout).where(Shout.id == shout_id).first()
|
||||
s.publishedAt = datetime.now(tz=timezone.utc)
|
||||
s.visibility = text('public')
|
||||
session.add(s)
|
||||
session.commit()
|
||||
|
||||
|
||||
def set_hidden(session, shout_id):
|
||||
s = session.query(Shout).where(Shout.id == shout_id).first()
|
||||
s.visibility = text('community')
|
||||
session.add(s)
|
||||
session.commit()
|
||||
|
||||
|
||||
@mutation.field("createReaction")
|
||||
@login_required
|
||||
async def create_reaction(_, info, reaction):
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
reaction['createdBy'] = auth.user_id
|
||||
rdict = {}
|
||||
with local_session() as session:
|
||||
shout = session.query(Shout).where(Shout.id == reaction["shout"]).one()
|
||||
author = session.query(User).where(User.id == auth.user_id).one()
|
||||
|
||||
if reaction["kind"] in [
|
||||
ReactionKind.DISLIKE.name,
|
||||
ReactionKind.LIKE.name
|
||||
]:
|
||||
existing_reaction = session.query(Reaction).where(
|
||||
and_(
|
||||
Reaction.shout == reaction["shout"],
|
||||
Reaction.createdBy == auth.user_id,
|
||||
Reaction.kind == reaction["kind"],
|
||||
Reaction.replyTo == reaction.get("replyTo")
|
||||
)
|
||||
).first()
|
||||
|
||||
if existing_reaction is not None:
|
||||
raise OperationNotAllowed("You can't vote twice")
|
||||
|
||||
opposite_reaction_kind = ReactionKind.DISLIKE if reaction["kind"] == ReactionKind.LIKE.name else ReactionKind.LIKE
|
||||
opposite_reaction = session.query(Reaction).where(
|
||||
and_(
|
||||
Reaction.shout == reaction["shout"],
|
||||
Reaction.createdBy == auth.user_id,
|
||||
Reaction.kind == opposite_reaction_kind,
|
||||
Reaction.replyTo == reaction.get("replyTo")
|
||||
)
|
||||
).first()
|
||||
|
||||
if opposite_reaction is not None:
|
||||
session.delete(opposite_reaction)
|
||||
|
||||
r = Reaction.create(**reaction)
|
||||
|
||||
# Proposal accepting logix
|
||||
if r.replyTo is not None and \
|
||||
r.kind == ReactionKind.ACCEPT and \
|
||||
auth.user_id in shout.dict()['authors']:
|
||||
replied_reaction = session.query(Reaction).where(Reaction.id == r.replyTo).first()
|
||||
if replied_reaction and replied_reaction.kind == ReactionKind.PROPOSE:
|
||||
if replied_reaction.range:
|
||||
old_body = shout.body
|
||||
start, end = replied_reaction.range.split(':')
|
||||
start = int(start)
|
||||
end = int(end)
|
||||
new_body = old_body[:start] + replied_reaction.body + old_body[end:]
|
||||
shout.body = new_body
|
||||
# TODO: update git version control
|
||||
|
||||
session.add(r)
|
||||
session.commit()
|
||||
rdict = r.dict()
|
||||
rdict['shout'] = shout.dict()
|
||||
rdict['createdBy'] = author.dict()
|
||||
|
||||
# self-regulation mechanics
|
||||
|
||||
if check_to_hide(session, auth.user_id, r):
|
||||
set_hidden(session, r.shout)
|
||||
elif check_to_publish(session, auth.user_id, r):
|
||||
set_published(session, r.shout)
|
||||
|
||||
try:
|
||||
reactions_follow(auth.user_id, reaction["shout"], True)
|
||||
except Exception as e:
|
||||
print(f"[resolvers.reactions] error on reactions autofollowing: {e}")
|
||||
|
||||
rdict['stat'] = {
|
||||
"commented": 0,
|
||||
"reacted": 0,
|
||||
"rating": 0
|
||||
}
|
||||
return {"reaction": rdict}
|
||||
|
||||
|
||||
@mutation.field("updateReaction")
|
||||
@login_required
|
||||
async def update_reaction(_, info, id, reaction={}):
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
|
||||
with local_session() as session:
|
||||
user = session.query(User).where(User.id == auth.user_id).first()
|
||||
q = select(Reaction).filter(Reaction.id == id)
|
||||
q = add_reaction_stat_columns(q)
|
||||
q = q.group_by(Reaction.id)
|
||||
|
||||
[r, reacted_stat, commented_stat, rating_stat] = session.execute(q).unique().one()
|
||||
|
||||
if not r:
|
||||
return {"error": "invalid reaction id"}
|
||||
if r.createdBy != user.id:
|
||||
return {"error": "access denied"}
|
||||
|
||||
r.body = reaction["body"]
|
||||
r.updatedAt = datetime.now(tz=timezone.utc)
|
||||
if r.kind != reaction["kind"]:
|
||||
# NOTE: change mind detection can be here
|
||||
pass
|
||||
if reaction.get("range"):
|
||||
r.range = reaction.get("range")
|
||||
session.commit()
|
||||
r.stat = {
|
||||
"commented": commented_stat,
|
||||
"reacted": reacted_stat,
|
||||
"rating": rating_stat
|
||||
}
|
||||
|
||||
return {"reaction": r}
|
||||
|
||||
|
||||
@mutation.field("deleteReaction")
|
||||
@login_required
|
||||
async def delete_reaction(_, info, id):
|
||||
auth: AuthCredentials = info.context["request"].auth
|
||||
|
||||
with local_session() as session:
|
||||
r = session.query(Reaction).filter(Reaction.id == id).first()
|
||||
if not r:
|
||||
return {"error": "invalid reaction id"}
|
||||
if r.createdBy != auth.user_id:
|
||||
return {"error": "access denied"}
|
||||
|
||||
if r.kind in [
|
||||
ReactionKind.LIKE,
|
||||
ReactionKind.DISLIKE
|
||||
]:
|
||||
session.delete(r)
|
||||
else:
|
||||
r.deletedAt = datetime.now(tz=timezone.utc)
|
||||
session.commit()
|
||||
return {
|
||||
"reaction": r
|
||||
}
|
||||
|
||||
|
||||
@query.field("loadReactionsBy")
|
||||
async def load_reactions_by(_, _info, by, limit=50, offset=0):
|
||||
"""
|
||||
:param by: {
|
||||
:shout - filter by slug
|
||||
:shouts - filer by shout slug list
|
||||
:createdBy - to filter by author
|
||||
:topic - to filter by topic
|
||||
:search - to search by reactions' body
|
||||
:comment - true if body.length > 0
|
||||
:days - a number of days ago
|
||||
:sort - a fieldname to sort desc by default
|
||||
}
|
||||
:param limit: int amount of shouts
|
||||
:param offset: int offset in this order
|
||||
:return: Reaction[]
|
||||
"""
|
||||
|
||||
q = select(
|
||||
Reaction, User, Shout
|
||||
).join(
|
||||
User, Reaction.createdBy == User.id
|
||||
).join(
|
||||
Shout, Reaction.shout == Shout.id
|
||||
)
|
||||
|
||||
if by.get("shout"):
|
||||
q = q.filter(Shout.slug == by["shout"])
|
||||
elif by.get("shouts"):
|
||||
q = q.filter(Shout.slug.in_(by["shouts"]))
|
||||
|
||||
if by.get("createdBy"):
|
||||
q = q.filter(User.slug == by.get("createdBy"))
|
||||
|
||||
if by.get("topic"):
|
||||
# TODO: check
|
||||
q = q.filter(Shout.topics.contains(by["topic"]))
|
||||
|
||||
if by.get("comment"):
|
||||
q = q.filter(func.length(Reaction.body) > 0)
|
||||
|
||||
if len(by.get('search', '')) > 2:
|
||||
q = q.filter(Reaction.body.ilike(f'%{by["body"]}%'))
|
||||
|
||||
if by.get("days"):
|
||||
after = datetime.now(tz=timezone.utc) - timedelta(days=int(by["days"]) or 30)
|
||||
q = q.filter(Reaction.createdAt > after)
|
||||
|
||||
order_way = asc if by.get("sort", "").startswith("-") else desc
|
||||
order_field = by.get("sort", "").replace('-', '') or Reaction.createdAt
|
||||
|
||||
q = q.group_by(
|
||||
Reaction.id, User.id, Shout.id
|
||||
).order_by(
|
||||
order_way(order_field)
|
||||
)
|
||||
|
||||
q = add_reaction_stat_columns(q)
|
||||
|
||||
q = q.where(Reaction.deletedAt.is_(None))
|
||||
q = q.limit(limit).offset(offset)
|
||||
reactions = []
|
||||
|
||||
with local_session() as session:
|
||||
for [reaction, user, shout, reacted_stat, commented_stat, rating_stat] in session.execute(q):
|
||||
reaction.createdBy = user
|
||||
reaction.shout = shout
|
||||
reaction.stat = {
|
||||
"rating": rating_stat,
|
||||
"commented": commented_stat,
|
||||
"reacted": reacted_stat
|
||||
}
|
||||
|
||||
reaction.kind = reaction.kind.name
|
||||
|
||||
reactions.append(reaction)
|
||||
|
||||
# ?
|
||||
if by.get("stat"):
|
||||
reactions.sort(lambda r: r.stat.get(by["stat"]) or r.createdAt)
|
||||
|
||||
return reactions
|
@@ -1,165 +0,0 @@
|
||||
from sqlalchemy import and_, select, distinct, func
|
||||
from sqlalchemy.orm import aliased
|
||||
|
||||
from auth.authenticate import login_required
|
||||
from base.orm import local_session
|
||||
from base.resolvers import mutation, query
|
||||
from orm.shout import ShoutTopic, ShoutAuthor
|
||||
from orm.topic import Topic, TopicFollower
|
||||
from orm import User
|
||||
|
||||
|
||||
def add_topic_stat_columns(q):
|
||||
aliased_shout_author = aliased(ShoutAuthor)
|
||||
aliased_topic_follower = aliased(TopicFollower)
|
||||
|
||||
q = q.outerjoin(ShoutTopic, Topic.id == ShoutTopic.topic).add_columns(
|
||||
func.count(distinct(ShoutTopic.shout)).label('shouts_stat')
|
||||
).outerjoin(aliased_shout_author, ShoutTopic.shout == aliased_shout_author.shout).add_columns(
|
||||
func.count(distinct(aliased_shout_author.user)).label('authors_stat')
|
||||
).outerjoin(aliased_topic_follower).add_columns(
|
||||
func.count(distinct(aliased_topic_follower.follower)).label('followers_stat')
|
||||
)
|
||||
|
||||
q = q.group_by(Topic.id)
|
||||
|
||||
return q
|
||||
|
||||
|
||||
def add_stat(topic, stat_columns):
|
||||
[shouts_stat, authors_stat, followers_stat] = stat_columns
|
||||
topic.stat = {
|
||||
"shouts": shouts_stat,
|
||||
"authors": authors_stat,
|
||||
"followers": followers_stat
|
||||
}
|
||||
|
||||
return topic
|
||||
|
||||
|
||||
def get_topics_from_query(q):
|
||||
topics = []
|
||||
with local_session() as session:
|
||||
for [topic, *stat_columns] in session.execute(q):
|
||||
topic = add_stat(topic, stat_columns)
|
||||
topics.append(topic)
|
||||
|
||||
return topics
|
||||
|
||||
|
||||
def followed_by_user(user_id):
|
||||
q = select(Topic)
|
||||
q = add_topic_stat_columns(q)
|
||||
q = q.join(TopicFollower).where(TopicFollower.follower == user_id)
|
||||
|
||||
return get_topics_from_query(q)
|
||||
|
||||
|
||||
@query.field("topicsAll")
|
||||
async def topics_all(_, _info):
|
||||
q = select(Topic)
|
||||
q = add_topic_stat_columns(q)
|
||||
|
||||
return get_topics_from_query(q)
|
||||
|
||||
|
||||
@query.field("topicsByCommunity")
|
||||
async def topics_by_community(_, info, community):
|
||||
q = select(Topic).where(Topic.community == community)
|
||||
q = add_topic_stat_columns(q)
|
||||
|
||||
return get_topics_from_query(q)
|
||||
|
||||
|
||||
@query.field("topicsByAuthor")
|
||||
async def topics_by_author(_, _info, author):
|
||||
q = select(Topic)
|
||||
q = add_topic_stat_columns(q)
|
||||
q = q.join(User).where(User.slug == author)
|
||||
|
||||
return get_topics_from_query(q)
|
||||
|
||||
|
||||
@query.field("getTopic")
|
||||
async def get_topic(_, _info, slug):
|
||||
q = select(Topic).where(Topic.slug == slug)
|
||||
q = add_topic_stat_columns(q)
|
||||
|
||||
topics = get_topics_from_query(q)
|
||||
return topics[0]
|
||||
|
||||
|
||||
@mutation.field("createTopic")
|
||||
@login_required
|
||||
async def create_topic(_, _info, inp):
|
||||
with local_session() as session:
|
||||
# TODO: check user permissions to create topic for exact community
|
||||
new_topic = Topic.create(**inp)
|
||||
session.add(new_topic)
|
||||
session.commit()
|
||||
|
||||
return {"topic": new_topic}
|
||||
|
||||
|
||||
@mutation.field("updateTopic")
|
||||
@login_required
|
||||
async def update_topic(_, _info, inp):
|
||||
slug = inp["slug"]
|
||||
with local_session() as session:
|
||||
topic = session.query(Topic).filter(Topic.slug == slug).first()
|
||||
if not topic:
|
||||
return {"error": "topic not found"}
|
||||
else:
|
||||
topic.update(**inp)
|
||||
session.commit()
|
||||
|
||||
return {"topic": topic}
|
||||
|
||||
|
||||
def topic_follow(user_id, slug):
|
||||
try:
|
||||
with local_session() as session:
|
||||
topic = session.query(Topic).where(Topic.slug == slug).one()
|
||||
|
||||
following = TopicFollower.create(topic=topic.id, follower=user_id)
|
||||
session.add(following)
|
||||
session.commit()
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
def topic_unfollow(user_id, slug):
|
||||
try:
|
||||
with local_session() as session:
|
||||
sub = (
|
||||
session.query(TopicFollower).join(Topic).filter(
|
||||
and_(
|
||||
TopicFollower.follower == user_id,
|
||||
Topic.slug == slug
|
||||
)
|
||||
).first()
|
||||
)
|
||||
if sub:
|
||||
session.delete(sub)
|
||||
session.commit()
|
||||
return True
|
||||
except:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
@query.field("topicsRandom")
|
||||
async def topics_random(_, info, amount=12):
|
||||
q = select(Topic)
|
||||
q = q.join(ShoutTopic)
|
||||
q = q.group_by(Topic.id)
|
||||
q = q.having(func.count(distinct(ShoutTopic.shout)) > 2)
|
||||
q = q.order_by(func.random()).limit(amount)
|
||||
|
||||
topics = []
|
||||
with local_session() as session:
|
||||
for [topic] in session.execute(q):
|
||||
topics.append(topic)
|
||||
|
||||
return topics
|
Reference in New Issue
Block a user