lizerk d5b4ae9f43 refactor: Полный переход на новую архитектуру уведомлений v2.0
BREAKING CHANGES:
- Удалена старая система (6 моделей → 2 модели)
- models_new.py → models.py (Notification, UserChannelPreferences)
- signals_new.py → signals.py (notify.send API)
- admin_new.py → admin.py

Новая архитектура:
- Все отправки через Celery (полностью асинхронно)
- Модульная структура tasks/ (base, email, push, websocket)
- Каждый канал - отдельный класс задачи наследующий BaseNotificationTask
- Rate limiting, retry, приоритеты из коробки

Обратная совместимость:
- Создан services.py facade для старого API
- NotificationService.create_notification() работает через notify.send()
- Старый код продолжает работать без изменений

Удалено:
- Старые models.py, signals.py, admin.py, tasks.py (→ .old)
- telegram_bot.py, telegram_models.py (Telegram отключен)
- test_views.py, views.py, urls.py (устаревшие)

Создано:
- tasks/ модуль с классовой архитектурой (как senders/)
- tasks/base.py - BaseNotificationTask
- tasks/email.py - EmailNotificationTask + DigestEmailTask
- tasks/push.py - PushNotificationTask
- tasks/websocket.py - WebSocketNotificationTask

Обновлено:
- apps.py - загружает signals, channels, tasks
- channels.py - все отправки через Celery задачи
- Все импорты models_new → models
2026-03-09 16:36:14 +03:00

65 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
class WebSocketNotificationTask(BaseNotificationTask):
"""
Celery задача для асинхронной отправки WebSocket уведомлений.
Особенности:
- Минимальный retry (1 попытка) - realtime не критично
- Быстрая повторная попытка (5 секунд)
- Поддержка silent режима (DND)
"""
task_name = "notifications.send_websocket"
max_retries = 1 # WebSocket - не критично, 1 попытка достаточно
retry_delay = 5 # 5 секунд (быстро)
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()