core/resolvers/reaction.py

442 lines
15 KiB
Python
Raw Normal View History

2024-01-25 19:41:27 +00:00
import logging
2023-11-03 10:10:22 +00:00
import time
2023-11-22 16:38:39 +00:00
from typing import List
2024-01-25 19:41:27 +00:00
from sqlalchemy import and_, case, desc, func, select
2023-11-30 07:38:41 +00:00
from sqlalchemy.orm import aliased, joinedload
2024-01-23 01:58:45 +00:00
from sqlalchemy.sql import union
2023-12-17 20:30:20 +00:00
from orm.author import Author
from orm.reaction import Reaction, ReactionKind
2024-02-02 12:03:44 +00:00
from orm.shout import Shout, ShoutVisibility
from resolvers.editor import handle_proposing
from resolvers.follower import reactions_follow
from resolvers.rater import RATING_REACTIONS, is_negative, is_positive
2024-01-25 19:41:27 +00:00
from services.auth import add_user_role, login_required
2023-10-23 14:51:13 +00:00
from services.db import local_session
2023-12-17 20:30:20 +00:00
from services.notify import notify_reaction
2023-10-23 14:51:13 +00:00
from services.schema import mutation, query
2024-01-23 08:50:58 +00:00
from services.viewed import ViewedStorage
2022-09-19 13:50:43 +00:00
2024-01-25 19:41:27 +00:00
logger = logging.getLogger('\t[resolvers.reaction]\t')
2024-01-13 08:49:12 +00:00
logger.setLevel(logging.DEBUG)
2023-01-17 21:07:44 +00:00
2024-01-25 19:41:27 +00:00
def add_stat_columns(q, aliased_reaction):
2024-01-23 00:06:48 +00:00
q = q.outerjoin(aliased_reaction).add_columns(
2024-01-29 12:20:28 +00:00
func.sum(aliased_reaction.id).label('reacted_stat'),
2024-01-25 19:41:27 +00:00
func.sum(case((aliased_reaction.kind == ReactionKind.COMMENT.value, 1), else_=0)).label('comments_stat'),
func.sum(case((aliased_reaction.kind == ReactionKind.LIKE.value, 1), else_=0)).label('likes_stat'),
func.sum(case((aliased_reaction.kind == ReactionKind.DISLIKE.value, 1), else_=0)).label('dislikes_stat'),
func.max(
case(
(aliased_reaction.kind != ReactionKind.COMMENT.value, None),
else_=aliased_reaction.created_at,
)
).label('last_comment'),
2023-12-02 20:38:28 +00:00
)
2023-01-17 21:07:44 +00:00
2024-01-23 01:34:48 +00:00
return q
2024-02-02 12:03:44 +00:00
def is_featured_author(session, author_id):
"""checks if author has at least one featured publication"""
2023-10-05 18:46:18 +00:00
return (
session.query(Shout)
2024-01-22 22:21:01 +00:00
.where(Shout.authors.any(id=author_id))
2024-02-02 12:03:44 +00:00
.filter(and_(Shout.featured_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
2024-02-02 12:03:44 +00:00
def check_to_feature(session, approver_id, reaction):
2024-01-23 13:04:38 +00:00
"""set shout to public if publicated approvers amount > 4"""
if not reaction.reply_to and is_positive(reaction.kind):
2024-02-02 12:03:44 +00:00
if is_featured_author(session, approver_id):
approvers = []
approvers.append(approver_id)
2022-11-13 15:24:29 +00:00
# now count how many approvers are voted already
2024-02-02 12:03:44 +00:00
reacted_readers = session.query(Reaction).where(Reaction.shout == reaction.shout).all()
for reacted_reader in reacted_readers:
if is_featured_author(session, reacted_reader.id):
approvers.append(reacted_reader.id)
2022-11-13 15:24:29 +00:00
if len(approvers) > 4:
return True
return False
2024-02-02 12:03:44 +00:00
def check_to_unfeature(session, rejecter_id, reaction):
"""unfeature any shout if 20% of reactions are negative"""
2024-01-23 13:04:38 +00:00
if not reaction.reply_to and is_negative(reaction.kind):
2024-02-02 12:03:44 +00:00
if is_featured_author(session, rejecter_id):
reactions = session.query(Reaction).where(and_(Reaction.shout == reaction.shout, Reaction.kind.in_(RATING_REACTIONS))).all()
rejects = 0
for r in reactions:
approver = session.query(Author).filter(Author.id == r.created_by).first()
if is_featured_author(session, approver):
if is_negative(r.kind):
rejects += 1
if len(reactions) / rejects < 5:
return True
2022-11-13 15:24:29 +00:00
return False
2024-02-02 12:03:44 +00:00
async def set_featured(session, shout_id):
2022-12-01 14:45:19 +00:00
s = session.query(Shout).where(Shout.id == shout_id).first()
2024-02-02 12:03:44 +00:00
s.featured_at = int(time.time())
Shout.update(s, {'visibility': ShoutVisibility.FEATURED.value})
2024-01-10 13:29:49 +00:00
author = session.query(Author).filter(Author.id == s.created_by).first()
if author:
await add_user_role(str(author.user))
2022-11-13 15:24:29 +00:00
session.add(s)
session.commit()
2024-02-02 12:03:44 +00:00
def set_unfeatured(session, shout_id):
2022-12-01 14:45:19 +00:00
s = session.query(Shout).where(Shout.id == shout_id).first()
2024-01-25 19:41:27 +00:00
Shout.update(s, {'visibility': ShoutVisibility.COMMUNITY.value})
2022-11-13 15:24:29 +00:00
session.add(s)
session.commit()
2024-01-23 13:04:38 +00:00
async def _create_reaction(session, shout, author, reaction):
r = Reaction(**reaction)
session.add(r)
session.commit()
2024-01-31 00:09:58 +00:00
rdict = r.dict()
2024-01-23 13:04:38 +00:00
2024-02-02 12:03:44 +00:00
# collaborative editing
if rdict.get('reply_to') and r.kind in RATING_REACTIONS and author.id in shout.authors:
handle_proposing(session, r, shout)
# self-regultaion mechanics
if check_to_unfeature(session, author.id, r):
set_unfeatured(session, shout.id)
elif check_to_feature(session, author.id, r):
await set_featured(session, shout.id)
# reactions auto-following
2024-01-25 19:41:27 +00:00
reactions_follow(author.id, reaction['shout'], True)
2024-01-23 13:04:38 +00:00
2024-01-25 19:41:27 +00:00
rdict['shout'] = shout.dict()
rdict['created_by'] = author.dict()
rdict['stat'] = {'commented': 0, 'reacted': 0, 'rating': 0}
2024-01-23 13:04:38 +00:00
2024-02-02 12:03:44 +00:00
# notifications call
2024-01-25 19:41:27 +00:00
await notify_reaction(rdict, 'create')
2024-01-23 13:04:38 +00:00
return rdict
2024-01-25 19:41:27 +00:00
@mutation.field('create_reaction')
@login_required
2023-02-26 21:23:25 +00:00
async def create_reaction(_, info, reaction):
2024-01-25 19:41:27 +00:00
user_id = info.context['user_id']
2024-01-22 20:54:02 +00:00
2024-01-25 19:41:27 +00:00
shout_id = reaction.get('shout')
2024-01-22 20:54:02 +00:00
if not shout_id:
2024-01-25 19:41:27 +00:00
return {'error': 'Shout ID is required to create a reaction.'}
2024-01-22 20:54:02 +00:00
try:
with local_session() as session:
2024-02-02 12:03:44 +00:00
shout = session.query(Shout).filter(Shout.id == shout_id).first()
2024-01-22 20:54:02 +00:00
author = session.query(Author).filter(Author.user == user_id).first()
if shout and author:
2024-01-25 19:41:27 +00:00
reaction['created_by'] = author.id
kind = reaction.get('kind')
2024-01-23 13:04:38 +00:00
shout_id = shout.id
2024-02-02 12:03:44 +00:00
if not kind and isinstance(reaction.get('body'), str):
2024-01-22 22:11:34 +00:00
kind = ReactionKind.COMMENT.value
2024-01-23 13:04:38 +00:00
2024-01-22 22:11:34 +00:00
if not kind:
2024-01-25 19:41:27 +00:00
return {'error': 'cannot create reaction with this kind'}
2024-01-23 13:04:38 +00:00
2024-01-25 19:41:27 +00:00
if kind in ['LIKE', 'DISLIKE', 'AGREE', 'DISAGREE']:
2024-01-23 13:04:38 +00:00
same_reaction = (
session.query(Reaction)
.filter(
and_(
Reaction.shout == shout_id,
Reaction.created_by == author.id,
Reaction.kind == kind,
2024-01-25 19:41:27 +00:00
Reaction.reply_to == reaction.get('reply_to'),
2024-01-23 13:04:38 +00:00
)
2023-11-27 16:03:47 +00:00
)
2024-01-23 13:04:38 +00:00
.first()
2023-10-05 18:46:18 +00:00
)
2023-02-26 21:23:25 +00:00
2024-01-23 13:04:38 +00:00
if same_reaction is not None:
2024-01-25 19:41:27 +00:00
return {'error': "You can't like or dislike same thing twice"}
2023-02-26 21:23:25 +00:00
2024-01-23 13:04:38 +00:00
opposite_reaction_kind = (
ReactionKind.DISLIKE.value
2024-01-25 19:41:27 +00:00
if reaction['kind'] == ReactionKind.LIKE.value
2024-01-23 13:04:38 +00:00
else ReactionKind.LIKE.value
)
opposite_reaction = (
session.query(Reaction)
.filter(
and_(
2024-01-25 19:41:27 +00:00
Reaction.shout == reaction['shout'],
2024-01-23 13:04:38 +00:00
Reaction.created_by == author.id,
Reaction.kind == opposite_reaction_kind,
2024-01-25 19:41:27 +00:00
Reaction.reply_to == reaction.get('reply_to'),
2024-01-23 13:04:38 +00:00
)
2023-11-27 16:03:47 +00:00
)
2024-01-23 13:04:38 +00:00
.first()
2023-02-26 21:23:25 +00:00
)
2024-01-22 22:11:34 +00:00
2024-01-23 13:04:38 +00:00
if opposite_reaction is not None:
2024-01-25 19:41:27 +00:00
return {'error': 'Remove opposite vote first'}
2024-01-23 13:04:38 +00:00
else:
rdict = await _create_reaction(session, shout, author, reaction)
2024-01-25 19:41:27 +00:00
return {'reaction': rdict}
2024-01-22 20:54:02 +00:00
except Exception as e:
2024-01-22 21:27:57 +00:00
import traceback
2024-01-25 19:41:27 +00:00
traceback.print_exc()
logger.error(f'{type(e).__name__}: {e}')
2023-10-23 14:47:11 +00:00
2024-01-25 19:41:27 +00:00
return {'error': 'Cannot create reaction.'}
2024-01-25 19:41:27 +00:00
@mutation.field('update_reaction')
@login_required
2023-11-22 16:38:39 +00:00
async def update_reaction(_, info, rid, reaction):
2024-01-25 19:41:27 +00:00
user_id = info.context['user_id']
with local_session() as session:
2023-10-23 14:47:11 +00:00
q = select(Reaction).filter(Reaction.id == rid)
2024-01-23 01:34:48 +00:00
aliased_reaction = aliased(Reaction)
q = add_stat_columns(q, aliased_reaction)
2023-02-06 13:15:47 +00:00
q = q.group_by(Reaction.id)
2022-11-28 08:47:39 +00:00
2024-01-29 12:20:28 +00:00
[r, reacted_stat, commented_stat, likes_stat, dislikes_stat, _l] = session.execute(q).unique().first()
2022-11-28 08:47:39 +00:00
if not r:
2024-01-25 19:41:27 +00:00
return {'error': 'invalid reaction id'}
2023-11-23 23:00:28 +00:00
author = session.query(Author).filter(Author.user == user_id).first()
if author:
if r.created_by != author.id:
2024-01-25 19:41:27 +00:00
return {'error': 'access denied'}
body = reaction.get('body')
2023-11-23 23:00:28 +00:00
if body:
r.body = body
r.updated_at = int(time.time())
2024-01-25 19:41:27 +00:00
if r.kind != reaction['kind']:
2023-12-25 07:48:50 +00:00
# TODO: change mind detection can be here
2023-11-23 23:00:28 +00:00
pass
session.commit()
r.stat = {
2024-01-29 12:20:28 +00:00
'reacted': reacted_stat,
2024-01-25 19:41:27 +00:00
'commented': commented_stat,
'rating': int(likes_stat or 0) - int(dislikes_stat or 0),
2023-11-23 23:00:28 +00:00
}
2024-01-25 19:41:27 +00:00
await notify_reaction(r.dict(), 'update')
2023-11-23 23:00:28 +00:00
2024-01-25 19:41:27 +00:00
return {'reaction': r}
2023-11-23 23:00:28 +00:00
else:
2024-01-25 19:41:27 +00:00
return {'error': 'not authorized'}
return {'error': 'cannot create reaction'}
2024-01-25 19:41:27 +00:00
@mutation.field('delete_reaction')
@login_required
2024-01-23 19:52:40 +00:00
async def delete_reaction(_, info, reaction_id):
2024-01-25 19:41:27 +00:00
user_id = info.context['user_id']
with local_session() as session:
2024-01-23 19:52:40 +00:00
r = session.query(Reaction).filter(Reaction.id == reaction_id).first()
if not r:
2024-01-25 19:41:27 +00:00
return {'error': 'invalid reaction id'}
2023-11-23 23:00:28 +00:00
author = session.query(Author).filter(Author.user == user_id).first()
2023-11-28 07:53:48 +00:00
if author:
2023-11-29 08:00:00 +00:00
if r.created_by is author.id:
2024-01-25 19:41:27 +00:00
return {'error': 'access denied'}
2023-02-26 21:23:25 +00:00
2023-11-30 07:38:41 +00:00
if r.kind in [ReactionKind.LIKE.value, ReactionKind.DISLIKE.value]:
2023-11-28 07:53:48 +00:00
session.delete(r)
2024-01-23 14:14:43 +00:00
session.commit()
2024-01-25 19:41:27 +00:00
await notify_reaction(r.dict(), 'delete')
2023-11-28 07:53:48 +00:00
else:
2024-01-25 19:41:27 +00:00
return {'error': 'access denied'}
2024-01-23 14:14:43 +00:00
return {}
2022-11-28 20:29:02 +00:00
2023-11-29 09:59:00 +00:00
def apply_reaction_filters(by, q):
2024-01-25 19:41:27 +00:00
if by.get('shout'):
q = q.filter(Shout.slug == by['shout'])
2023-11-29 09:59:00 +00:00
2024-01-25 19:41:27 +00:00
elif by.get('shouts'):
q = q.filter(Shout.slug.in_(by['shouts']))
2023-11-29 09:59:00 +00:00
2024-01-25 19:41:27 +00:00
if by.get('created_by'):
q = q.filter(Author.id == by['created_by'])
2023-11-29 09:59:00 +00:00
2024-01-25 19:41:27 +00:00
if by.get('topic'):
q = q.filter(Shout.topics.contains(by['topic']))
2023-11-29 09:59:00 +00:00
2024-01-25 19:41:27 +00:00
if by.get('comment'):
2023-11-29 09:59:00 +00:00
q = q.filter(func.length(Reaction.body) > 0)
# NOTE: not using ElasticSearch here
2024-01-25 19:41:27 +00:00
by_search = by.get('search', '')
2023-11-29 09:59:00 +00:00
if len(by_search) > 2:
2024-01-25 19:41:27 +00:00
q = q.filter(Reaction.body.ilike(f'%{by_search}%'))
2023-11-29 09:59:00 +00:00
2024-01-25 19:41:27 +00:00
if by.get('after'):
after = int(by['after'])
2023-11-29 09:59:00 +00:00
q = q.filter(Reaction.created_at > after)
return q
2024-01-25 19:41:27 +00:00
@query.field('load_reactions_by')
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-29 07:23:41 +00:00
:after - 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
2023-11-30 07:38:41 +00:00
# calculate counters
2024-01-23 01:34:48 +00:00
aliased_reaction = aliased(Reaction)
q = add_stat_columns(q, aliased_reaction)
2023-11-29 11:16:09 +00:00
2023-11-30 07:38:41 +00:00
# filter
2023-11-29 09:59:00 +00:00
q = apply_reaction_filters(by, q)
2023-11-30 07:38:41 +00:00
q = q.where(Reaction.deleted_at.is_(None))
2023-11-29 11:16:09 +00:00
2024-01-13 07:27:45 +00:00
# group by
2024-01-13 08:15:45 +00:00
q = q.group_by(Reaction.id, Author.id, Shout.id, aliased_reaction.id)
# order by
2024-01-25 19:41:27 +00:00
q = q.order_by(desc('created_at'))
2023-11-29 11:16:09 +00:00
2023-11-30 07:38:41 +00:00
# pagination
2022-11-22 07:29:54 +00:00
q = q.limit(limit).offset(offset)
2023-11-30 07:38:41 +00:00
2024-01-30 22:53:54 +00:00
reactions = set()
2023-11-29 10:50:20 +00:00
with local_session() as session:
result_rows = session.execute(q)
for [
reaction,
author,
shout,
2024-01-29 12:20:28 +00:00
reacted_stat,
2023-11-29 10:50:20 +00:00
commented_stat,
2024-01-23 01:58:45 +00:00
likes_stat,
dislikes_stat,
2024-01-25 19:41:27 +00:00
_last_comment,
2023-11-29 10:50:20 +00:00
] in result_rows:
reaction.created_by = author
reaction.shout = shout
2024-01-23 01:58:45 +00:00
reaction.stat = {
2024-01-25 19:41:27 +00:00
'rating': int(likes_stat or 0) - int(dislikes_stat or 0),
2024-01-29 12:20:28 +00:00
'reacted': reacted_stat,
2024-01-25 19:41:27 +00:00
'commented': commented_stat,
}
2024-01-30 22:53:54 +00:00
reactions.add(reaction)
2023-11-29 10:50:20 +00:00
# sort if by stat is present
2024-01-25 19:41:27 +00:00
stat_sort = by.get('stat')
2024-01-13 08:15:45 +00:00
if stat_sort:
2024-01-25 19:41:27 +00:00
reactions = sorted(
reactions,
key=lambda r: r.stat.get(stat_sort) or r.created_at,
reverse=stat_sort.startswith('-'),
)
2022-11-23 02:05:34 +00:00
return reactions
2023-10-23 14:47:11 +00:00
2024-01-23 01:58:45 +00:00
async def reacted_shouts_updates(follower_id: int, limit=50, offset=0) -> List[Shout]:
2023-11-28 07:53:48 +00:00
shouts: List[Shout] = []
2023-11-22 16:38:39 +00:00
with local_session() as session:
2024-01-23 01:34:48 +00:00
author = session.query(Author).filter(Author.id == follower_id).first()
2023-11-22 16:38:39 +00:00
if author:
2024-01-23 01:34:48 +00:00
# Shouts where follower is the author
2024-01-25 19:41:27 +00:00
q1 = (
select(Shout)
.outerjoin(
Reaction,
and_(
Reaction.shout_id == Shout.id,
Reaction.created_by == follower_id,
),
)
.outerjoin(Author, Shout.authors.any(id=follower_id))
.options(joinedload(Shout.reactions), joinedload(Shout.authors))
2024-01-23 01:58:45 +00:00
)
q1 = add_stat_columns(q1, aliased(Reaction))
q1 = q1.filter(Author.id == follower_id).group_by(Shout.id)
# Shouts where follower reacted
q2 = (
select(Shout)
2024-01-23 01:34:48 +00:00
.join(Reaction, Reaction.shout_id == Shout.id)
2024-01-25 19:41:27 +00:00
.options(joinedload(Shout.reactions), joinedload(Shout.authors))
2023-11-29 08:00:00 +00:00
.filter(Reaction.created_by == follower_id)
2024-01-23 01:34:48 +00:00
.group_by(Shout.id)
2023-11-22 16:38:39 +00:00
)
2024-01-23 01:58:45 +00:00
q2 = add_stat_columns(q2, aliased(Reaction))
2024-01-23 01:34:48 +00:00
# Sort shouts by the `last_comment` field
2024-01-25 19:41:27 +00:00
combined_query = union(q1, q2).order_by(desc('last_comment')).limit(limit).offset(offset)
2024-01-23 01:58:45 +00:00
results = session.execute(combined_query).scalars()
with local_session() as session:
for [
shout,
2024-01-29 12:20:28 +00:00
reacted_stat,
2024-01-23 01:58:45 +00:00
commented_stat,
likes_stat,
dislikes_stat,
2024-01-25 19:41:27 +00:00
last_comment,
2024-01-23 01:58:45 +00:00
] in results:
shout.stat = {
2024-01-25 19:41:27 +00:00
'viewed': await ViewedStorage.get_shout(shout.slug),
'rating': int(likes_stat or 0) - int(dislikes_stat or 0),
2024-01-29 12:20:28 +00:00
'reacted': reacted_stat,
2024-01-25 19:41:27 +00:00
'commented': commented_stat,
'last_comment': last_comment,
}
2024-01-23 01:58:45 +00:00
shouts.append(shout)
2024-01-23 01:34:48 +00:00
return shouts
2023-11-22 16:38:39 +00:00
2024-01-25 19:41:27 +00:00
@query.field('load_shouts_followed')
2024-01-22 23:28:54 +00:00
@login_required
2023-11-28 07:53:48 +00:00
async def load_shouts_followed(_, info, limit=50, offset=0) -> List[Shout]:
2024-01-25 19:41:27 +00:00
user_id = info.context['user_id']
2023-11-23 23:00:28 +00:00
with local_session() as session:
author = session.query(Author).filter(Author.user == user_id).first()
if author:
2024-01-13 08:49:12 +00:00
try:
2024-01-25 19:41:27 +00:00
author_id: int = author.dict()['id']
2024-01-23 01:58:45 +00:00
shouts = await reacted_shouts_updates(author_id, limit, offset)
2024-01-13 08:49:12 +00:00
return shouts
except Exception as error:
logger.debug(error)
return []