core/resolvers/reaction.py

657 lines
23 KiB
Python
Raw Normal View History

2023-11-03 10:10:22 +00:00
import time
2023-11-22 16:38:39 +00:00
from typing import List
2024-04-08 07:38:58 +00:00
from sqlalchemy import and_, asc, case, desc, func, select, text
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
2024-04-24 07:42:33 +00:00
from orm.rating import PROPOSAL_REACTIONS, RATING_REACTIONS, is_negative, is_positive
2024-02-19 11:45:55 +00:00
from orm.reaction import Reaction, ReactionKind
2024-02-02 16:36:30 +00:00
from orm.shout import Shout
2024-02-02 12:03:44 +00:00
from resolvers.editor import handle_proposing
2024-06-05 15:29:15 +00:00
from resolvers.follower import follow
2024-04-19 15:22:07 +00:00
from resolvers.stat import update_author_stat
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
2024-04-08 07:38:58 +00:00
from services.logger import root_logger as logger
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
2024-01-13 08:49:12 +00:00
2023-01-17 21:07:44 +00:00
2024-02-22 23:08:43 +00:00
def add_reaction_stat_columns(q, aliased_reaction):
2024-08-06 15:53:25 +00:00
q = q.outerjoin(aliased_reaction, aliased_reaction.deleted_at.is_(None)).add_columns(
func.sum(aliased_reaction.id).label("reacted_stat"),
func.sum(case((aliased_reaction.kind == str(ReactionKind.COMMENT.value), 1), else_=0)).label("comments_stat"),
func.sum(case((aliased_reaction.kind == str(ReactionKind.LIKE.value), 1), else_=0)).label("likes_stat"),
func.sum(case((aliased_reaction.kind == str(ReactionKind.DISLIKE.value), 1), else_=0)).label("dislikes_stat"),
func.max(aliased_reaction.created_at).label("last_comment_stat"),
)
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:59:22 +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):
2024-02-24 18:45:38 +00:00
approvers = [approver_id]
2022-11-13 15:24:29 +00:00
# now count how many approvers are voted already
2024-05-30 04:12:00 +00:00
reacted_readers = session.query(Reaction).where(Reaction.shout == reaction.shout).all()
2024-02-02 12:03:44 +00:00
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):
2024-02-02 12:59:22 +00:00
reactions = (
session.query(Reaction)
2024-02-21 07:27:16 +00:00
.where(
and_(
Reaction.shout == reaction.shout,
Reaction.kind.in_(RATING_REACTIONS),
)
)
2024-02-02 12:59:22 +00:00
.all()
)
2024-02-02 12:03:44 +00:00
rejects = 0
for r in reactions:
2024-05-30 04:12:00 +00:00
approver = session.query(Author).filter(Author.id == r.created_by).first()
2024-02-02 12:03:44 +00:00
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())
2024-04-17 15:32:23 +00:00
Shout.update(s, {"featured_at": int(time.time())})
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-04-17 15:32:23 +00:00
Shout.update(s, {"featured_at": None})
2022-11-13 15:24:29 +00:00
session.add(s)
session.commit()
2024-01-23 13:04:38 +00:00
2024-06-05 15:29:15 +00:00
async def _create_reaction(session, info, shout, author_id: int, reaction):
2024-01-23 13:04:38 +00:00
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-04-09 13:43:06 +00:00
# пересчет счетчика комментариев
2024-04-18 09:34:04 +00:00
if str(r.kind) == ReactionKind.COMMENT.value:
2024-06-11 19:46:35 +00:00
update_author_stat(author_id)
2024-04-09 13:43:06 +00:00
2024-02-02 12:03:44 +00:00
# collaborative editing
2024-05-30 04:12:00 +00:00
if rdict.get("reply_to") and r.kind in PROPOSAL_REACTIONS and author_id in shout.authors:
2024-02-02 12:03:44 +00:00
handle_proposing(session, r, shout)
2024-04-09 13:43:06 +00:00
# рейтинг и саморегуляция
2024-04-09 11:03:50 +00:00
if r.kind in RATING_REACTIONS:
# self-regultaion mechanics
2024-04-19 15:22:07 +00:00
if check_to_unfeature(session, author_id, r):
2024-04-09 11:03:50 +00:00
set_unfeatured(session, shout.id)
2024-04-19 15:22:07 +00:00
elif check_to_feature(session, author_id, r):
2024-04-09 11:03:50 +00:00
await set_featured(session, shout.id)
# follow if liked
if r.kind == ReactionKind.LIKE.value:
try:
# reactions auto-following
2024-06-05 15:29:15 +00:00
follow(None, info, "shout", shout.slug)
2024-04-09 11:03:50 +00:00
except Exception:
pass
2024-01-23 13:04:38 +00:00
2024-04-09 13:43:06 +00:00
# обновление счетчика комментариев в кеше
2024-04-18 09:34:04 +00:00
if str(r.kind) == ReactionKind.COMMENT.value:
2024-06-11 19:46:35 +00:00
update_author_stat(author_id)
2024-04-09 13:43:06 +00:00
2024-04-17 15:32:23 +00:00
rdict["shout"] = shout.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-04-17 15:32:23 +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
2024-04-19 15:22:07 +00:00
def prepare_new_rating(reaction: dict, shout_id: int, session, author_id: int):
2024-04-17 15:32:23 +00:00
kind = reaction.get("kind")
2024-05-30 04:12:00 +00:00
opposite_kind = ReactionKind.DISLIKE.value if is_positive(kind) else ReactionKind.LIKE.value
2024-02-24 18:45:38 +00:00
q = select(Reaction).filter(
and_(
Reaction.shout == shout_id,
2024-04-19 15:22:07 +00:00
Reaction.created_by == author_id,
2024-02-24 18:45:38 +00:00
Reaction.kind.in_(RATING_REACTIONS),
2024-05-04 21:00:58 +00:00
Reaction.deleted_at.is_not(None),
2024-02-24 18:45:38 +00:00
)
)
2024-04-17 15:32:23 +00:00
reply_to = reaction.get("reply_to")
2024-02-24 18:45:38 +00:00
if reply_to and isinstance(reply_to, int):
q = q.filter(Reaction.reply_to == reply_to)
rating_reactions = session.execute(q).all()
2024-05-04 21:00:58 +00:00
if rating_reactions:
same_rating = filter(
lambda r: r.created_by == author_id and r.kind == kind,
rating_reactions,
)
opposite_rating = filter(
lambda r: r.created_by == author_id and r.kind == opposite_kind,
rating_reactions,
)
if same_rating:
return {"error": "You can't rate the same thing twice"}
elif opposite_rating:
return {"error": "Remove opposite vote first"}
elif filter(lambda r: r.created_by == author_id, rating_reactions):
return {"error": "You can't rate your own thing"}
2024-02-24 18:45:38 +00:00
return
2024-04-17 15:32:23 +00:00
@mutation.field("create_reaction")
@login_required
2023-02-26 21:23:25 +00:00
async def create_reaction(_, info, reaction):
2024-05-18 14:41:04 +00:00
# logger.debug(f"{info.context} for {reaction}")
2024-04-19 15:22:07 +00:00
info.context.get("user_id")
2024-05-18 14:41:04 +00:00
author_dict = info.context.get("author", {})
if not isinstance(author_dict, dict):
2024-05-18 09:38:46 +00:00
return {"error": "Unauthorized"}
2024-05-18 14:41:04 +00:00
author_id = author_dict.get("id")
shout_id = reaction.get("shout")
2024-01-22 20:54:02 +00:00
if not shout_id:
2024-04-17 15:32:23 +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-04-19 15:22:07 +00:00
if shout and author_id:
reaction["created_by"] = int(author_id)
2024-04-17 15:32:23 +00:00
kind = reaction.get("kind")
2024-01-23 13:04:38 +00:00
2024-04-17 15:32:23 +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-04-17 15:32:23 +00:00
return {"error": "cannot create reaction without a kind"}
2024-01-23 13:04:38 +00:00
2024-02-07 13:41:17 +00:00
if kind in RATING_REACTIONS:
2024-05-30 04:12:00 +00:00
error_result = prepare_new_rating(reaction, shout_id, session, author_id)
2024-03-06 09:15:26 +00:00
if error_result:
return error_result
2024-02-07 13:41:17 +00:00
2024-06-05 15:29:15 +00:00
rdict = await _create_reaction(session, info, shout, author_id, reaction)
2024-03-06 09:15:26 +00:00
# TODO: call recount ratings periodically
2024-05-18 14:41:04 +00:00
rdict["created_by"] = author_dict
2024-04-17 15:32:23 +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()
2024-04-17 15:32:23 +00:00
logger.error(f"{type(e).__name__}: {e}")
2023-10-23 14:47:11 +00:00
2024-04-17 15:32:23 +00:00
return {"error": "Cannot create reaction."}
2024-04-17 15:32:23 +00:00
@mutation.field("update_reaction")
@login_required
2024-02-16 16:46:57 +00:00
async def update_reaction(_, info, reaction):
2024-04-17 15:32:23 +00:00
logger.debug(f"{info.context} for {reaction}")
user_id = info.context.get("user_id")
roles = info.context.get("roles")
rid = reaction.get("id")
2024-02-24 18:30:19 +00:00
if rid and isinstance(rid, int) and user_id and roles:
2024-04-17 15:32:23 +00:00
del reaction["id"]
2024-02-05 09:47:26 +00:00
with local_session() as session:
2024-02-24 18:30:19 +00:00
reaction_query = select(Reaction).filter(Reaction.id == rid)
2024-02-05 09:47:26 +00:00
aliased_reaction = aliased(Reaction)
2024-02-22 23:08:43 +00:00
reaction_query = add_reaction_stat_columns(reaction_query, aliased_reaction)
2024-02-16 16:46:57 +00:00
reaction_query = reaction_query.group_by(Reaction.id)
2022-11-28 08:47:39 +00:00
2024-02-16 16:46:57 +00:00
try:
2024-04-18 09:34:04 +00:00
result = session.execute(reaction_query).unique().first()
if result:
[
r,
reacted_stat,
commented_stat,
likes_stat,
dislikes_stat,
2024-08-06 15:18:51 +00:00
last_reacted_at,
2024-04-18 09:34:04 +00:00
] = result
if not r:
return {"error": "invalid reaction id"}
2024-05-30 04:12:00 +00:00
author = session.query(Author).filter(Author.user == user_id).first()
2024-04-18 09:34:04 +00:00
if author:
if r.created_by != author.id and "editor" not in roles:
return {"error": "access denied"}
body = reaction.get("body")
if body:
r.body = body
r.updated_at = int(time.time())
if r.kind != reaction["kind"]:
# Определение изменения мнения может быть реализовано здесь
pass
Reaction.update(r, reaction)
session.add(r)
session.commit()
r.stat = {
"reacted": reacted_stat,
"commented": commented_stat,
"rating": int(likes_stat or 0) - int(dislikes_stat or 0),
}
await notify_reaction(r.dict(), "update")
return {"reaction": r}
else:
return {"error": "not authorized"}
2024-02-16 16:46:57 +00:00
except Exception:
import traceback
traceback.print_exc()
2024-04-17 15:32:23 +00:00
return {"error": "cannot create reaction"}
2024-01-25 19:41:27 +00:00
2024-04-17 15:32:23 +00:00
@mutation.field("delete_reaction")
@login_required
2024-02-07 13:41:17 +00:00
async def delete_reaction(_, info, reaction_id: int):
2024-04-17 15:32:23 +00:00
logger.debug(f"{info.context} for {reaction_id}")
user_id = info.context.get("user_id")
2024-04-19 15:22:07 +00:00
author_id = info.context.get("author", {}).get("id")
2024-04-17 15:32:23 +00:00
roles = info.context.get("roles", [])
2024-03-06 09:09:46 +00:00
if user_id:
2024-02-07 13:41:17 +00:00
with local_session() as session:
try:
author = session.query(Author).filter(Author.user == user_id).one()
r = session.query(Reaction).filter(Reaction.id == reaction_id).one()
2024-04-19 15:22:07 +00:00
if r.created_by != author_id and "editor" not in roles:
2024-04-17 15:32:23 +00:00
return {"error": "access denied"}
2024-02-07 13:41:17 +00:00
2024-04-17 15:32:23 +00:00
logger.debug(f"{user_id} user removing his #{reaction_id} reaction")
2024-04-09 13:43:06 +00:00
reaction_dict = r.dict()
session.delete(r)
session.commit()
# обновление счетчика комментариев в кеше
2024-04-18 09:34:04 +00:00
if str(r.kind) == ReactionKind.COMMENT.value:
2024-06-11 19:46:35 +00:00
update_author_stat(author.id)
2024-04-17 15:32:23 +00:00
await notify_reaction(reaction_dict, "delete")
2024-04-08 18:33:47 +00:00
2024-04-17 15:32:23 +00:00
return {"error": None, "reaction": reaction_dict}
2024-02-07 13:41:17 +00:00
except Exception as exc:
2024-04-17 15:32:23 +00:00
return {"error": f"cannot delete reaction: {exc}"}
return {"error": "cannot delete reaction"}
2022-11-28 20:29:02 +00:00
2023-11-29 09:59:00 +00:00
def apply_reaction_filters(by, q):
2024-04-17 15:32:23 +00:00
shout_slug = by.get("shout", None)
2024-02-02 22:39:57 +00:00
if shout_slug:
q = q.filter(Shout.slug == shout_slug)
2023-11-29 09:59:00 +00:00
2024-04-17 15:32:23 +00:00
elif by.get("shouts"):
q = q.filter(Shout.slug.in_(by.get("shouts", [])))
2023-11-29 09:59:00 +00:00
2024-04-17 15:32:23 +00:00
created_by = by.get("created_by", None)
2024-02-02 22:39:57 +00:00
if created_by:
q = q.filter(Author.id == created_by)
2023-11-29 09:59:00 +00:00
2024-07-18 06:05:10 +00:00
author_slug = by.get("author", None)
if author_slug:
q = q.filter(Author.slug == author_slug)
2024-04-17 15:32:23 +00:00
topic = by.get("topic", None)
2024-04-09 19:24:47 +00:00
if isinstance(topic, int):
2024-04-09 19:09:26 +00:00
q = q.filter(Shout.topics.any(id=topic))
2023-11-29 09:59:00 +00:00
2024-04-17 15:32:23 +00:00
if by.get("comment", False):
2024-02-03 09:10:38 +00:00
q = q.filter(Reaction.kind == ReactionKind.COMMENT.value)
2024-07-15 22:06:43 +00:00
2024-04-17 15:32:23 +00:00
if by.get("rating", False):
2024-02-07 15:39:55 +00:00
q = q.filter(Reaction.kind.in_(RATING_REACTIONS))
2023-11-29 09:59:00 +00:00
2024-04-17 15:32:23 +00:00
by_search = by.get("search", "")
2023-11-29 09:59:00 +00:00
if len(by_search) > 2:
2024-04-17 15:32:23 +00:00
q = q.filter(Reaction.body.ilike(f"%{by_search}%"))
2023-11-29 09:59:00 +00:00
2024-04-17 15:32:23 +00:00
after = by.get("after", None)
2024-02-07 16:50:01 +00:00
if isinstance(after, int):
q = q.filter(Reaction.created_at > after)
2023-11-29 09:59:00 +00:00
return q
2024-04-17 15:32:23 +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
2024-07-18 06:05:10 +00:00
:created_by - to filter by author ID
:author - to filter by author slug
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
2024-07-15 22:06:43 +00:00
:rating - true if kind is rating related
2023-11-29 07:23:41 +00:00
:after - amount of time ago
2024-02-29 12:39:55 +00:00
:sort - a fieldname to sort desc by default
2022-11-23 02:05:34 +00:00
}
2024-07-22 08:32:47 +00:00
:param limit: int amount of reactions
2022-11-23 02:05:34 +00:00
:param offset: int offset in this order
:return: Reaction[]
"""
2024-02-29 12:39:55 +00:00
2023-10-05 18:46:18 +00:00
q = (
2024-02-29 12:39:55 +00:00
select(Reaction, Author, Shout)
2024-02-29 12:21:46 +00:00
.select_from(Reaction)
2024-02-29 12:39:55 +00:00
.join(Author, Reaction.created_by == Author.id)
.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-02-29 12:21:46 +00:00
aliased_reaction = aliased(Reaction)
q = add_reaction_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)
2024-02-29 12:21:46 +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-02-29 12:21:46 +00:00
q = q.group_by(Reaction.id, Author.id, Shout.id, aliased_reaction.id)
2024-01-13 08:15:45 +00:00
# order by
2024-04-17 15:32:23 +00:00
order_stat = by.get("sort", "").lower() # 'like' | 'dislike' | 'newest' | 'oldest'
2024-02-29 12:39:55 +00:00
order_by_stmt = desc(Reaction.created_at)
2024-04-17 15:32:23 +00:00
if order_stat == "oldest":
2024-02-29 12:39:55 +00:00
order_by_stmt = asc(Reaction.created_at)
2024-04-17 15:32:23 +00:00
elif order_stat.endswith("like"):
order_by_stmt = desc(f"{order_stat}s_stat")
2024-02-29 12:39:55 +00:00
q = q.order_by(order_by_stmt)
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-02-26 17:07:42 +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-08-06 15:18:51 +00:00
last_reacted_at,
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-04-17 15:32:23 +00:00
"rating": int(likes_stat or 0) - int(dislikes_stat or 0),
"reacted": reacted_stat,
"commented": commented_stat,
2024-08-06 15:53:25 +00:00
"last_reacted_at": last_reacted_at,
2024-01-25 19:41:27 +00:00
}
2024-07-22 07:42:41 +00:00
reactions.add(reaction)
2024-02-26 17:07:42 +00:00
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,
2024-07-22 07:42:41 +00:00
and_(Reaction.shout == Shout.id, Reaction.created_by == follower_id, Reaction.deleted_at.is_(None)),
2024-01-25 19:41:27 +00:00
)
.outerjoin(Author, Shout.authors.any(id=follower_id))
.options(joinedload(Shout.reactions), joinedload(Shout.authors))
2024-01-23 01:58:45 +00:00
)
2024-02-22 23:08:43 +00:00
q1 = add_reaction_stat_columns(q1, aliased(Reaction))
2024-01-23 01:58:45 +00:00
q1 = q1.filter(Author.id == follower_id).group_by(Shout.id)
# Shouts where follower reacted
q2 = (
select(Shout)
2024-03-06 11:27:30 +00:00
.join(Reaction, Reaction.shout == Shout.id)
2024-01-25 19:41:27 +00:00
.options(joinedload(Shout.reactions), joinedload(Shout.authors))
2024-07-22 07:42:41 +00:00
.filter(and_(Reaction.created_by == follower_id, Reaction.deleted_at.is_(None)))
2024-01-23 01:34:48 +00:00
.group_by(Shout.id)
2023-11-22 16:38:39 +00:00
)
2024-02-22 23:08:43 +00:00
q2 = add_reaction_stat_columns(q2, aliased(Reaction))
2024-01-23 01:34:48 +00:00
2024-08-06 15:18:51 +00:00
# Sort shouts by the `last_reacted_at` field
combined_query = union(q1, q2).order_by(desc(text("last_reacted_at"))).limit(limit).offset(offset)
2024-02-24 10:22:35 +00:00
2024-01-23 01:58:45 +00:00
results = session.execute(combined_query).scalars()
2024-02-24 10:22:35 +00:00
for [
shout,
reacted_stat,
commented_stat,
likes_stat,
dislikes_stat,
2024-08-06 15:18:51 +00:00
last_reacted_at,
2024-02-24 10:22:35 +00:00
] in results:
shout.stat = {
2024-04-17 15:32:23 +00:00
"viewed": await ViewedStorage.get_shout(shout.slug),
"rating": int(likes_stat or 0) - int(dislikes_stat or 0),
"reacted": reacted_stat,
"commented": commented_stat,
2024-08-06 15:18:51 +00:00
"last_reacted_at": last_reacted_at,
2024-02-24 10:22:35 +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
2024-04-17 15:32:23 +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-04-17 15:32:23 +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-04-17 15:32:23 +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 []
2024-07-03 12:35:12 +00:00
@query.field("load_shouts_followed_by")
async def load_shouts_followed_by(_, info, slug: str, limit=50, offset=0) -> List[Shout]:
with local_session() as session:
author = session.query(Author).filter(Author.slug == slug).first()
if author:
try:
author_id: int = author.dict()["id"]
shouts = await reacted_shouts_updates(author_id, limit, offset)
return shouts
except Exception as error:
logger.debug(error)
return []
2024-07-22 07:42:41 +00:00
@query.field("load_shout_ratings")
async def load_shout_ratings(_, info, shout: int, limit=100, offset=0):
"""
get paginated reactions with no stats
:param info: graphql meta
:param shout: int shout id
2024-07-22 08:32:47 +00:00
:param limit: int amount of reactions
2024-07-22 07:42:41 +00:00
:param offset: int offset in this order
:return: Reaction[]
"""
q = (
select(Reaction, Author, Shout)
.select_from(Reaction)
.join(Author, Reaction.created_by == Author.id)
.join(Shout, Reaction.shout == Shout.id)
)
# filter, group, order, limit, offset
q = q.filter(and_(Reaction.deleted_at.is_(None), Reaction.shout == shout, Reaction.kind.in_(RATING_REACTIONS)))
q = q.group_by(Reaction.id)
q = q.order_by(desc(Reaction.created_at))
q = q.limit(limit).offset(offset)
reactions = set()
with local_session() as session:
result_rows = session.execute(q)
for [
reaction,
author,
shout,
] in result_rows:
reaction.created_by = author
reaction.shout = shout
reactions.add(reaction)
return reactions
@query.field("load_shout_comments")
async def load_shout_comments(_, info, shout: int, limit=50, offset=0):
"""
getting paginated comments with stats
:param info: graphql meta
:param shout: int shout id
2024-07-22 08:32:47 +00:00
:param limit: int amount of reactions
2024-07-22 07:42:41 +00:00
:param offset: int offset in this order
:return: Reaction[]
"""
2024-07-26 13:56:30 +00:00
aliased_reaction = aliased(Reaction)
2024-07-22 07:42:41 +00:00
q = (
2024-07-26 13:56:30 +00:00
select(
Reaction,
Author,
Shout,
func.count(aliased_reaction.id).label("reacted_stat"),
func.count(aliased_reaction.body).label("commented_stat"),
2024-07-30 02:19:16 +00:00
func.sum(case((aliased_reaction.kind == str(ReactionKind.LIKE.value), 1), else_=0)).label("likes_stat"),
2024-08-06 11:34:12 +00:00
func.sum(case((aliased_reaction.kind == str(ReactionKind.DISLIKE.value), 1), else_=0)).label(
"dislikes_stat"
),
2024-07-26 13:56:30 +00:00
)
2024-07-22 07:42:41 +00:00
.select_from(Reaction)
.join(Author, Reaction.created_by == Author.id)
.join(Shout, Reaction.shout == Shout.id)
)
# filter, group, order, limit, offset
q = q.filter(and_(Reaction.deleted_at.is_(None), Reaction.shout == shout, Reaction.body.is_not(None)))
2024-07-26 13:56:30 +00:00
q = q.group_by(Reaction.id, Author.id, Shout.id)
2024-07-22 07:42:41 +00:00
q = q.order_by(desc(Reaction.created_at))
q = q.limit(limit).offset(offset)
reactions = set()
with local_session() as session:
result_rows = session.execute(q)
2024-07-26 13:56:30 +00:00
for row in result_rows:
reaction, author, shout, reacted_stat, commented_stat, likes_stat, dislikes_stat = row
2024-07-22 07:42:41 +00:00
reaction.created_by = author
reaction.shout = shout
reaction.stat = {
"rating": int(likes_stat or 0) - int(dislikes_stat or 0),
"reacted": reacted_stat,
"commented": commented_stat,
}
reactions.add(reaction)
2024-07-26 13:56:30 +00:00
return list(reactions)
2024-07-26 16:04:40 +00:00
2024-08-06 11:34:12 +00:00
2024-07-26 16:04:40 +00:00
@query.field("load_comment_ratings")
async def load_comment_ratings(_, info, comment: int, limit=50, offset=0):
"""
getting paginated comments with stats
:param info: graphql meta
:param comment: int replied comment id
:param limit: int amount of reactions
:param offset: int offset in this order
:return: Reaction[]
"""
aliased_reaction = aliased(Reaction)
q = (
select(
Reaction,
Author,
Shout,
func.count(aliased_reaction.id).label("reacted_stat"),
func.count(aliased_reaction.body).label("commented_stat"),
2024-07-30 02:19:16 +00:00
func.sum(case((aliased_reaction.kind == str(ReactionKind.LIKE.value), 1), else_=0)).label("likes_stat"),
2024-08-06 11:34:12 +00:00
func.sum(case((aliased_reaction.kind == str(ReactionKind.DISLIKE.value), 1), else_=0)).label(
"dislikes_stat"
),
2024-07-26 16:04:40 +00:00
)
.select_from(Reaction)
.join(Author, Reaction.created_by == Author.id)
.join(Shout, Reaction.shout == Shout.id)
)
# filter, group, order, limit, offset
q = q.filter(and_(Reaction.deleted_at.is_(None), Reaction.reply_to == comment, Reaction.body.is_not(None)))
q = q.group_by(Reaction.id, Author.id, Shout.id)
q = q.order_by(desc(Reaction.created_at))
q = q.limit(limit).offset(offset)
reactions = set()
with local_session() as session:
result_rows = session.execute(q)
for row in result_rows:
reaction, author, shout, reacted_stat, commented_stat, likes_stat, dislikes_stat = row
reaction.created_by = author
reaction.shout = shout
reaction.stat = {
"rating": int(likes_stat or 0) - int(dislikes_stat or 0),
"reacted": reacted_stat,
"commented": commented_stat,
}
reactions.add(reaction)
return list(reactions)