core/resolvers/reaction.py

416 lines
13 KiB
Python
Raw Normal View History

2023-11-03 10:10:22 +00:00
import time
2023-01-17 21:07:44 +00:00
from sqlalchemy import and_, asc, desc, select, text, func, case
from sqlalchemy.orm import aliased
2023-10-25 18:33:53 +00:00
from services.notify import notify_reaction
2023-10-23 14:47:11 +00:00
from services.auth import login_required
from base.exceptions import OperationNotAllowed
2023-10-23 14:51:13 +00:00
from services.db import local_session
from services.schema import mutation, query
2022-11-13 15:24:29 +00:00
from orm.reaction import Reaction, ReactionKind
from orm.shout import Shout, ShoutReactionsFollower
2023-10-23 14:47:11 +00:00
from orm.author import Author
2022-09-19 13:50:43 +00:00
def add_reaction_stat_columns(q):
2023-01-17 21:07:44 +00:00
aliased_reaction = aliased(Reaction)
2023-10-05 18:46:18 +00:00
q = q.outerjoin(
2023-11-03 10:10:22 +00:00
aliased_reaction, Reaction.id == aliased_reaction.reply_to
2023-10-05 18:46:18 +00:00
).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"
),
2023-01-17 21:07:44 +00:00
func.sum(
case(
2023-10-05 18:46:18 +00:00
(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,
2023-01-17 21:07:44 +00:00
)
2023-10-05 18:46:18 +00:00
).label("rating_stat"),
)
2023-01-17 21:07:44 +00:00
return q
2023-10-23 14:47:11 +00:00
def reactions_follow(author_id, shout_id: int, auto=False):
2023-02-20 17:38:20 +00:00
try:
with local_session() as session:
shout = session.query(Shout).where(Shout.id == shout_id).one()
2022-11-29 12:36:46 +00:00
2023-02-20 17:38:20 +00:00
following = (
2023-10-05 18:46:18 +00:00
session.query(ShoutReactionsFollower)
.where(
and_(
2023-10-23 14:47:11 +00:00
ShoutReactionsFollower.follower == author_id,
2023-10-05 18:46:18 +00:00
ShoutReactionsFollower.shout == shout.id,
)
)
.first()
2022-09-18 14:29:21 +00:00
)
2023-02-20 17:38:20 +00:00
if not following:
following = ShoutReactionsFollower.create(
2023-10-23 14:47:11 +00:00
follower=author_id, shout=shout.id, auto=auto
2023-02-20 17:38:20 +00:00
)
session.add(following)
session.commit()
return True
2023-10-16 15:18:29 +00:00
except Exception:
2023-02-20 17:38:20 +00:00
return False
2023-10-23 14:47:11 +00:00
def reactions_unfollow(author_id: int, shout_id: int):
2023-02-20 17:38:20 +00:00
try:
with local_session() as session:
shout = session.query(Shout).where(Shout.id == shout_id).one()
2022-11-29 12:36:46 +00:00
2023-02-20 17:38:20 +00:00
following = (
2023-10-05 18:46:18 +00:00
session.query(ShoutReactionsFollower)
.where(
and_(
2023-10-23 14:47:11 +00:00
ShoutReactionsFollower.follower == author_id,
2023-10-05 18:46:18 +00:00
ShoutReactionsFollower.shout == shout.id,
)
)
.first()
2023-02-20 17:38:20 +00:00
)
2022-11-29 12:36:46 +00:00
2023-02-20 17:38:20 +00:00
if following:
session.delete(following)
session.commit()
return True
2023-10-16 15:18:29 +00:00
except Exception:
2023-02-20 17:38:20 +00:00
pass
return False
2023-10-23 14:47:11 +00:00
def is_published_author(session, author_id):
"""checks if author has at least one publication"""
2023-10-05 18:46:18 +00:00
return (
session.query(Shout)
2023-10-23 14:47:11 +00:00
.where(Shout.authors.contains(author_id))
2023-11-03 10:10:22 +00:00
.filter(and_(Shout.published_at.is_not(None), Shout.deleted_at.is_(None)))
2023-10-05 18:46:18 +00:00
.count()
> 0
)
2022-11-13 15:24:29 +00:00
2023-10-23 14:47:11 +00:00
def check_to_publish(session, author_id, reaction):
2023-10-05 18:46:18 +00:00
"""set shout to public if publicated approvers amount > 4"""
2023-11-03 10:10:22 +00:00
if not reaction.reply_to and reaction.kind in [
2022-11-13 15:24:29 +00:00
ReactionKind.ACCEPT,
ReactionKind.LIKE,
2023-10-05 18:46:18 +00:00
ReactionKind.PROOF,
2022-11-13 15:24:29 +00:00
]:
2023-10-23 14:47:11 +00:00
if is_published_author(author_id):
2022-11-13 15:24:29 +00:00
# now count how many approvers are voted already
2023-10-05 18:46:18 +00:00
approvers_reactions = (
session.query(Reaction).where(Reaction.shout == reaction.shout).all()
)
approvers = [
2023-10-23 14:47:11 +00:00
author_id,
2023-10-05 18:46:18 +00:00
]
2022-11-13 15:24:29 +00:00
for ar in approvers_reactions:
2023-11-03 10:10:22 +00:00
a = ar.created_by
2022-11-13 15:24:29 +00:00
if is_published_author(session, a):
approvers.append(a)
if len(approvers) > 4:
return True
return False
2023-10-23 14:47:11 +00:00
def check_to_hide(session, reaction):
2023-10-05 18:46:18 +00:00
"""hides any shout if 20% of reactions are negative"""
2023-11-03 10:10:22 +00:00
if not reaction.reply_to and reaction.kind in [
2022-12-23 16:37:17 +00:00
ReactionKind.REJECT,
ReactionKind.DISLIKE,
2023-10-05 18:46:18 +00:00
ReactionKind.DISPROOF,
2022-11-13 15:24:29 +00:00
]:
2023-10-23 14:47:11 +00:00
# if is_published_author(author_id):
2023-10-05 18:46:18 +00:00
approvers_reactions = (
session.query(Reaction).where(Reaction.shout == reaction.shout).all()
)
2022-12-23 16:37:17 +00:00
rejects = 0
2022-11-13 15:24:29 +00:00
for r in approvers_reactions:
if r.kind in [
2022-12-23 16:37:17 +00:00
ReactionKind.REJECT,
ReactionKind.DISLIKE,
2023-10-05 18:46:18 +00:00
ReactionKind.DISPROOF,
2022-11-13 15:24:29 +00:00
]:
2022-12-23 16:37:17 +00:00
rejects += 1
if len(approvers_reactions) / rejects < 5:
2022-11-13 15:24:29 +00:00
return True
return False
2023-03-27 14:46:14 +00:00
def set_published(session, shout_id):
2022-12-01 14:45:19 +00:00
s = session.query(Shout).where(Shout.id == shout_id).first()
2023-11-03 10:10:22 +00:00
s.published_at = int(time.time())
2023-10-05 18:46:18 +00:00
s.visibility = text("public")
2022-11-13 15:24:29 +00:00
session.add(s)
session.commit()
2022-12-01 14:45:19 +00:00
def set_hidden(session, shout_id):
s = session.query(Shout).where(Shout.id == shout_id).first()
2023-10-05 18:46:18 +00:00
s.visibility = text("community")
2022-11-13 15:24:29 +00:00
session.add(s)
session.commit()
@mutation.field("createReaction")
@login_required
2023-02-26 21:23:25 +00:00
async def create_reaction(_, info, reaction):
2023-10-23 14:47:11 +00:00
author_id = info.context["author_id"]
2022-10-14 09:25:45 +00:00
with local_session() as session:
2023-11-03 10:10:22 +00:00
reaction["created_by"] = author_id
2023-02-26 21:23:25 +00:00
shout = session.query(Shout).where(Shout.id == reaction["shout"]).one()
2023-01-17 19:56:48 +00:00
2023-10-05 18:46:18 +00:00
if reaction["kind"] in [ReactionKind.DISLIKE.name, ReactionKind.LIKE.name]:
existing_reaction = (
session.query(Reaction)
.where(
and_(
Reaction.shout == reaction["shout"],
2023-11-03 10:10:22 +00:00
Reaction.created_by == author_id,
2023-10-05 18:46:18 +00:00
Reaction.kind == reaction["kind"],
2023-11-03 10:10:22 +00:00
Reaction.reply_to == reaction.get("reply_to"),
2023-10-05 18:46:18 +00:00
)
2023-02-26 21:23:25 +00:00
)
2023-10-05 18:46:18 +00:00
.first()
)
2023-02-26 21:23:25 +00:00
if existing_reaction is not None:
raise OperationNotAllowed("You can't vote twice")
2023-10-05 18:46:18 +00:00
opposite_reaction_kind = (
ReactionKind.DISLIKE
if reaction["kind"] == ReactionKind.LIKE.name
else ReactionKind.LIKE
)
opposite_reaction = (
session.query(Reaction)
.where(
2023-02-26 21:23:25 +00:00
and_(
Reaction.shout == reaction["shout"],
2023-11-03 10:10:22 +00:00
Reaction.created_by == author_id,
2023-02-26 21:23:25 +00:00
Reaction.kind == opposite_reaction_kind,
2023-11-03 10:10:22 +00:00
Reaction.reply_to == reaction.get("reply_to"),
2023-02-26 21:23:25 +00:00
)
2023-10-05 18:46:18 +00:00
)
.first()
)
2023-02-26 21:23:25 +00:00
if opposite_reaction is not None:
session.delete(opposite_reaction)
r = Reaction.create(**reaction)
2023-01-17 19:56:48 +00:00
# Proposal accepting logix
2023-10-05 18:46:18 +00:00
if (
2023-11-03 10:10:22 +00:00
r.reply_to is not None
2023-10-05 18:46:18 +00:00
and r.kind == ReactionKind.ACCEPT
2023-10-23 14:47:11 +00:00
and author_id in shout.dict()["authors"]
2023-10-05 18:46:18 +00:00
):
replied_reaction = (
2023-11-03 10:10:22 +00:00
session.query(Reaction).where(Reaction.id == r.reply_to).first()
2023-10-05 18:46:18 +00:00
)
2023-01-17 19:56:48 +00:00
if replied_reaction and replied_reaction.kind == ReactionKind.PROPOSE:
if replied_reaction.range:
old_body = shout.body
2023-10-05 18:46:18 +00:00
start, end = replied_reaction.range.split(":")
2023-01-17 19:56:48 +00:00
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)
2022-10-14 09:25:45 +00:00
session.commit()
2023-02-17 15:31:49 +00:00
rdict = r.dict()
2023-10-05 18:46:18 +00:00
rdict["shout"] = shout.dict()
2023-10-23 14:47:11 +00:00
author = session.query(Author).where(Author.id == author_id).first()
2023-11-03 10:10:22 +00:00
rdict["created_by"] = author.dict()
2022-12-23 16:37:17 +00:00
2022-11-13 15:24:29 +00:00
# self-regulation mechanics
2023-10-23 14:47:11 +00:00
if check_to_hide(session, r):
set_hidden(session, r.shout)
2023-10-23 14:47:11 +00:00
elif check_to_publish(session, author_id, r):
2023-03-27 14:46:14 +00:00
set_published(session, r.shout)
2022-11-13 15:24:29 +00:00
2023-10-23 14:47:11 +00:00
try:
reactions_follow(author_id, reaction["shout"], True)
except Exception as e:
print(f"[resolvers.reactions] error on reactions auto following: {e}")
rdict["stat"] = {"commented": 0, "reacted": 0, "rating": 0}
2023-10-23 14:47:11 +00:00
# notification call
notify_reaction(rdict)
return {"reaction": rdict}
@mutation.field("updateReaction")
@login_required
2023-10-23 14:47:11 +00:00
async def update_reaction(_, info, rid, reaction={}):
author_id = info.context["author_id"]
with local_session() as session:
2023-10-23 14:47:11 +00:00
q = select(Reaction).filter(Reaction.id == rid)
2022-11-28 22:16:39 +00:00
q = add_reaction_stat_columns(q)
2023-02-06 13:15:47 +00:00
q = q.group_by(Reaction.id)
2022-11-28 08:47:39 +00:00
2023-10-05 18:46:18 +00:00
[r, reacted_stat, commented_stat, rating_stat] = (
session.execute(q).unique().one()
)
2022-11-28 08:47:39 +00:00
if not r:
return {"error": "invalid reaction id"}
2023-11-03 10:10:22 +00:00
if r.created_by != author_id:
return {"error": "access denied"}
2022-11-28 08:47:39 +00:00
r.body = reaction["body"]
2023-11-03 10:10:22 +00:00
r.updated_at = int(time.time())
if r.kind != reaction["kind"]:
2022-08-11 11:22:10 +00:00
# NOTE: change mind detection can be here
pass
if reaction.get("range"):
r.range = reaction.get("range")
session.commit()
r.stat = {
2022-11-28 22:16:39 +00:00
"commented": commented_stat,
"reacted": reacted_stat,
2023-10-05 18:46:18 +00:00
"rating": rating_stat,
2022-11-28 08:47:39 +00:00
}
2022-09-19 13:50:43 +00:00
2023-10-23 14:47:11 +00:00
notify_reaction(r.dict(), "update")
return {"reaction": r}
@mutation.field("deleteReaction")
@login_required
2023-10-23 14:47:11 +00:00
async def delete_reaction(_, info, rid):
author_id = info.context["author_id"]
with local_session() as session:
2023-10-23 14:47:11 +00:00
r = session.query(Reaction).filter(Reaction.id == rid).first()
if not r:
return {"error": "invalid reaction id"}
2023-11-03 10:10:22 +00:00
if r.created_by != author_id:
return {"error": "access denied"}
2023-02-26 21:23:25 +00:00
2023-10-05 18:46:18 +00:00
if r.kind in [ReactionKind.LIKE, ReactionKind.DISLIKE]:
2023-02-26 21:23:25 +00:00
session.delete(r)
else:
2023-11-03 10:10:22 +00:00
r.deleted_at = int(time.time())
session.commit()
2023-10-23 14:47:11 +00:00
notify_reaction(r.dict(), "delete")
2023-10-05 18:46:18 +00:00
return {"reaction": r}
2022-11-28 20:29:02 +00:00
2022-11-23 02:05:34 +00:00
@query.field("loadReactionsBy")
2023-10-23 14:47:11 +00:00
async def load_reactions_by(_, info, by, limit=50, offset=0):
2022-11-23 02:05:34 +00:00
"""
2023-10-23 14:47:11 +00:00
:param info: graphql meta
2022-11-23 02:05:34 +00:00
:param by: {
:shout - filter by slug
2023-02-12 03:27:55 +00:00
:shouts - filer by shout slug list
2023-11-03 10:10:22 +00:00
:created_by - to filter by author
2022-11-23 02:05:34 +00:00
:topic - to filter by topic
:search - to search by reactions' body
:comment - true if body.length > 0
2023-11-03 10:10:22 +00:00
:time_ago - amount of time ago
2022-11-23 02:05:34 +00:00
:sort - a fieldname to sort desc by default
}
:param limit: int amount of shouts
:param offset: int offset in this order
:return: Reaction[]
"""
2023-10-05 18:46:18 +00:00
q = (
2023-10-23 14:47:11 +00:00
select(Reaction, Author, Shout)
2023-11-03 10:10:22 +00:00
.join(Author, Reaction.created_by == Author.id)
2023-10-05 18:46:18 +00:00
.join(Shout, Reaction.shout == Shout.id)
2022-11-27 08:19:38 +00:00
)
2022-09-03 10:50:14 +00:00
2022-11-22 07:29:54 +00:00
if by.get("shout"):
2022-12-06 16:00:19 +00:00
q = q.filter(Shout.slug == by["shout"])
2022-11-22 15:32:58 +00:00
elif by.get("shouts"):
2023-02-26 21:23:25 +00:00
q = q.filter(Shout.slug.in_(by["shouts"]))
2022-12-06 16:00:19 +00:00
2023-11-03 10:10:22 +00:00
if by.get("created_by"):
q = q.filter(Author.id == by.get("created_by"))
2022-12-06 16:00:19 +00:00
2022-11-22 15:32:58 +00:00
if by.get("topic"):
2022-11-29 12:36:46 +00:00
# TODO: check
2022-11-22 15:32:58 +00:00
q = q.filter(Shout.topics.contains(by["topic"]))
2022-12-06 16:00:19 +00:00
2022-11-22 18:48:28 +00:00
if by.get("comment"):
q = q.filter(func.length(Reaction.body) > 0)
2022-12-06 16:00:19 +00:00
2023-10-05 18:46:18 +00:00
if len(by.get("search", "")) > 2:
2022-11-22 18:48:28 +00:00
q = q.filter(Reaction.body.ilike(f'%{by["body"]}%'))
2022-12-06 16:00:19 +00:00
2023-11-03 10:10:22 +00:00
if by.get("time_ago"):
after = int(time.time()) - int(by.get("time_ago", 0))
q = q.filter(Reaction.created_at > after)
2022-11-28 13:37:05 +00:00
2022-11-22 15:32:58 +00:00
order_way = asc if by.get("sort", "").startswith("-") else desc
2023-11-03 10:10:22 +00:00
order_field = by.get("sort", "").replace("-", "") or Reaction.created_at
2023-10-23 14:47:11 +00:00
q = q.group_by(Reaction.id, Author.id, Shout.id).order_by(order_way(order_field))
2022-11-28 22:16:39 +00:00
q = add_reaction_stat_columns(q)
2023-11-03 10:10:22 +00:00
q = q.where(Reaction.deleted_at.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 = []
2023-10-23 14:47:11 +00:00
session = info.context["session"]
for [
reaction,
author,
shout,
reacted_stat,
commented_stat,
rating_stat,
] in session.execute(q):
2023-11-03 10:10:22 +00:00
reaction.created_by = author
2023-10-23 14:47:11 +00:00
reaction.shout = shout
reaction.stat = {
"rating": rating_stat,
"commented": commented_stat,
"reacted": reacted_stat,
}
reaction.kind = reaction.kind.name
reactions.append(reaction)
2022-11-28 08:47:39 +00:00
2022-11-28 22:16:39 +00:00
# ?
2022-11-28 08:47:39 +00:00
if by.get("stat"):
2023-11-03 10:10:22 +00:00
reactions.sort(lambda r: r.stat.get(by["stat"]) or r.created_at)
2022-11-23 02:05:34 +00:00
return reactions
2023-10-23 14:47:11 +00:00
@login_required
@query.field("followedReactions")
async def followed_reactions(_, info):
author_id = info.context["author_id"]
# FIXME: method should return array of shouts
with local_session() as session:
author = session.query(Author).where(Author.id == author_id).first()
reactions = (
session.query(Reaction.shout)
2023-11-03 10:10:22 +00:00
.where(Reaction.created_by == author.id)
.filter(Reaction.created_at > author.last_seen)
2023-10-23 14:47:11 +00:00
.all()
)
return reactions