326 lines
12 KiB
Python

"""
Web Push отправитель для browser push notifications
"""
import json
from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from push_notifications.models import WebPushDevice
from .base import BaseNotificationSender
from ..config import get
from ..models import NotificationDeliveryRouting, NotificationInstallation
from ..routing import APP_MAIN, APP_MESSENGER, normalize_routes, notification_category
class PushNotificationSender(BaseNotificationSender):
"""
Отправитель Web Push уведомлений через django-push-notifications.
Доставляет уведомления в браузер даже когда вкладка закрыта.
"""
CHAT_NOTIFICATION_VERBS = {
"chat_new_message",
"chat_mention",
"chat_reply",
"announcement_new_message",
}
DEFAULT_TITLE = "Новое уведомление"
def can_send(self, notification, user_preferences) -> bool:
"""Проверяет, включены ли push уведомления"""
if not user_preferences.push_enabled:
self.log_skip(notification, "push_enabled=False")
return False
return True
def _get_actor_name(self, notification) -> str:
actor = notification.actor
if not actor:
return ""
return str(actor).strip()
def _get_data_title(self, notification) -> str:
data = notification.data if isinstance(notification.data, dict) else {}
title = data.get("title")
if not isinstance(title, str):
return ""
return title.strip()
def _get_site_url(self) -> str:
site_url = getattr(settings, "SITE_URL", "").strip()
if site_url:
return site_url.rstrip("/")
if settings.ALLOWED_HOSTS and settings.ALLOWED_HOSTS[0] != "*":
protocol = (
"https"
if getattr(settings, "SECURE_SSL_REDIRECT", False)
else "http"
)
return f"{protocol}://{settings.ALLOWED_HOSTS[0]}"
return "http://localhost:9000"
def _get_actor_avatar_url(self, notification) -> str:
actor = notification.actor
if not actor:
return ""
try:
avatar = getattr(actor, "avatar", None)
if not avatar:
return ""
avatar_url = avatar.url
except Exception:
return ""
if not avatar_url:
return ""
if avatar_url.startswith(("http://", "https://")):
return avatar_url
if avatar_url.startswith("/"):
return f"{self._get_site_url()}{avatar_url}"
return f"{self._get_site_url()}/{avatar_url}"
def _build_title(self, notification) -> str:
if notification.verb in self.CHAT_NOTIFICATION_VERBS:
return self._get_actor_name(notification) or self.DEFAULT_TITLE
return self._get_data_title(notification) or self.DEFAULT_TITLE
def _is_permanent_device_error(self, error: Exception) -> bool:
error_text = str(error).lower()
permanent_markers = (
"expired",
"unregistered",
"invalid subscription",
"invalidregistration",
"not found",
"gone",
"404",
"410",
"400 bad request",
)
return any(marker in error_text for marker in permanent_markers)
def _deactivate_device(self, device, reason: str) -> None:
if not device.active:
return
device.active = False
device.save(update_fields=["active"])
NotificationInstallation.objects.filter(
push_device_id=device.id,
).update(endpoint=None, push_device_id=None)
self.logger.info(
"Push device %s deactivated after permanent delivery error: %s",
device.id,
reason,
)
def _delivery_devices(self, notification):
user = notification.recipient
active_devices = list(
WebPushDevice.objects.filter(user=user, active=True)
)
if not active_devices:
return [], {}
devices_by_endpoint = {
device.registration_id: device for device in active_devices
}
installations = list(
NotificationInstallation.objects.filter(
user=user,
active=True,
endpoint__in=devices_by_endpoint,
)
)
represented_endpoints = {
installation.endpoint for installation in installations
}
selected = [
device
for device in active_devices
if device.registration_id not in represented_endpoints
]
fallback_by_device_id = {}
category = notification_category(notification.verb)
routing_by_group = {
str(routing.device_group_id): normalize_routes(routing.routes)
for routing in NotificationDeliveryRouting.objects.filter(
user=user,
device_group_id__in={
installation.device_group_id
for installation in installations
},
)
}
grouped = {}
messenger_cutoff = timezone.now() - timedelta(
days=getattr(settings, "MESSENGER_PUSH_LEASE_DAYS", 30),
)
for installation in installations:
if (
installation.app_kind == APP_MESSENGER
and installation.last_seen_at < messenger_cutoff
):
continue
grouped.setdefault(str(installation.device_group_id), {}).setdefault(
installation.app_kind,
[],
).append(devices_by_endpoint[installation.endpoint])
for group_id, app_devices in grouped.items():
routes = routing_by_group.get(group_id, normalize_routes({}))
destinations = routes[category]
main_devices = app_devices.get(APP_MAIN, [])
messenger_devices = app_devices.get(APP_MESSENGER, [])
if APP_MAIN in destinations:
selected.extend(main_devices)
if APP_MESSENGER in destinations:
if messenger_devices:
selected.extend(messenger_devices)
if APP_MAIN not in destinations and main_devices:
for messenger_device in messenger_devices:
fallback_by_device_id[messenger_device.id] = main_devices
elif APP_MAIN not in destinations:
selected.extend(main_devices)
unique_selected = {device.id: device for device in selected}
return list(unique_selected.values()), fallback_by_device_id
def send(self, notification, **kwargs) -> bool:
"""
Отправляет Web Push уведомление.
Args:
notification: Объект Notification
**kwargs: Дополнительные параметры
Returns:
True если отправлено успешно, False иначе
"""
try:
devices, fallback_by_device_id = self._delivery_devices(notification)
if not devices:
self.log_skip(notification, "no active push devices")
return False
# Формируем данные для push без технических verb в видимом тексте.
title = self._build_title(notification)
# Ограничиваем длину body.
# Web Push имеет лимит ~4KB на весь payload.
# Оставляем 300 символов для body, чтобы гарантировать что весь
# message
# поместится
body = notification.description or ""
if len(body) > 300:
body = body[:297] + "..."
# Получаем иконки из конфигурации (None = browser default)
actor_icon = (
self._get_actor_avatar_url(notification)
if notification.verb in self.CHAT_NOTIFICATION_VERBS
else ""
)
default_icon = get("PUSH_DEFAULT_ICON")
default_badge = get("PUSH_DEFAULT_BADGE")
# django-push-notifications использует другой формат
# Формируем данные для Web Push API
message_data = {
"title": title,
"head": title,
"body": body,
"url": notification.action_url or "/",
"tag": f"notification-{notification.id}",
"requireInteraction": False,
"data": {
"url": notification.action_url or "/",
"notification_id": notification.id,
},
}
# Для сообщений используем аватар автора, иначе текущую иконку.
if actor_icon:
message_data["icon"] = actor_icon
elif default_icon:
message_data["icon"] = default_icon
if default_badge:
message_data["badge"] = default_badge
# Преобразуем в JSON-строку для send_message()
message = json.dumps(message_data)
sent_count = 0
failed_count = 0
# Отправляем через все устройства пользователя
sent_device_ids = set()
def send_to_device(device):
nonlocal sent_count, failed_count
try:
device.send_message(message)
sent_count += 1
sent_device_ids.add(device.id)
self.logger.debug(
"Push отправлен на device %s (%s)",
device.id,
device.browser,
)
return True
except Exception as e:
failed_count += 1
# Вычисляем размер payload для диагностики
message_size = len(message.encode("utf-8"))
error_text = str(e)
self.logger.error(
f"Ошибка отправки push на device {device.id}: {e} "
f"(payload size: {message_size} bytes)"
)
if self._is_permanent_device_error(e):
self._deactivate_device(device, error_text)
return False
for device in devices:
delivered = send_to_device(device)
if delivered:
continue
for fallback_device in fallback_by_device_id.get(device.id, []):
if fallback_device.id in sent_device_ids:
continue
if send_to_device(fallback_device):
break
if sent_count > 0:
self.log_success(notification, f"{sent_count} devices")
if failed_count > 0:
self.logger.warning(
f"Push отправлен частично: {sent_count} успешно, "
f"{failed_count} ошибок"
)
return True
else:
self.log_skip(
notification,
f"no successful sends ({failed_count} failures)",
)
return False
except ImportError:
self.log_skip(
notification, "django-push-notifications not installed"
)
return False
except Exception as e:
self.log_error(notification, e, f"user_{notification.recipient.id}")
return False