Files
core/resolvers/reaction.py

523 lines
18 KiB
Python
Raw Normal View History

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