lizerk 5220a96684 refactor: Модуль notifications полностью самостоятельный и переиспользуемый
КРИТИЧНЫЕ УЛУЧШЕНИЯ:
✅ Убран хардкод 'EUSRR' → универсальное 'My Site'
✅ Созданы email шаблоны внутри модуля (4 файла)
✅ Централизованная конфигурация в config.py
✅ API перемещен в notifications/api/

Новые файлы:
- config.py - централизованные настройки с fallback значениями
- templates/notifications/email/*.html/*.txt - HTML и текстовые шаблоны
- api/__init__.py, api/views.py, api/urls.py - REST API внутри модуля

Изменения в существующих файлах:
- senders/email.py: использует config.site_name() и config.from_email()
- tasks/email.py: rate_limit, max_retries, retry_delay из config
- tasks/push.py: rate_limit, max_retries, retry_delay из config
- tasks/websocket.py: max_retries, retry_delay из config
- api/v1/notifications/urls.py: реэкспорт из notifications.api (обратная совместимость)

Структура шаблонов:
📁 notifications/templates/notifications/email/
  ├── notification.html - красивый HTML для обычных уведомлений
  ├── notification.txt - текстовая версия
  ├── digest.html - HTML дайджест (daily/weekly)
  └── digest.txt - текстовая версия дайджеста

Конфигурация (config.py):
- DEFAULT_CONFIG с fallback значениями для всех параметров
- get_config() - объединяет с settings.NOTIFICATIONS_CONFIG
- Удобные функции: email_rate_limit(), push_max_retries(), site_name()
- Полностью настраиваемо через settings проекта

API внутри модуля:
- notifications/api/views.py - все endpoint'ы
- notifications/api/urls.py - URL patterns
- Относительные импорты (from ..models)
- Обратная совместимость через api/v1/notifications/urls.py

УНИВЕРСАЛЬНОСТЬ:
✅ Нет хардкода проекта
✅ Все шаблоны внутри модуля
✅ API внутри модуля
✅ Конфигурация через settings
✅ Можно скопировать в любой проект Django 5.2+
2026-03-09 17:06:20 +03:00

66 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
Celery задачи для отправки WebSocket уведомлений (realtime)
"""
from .base import BaseNotificationTask
from notifications import config
class WebSocketNotificationTask(BaseNotificationTask):
"""
Celery задача для асинхронной отправки WebSocket уведомлений.
Особенности:
- Минимальный retry: из config (default: 1 попытка)
- Быстрая повторная попытка: из config (default: 5 секунд)
- Поддержка silent режима (DND)
"""
task_name = "notifications.send_websocket"
max_retries = config.websocket_max_retries()
retry_delay = config.websocket_retry_delay()
rate_limit = None # Без ограничений для realtime
def execute(self, celery_task, notification_id: int, silent: bool = False, **kwargs):
"""Переопределяем для поддержки параметра silent"""
try:
notification = self.get_notification(notification_id)
if not notification:
self.logger.error(f"❌ Notification {notification_id} not found")
return False
# Отправляем с учетом silent режима
success = self.send_notification(notification, silent=silent, **kwargs)
if success:
self.log_success(notification)
else:
self.log_failure(notification)
return success
except Exception as exc:
self.log_error(notification_id, exc)
raise celery_task.retry(exc=exc)
def send_notification(self, notification, silent: bool = False, **kwargs) -> bool:
"""
Отправляет WebSocket через WebSocketNotificationSender.
Args:
notification: Объект Notification
silent: Если True, уведомление без звука/визуальных эффектов
**kwargs: Дополнительные параметры
Returns:
True если успешно, False иначе
"""
from notifications.senders.websocket import WebSocketNotificationSender
sender = WebSocketNotificationSender()
return sender.send(notification, silent=silent, **kwargs)
# Регистрируем задачу в Celery
send_websocket_notification = WebSocketNotificationTask.register_task()