Merge branch 'prealpha' into main

This commit is contained in:
2022-12-02 11:51:53 +03:00
19 changed files with 221 additions and 210 deletions

View File

@@ -1,4 +1,5 @@
from auth.authenticate import login_required
from auth.credentials import AuthCredentials
from base.resolvers import mutation
# from resolvers.community import community_follow, community_unfollow
from resolvers.zine.profile import author_follow, author_unfollow
@@ -9,17 +10,18 @@ from resolvers.zine.topics import topic_follow, topic_unfollow
@mutation.field("follow")
@login_required
async def follow(_, info, what, slug):
user = info.context["request"].user
auth: AuthCredentials = info.context["request"].auth
try:
if what == "AUTHOR":
author_follow(user, slug)
author_follow(auth.user_id, slug)
elif what == "TOPIC":
topic_follow(user, slug)
topic_follow(auth.user_id, slug)
elif what == "COMMUNITY":
# community_follow(user, slug)
pass
elif what == "REACTIONS":
reactions_follow(user, slug)
reactions_follow(auth.user_id, slug)
except Exception as e:
return {"error": str(e)}
@@ -29,18 +31,18 @@ async def follow(_, info, what, slug):
@mutation.field("unfollow")
@login_required
async def unfollow(_, info, what, slug):
user = info.context["request"].user
auth: AuthCredentials = info.context["request"].auth
try:
if what == "AUTHOR":
author_unfollow(user, slug)
author_unfollow(auth.user_id, slug)
elif what == "TOPIC":
topic_unfollow(user, slug)
topic_unfollow(auth.user_id, slug)
elif what == "COMMUNITY":
# community_unfollow(user, slug)
pass
elif what == "REACTIONS":
reactions_unfollow(user, slug)
reactions_unfollow(auth.user_id, slug)
except Exception as e:
return {"error": str(e)}

View File

@@ -1,6 +1,8 @@
from datetime import datetime, timedelta, timezone
from sqlalchemy.orm import joinedload, aliased
from sqlalchemy.sql.expression import desc, asc, select, func
from auth.credentials import AuthCredentials
from base.orm import local_session
from base.resolvers import query
from orm import ViewedEntry
@@ -15,10 +17,10 @@ def add_stat_columns(q):
return add_common_stat_columns(q)
def apply_filters(q, filters, user=None):
def apply_filters(q, filters, user_id=None):
if filters.get("reacted") and user:
q.join(Reaction, Reaction.createdBy == user.id)
if filters.get("reacted") and user_id:
q.join(Reaction, Reaction.createdBy == user_id)
v = filters.get("visibility")
if v == "public":
@@ -105,17 +107,15 @@ async def load_shouts_by(_, info, options):
q = add_stat_columns(q)
user = info.context["request"].user
q = apply_filters(q, options.get("filters", {}), user)
auth: AuthCredentials = info.context["request"].auth
q = apply_filters(q, options.get("filters", {}), auth.user_id)
order_by = options.get("order_by", Shout.createdAt)
if order_by == 'reacted':
aliased_reaction = aliased(Reaction)
q.outerjoin(aliased_reaction).add_columns(func.max(aliased_reaction.createdAt).label('reacted'))
order_by_desc = options.get('order_by_desc', True)
query_order_by = desc(order_by) if order_by_desc else asc(order_by)
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)

View File

@@ -4,6 +4,7 @@ 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
@@ -40,11 +41,10 @@ def add_author_stat_columns(q):
# func.sum(user_rating_aliased.value).label('rating_stat')
# )
# 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')
)
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')
# )
q = q.group_by(User.id)
@@ -74,25 +74,25 @@ def get_authors_from_query(q):
return authors
async def user_subscriptions(slug: str):
async def user_subscriptions(user_id: int):
return {
"unread": await get_total_unread_counter(slug), # unread inbox messages counter
"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
"reactions": await followed_reactions(slug)
"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, slug) -> List[Topic]:
return await followed_reactions(slug)
# @login_required
async def followed_discussions(_, info, user_id) -> List[Topic]:
return await followed_reactions(user_id)
async def followed_reactions(slug):
async def followed_reactions(user_id):
with local_session() as session:
user = session.query(User).where(User.slug == slug).first()
user = session.query(User).where(User.id == user_id).first()
return session.query(
Reaction.shout
).where(
@@ -104,31 +104,26 @@ async def followed_reactions(slug):
@query.field("userFollowedTopics")
@login_required
async def get_followed_topics(_, info, slug) -> List[Topic]:
return await followed_topics(slug)
async def get_followed_topics(_, info, user_id) -> List[Topic]:
return await followed_topics(user_id)
async def followed_topics(slug):
return followed_by_user(slug)
async def followed_topics(user_id):
return followed_by_user(user_id)
@query.field("userFollowedAuthors")
async def get_followed_authors(_, _info, slug) -> List[User]:
return await followed_authors(slug)
async def get_followed_authors(_, _info, user_id: int) -> List[User]:
return await followed_authors(user_id)
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)
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
)
return get_authors_from_query(q)
@query.field("userFollowers")
@@ -157,25 +152,16 @@ async def get_user_roles(slug):
.all()
)
return roles
return [] # roles
@mutation.field("updateProfile")
@login_required
async def update_profile(_, info, profile):
print('[zine] update_profile')
print(profile)
auth = info.context["request"].auth
user_id = auth.user_id
with local_session() as session:
session.query(User).filter(User.id == user_id).update({
"name": profile['name'],
"slug": profile['slug'],
"bio": profile['bio'],
"userpic": profile['userpic'],
"about": profile['about'],
"links": profile['links']
})
session.query(User).filter(User.id == user_id).update(profile)
session.commit()
return {}
@@ -183,11 +169,12 @@ async def update_profile(_, info, profile):
@mutation.field("rateUser")
@login_required
async def rate_user(_, info, rated_userslug, value):
user = info.context["request"].user
auth: AuthCredentials = info.context["request"].auth
with local_session() as session:
rating = (
session.query(UserRating)
.filter(and_(UserRating.rater == user.slug, UserRating.user == rated_userslug))
.filter(and_(UserRating.rater == auth.user_id, UserRating.user == rated_userslug))
.first()
)
if rating:
@@ -195,30 +182,30 @@ async def rate_user(_, info, rated_userslug, value):
session.commit()
return {}
try:
UserRating.create(rater=user.slug, user=rated_userslug, value=value)
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, slug):
def author_follow(user_id, slug):
with local_session() as session:
author = session.query(User).where(User.slug == slug).one()
af = AuthorFollower.create(follower=user.id, author=author.id)
af = AuthorFollower.create(follower=user_id, author=author.id)
session.add(af)
session.commit()
# for mutation.field("unfollow")
def author_unfollow(user, slug):
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
AuthorFollower.follower == user_id, User.slug == slug
)
).first()
)

View File

@@ -2,6 +2,7 @@ from datetime import datetime, timedelta, timezone
from sqlalchemy import and_, asc, desc, select, text, func
from sqlalchemy.orm import aliased
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, ReactionKind
@@ -14,20 +15,20 @@ def add_reaction_stat_columns(q):
return add_common_stat_columns(q)
def reactions_follow(user: User, slug: str, auto=False):
def reactions_follow(user_id, slug: str, auto=False):
with local_session() as session:
shout = session.query(Shout).where(Shout.slug == slug).one()
following = (
session.query(ShoutReactionsFollower).where(and_(
ShoutReactionsFollower.follower == user.id,
ShoutReactionsFollower.follower == user_id,
ShoutReactionsFollower.shout == shout.id,
)).first()
)
if not following:
following = ShoutReactionsFollower.create(
follower=user.id,
follower=user_id,
shout=shout.id,
auto=auto
)
@@ -35,13 +36,13 @@ def reactions_follow(user: User, slug: str, auto=False):
session.commit()
def reactions_unfollow(user, slug):
def reactions_unfollow(user_id, slug):
with local_session() as session:
shout = session.query(Shout).where(Shout.slug == slug).one()
following = (
session.query(ShoutReactionsFollower).where(and_(
ShoutReactionsFollower.follower == user.id,
ShoutReactionsFollower.follower == user_id,
ShoutReactionsFollower.shout == shout.id
)).first()
)
@@ -51,12 +52,12 @@ def reactions_unfollow(user, slug):
session.commit()
def is_published_author(session, userslug):
def is_published_author(session, user_id):
''' checks if user has at least one publication '''
return session.query(
Shout
).where(
Shout.authors.contains(userslug)
Shout.authors.contains(user_id)
).filter(
and_(
Shout.publishedAt.is_not(None),
@@ -65,17 +66,17 @@ def is_published_author(session, userslug):
).count() > 0
def check_to_publish(session, user, reaction):
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):
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.slug, ]
approvers = [user_id, ]
for ar in approvers_reactions:
a = ar.createdBy
if is_published_author(session, a):
@@ -85,7 +86,7 @@ def check_to_publish(session, user, reaction):
return False
def check_to_hide(session, user, reaction):
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.DECLINE,
@@ -107,8 +108,8 @@ def check_to_hide(session, user, reaction):
return False
def set_published(session, slug, publisher):
s = session.query(Shout).where(Shout.slug == slug).first()
def set_published(session, shout_id, publisher):
s = session.query(Shout).where(Shout.id == shout_id).first()
s.publishedAt = datetime.now(tz=timezone.utc)
s.publishedBy = publisher
s.visibility = text('public')
@@ -116,8 +117,8 @@ def set_published(session, slug, publisher):
session.commit()
def set_hidden(session, slug):
s = session.query(Shout).where(Shout.slug == slug).first()
def set_hidden(session, shout_id):
s = session.query(Shout).where(Shout.id == shout_id).first()
s.visibility = text('authors')
s.publishedAt = None # TODO: discuss
s.publishedBy = None # TODO: store changes history in git
@@ -128,7 +129,7 @@ def set_hidden(session, slug):
@mutation.field("createReaction")
@login_required
async def create_reaction(_, info, inp):
user = info.context["request"].user
auth: AuthCredentials = info.context["request"].auth
with local_session() as session:
reaction = Reaction.create(**inp)
@@ -137,13 +138,13 @@ async def create_reaction(_, info, inp):
# self-regulation mechanics
if check_to_hide(session, user, reaction):
if check_to_hide(session, auth.user_id, reaction):
set_hidden(session, reaction.shout)
elif check_to_publish(session, user, reaction):
elif check_to_publish(session, auth.user_id, reaction):
set_published(session, reaction.shout, reaction.createdBy)
try:
reactions_follow(user, inp["shout"], True)
reactions_follow(auth.user_id, inp["shout"], True)
except Exception as e:
print(f"[resolvers.reactions] error on reactions autofollowing: {e}")
@@ -158,11 +159,10 @@ async def create_reaction(_, info, inp):
@mutation.field("updateReaction")
@login_required
async def update_reaction(_, info, inp):
auth = info.context["request"].auth
user_id = auth.user_id
auth: AuthCredentials = info.context["request"].auth
with local_session() as session:
user = session.query(User).where(User.id == user_id).first()
user = session.query(User).where(User.id == auth.user_id).first()
q = select(Reaction).filter(Reaction.id == inp.id)
q = add_reaction_stat_columns(q)
@@ -193,10 +193,10 @@ async def update_reaction(_, info, inp):
@mutation.field("deleteReaction")
@login_required
async def delete_reaction(_, info, rid):
auth = info.context["request"].auth
user_id = auth.user_id
auth: AuthCredentials = info.context["request"].auth
with local_session() as session:
user = session.query(User).where(User.id == user_id).first()
user = session.query(User).where(User.id == auth.user_id).first()
reaction = session.query(Reaction).filter(Reaction.id == rid).first()
if not reaction:
return {"error": "invalid reaction id"}

View File

@@ -1,4 +1,6 @@
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
@@ -8,16 +10,20 @@ from orm import Shout, User
def add_topic_stat_columns(q):
q = q.outerjoin(ShoutTopic, Topic.id == ShoutTopic.topic).add_columns(
func.count(distinct(ShoutTopic.shout)).label('shouts_stat')
).outerjoin(ShoutAuthor, ShoutTopic.shout == ShoutAuthor.shout).add_columns(
func.count(distinct(ShoutAuthor.user)).label('authors_stat')
).outerjoin(TopicFollower,
aliased_shout_topic = aliased(ShoutTopic)
aliased_shout_author = aliased(ShoutAuthor)
aliased_topic_follower = aliased(TopicFollower)
q = q.outerjoin(aliased_shout_topic, Topic.id == aliased_shout_topic.topic).add_columns(
func.count(distinct(aliased_shout_topic.shout)).label('shouts_stat')
).outerjoin(aliased_shout_author, aliased_shout_topic.shout == aliased_shout_author.shout).add_columns(
func.count(distinct(aliased_shout_author.user)).label('authors_stat')
).outerjoin(aliased_topic_follower,
and_(
TopicFollower.topic == Topic.id,
TopicFollower.follower == ShoutAuthor.id
aliased_topic_follower.topic == Topic.id,
aliased_topic_follower.follower == aliased_shout_author.id
)).add_columns(
func.count(distinct(TopicFollower.follower)).label('followers_stat')
func.count(distinct(aliased_topic_follower.follower)).label('followers_stat')
)
q = q.group_by(Topic.id)
@@ -46,10 +52,10 @@ def get_topics_from_query(q):
return topics
def followed_by_user(user_slug):
def followed_by_user(user_id):
q = select(Topic)
q = add_topic_stat_columns(q)
q = q.join(User).where(User.slug == user_slug)
q = q.join(TopicFollower).where(TopicFollower.follower == user_id)
return get_topics_from_query(q)
@@ -115,21 +121,21 @@ async def update_topic(_, _info, inp):
return {"topic": topic}
async def topic_follow(user, slug):
def topic_follow(user_id, slug):
with local_session() as session:
topic = session.query(Topic).where(Topic.slug == slug).one()
following = TopicFollower.create(topic=topic.id, follower=user.id)
following = TopicFollower.create(topic=topic.id, follower=user_id)
session.add(following)
session.commit()
async def topic_unfollow(user, slug):
def topic_unfollow(user_id, slug):
with local_session() as session:
sub = (
session.query(TopicFollower).join(Topic).filter(
and_(
TopicFollower.follower == user.id,
TopicFollower.follower == user_id,
Topic.slug == slug
)
).first()
@@ -145,7 +151,7 @@ async def topic_unfollow(user, slug):
async def topics_random(_, info, amount=12):
q = select(Topic)
q = add_topic_stat_columns(q)
q = q.join(Shout, ShoutTopic.shout == Shout.id).group_by(Topic.id).having(func.count(Shout.id) > 2)
q = q.join(ShoutTopic).join(Shout, ShoutTopic.shout == Shout.id).group_by(Topic.id).having(func.count(Shout.id) > 2)
q = q.order_by(func.random()).limit(amount)
return get_topics_from_query(q)