core/resolvers/notifier.py

324 lines
12 KiB
Python
Raw Normal View History

2024-03-04 07:35:33 +00:00
import time
from typing import Any
2024-03-04 07:35:33 +00:00
2025-03-20 08:55:21 +00:00
import orjson
from graphql import GraphQLResolveInfo
2024-04-08 07:38:58 +00:00
from sqlalchemy import and_, select
2024-03-04 07:35:33 +00:00
from sqlalchemy.exc import SQLAlchemyError
2024-04-08 07:38:58 +00:00
from sqlalchemy.orm import aliased
from sqlalchemy.sql import not_
2024-03-04 07:35:33 +00:00
2025-05-16 06:23:48 +00:00
from auth.orm import Author
2024-08-09 06:37:06 +00:00
from orm.notification import (
Notification,
NotificationAction,
NotificationEntity,
NotificationSeen,
)
2024-03-04 10:43:02 +00:00
from orm.shout import Shout
2024-03-04 07:35:33 +00:00
from services.auth import login_required
from services.db import local_session
2024-04-08 07:38:58 +00:00
from services.schema import mutation, query
2024-08-09 06:37:06 +00:00
from utils.logger import root_logger as logger
2024-03-04 07:35:33 +00:00
def query_notifications(author_id: int, after: int = 0) -> tuple[int, int, list[tuple[Notification, bool]]]:
2024-03-04 07:35:33 +00:00
notification_seen_alias = aliased(NotificationSeen)
2024-04-17 15:32:23 +00:00
q = select(Notification, notification_seen_alias.viewer.label("seen")).outerjoin(
2024-03-06 09:25:55 +00:00
NotificationSeen,
and_(
NotificationSeen.viewer == author_id,
NotificationSeen.notification == Notification.id,
),
2024-03-04 07:35:33 +00:00
)
if after:
q = q.filter(Notification.created_at > after)
q = q.group_by(NotificationSeen.notification, Notification.created_at)
with local_session() as session:
total = (
session.query(Notification)
.filter(
and_(
Notification.action == NotificationAction.CREATE.value,
Notification.created_at > after,
)
)
.count()
)
unread = (
session.query(Notification)
.filter(
and_(
Notification.action == NotificationAction.CREATE.value,
Notification.created_at > after,
not_(Notification.seen),
)
)
.count()
)
notifications_result = session.execute(q)
notifications = []
for n, seen in notifications_result:
notifications.append((n, seen))
return total, unread, notifications
def group_notification(
thread: str,
authors: list[Any] | None = None,
shout: Any | None = None,
reactions: list[Any] | None = None,
entity: str = "follower",
action: str = "follow",
) -> dict:
2024-03-04 10:43:02 +00:00
reactions = reactions or []
authors = authors or []
2024-03-04 07:35:33 +00:00
return {
2024-04-17 15:32:23 +00:00
"thread": thread,
"authors": authors,
"updated_at": int(time.time()),
"shout": shout,
"reactions": reactions,
"entity": entity,
"action": action,
2024-03-04 07:35:33 +00:00
}
def get_notifications_grouped(author_id: int, after: int = 0, limit: int = 10, offset: int = 0) -> list[dict]:
2024-03-04 07:35:33 +00:00
"""
Retrieves notifications for a given author.
Args:
author_id (int): The ID of the author for whom notifications are retrieved.
after (int, optional): If provided, selects only notifications created after this timestamp will be considered.
limit (int, optional): The maximum number of groupa to retrieve.
2024-03-04 12:47:17 +00:00
offset (int, optional): offset
2024-03-04 07:35:33 +00:00
Returns:
Dict[str, NotificationGroup], int, int: A dictionary where keys are thread IDs
and values are NotificationGroup objects, unread and total amounts.
This function queries the database to retrieve notifications for the specified author, considering optional filters.
The result is a dictionary where each key is a thread ID, and the corresponding value is a NotificationGroup
containing information about the notifications within that thread.
NotificationGroup structure:
{
entity: str, # Type of entity (e.g., 'reaction', 'shout', 'follower').
updated_at: int, # Timestamp of the latest update in the thread.
shout: Optional[NotificationShout]
reactions: List[int], # List of reaction ids within the thread.
authors: List[NotificationAuthor], # List of authors involved in the thread.
}
"""
total, unread, notifications = query_notifications(author_id, after)
groups_by_thread = {}
groups_amount = 0
for notification, _seen in notifications:
2024-03-04 12:47:17 +00:00
if (groups_amount + offset) >= limit:
2024-03-04 07:35:33 +00:00
break
2025-03-20 08:55:21 +00:00
payload = orjson.loads(str(notification.payload))
2024-03-04 07:35:33 +00:00
2024-03-28 12:56:32 +00:00
if str(notification.entity) == NotificationEntity.SHOUT.value:
2024-03-04 10:43:02 +00:00
shout = payload
2024-04-17 15:32:23 +00:00
shout_id = shout.get("id")
author_id = shout.get("created_by")
thread_id = f"shout-{shout_id}"
2024-03-04 10:43:02 +00:00
with local_session() as session:
author = session.query(Author).filter(Author.id == author_id).first()
shout = session.query(Shout).filter(Shout.id == shout_id).first()
if author and shout:
author_dict = author.dict()
shout_dict = shout.dict()
2024-03-06 09:25:55 +00:00
group = group_notification(
thread_id,
shout=shout_dict,
authors=[author_dict],
2024-03-28 12:56:32 +00:00
action=str(notification.action),
entity=str(notification.entity),
2024-03-06 09:25:55 +00:00
)
2024-03-04 07:35:33 +00:00
groups_by_thread[thread_id] = group
groups_amount += 1
2024-03-28 12:56:32 +00:00
elif str(notification.entity) == NotificationEntity.REACTION.value:
2024-03-04 10:43:02 +00:00
reaction = payload
2024-04-23 11:31:34 +00:00
if not isinstance(reaction, dict):
msg = "reaction data is not consistent"
raise ValueError(msg)
2024-04-23 11:31:34 +00:00
shout_id = reaction.get("shout")
author_id = reaction.get("created_by", 0)
2024-03-28 11:05:46 +00:00
if shout_id and author_id:
with local_session() as session:
2024-05-30 04:12:00 +00:00
author = session.query(Author).filter(Author.id == author_id).first()
2024-03-28 11:05:46 +00:00
shout = session.query(Shout).filter(Shout.id == shout_id).first()
if shout and author:
author_dict = author.dict()
shout_dict = shout.dict()
2024-04-17 15:32:23 +00:00
reply_id = reaction.get("reply_to")
thread_id = f"shout-{shout_id}"
if reply_id and reaction.get("kind", "").lower() == "comment":
thread_id += f"{reply_id}"
2024-03-28 11:05:46 +00:00
existing_group = groups_by_thread.get(thread_id)
if existing_group:
2024-04-17 15:32:23 +00:00
existing_group["seen"] = False
existing_group["authors"].append(author_id)
2024-05-30 04:12:00 +00:00
existing_group["reactions"] = existing_group["reactions"] or []
2024-04-17 15:32:23 +00:00
existing_group["reactions"].append(reaction)
2024-03-28 11:05:46 +00:00
groups_by_thread[thread_id] = existing_group
else:
group = group_notification(
thread_id,
authors=[author_dict],
shout=shout_dict,
2024-03-28 11:05:46 +00:00
reactions=[reaction],
2024-03-28 12:56:32 +00:00
entity=str(notification.entity),
action=str(notification.action),
2024-03-28 11:05:46 +00:00
)
if group:
groups_by_thread[thread_id] = group
groups_amount += 1
2024-03-04 10:43:02 +00:00
2024-04-17 15:32:23 +00:00
elif str(notification.entity) == "follower":
thread_id = "followers"
2025-03-20 08:55:21 +00:00
follower = orjson.loads(payload)
existing_group = groups_by_thread.get(thread_id)
if existing_group:
2024-04-17 15:32:23 +00:00
if str(notification.action) == "follow":
existing_group["authors"].append(follower)
2024-04-17 15:32:23 +00:00
elif str(notification.action) == "unfollow":
follower_id = follower.get("id")
for author in existing_group["authors"]:
if isinstance(author, dict) and author.get("id") == follower_id:
existing_group["authors"].remove(author)
2024-03-28 11:05:46 +00:00
break
else:
group = group_notification(
thread_id,
authors=[follower],
2024-03-28 12:56:32 +00:00
entity=str(notification.entity),
action=str(notification.action),
2024-03-28 11:05:46 +00:00
)
groups_amount += 1
existing_group = group
groups_by_thread[thread_id] = existing_group
return list(groups_by_thread.values())
2024-03-04 07:35:33 +00:00
2024-04-17 15:32:23 +00:00
@query.field("load_notifications")
2024-03-04 07:35:33 +00:00
@login_required
async def load_notifications(_: None, info: GraphQLResolveInfo, after: int, limit: int = 50, offset: int = 0) -> dict:
2025-05-29 14:09:32 +00:00
author_dict = info.context.get("author") or {}
2024-04-19 15:22:07 +00:00
author_id = author_dict.get("id")
2024-03-04 10:43:02 +00:00
error = None
total = 0
unread = 0
notifications = []
try:
if author_id:
groups_list = get_notifications_grouped(author_id, after, limit)
notifications = sorted(groups_list, key=lambda group: group.get("updated_at", 0), reverse=True)
2024-03-04 10:43:02 +00:00
except Exception as e:
error = str(e)
2024-03-04 10:43:02 +00:00
logger.error(e)
2024-03-06 09:25:55 +00:00
return {
2024-04-17 15:32:23 +00:00
"notifications": notifications,
"total": total,
"unread": unread,
"error": error,
2024-03-06 09:25:55 +00:00
}
2024-03-04 07:35:33 +00:00
2024-04-17 15:32:23 +00:00
@mutation.field("notification_mark_seen")
2024-03-04 07:35:33 +00:00
@login_required
async def notification_mark_seen(_: None, info: GraphQLResolveInfo, notification_id: int) -> dict:
2024-04-19 15:22:07 +00:00
author_id = info.context.get("author", {}).get("id")
2024-03-04 07:35:33 +00:00
if author_id:
with local_session() as session:
try:
ns = NotificationSeen(notification=notification_id, viewer=author_id)
session.add(ns)
session.commit()
except SQLAlchemyError as e:
session.rollback()
2024-04-17 15:32:23 +00:00
logger.error(f"seen mutation failed: {e}")
return {"error": "cant mark as read"}
return {"error": None}
2024-03-04 07:35:33 +00:00
2024-04-17 15:32:23 +00:00
@mutation.field("notifications_seen_after")
2024-03-04 07:35:33 +00:00
@login_required
async def notifications_seen_after(_: None, info: GraphQLResolveInfo, after: int) -> dict:
2024-03-04 07:35:33 +00:00
# TODO: use latest loaded notification_id as input offset parameter
error = None
try:
2024-04-19 15:22:07 +00:00
author_id = info.context.get("author", {}).get("id")
2024-03-04 07:35:33 +00:00
if author_id:
with local_session() as session:
2024-05-30 04:12:00 +00:00
nnn = session.query(Notification).filter(and_(Notification.created_at > after)).all()
for notification in nnn:
ns = NotificationSeen(notification=notification.id, author=author_id)
session.add(ns)
session.commit()
2024-03-04 07:35:33 +00:00
except Exception as e:
print(e)
2024-04-17 15:32:23 +00:00
error = "cant mark as read"
return {"error": error}
2024-03-04 07:35:33 +00:00
2024-04-17 15:32:23 +00:00
@mutation.field("notifications_seen_thread")
2024-03-04 07:35:33 +00:00
@login_required
async def notifications_seen_thread(_: None, info: GraphQLResolveInfo, thread: str, after: int) -> dict:
2024-03-04 07:35:33 +00:00
error = None
2024-04-19 15:22:07 +00:00
author_id = info.context.get("author", {}).get("id")
2024-03-04 07:35:33 +00:00
if author_id:
2024-04-17 15:32:23 +00:00
[shout_id, reply_to_id] = thread.split(":")
2024-03-04 07:35:33 +00:00
with local_session() as session:
# TODO: handle new follower and new shout notifications
new_reaction_notifications = (
session.query(Notification)
.filter(
2024-04-17 15:32:23 +00:00
Notification.action == "create",
Notification.entity == "reaction",
2024-03-04 07:35:33 +00:00
Notification.created_at > after,
2024-03-06 09:25:55 +00:00
)
2024-03-04 07:35:33 +00:00
.all()
)
removed_reaction_notifications = (
session.query(Notification)
.filter(
2024-04-17 15:32:23 +00:00
Notification.action == "delete",
Notification.entity == "reaction",
2024-03-04 07:35:33 +00:00
Notification.created_at > after,
2024-03-06 09:25:55 +00:00
)
2024-03-04 07:35:33 +00:00
.all()
)
exclude = set()
for nr in removed_reaction_notifications:
2025-03-20 08:55:21 +00:00
reaction = orjson.loads(str(nr.payload))
2024-04-17 15:32:23 +00:00
reaction_id = reaction.get("id")
2024-03-04 07:35:33 +00:00
exclude.add(reaction_id)
for n in new_reaction_notifications:
2025-03-20 08:55:21 +00:00
reaction = orjson.loads(str(n.payload))
2024-04-17 15:32:23 +00:00
reaction_id = reaction.get("id")
2024-03-04 07:35:33 +00:00
if (
2024-03-06 09:25:55 +00:00
reaction_id not in exclude
2024-04-17 15:32:23 +00:00
and reaction.get("shout") == shout_id
and reaction.get("reply_to") == reply_to_id
2024-03-04 07:35:33 +00:00
):
try:
ns = NotificationSeen(notification=n.id, viewer=author_id)
session.add(ns)
session.commit()
except Exception as e:
logger.warn(e)
session.rollback()
else:
2024-04-17 15:32:23 +00:00
error = "You are not logged in"
return {"error": error}