Coverage for src/couchers/notifications/notify.py: 100%
14 statements
« prev ^ index » next coverage.py v7.5.0, created at 2024-11-21 04:21 +0000
« prev ^ index » next coverage.py v7.5.0, created at 2024-11-21 04:21 +0000
1import logging
3from google.protobuf import empty_pb2
5from couchers.jobs.enqueue import queue_job
6from couchers.models import Notification
7from couchers.notifications.utils import enum_from_topic_action
8from proto.internal import jobs_pb2
10logger = logging.getLogger(__name__)
13def notify(
14 session,
15 *,
16 user_id,
17 topic_action,
18 key="",
19 data=None,
20):
21 """
22 Queues a notification given the notification and a target, i.e. a tuple (user_id, topic, key), and an action.
24 Notifications are sent to user identified by user_id, and are collapsed/grouped based on the combination of
25 (topic, key).
27 For example, topic may be "chat" for a group chat/direct message, and the key might be the chat id; so that messages
28 in the same group chat show up in one group.
30 The action is a simple identifier describing the action that caused the notification. For the above example, the
31 action might be "add_admin" if the notification was caused by another user adding an admin into the gorup chat.
33 Each different notification type should have its own action.
34 """
35 logger.info(f"Generating notification of type {topic_action} for user {user_id}")
36 topic, action = topic_action.split(":")
38 notification = Notification(
39 user_id=user_id,
40 topic_action=enum_from_topic_action[topic, action],
41 key=key,
42 data=(data or empty_pb2.Empty()).SerializeToString(),
43 )
44 session.add(notification)
45 session.flush()
47 queue_job(
48 session,
49 job_type="handle_notification",
50 payload=jobs_pb2.HandleNotificationPayload(
51 notification_id=notification.id,
52 ),
53 )