From 6e2f2f29b950716ba62d28a1d7d2df2186fcdd73 Mon Sep 17 00:00:00 2001 From: Ilya Mukhortov Date: Thu, 15 Oct 2026 11:24:03 +1000 Subject: [PATCH] Signal unread_count_changed when browser notifications change. Host apps can subscribe and decide how to refresh the unread count. Co-authored-by: Cursor --- Readme.md | 12 ++++++ notify/api.py | 5 ++- notify/receivers.py | 22 ++++++++++- notify/signals.py | 25 +++++++++++++ tests/test_unread_signal.py | 73 +++++++++++++++++++++++++++++++++++++ 5 files changed, 135 insertions(+), 2 deletions(-) create mode 100644 notify/signals.py create mode 100644 tests/test_unread_signal.py diff --git a/Readme.md b/Readme.md index 0ce8c9a..10d3f87 100644 --- a/Readme.md +++ b/Readme.md @@ -232,6 +232,18 @@ NOTIFY_CODE_RESEND_INTERVAL = 60 # секунд, 0 — без ограниче - `POST make-all-read/` - `POST preferences/` +Когда у пользователя меняются непрочитанные browser-уведомления, после коммита уходит сигнал `unread_count_changed` с аргументом `user`. Подписчик сам решает, что делать, например заново прочитать `GET unread-count/`. + +```python +from django.dispatch import receiver + +from notify.signals import unread_count_changed + +@receiver(unread_count_changed) +def on_unread_changed(sender, user, **kwargs): + ... +``` + Просроченные уведомления в эти выборки не входят. Некорректный id возвращает 404. `GET list/` отдаёт `content_type` (`app_label.model` или `null`), `object_id`, `show_popup` и `attachments`: `id`, `name`, `size`, `content_type`, `url`. Тот же `show_popup` входит в ответы `POST make-read/{id}/` и `POST make-unread/{id}/`. Фильтры списка: `content_type`, `object_id`, `object_id__ne`, `object_id__ne__in`. `GET attachments/{id}/` скачивает файл, если у текущего пользователя есть получатель этого уведомления и срок не истёк. Чужой и просроченный файл возвращают 404. diff --git a/notify/api.py b/notify/api.py index 94724bf..4518bbe 100644 --- a/notify/api.py +++ b/notify/api.py @@ -25,6 +25,7 @@ from .models import ( NotificationType, ) from .services import channel_preferences, save_channel_preferences +from .signals import schedule_unread_count_changed __all__ = [ "api", @@ -135,7 +136,9 @@ def make_unread(request, path: Path[DetailPath]): @api.post("make-all-read/") def make_all_read(request, filters: NotificationFilterSchema = Query(...)): qs = filters.filter(_base_user_queryset(request.user)) - qs.filter(unread=True).update(unread=False) + updated = qs.filter(unread=True).update(unread=False) + if updated: + schedule_unread_count_changed(request.user.pk) return {} diff --git a/notify/receivers.py b/notify/receivers.py index 58ff278..264426a 100644 --- a/notify/receivers.py +++ b/notify/receivers.py @@ -3,10 +3,13 @@ from django.db.models.signals import post_delete, post_save from django.dispatch import receiver from notify.delivery import get_provider -from notify.models import NotificationAttachment, NotificationRecipient +from notify.models import DeliveryChannel, NotificationAttachment, NotificationRecipient +from notify.signals import schedule_unread_count_changed __all__ = [ "delete_attachment_file", + "emit_unread_count_on_delete", + "emit_unread_count_on_save", "post_save_notification", ] @@ -28,6 +31,23 @@ def post_save_notification(sender, instance: NotificationRecipient, created, **k transaction.on_commit(enqueue) +@receiver(post_save, sender=NotificationRecipient) +def emit_unread_count_on_save(sender, instance: NotificationRecipient, created, **kwargs): + if instance.channel != DeliveryChannel.BROWSER or not instance.user_id: + return + update_fields = kwargs.get("update_fields") + if not created and update_fields is not None and "unread" not in update_fields: + return + schedule_unread_count_changed(instance.user_id) + + +@receiver(post_delete, sender=NotificationRecipient) +def emit_unread_count_on_delete(sender, instance: NotificationRecipient, **kwargs): + if instance.channel != DeliveryChannel.BROWSER or not instance.user_id or not instance.unread: + return + schedule_unread_count_changed(instance.user_id) + + @receiver(post_delete, sender=NotificationAttachment) def delete_attachment_file(sender, instance: NotificationAttachment, **kwargs): if instance.file: diff --git a/notify/signals.py b/notify/signals.py new file mode 100644 index 0000000..18fee17 --- /dev/null +++ b/notify/signals.py @@ -0,0 +1,25 @@ +from django.contrib.auth import get_user_model +from django.db import transaction +from django.dispatch import Signal + +from notify.models import NotificationRecipient + +__all__ = [ + "schedule_unread_count_changed", + "unread_count_changed", +] + +unread_count_changed = Signal() + + +def schedule_unread_count_changed(user_id: int) -> None: + if not user_id: + return + + def emit(): + user = get_user_model().objects.filter(pk=user_id).first() + if user is None: + return + unread_count_changed.send(sender=NotificationRecipient, user=user) + + transaction.on_commit(emit) diff --git a/tests/test_unread_signal.py b/tests/test_unread_signal.py new file mode 100644 index 0000000..1c01054 --- /dev/null +++ b/tests/test_unread_signal.py @@ -0,0 +1,73 @@ +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.test import TestCase + +from notify.models import DeliveryChannel +from notify.services import create_notification +from notify.signals import unread_count_changed + +User = get_user_model() + + +class UnreadCountSignalTests(TestCase): + def setUp(self): + self.user = User.objects.create_user("alice", "alice@example.com", "pass") + self.client.force_login(self.user) + self.users = [] + unread_count_changed.connect(self._record) + + def tearDown(self): + unread_count_changed.disconnect(self._record) + + def _record(self, sender, user, **kwargs): + self.users.append(user.pk) + + def test_browser_create_read_and_delete(self): + with self.captureOnCommitCallbacks(execute=True): + notification = create_notification( + title="Hi", + recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + ) + self.assertEqual(self.users, [self.user.pk]) + + recipient = notification.recipients.get() + with self.captureOnCommitCallbacks(execute=True): + recipient.make_read() + self.assertEqual(self.users, [self.user.pk, self.user.pk]) + + with self.captureOnCommitCallbacks(execute=True): + recipient.make_unread() + with self.captureOnCommitCallbacks(execute=True): + notification.delete() + self.assertEqual(self.users, [self.user.pk, self.user.pk, self.user.pk, self.user.pk]) + + def test_email_does_not_send(self): + with patch("notify.tasks.deliver_notification.apply_async"): + with self.captureOnCommitCallbacks(execute=True): + create_notification( + title="Mail", + recipients=[ + { + "user": self.user, + "channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}], + } + ], + ) + self.assertEqual(self.users, []) + + def test_make_all_read_sends_once(self): + with self.captureOnCommitCallbacks(execute=True): + create_notification( + title="One", + recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + ) + create_notification( + title="Two", + recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + ) + self.users.clear() + with self.captureOnCommitCallbacks(execute=True): + response = self.client.post("/api/make-all-read/") + self.assertEqual(response.status_code, 200) + self.assertEqual(self.users, [self.user.pk])