259 lines
8.8 KiB
Python
259 lines
8.8 KiB
Python
from django.db import IntegrityError, transaction
|
|
from django.utils import timezone
|
|
|
|
from notify.attachments import discard_attachments, prepare_attachments, store_attachments
|
|
from notify.delivery import get_provider
|
|
from notify.models import (
|
|
DeliveryChannel,
|
|
Notification,
|
|
NotificationChannelPreference,
|
|
NotificationLevel,
|
|
NotificationRecipient,
|
|
NotificationType,
|
|
)
|
|
|
|
__all__ = [
|
|
"create_notification",
|
|
"channel_preferences",
|
|
"save_channel_preferences",
|
|
]
|
|
|
|
|
|
def _resolve_type(notification_type):
|
|
if notification_type is None:
|
|
return None
|
|
if isinstance(notification_type, NotificationType):
|
|
return notification_type
|
|
return NotificationType.objects.get(code=notification_type)
|
|
|
|
|
|
def _existing_idempotent(idempotency_key):
|
|
if not idempotency_key:
|
|
return None
|
|
return Notification.objects.filter(idempotency_key=idempotency_key).first()
|
|
|
|
|
|
def _allowed_channels(notification_type, user, channels):
|
|
if notification_type is None or not notification_type.configurable:
|
|
return channels
|
|
allowed = set(notification_type.channels)
|
|
prefs = {
|
|
pref.channel: pref.enabled
|
|
for pref in NotificationChannelPreference.objects.filter(
|
|
user=user,
|
|
type=notification_type,
|
|
channel__in=allowed,
|
|
)
|
|
}
|
|
kept = []
|
|
for channel_data in channels:
|
|
channel = channel_data["channel"]
|
|
if channel not in allowed:
|
|
raise ValueError(
|
|
f"Channel {channel} is not allowed for notification type {notification_type.code}"
|
|
)
|
|
if prefs.get(channel, notification_type.enabled_by_default):
|
|
kept.append(channel_data)
|
|
return kept
|
|
|
|
|
|
def _grouped_notification(notification_type, user, object_id):
|
|
if notification_type is None or not object_id:
|
|
return None
|
|
return (
|
|
Notification.objects.select_for_update()
|
|
.filter(
|
|
type=notification_type,
|
|
object_id=object_id,
|
|
expires_at__gte=timezone.now(),
|
|
recipients__user=user,
|
|
recipients__delivery_channel=DeliveryChannel.BROWSER,
|
|
recipients__unread=True,
|
|
)
|
|
.order_by("-created_at")
|
|
.first()
|
|
)
|
|
|
|
|
|
def _bump_group(notification, verb):
|
|
payload = dict(notification.data or {})
|
|
payload["count"] = int(payload.get("count", 1)) + 1
|
|
notification.data = payload
|
|
if verb:
|
|
notification.verb = verb
|
|
notification.save(update_fields=["data", "verb"])
|
|
return notification
|
|
|
|
|
|
def _collapse_grouped(notification_type, recipients, object_id, verb):
|
|
pending = []
|
|
grouped = []
|
|
seen = set()
|
|
for recipient_data in recipients:
|
|
found = _grouped_notification(notification_type, recipient_data["user"], object_id)
|
|
if found is None:
|
|
pending.append(recipient_data)
|
|
continue
|
|
if found.pk not in seen:
|
|
seen.add(found.pk)
|
|
grouped.append(found)
|
|
for notification in grouped:
|
|
_bump_group(notification, verb)
|
|
return pending, grouped
|
|
|
|
|
|
def _attach_recipients(notification, recipients, notification_type):
|
|
created = 0
|
|
seen = set()
|
|
allowed_channels = set(notification_type.channels) if notification_type is not None else None
|
|
for recipient_data in recipients:
|
|
channels = recipient_data.get("channels") or []
|
|
if not channels:
|
|
raise ValueError("Recipient has no channels")
|
|
user = recipient_data["user"]
|
|
channels = _allowed_channels(notification_type, user, channels)
|
|
for channel_data in channels:
|
|
channel = channel_data["channel"]
|
|
if allowed_channels is not None and channel not in allowed_channels:
|
|
raise ValueError(
|
|
f"Channel {channel} is not allowed for notification type {notification_type.code}"
|
|
)
|
|
identity = (user.pk, channel)
|
|
if identity in seen:
|
|
raise ValueError(f"Duplicate recipient for user {user.pk} and channel {channel}")
|
|
seen.add(identity)
|
|
provider = get_provider(channel)
|
|
if provider is None:
|
|
raise ValueError(f"No delivery provider registered for channel: {channel}")
|
|
target = provider.validate_target(channel_data.get("target"))
|
|
NotificationRecipient.objects.create(
|
|
notification=notification,
|
|
user=user,
|
|
delivery_channel=channel,
|
|
delivery_target=target.model_dump() if target is not None else None,
|
|
)
|
|
created += 1
|
|
if created == 0:
|
|
raise ValueError("No recipients to deliver")
|
|
return created
|
|
|
|
|
|
def create_notification(
|
|
*,
|
|
recipients: list[dict],
|
|
verb: str | None = None,
|
|
url: str | None = None,
|
|
type: NotificationType | str | None = None,
|
|
level: str = NotificationLevel.INFO,
|
|
object_id: str = "",
|
|
description: str | None = None,
|
|
data: dict | None = None,
|
|
expires_at=None,
|
|
idempotency_key: str | None = None,
|
|
group: bool = False,
|
|
attachments=None,
|
|
) -> Notification:
|
|
if isinstance(idempotency_key, str):
|
|
idempotency_key = idempotency_key.strip() or None
|
|
existing = _existing_idempotent(idempotency_key)
|
|
if existing is not None:
|
|
return existing
|
|
|
|
prepared_attachments = prepare_attachments(attachments)
|
|
notification_type = _resolve_type(type)
|
|
if notification_type is not None and not notification_type.is_active:
|
|
raise ValueError(f"Notification type {notification_type.code} is inactive")
|
|
|
|
if not verb:
|
|
verb = notification_type.verb if notification_type is not None else None
|
|
if not verb:
|
|
raise ValueError("verb is required")
|
|
|
|
if not recipients:
|
|
raise ValueError("At least one recipient is required")
|
|
|
|
stored_attachments = []
|
|
try:
|
|
with transaction.atomic():
|
|
for recipient_data in recipients:
|
|
if not (recipient_data.get("channels") or []):
|
|
raise ValueError("Recipient has no channels")
|
|
to_create = recipients
|
|
if group:
|
|
to_create, grouped = _collapse_grouped(
|
|
notification_type,
|
|
recipients,
|
|
object_id or "",
|
|
verb,
|
|
)
|
|
for grouped_notification in grouped:
|
|
store_attachments(grouped_notification, prepared_attachments, stored_attachments)
|
|
if not to_create:
|
|
return grouped[0]
|
|
fields = dict(
|
|
url=url,
|
|
type=notification_type,
|
|
level=level,
|
|
verb=verb,
|
|
object_id=object_id or "",
|
|
description=description,
|
|
data=data or {},
|
|
idempotency_key=idempotency_key,
|
|
)
|
|
if expires_at is not None:
|
|
fields["expires_at"] = expires_at
|
|
notification = Notification.objects.create(**fields)
|
|
_attach_recipients(notification, to_create, notification_type)
|
|
store_attachments(notification, prepared_attachments, stored_attachments)
|
|
except IntegrityError:
|
|
discard_attachments(stored_attachments)
|
|
existing = _existing_idempotent(idempotency_key)
|
|
if existing is None:
|
|
raise
|
|
return existing
|
|
except Exception:
|
|
discard_attachments(stored_attachments)
|
|
raise
|
|
return notification
|
|
|
|
|
|
def channel_preferences(user):
|
|
types = NotificationType.objects.filter(is_active=True, configurable=True)
|
|
saved = {
|
|
(pref.type_id, pref.channel): pref.enabled
|
|
for pref in NotificationChannelPreference.objects.filter(user=user)
|
|
}
|
|
return [
|
|
{
|
|
"code": notification_type.code,
|
|
"channels": [
|
|
{
|
|
"channel": channel,
|
|
"enabled": saved.get(
|
|
(notification_type.id, channel),
|
|
notification_type.enabled_by_default,
|
|
),
|
|
}
|
|
for channel in notification_type.channels
|
|
],
|
|
}
|
|
for notification_type in types
|
|
]
|
|
|
|
|
|
def save_channel_preferences(user, items):
|
|
for item in items:
|
|
notification_type = NotificationType.objects.get(code=item["code"], configurable=True)
|
|
for channel_item in item["channels"]:
|
|
channel = channel_item["channel"]
|
|
if channel not in notification_type.channels:
|
|
raise ValueError(
|
|
f"Channel {channel} is not allowed for {notification_type.code}"
|
|
)
|
|
NotificationChannelPreference.objects.update_or_create(
|
|
user=user,
|
|
type=notification_type,
|
|
channel=channel,
|
|
defaults={"enabled": channel_item["enabled"]},
|
|
)
|