Signal browser_notification_created when a browser recipient is added.

Hosts receive the user and the notification after the row is committed.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Ilya Mukhortov 2026-10-15 11:56:59 +10:00
parent ff66bbde52
commit 0ecd07d2a9
4 changed files with 86 additions and 3 deletions

View File

@ -245,6 +245,18 @@ def on_unread_changed(sender, user, **kwargs):
unread_count(user)
```
Новый browser-получатель после коммита шлёт `browser_notification_created` с аргументами `user` и `notification`. Прочтение, удаление и остальные каналы этот сигнал не вызывают.
```python
from django.dispatch import receiver
from notify.signals import browser_notification_created
@receiver(browser_notification_created)
def on_browser_notification(sender, user, notification, **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.

View File

@ -4,10 +4,11 @@ from django.dispatch import receiver
from notify.delivery import get_provider
from notify.models import DeliveryChannel, NotificationAttachment, NotificationRecipient
from notify.signals import schedule_unread_count_changed
from notify.signals import schedule_browser_notification_created, schedule_unread_count_changed
__all__ = [
"delete_attachment_file",
"emit_browser_notification_created",
"emit_unread_count_on_delete",
"emit_unread_count_on_save",
"post_save_notification",
@ -41,6 +42,13 @@ def emit_unread_count_on_save(sender, instance: NotificationRecipient, created,
schedule_unread_count_changed(instance.user_id)
@receiver(post_save, sender=NotificationRecipient)
def emit_browser_notification_created(sender, instance: NotificationRecipient, created, **kwargs):
if not created or instance.channel != DeliveryChannel.BROWSER or not instance.user_id:
return
schedule_browser_notification_created(instance.user_id, instance.notification_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:

View File

@ -2,9 +2,11 @@ from django.contrib.auth import get_user_model
from django.db import transaction
from django.dispatch import Signal
from notify.models import NotificationRecipient
from notify.models import Notification, NotificationRecipient
__all__ = [
"browser_notification_created",
"schedule_browser_notification_created",
"schedule_unread_count_changed",
"unread_count_changed",
]
@ -23,3 +25,24 @@ def schedule_unread_count_changed(user_id: int) -> None:
unread_count_changed.send(sender=NotificationRecipient, user=user)
transaction.on_commit(emit)
browser_notification_created = Signal()
def schedule_browser_notification_created(user_id: int, notification_id: int) -> None:
if not user_id or not notification_id:
return
def emit():
user = get_user_model().objects.filter(pk=user_id).first()
notification = Notification.objects.filter(pk=notification_id).first()
if user is None or notification is None:
return
browser_notification_created.send(
sender=NotificationRecipient,
user=user,
notification=notification,
)
transaction.on_commit(emit)

View File

@ -7,7 +7,7 @@ from django.utils import timezone
from notify.models import DeliveryChannel
from notify.services import create_notification, unread_count
from notify.signals import unread_count_changed
from notify.signals import browser_notification_created, unread_count_changed
User = get_user_model()
@ -113,3 +113,43 @@ class UnreadCountTests(TestCase):
self.assertEqual(unread_count(self.user), 1)
self.assertEqual(unread_count(self.other), 1)
self.assertEqual(unread_count(None), 0)
class BrowserNotificationCreatedTests(TestCase):
def setUp(self):
self.user = User.objects.create_user("alice", "alice@example.com", "pass")
self.events = []
browser_notification_created.connect(self._record)
def tearDown(self):
browser_notification_created.disconnect(self._record)
def _record(self, sender, user, notification, **kwargs):
self.events.append((user.pk, notification.pk))
def test_browser_create_sends_user_and_notification(self):
with self.captureOnCommitCallbacks(execute=True):
notification = create_notification(
title="Hi",
recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}],
)
self.assertEqual(self.events, [(self.user.pk, notification.pk)])
self.events.clear()
with self.captureOnCommitCallbacks(execute=True):
notification.recipients.get().make_read()
self.assertEqual(self.events, [])
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.events, [])