core/resolvers/zine/reactions.py

283 lines
8.8 KiB
Python
Raw Normal View History

2022-11-23 14:09:35 +00:00
from datetime import datetime, timedelta, timezone
2022-11-23 11:30:44 +00:00
from sqlalchemy import and_, asc, desc, select, text, func
2022-11-23 02:05:34 +00:00
from sqlalchemy.orm import aliased
2022-11-16 06:35:51 +00:00
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
2022-11-13 15:24:29 +00:00
from orm.reaction import Reaction, ReactionKind
from orm.shout import Shout, ShoutReactionsFollower
from orm.user import User
2022-11-28 08:47:39 +00:00
# from services.stat.reacted import ReactedStorage
from resolvers.zine.load import calc_reactions
2022-09-03 10:50:14 +00:00
2022-09-22 10:31:44 +00:00
def reactions_follow(user: User, slug: str, auto=False):
with local_session() as session:
2022-09-18 14:29:21 +00:00
following = (
2022-11-23 11:30:44 +00:00
session.query(ShoutReactionsFollower).where(and_(
2022-09-03 10:50:14 +00:00
ShoutReactionsFollower.follower == user.slug,
2022-09-18 14:29:21 +00:00
ShoutReactionsFollower.shout == slug
2022-11-23 11:30:44 +00:00
)).first()
2022-09-03 10:50:14 +00:00
)
2022-09-18 14:29:21 +00:00
if not following:
following = ShoutReactionsFollower.create(
follower=user.slug,
shout=slug,
auto=auto
)
session.add(following)
session.commit()
def reactions_unfollow(user, slug):
with local_session() as session:
2022-09-03 10:50:14 +00:00
following = (
2022-11-23 11:30:44 +00:00
session.query(ShoutReactionsFollower).where(and_(
2022-09-03 10:50:14 +00:00
ShoutReactionsFollower.follower == user.slug,
2022-09-22 10:31:44 +00:00
ShoutReactionsFollower.shout == slug
2022-11-23 11:30:44 +00:00
)).first()
2022-09-03 10:50:14 +00:00
)
2022-09-18 14:29:21 +00:00
if following:
session.delete(following)
2022-09-18 14:29:21 +00:00
session.commit()
2022-11-13 15:24:29 +00:00
def is_published_author(session, userslug):
''' checks if user has at least one publication '''
return session.query(
Shout
).where(
Shout.authors.contains(userslug)
).filter(
and_(
Shout.publishedAt.is_not(None),
Shout.deletedAt.is_(None)
)
).count() > 0
def check_to_publish(session, user, 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):
# now count how many approvers are voted already
approvers_reactions = session.query(Reaction).where(Reaction.shout == reaction.shout).all()
approvers = [user.slug, ]
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, reaction):
''' hides any shout if 20% of reactions are negative '''
if not reaction.replyTo and reaction.kind in [
ReactionKind.DECLINE,
ReactionKind.UNLIKE,
ReactionKind.UNPROOF
]:
# if is_published_author(user):
approvers_reactions = session.query(Reaction).where(Reaction.shout == reaction.shout).all()
declines = 0
for r in approvers_reactions:
if r.kind in [
ReactionKind.DECLINE,
ReactionKind.UNLIKE,
ReactionKind.UNPROOF
]:
declines += 1
if len(approvers_reactions) / declines < 5:
return True
return False
def set_published(session, slug, publisher):
s = session.query(Shout).where(Shout.slug == slug).first()
2022-11-23 14:09:35 +00:00
s.publishedAt = datetime.now(tz=timezone.utc)
2022-11-13 15:24:29 +00:00
s.publishedBy = publisher
2022-11-15 16:49:38 +00:00
s.visibility = text('public')
2022-11-13 15:24:29 +00:00
session.add(s)
session.commit()
def set_hidden(session, slug):
s = session.query(Shout).where(Shout.slug == slug).first()
2022-11-15 16:49:38 +00:00
s.visibility = text('authors')
s.publishedAt = None # TODO: discuss
s.publishedBy = None # TODO: store changes history in git
2022-11-13 15:24:29 +00:00
session.add(s)
session.commit()
@mutation.field("createReaction")
@login_required
async def create_reaction(_, info, inp):
user = info.context["request"].user
2022-09-01 10:16:22 +00:00
2022-10-14 09:25:45 +00:00
with local_session() as session:
reaction = Reaction.create(**inp)
session.add(reaction)
session.commit()
2022-11-13 15:24:29 +00:00
# self-regulation mechanics
if check_to_hide(session, user, reaction):
set_hidden(session, reaction.shout)
elif check_to_publish(session, user, reaction):
set_published(session, reaction.shout, reaction.createdBy)
2022-11-28 08:47:39 +00:00
# ReactedStorage.react(reaction)
try:
2022-09-03 10:50:14 +00:00
reactions_follow(user, inp["shout"], True)
except Exception as e:
print(f"[resolvers.reactions] error on reactions autofollowing: {e}")
2022-11-28 08:47:39 +00:00
reaction.stat = {
"commented": 0,
"reacted": 0,
"rating": 0
}
return {"reaction": reaction}
@mutation.field("updateReaction")
@login_required
async def update_reaction(_, info, inp):
auth = info.context["request"].auth
user_id = auth.user_id
with local_session() as session:
2022-09-22 10:31:44 +00:00
user = session.query(User).where(User.id == user_id).first()
2022-11-28 08:47:39 +00:00
q = select(Reaction).filter(Reaction.id == inp.id)
q = calc_reactions(q)
[reaction, rating, commented, reacted] = session.execute(q).unique().one()
if not reaction:
return {"error": "invalid reaction id"}
if reaction.createdBy != user.slug:
return {"error": "access denied"}
2022-11-28 08:47:39 +00:00
2022-09-03 10:50:14 +00:00
reaction.body = inp["body"]
2022-11-23 14:09:35 +00:00
reaction.updatedAt = datetime.now(tz=timezone.utc)
2022-09-03 10:50:14 +00:00
if reaction.kind != inp["kind"]:
2022-08-11 11:22:10 +00:00
# NOTE: change mind detection can be here
pass
2022-09-03 10:50:14 +00:00
if inp.get("range"):
reaction.range = inp.get("range")
session.commit()
2022-11-28 08:47:39 +00:00
reaction.stat = {
"commented": commented,
"reacted": reacted,
"rating": rating
}
2022-09-19 13:50:43 +00:00
return {"reaction": reaction}
@mutation.field("deleteReaction")
@login_required
2022-09-14 13:10:38 +00:00
async def delete_reaction(_, info, rid):
auth = info.context["request"].auth
user_id = auth.user_id
with local_session() as session:
2022-09-22 10:31:44 +00:00
user = session.query(User).where(User.id == user_id).first()
2022-09-14 13:10:38 +00:00
reaction = session.query(Reaction).filter(Reaction.id == rid).first()
if not reaction:
return {"error": "invalid reaction id"}
if reaction.createdBy != user.slug:
return {"error": "access denied"}
2022-11-23 14:09:35 +00:00
reaction.deletedAt = datetime.now(tz=timezone.utc)
session.commit()
return {}
2022-11-23 11:30:44 +00:00
2022-11-23 02:05:34 +00:00
def map_result_item(result_item):
2022-11-28 06:00:54 +00:00
[user, shout, reaction] = result_item
2022-11-28 08:47:39 +00:00
print(reaction)
2022-11-23 02:05:34 +00:00
reaction.createdBy = user
2022-11-27 08:19:38 +00:00
reaction.shout = shout
2022-11-28 06:00:54 +00:00
reaction.replyTo = reaction
2022-11-23 02:05:34 +00:00
return reaction
@query.field("loadReactionsBy")
async def load_reactions_by(_, _info, by, limit=50, offset=0):
"""
:param by: {
:shout - filter by slug
:shouts - filer by shouts luglist
: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[]
"""
CreatedByUser = aliased(User)
2022-11-27 08:19:38 +00:00
ReactedShout = aliased(Shout)
2022-11-23 02:05:34 +00:00
q = select(
2022-11-27 08:19:38 +00:00
Reaction, CreatedByUser, ReactedShout
).join(
CreatedByUser, Reaction.createdBy == CreatedByUser.slug
).join(
ReactedShout, Reaction.shout == ReactedShout.slug
)
2022-09-03 10:50:14 +00:00
2022-11-22 07:29:54 +00:00
if by.get("shout"):
2022-11-22 18:48:28 +00:00
q = q.filter(Reaction.shout == by["shout"])
2022-11-22 15:32:58 +00:00
elif by.get("shouts"):
2022-11-22 18:48:28 +00:00
q = q.filter(Reaction.shout.in_(by["shouts"]))
2022-11-22 15:32:58 +00:00
if by.get("createdBy"):
q = q.filter(Reaction.createdBy == by.get("createdBy"))
if by.get("topic"):
q = q.filter(Shout.topics.contains(by["topic"]))
2022-11-22 18:48:28 +00:00
if by.get("comment"):
q = q.filter(func.length(Reaction.body) > 0)
if by.get('search', 0) > 2:
q = q.filter(Reaction.body.ilike(f'%{by["body"]}%'))
2022-11-22 15:32:58 +00:00
if by.get("days"):
2022-11-23 14:09:35 +00:00
after = datetime.now(tz=timezone.utc) - timedelta(days=int(by["days"]) or 30)
2022-11-22 18:48:28 +00:00
q = q.filter(Reaction.createdAt > after)
2022-11-22 15:32:58 +00:00
order_way = asc if by.get("sort", "").startswith("-") else desc
order_field = by.get("sort") or Reaction.createdAt
q = q.group_by(
2022-11-27 08:19:38 +00:00
Reaction.id, CreatedByUser.id, ReactedShout.id
2022-11-22 15:32:58 +00:00
).order_by(
order_way(order_field)
)
2022-11-28 08:47:39 +00:00
q = calc_reactions(q)
2022-11-23 02:05:34 +00:00
q = q.where(Reaction.deletedAt.is_(None))
2022-11-22 07:29:54 +00:00
q = q.limit(limit).offset(offset)
2022-11-28 08:47:39 +00:00
reactions = []
with local_session() as session:
2022-11-28 08:47:39 +00:00
for [
[reaction, rating, commented, reacted], shout, reply
] in list(map(map_result_item, session.execute(q))):
reaction.shout = shout
reaction.replyTo = reply
reaction.stat = {
"rating": rating,
"commented": commented,
"reacted": reacted
}
reactions.append(reaction)
if by.get("stat"):
reactions.sort(lambda r: r.stat.get(by["stat"]) or r.createdAt)
2022-11-23 02:05:34 +00:00
return reactions