from django.db import transaction 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 DeliveryChannel, NotificationAttachment, NotificationRecipient 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", ] @receiver(post_save, sender=NotificationRecipient) def post_save_notification(sender, instance: NotificationRecipient, created, **kwargs): if not created: return provider = get_provider(instance.channel) if provider is None or not provider.requires_async_delivery: return recipient_id = instance.id def enqueue(): current = get_provider(instance.channel) if current is not None: current.enqueue(recipient_id) 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_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: return schedule_unread_count_changed(instance.user_id) @receiver(post_delete, sender=NotificationAttachment) def delete_attachment_file(sender, instance: NotificationAttachment, **kwargs): if instance.file: instance.file.delete(save=False)