Corp/backend/notifications/chat_suppression.py

38 lines
1.0 KiB
Python

"""Suppress chat alerts when the recipient is already viewing that chat."""
from communications.presence import user_is_viewing_chat
from communications.services import ChatNotificationReadService
CHAT_NOTIFICATION_VERBS = {
"chat_new_message",
"chat_mention",
"chat_reply",
"announcement_new_message",
}
def notification_chat_id(notification) -> int | None:
if notification.verb not in CHAT_NOTIFICATION_VERBS:
return None
data = notification.data if isinstance(notification.data, dict) else {}
try:
return int(data.get("chat_id"))
except (TypeError, ValueError):
return None
def suppress_for_active_chat(notification) -> bool:
chat_id = notification_chat_id(notification)
if chat_id is None or not user_is_viewing_chat(
user_id=notification.recipient_id,
chat_id=chat_id,
):
return False
ChatNotificationReadService().mark_chat_notifications_as_read(
user=notification.recipient,
chat_id=chat_id,
)
return True