Signal unread_count_changed when browser notifications change.

Host apps can subscribe and decide how to refresh the unread count.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Ilya Mukhortov 2026-10-15 11:24:03 +10:00
parent 95b231ae0a
commit 6e2f2f29b9
5 changed files with 135 additions and 2 deletions

View File

@ -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.

View File

@ -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 {}

View File

@ -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:

25
notify/signals.py Normal file
View File

@ -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)

View File

@ -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])