From 5c6ee4e80ebde1b2ab32d62cecb9159deaa45cb6 Mon Sep 17 00:00:00 2001 From: Florian Date: Thu, 12 Nov 2026 18:28:03 +0100 Subject: [PATCH] Added function to send notifications to all users --- pyproject.toml | 2 +- send_notifications/__init__.py | 6 ++-- send_notifications/notify_subscribers.py | 38 ++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) create mode 100644 send_notifications/notify_subscribers.py diff --git a/pyproject.toml b/pyproject.toml index d3e3d52..20e5dc2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "lib-send-notifications" -version = "0.2.2" +version = "0.3.0" description = "Shared library to send notifications via the internal backend API" requires-python = ">=3.10" authors = [{ name = "Florian Gänsejunge" }] diff --git a/send_notifications/__init__.py b/send_notifications/__init__.py index 28ee7a4..44124e4 100644 --- a/send_notifications/__init__.py +++ b/send_notifications/__init__.py @@ -6,12 +6,14 @@ from .send_notification import ( NotificationError, NotificationUnavailableError, ) +from .notify_subscribers import send_to_users logging.getLogger(__name__).addHandler(logging.NullHandler()) + __all__ = [ "InvalidNotificationError", "NotificationClient", "NotificationError", "NotificationUnavailableError", - ] - + "send_to_users", +] diff --git a/send_notifications/notify_subscribers.py b/send_notifications/notify_subscribers.py new file mode 100644 index 0000000..103a17f --- /dev/null +++ b/send_notifications/notify_subscribers.py @@ -0,0 +1,38 @@ +import logging + +from shared_models import Message + +from .send_notification import ( + NotificationClient, + NotificationError, + NotificationUnavailableError, +) + +logger = logging.getLogger(__name__) + +def send_to_users( + client: NotificationClient, + notifications: list[tuple[int, Message]] + ): + sent = 0 + failed = 0 + for index, (user_id, message) in enumerate(notifications): + try: + client.send( + user_id=user_id, + title=message.title, + body=message.body, + link=message.link, + category=message.category, + timestamp=message.timestamp, + ) + sent += 1 + except NotificationUnavailableError: + skipped = len(notifications) - index + failed += skipped + logger.error("Notification backend unavailable, skipping %s remaining", skipped) + break + except NotificationError: + failed +=1 + logger.exception("Failed to notify user_id=%s", user_id) + return sent, failed \ No newline at end of file