commit f7787359c3da03101f8e7c56fa425c2d687749db Author: Ilya Mukhortov Date: Fri Oct 9 12:26:18 2026 +1000 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1aa8217 --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +*.egg-info +*.pot +*.py[co] +*.bat +*.pyproj +*.sln +__pycache__ +.DS_Store +.idea/* +.venv/* +.tmp/* +.env +db.sqlite3 +media/ diff --git a/.python-version b/.python-version new file mode 100644 index 0000000..c8cfe39 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.10 diff --git a/Readme.md b/Readme.md new file mode 100644 index 0000000..eaf06d2 --- /dev/null +++ b/Readme.md @@ -0,0 +1,130 @@ +# notify + +Django-приложение для уведомлений пользователя: запись в базу, доставка по каналам и API непрочитанных сообщений в браузере. + +## Подключение + +```python +INSTALLED_APPS = [ + ... + "notify", +] +``` + +Приложение использует `AUTH_USER_MODEL` проекта. После подключения: + +```bash +python manage.py migrate +``` + +Создание уведомления из кода хоста: + +```python +from django.core.files.base import ContentFile + +from notify.services import create_notification + +create_notification( + verb="Заявка одобрена", + attachments=[ContentFile(b"...", name="report.pdf")], + recipients=[ + { + "user": user, + "channels": [ + {"channel": "browser"}, + {"channel": "email", "target": {"email": user.email}}, + ], + } + ], +) +``` + +`create_notification` выбрасывает `ValueError`, если тип выключен, канал не входит в тип, канал неизвестен или получатель продублирован. Неактивный тип и пропущенный канал не оставляют пустое уведомление в базе. + +Получатель канала задаётся словарём `target`, который проверяется pydantic-схемой провайдера: `email` — `{"email": ...}`, `telegram` — `{"chat_id": ...}`, `max` — `{"chat_id": ..., "user_id": ...}` (`user_id` необязателен). У `browser` `target` нет. В базе он хранится в `NotificationRecipient.delivery_target`. Если у типа `can_switch=True`, канал с `NotificationChannelPreference.enabled=False` не создаётся. Строки предпочтения нет — канал остаётся включённым. `can_switch=False` не смотрит на предпочтения. Если после фильтра не осталось получателей, уведомление откатывается. + +Повтор с тем же `idempotency_key` возвращает уже созданную строку и не добавляет новые файлы. `group=True` при непустом `object_id` увеличивает `data["count"]` у непрочитанного browser-уведомления того же типа и объекта и не создаёт новую строку. Файлы такого вызова копируются и на схлопнутое уведомление, и на новое, если часть получателей не схлопнулась. + +`attachments` — список Django-файлов (`UploadedFile`, `File`, `ContentFile` с именем). Пустое имя, больше 10 файлов или файл больше 10 МБ дают `ValueError`, уведомление не сохраняется. Лимиты переопределяются настройками `NOTIFY_MAX_ATTACHMENTS` и `NOTIFY_MAX_ATTACHMENT_BYTES`. Файлы лежат в default storage по пути `notify/attachments/` и не раздаются через `MEDIA_URL`. Удаление уведомления удаляет файлы из хранилища. В письмо они попадают вложением. Telegram и MAX остаются текстом. + +## Доставка + +Каналы `email`, `max` и `telegram` ставятся в Celery-задачу `notify.tasks.deliver_notification` после коммита транзакции. Канал `browser` помечается отправленным сразу и попадает в API. + +Воркер берёт строку получателя с блокировкой. Ошибка SMTP или временная ошибка HTTP повторяется до 5 раз с паузами 1, 2, 4, 8 и 16 минут (плюс до 10% случайной добавки). Таймаут SMTP и HTTP — 10 секунд. Каждая попытка увеличивает `attempts` и пишет `last_error`. Постоянная ошибка и исчерпание попыток ставят статус `FAILED`. Успех ставит `SENT` и `sent_at`. + +Нужен брокер Celery и автообнаружение задач установленного приложения `notify`. Расписание удаления просроченных уведомлений (раз в час): + +```python +from notify.tasks import BEAT_SCHEDULE + +app.conf.beat_schedule.update(BEAT_SCHEDULE) +``` + +Туда же входит удаление просроченных кодов подтверждения (раз в час, в :30). Без этой записи строки с истёкшим `expires_at` не удаляются. API их всё равно не показывает. + +Почтовый конфиг по умолчанию: порт `587`, `use_tls=True`, `use_ssl=False`. Одновременно включить SSL и TLS нельзя. Для каждого канала хранится один конфиг и один шаблон с `is_default=True` и пустым типом. Шаблон с указанным типом используется только для этой пары тип+канал, иначе берётся дефолт канала. + +Пароль SMTP и токены MAX и Telegram лежат в базе открытым текстом. В форме админки значение не подставляется обратно в HTML; пустое поле при сохранении оставляет прежний секрет. Проверка SMTP в админке — только POST. + +## Коды подтверждения + +Одноразовые коды отправляются в `email`, `telegram` и `max` синхронно, без Celery и без создания `Notification`: + +```python +from notify.codes import CodeThrottled, send_code, verify_code + +try: + send_code(purpose="login", channel="email", target={"email": user.email}, user=user) +except CodeThrottled as exc: + ... # exc.retry_after — сколько секунд ждать + +send_code(purpose="login", channel="telegram", target={"chat_id": 42}) + +verify_code(purpose="login", channel="email", target={"email": user.email}, code="123456") # True / False +``` + +`target` проверяется так же, как в `create_notification`. Неизвестный канал, `browser` или некорректный получатель дают `ValueError`. Ошибка провайдера пробрасывается как `DeliveryError` или `PermanentDeliveryError`. В этом случае новый код не сохраняется, а предыдущий остаётся действующим. + +Код ищется по ключу `purpose` + канал + получатель. Email сравнивается без учёта регистра, для MAX ключом служит `user_id`, если он передан, иначе `chat_id`. Новый код гасит предыдущий. Повторная отправка раньше `NOTIFY_CODE_RESEND_INTERVAL` даёт `CodeThrottled`. `verify_code` возвращает `False`, если кода нет, он истёк, уже использован или попытки исчерпаны. Каждая проверка увеличивает `attempts`, успешная помечает код использованным. + +В базе лежит только HMAC от `SECRET_KEY` и id строки. Смена `SECRET_KEY` делает выданные коды недействительными. Сам код не пишется в базу, логи и тексты исключений. + +Текст по умолчанию: «Код подтверждения: 123456. Действует 5 мин.». Чтобы задать свой, передайте `type=` (код или объект `NotificationType`) и создайте `NotificationTemplate` с этим типом и каналом. Контекст шаблона: `code`, `ttl_minutes`, `purpose`, `user.id`, `user.username` (`user` равен `None`, если пользователь не передан). Шаблон канала по умолчанию для кодов не используется. + +Настройки: + +```python +NOTIFY_CODE_LENGTH = 6 # цифр +NOTIFY_CODE_TTL = 300 # секунд +NOTIFY_CODE_MAX_ATTEMPTS = 5 +NOTIFY_CODE_RESEND_INTERVAL = 60 # секунд, 0 — без ограничения +``` + +Просроченные коды удаляет задача `notify.tasks.delete_expired_codes`, она входит в `BEAT_SCHEDULE`. + +## API + +Маршруты читают browser-уведомления текущего пользователя (сессионная авторизация django-ninja): + +- `GET unread-count/` +- `GET count/` +- `GET list/` +- `GET attachments/{id}/` +- `POST make-read/{id}/` +- `POST make-unread/{id}/` +- `POST make-all-read/` + +Просроченные уведомления в эти выборки не входят. Некорректный id возвращает 404. + +`GET list/` отдаёт `attachments`: `id`, `name`, `size`, `content_type`, `url`. `GET attachments/{id}/` скачивает файл, если у текущего пользователя есть получатель этого уведомления и срок не истёк. Чужой и просроченный файл возвращают 404. + +API не кэширует ответы и не требует кэша или Redis. + +Шаблоны subject и body пишутся на Jinja2 и экранируют HTML. Фильтр `markdown` рендерит текст в HTML, предварительно экранируя сырой HTML: `{{ notification.description | markdown }}`. Пропущенное поле остаётся пустой строкой. Контекст — обычные словари, не модели: `notification.verb`, `notification.description`, `notification.url`, `notification.level`, `notification.data`, `notification.object_id`, `recipient.delivery_target` (например, `recipient.delivery_target.email`), `recipient.delivery_channel`, `user.username`. + +## Тесты + +```bash +DJANGO_SETTINGS_MODULE=tests.settings python -m django test tests +``` diff --git a/demo/demo/__init__.py b/demo/demo/__init__.py new file mode 100644 index 0000000..fb989c4 --- /dev/null +++ b/demo/demo/__init__.py @@ -0,0 +1,3 @@ +from .celery import app as celery_app + +__all__ = ('celery_app',) diff --git a/demo/demo/apps.py b/demo/demo/apps.py new file mode 100644 index 0000000..4d9516a --- /dev/null +++ b/demo/demo/apps.py @@ -0,0 +1,11 @@ +from django.apps import AppConfig + + +class DemoConfig(AppConfig): + name = 'demo' + + def ready(self): + from demo.celery import app + from notify.tasks import BEAT_SCHEDULE + + app.conf.beat_schedule.update(BEAT_SCHEDULE) diff --git a/demo/demo/asgi.py b/demo/demo/asgi.py new file mode 100644 index 0000000..ac0c86a --- /dev/null +++ b/demo/demo/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for demo project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demo.settings') + +application = get_asgi_application() diff --git a/demo/demo/celery.py b/demo/demo/celery.py new file mode 100644 index 0000000..734cb6f --- /dev/null +++ b/demo/demo/celery.py @@ -0,0 +1,9 @@ +import os + +from celery import Celery + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demo.settings') + +app = Celery('demo') +app.config_from_object('django.conf:settings', namespace='CELERY') +app.autodiscover_tasks() diff --git a/demo/demo/settings.py b/demo/demo/settings.py new file mode 100644 index 0000000..8bab0ee --- /dev/null +++ b/demo/demo/settings.py @@ -0,0 +1,132 @@ +""" +Django settings for demo project. + +Generated by 'django-admin startproject' using Django 5.0.6. + +For more information on this file, see +https://docs.djangoproject.com/en/5.0/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/5.0/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-xsl5fk9rcbk_n6rv7-!i27+h!z(d&8*6ab6!%4kyijiohxvn(e' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = [] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + 'notify', + 'demo.apps.DemoConfig', +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'demo.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'demo.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/5.0/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +LOGIN_URL = '/admin/login/' + +# Internationalization +# https://docs.djangoproject.com/en/5.0/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/5.0/howto/static-files/ + +STATIC_URL = 'static/' +MEDIA_ROOT = BASE_DIR / 'media' +MEDIA_URL = '/media/' + +# Default primary key field type +# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' + +CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' +CELERY_TASK_IGNORE_RESULT = True diff --git a/demo/demo/static/demo/inbox.js b/demo/demo/static/demo/inbox.js new file mode 100644 index 0000000..a8961eb --- /dev/null +++ b/demo/demo/static/demo/inbox.js @@ -0,0 +1,187 @@ +(function () { + const listEl = document.getElementById("list"); + const countEl = document.getElementById("unread-count"); + const statusEl = document.getElementById("status"); + const form = document.getElementById("create-form"); + const formError = document.getElementById("form-error"); + const unreadOnly = document.getElementById("unread-only"); + const markAll = document.getElementById("mark-all"); + + let refreshing = false; + + function csrfToken() { + const match = document.cookie.match(/(?:^|; )csrftoken=([^;]*)/); + return match ? decodeURIComponent(match[1]) : ""; + } + + function showStatus(message) { + statusEl.hidden = !message; + statusEl.textContent = message || ""; + } + + async function api(path, options) { + const response = await fetch(path, { + credentials: "same-origin", + ...options, + headers: { + "X-CSRFToken": csrfToken(), + ...(options && options.headers), + }, + }); + if (!response.ok) { + throw new Error(response.status + " " + path); + } + if (response.status === 204) { + return null; + } + const text = await response.text(); + return text ? JSON.parse(text) : null; + } + + function renderItem(item) { + const card = document.createElement("article"); + card.className = "item " + (item.level || "INFO") + (item.unread ? " unread" : ""); + + const verb = document.createElement("div"); + verb.className = "verb"; + verb.textContent = item.verb || ""; + card.appendChild(verb); + + if (item.description) { + const description = document.createElement("div"); + description.textContent = item.description; + card.appendChild(description); + } + + const meta = document.createElement("div"); + meta.className = "meta"; + const level = document.createElement("span"); + level.textContent = item.level || ""; + const time = document.createElement("time"); + const created = item.created_at ? new Date(item.created_at) : null; + time.dateTime = item.created_at || ""; + time.textContent = created && !Number.isNaN(created.getTime()) + ? created.toLocaleString() + : ""; + meta.append(level, time); + if (item.url) { + const link = document.createElement("a"); + link.href = item.url; + link.textContent = item.url; + link.target = "_blank"; + link.rel = "noreferrer"; + meta.appendChild(link); + } + card.appendChild(meta); + + if (item.attachments && item.attachments.length) { + const files = document.createElement("div"); + files.className = "files"; + item.attachments.forEach(function (file) { + const link = document.createElement("a"); + link.href = file.url; + link.textContent = file.name; + files.appendChild(link); + }); + card.appendChild(files); + } + + const action = document.createElement("button"); + action.type = "button"; + action.className = "ghost"; + action.textContent = item.unread ? "Прочитать" : "Вернуть в непрочитанные"; + action.addEventListener("click", function () { + const path = item.unread + ? "/api/make-read/" + item.id + "/" + : "/api/make-unread/" + item.id + "/"; + api(path, { method: "POST" }).then(refresh).catch(function (error) { + showStatus(error.message); + }); + }); + card.appendChild(action); + + if (item.unread) { + card.addEventListener("click", function (event) { + if (event.target.closest("a, button")) { + return; + } + api("/api/make-read/" + item.id + "/", { method: "POST" }) + .then(refresh) + .catch(function (error) { + showStatus(error.message); + }); + }); + } + + return card; + } + + function renderList(items) { + listEl.replaceChildren(); + if (!items.length) { + const empty = document.createElement("p"); + empty.className = "empty"; + empty.textContent = "Нет уведомлений"; + listEl.appendChild(empty); + return; + } + items.forEach(function (item) { + listEl.appendChild(renderItem(item)); + }); + } + + function refresh() { + if (refreshing) { + return Promise.resolve(); + } + refreshing = true; + const listPath = unreadOnly.checked ? "/api/list/?unread=true" : "/api/list/"; + return Promise.all([ + api("/api/unread-count/"), + api(listPath), + ]).then(function (payload) { + countEl.textContent = String(payload[0].result); + renderList(payload[1].results || []); + showStatus(""); + }).catch(function (error) { + showStatus(error.message); + }).finally(function () { + refreshing = false; + }); + } + + form.addEventListener("submit", function (event) { + event.preventDefault(); + formError.hidden = true; + formError.textContent = ""; + fetch("/create/", { + method: "POST", + credentials: "same-origin", + headers: { "X-CSRFToken": csrfToken() }, + body: new FormData(form), + }).then(function (response) { + return response.json().then(function (data) { + if (!response.ok) { + formError.hidden = false; + formError.textContent = (data && data.error) || "Не удалось создать уведомление"; + return; + } + form.reset(); + return refresh(); + }); + }).catch(function () { + formError.hidden = false; + formError.textContent = "Не удалось создать уведомление"; + }); + }); + + unreadOnly.addEventListener("change", refresh); + markAll.addEventListener("click", function () { + api("/api/make-all-read/", { method: "POST" }).then(refresh).catch(function (error) { + showStatus(error.message); + }); + }); + + refresh(); + setInterval(refresh, 3000); +})(); diff --git a/demo/demo/templates/demo/inbox.html b/demo/demo/templates/demo/inbox.html new file mode 100644 index 0000000..a6a3900 --- /dev/null +++ b/demo/demo/templates/demo/inbox.html @@ -0,0 +1,201 @@ +{% load static %} + + + + + + Уведомления + + + +
+

Уведомления

+ +
+
+ {% csrf_token %} + + +
+ + +
+ + +
+ +
+
+
+ +
+
+ Непрочитанные: 0 + + +
+ +
+
+
+ + + diff --git a/demo/demo/urls.py b/demo/demo/urls.py new file mode 100644 index 0000000..bdf77a2 --- /dev/null +++ b/demo/demo/urls.py @@ -0,0 +1,27 @@ +""" +URL configuration for demo project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/5.0/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import include, path + +from demo.views import create_notification_view, inbox + +urlpatterns = [ + path('admin/', admin.site.urls), + path('api/', include('notify.urls')), + path('create/', create_notification_view, name='create-notification'), + path('', inbox, name='inbox'), +] diff --git a/demo/demo/views.py b/demo/demo/views.py new file mode 100644 index 0000000..4e802e5 --- /dev/null +++ b/demo/demo/views.py @@ -0,0 +1,49 @@ +from django.contrib.auth.decorators import login_required +from django.http import JsonResponse +from django.shortcuts import render +from django.views.decorators.http import require_GET, require_POST + +from notify.models import DeliveryChannel, NotificationLevel +from notify.services import create_notification + + +@login_required +@require_GET +def inbox(request): + return render(request, "demo/inbox.html") + + +@login_required +@require_POST +def create_notification_view(request): + verb = (request.POST.get("verb") or "").strip() + description = (request.POST.get("description") or "").strip() or None + level = (request.POST.get("level") or NotificationLevel.INFO).strip() + url = (request.POST.get("url") or "").strip() or None + + if level not in NotificationLevel.values: + return JsonResponse({"ok": False, "error": "Unknown level"}, status=400) + + attachments = [ + uploaded + for uploaded in request.FILES.getlist("attachments") + if getattr(uploaded, "name", "") + ] + try: + create_notification( + verb=verb, + description=description, + level=level, + url=url, + attachments=attachments, + recipients=[ + { + "user": request.user, + "channels": [{"channel": DeliveryChannel.BROWSER}], + } + ], + ) + except ValueError as exc: + return JsonResponse({"ok": False, "error": str(exc)}, status=400) + + return JsonResponse({"ok": True}) diff --git a/demo/demo/wsgi.py b/demo/demo/wsgi.py new file mode 100644 index 0000000..235cded --- /dev/null +++ b/demo/demo/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for demo project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demo.settings') + +application = get_wsgi_application() diff --git a/demo/manage.py b/demo/manage.py new file mode 100755 index 0000000..d4cdb72 --- /dev/null +++ b/demo/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'demo.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/notify/__init__.py b/notify/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/notify/admin.py b/notify/admin.py new file mode 100644 index 0000000..4d01232 --- /dev/null +++ b/notify/admin.py @@ -0,0 +1,282 @@ + +from django import forms +from django.contrib import admin +from django.contrib.auth import get_user_model +from django.urls import reverse, path +from notify.admin_views import ( + delivery_email_test_connection, + delivery_email_send_test_message, +) +from ace_editor.widgets import AceEditorWidget + +from .models import ( + DeliveryChannel, + DeliveryEmailConfig, + DeliveryTokenConfig, + NotificationAttachment, + NotificationChannelPreference, + NotificationGroup, + NotificationTemplate, + NotificationType, + Notification, + NotificationRecipient, + VerificationCode, +) + +__all__ = [ + "DeliveryEmailConfigForm", + "DeliveryTokenConfigForm", + "DeliveryEmailConfigAdmin", + "DeliveryTokenConfigAdmin", + "NotificationTemplateAdmin", + "NotificationGroupAdmin", + "NotificationTypeAdmin", + "NotificationAttachmentInline", + "NotificationRecipientInline", + "NotificationAdmin", + "NotificationRecipientAdmin", + "VerificationCodeAdmin", +] + + +class DeliveryEmailConfigForm(forms.ModelForm): + class Meta: + model = DeliveryEmailConfig + fields = "__all__" + widgets = { + "password": forms.PasswordInput(render_value=False), + } + + def clean_password(self): + password = self.cleaned_data.get("password") + if not password and self.instance.pk: + return self.instance.password + return password + + +class DeliveryTokenConfigForm(forms.ModelForm): + class Meta: + model = DeliveryTokenConfig + fields = "__all__" + widgets = { + "token": forms.PasswordInput(render_value=False), + } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + allowed = {DeliveryChannel.MAX, DeliveryChannel.TELEGRAM} + self.fields["channel"].choices = [ + choice for choice in DeliveryChannel.choices if choice[0] in allowed + ] + + def clean_token(self): + token = self.cleaned_data.get("token") + if not token and self.instance.pk: + return self.instance.token + return token + + +@admin.register(DeliveryEmailConfig) +class DeliveryEmailConfigAdmin(admin.ModelAdmin): + list_display = ( + 'name', 'host', 'port', 'username', 'is_default' + ) + form = DeliveryEmailConfigForm + readonly_fields = ['id'] + + def change_view(self, request, object_id, form_url='', extra_context=None): + extra_context = extra_context or {} + info = self.model._meta.app_label, self.model._meta.model_name + extra_context['mailbox_test_connection_url'] = reverse( + 'admin:%s_%s_test_connection' % info, + args=[object_id], + ) + extra_context['mailbox_send_test_email_url'] = reverse( + 'admin:%s_%s_send_test_email' % info, + args=[object_id], + ) + return super().change_view(request, object_id, form_url, extra_context) + + def get_urls(self): + info = self.model._meta.app_label, self.model._meta.model_name + return [ + path( + '/test-connection/', + self.admin_site.admin_view(delivery_email_test_connection), + name='%s_%s_test_connection' % info, + ), + path( + '/send-test-email/', + self.admin_site.admin_view(delivery_email_send_test_message), + name='%s_%s_send_test_email' % info, + ), + ] + super().get_urls() + + +@admin.register(DeliveryTokenConfig) +class DeliveryTokenConfigAdmin(admin.ModelAdmin): + list_display = ( + 'name', 'channel', 'is_default' + ) + list_filter = ( + 'channel', + ) + readonly_fields = ['id'] + form = DeliveryTokenConfigForm + + +@admin.register(NotificationTemplate) +class NotificationTemplateAdmin(admin.ModelAdmin): + list_display = ( + 'id', + 'name', + 'channel', + 'type', + 'is_default', + ) + readonly_fields = ['id'] + form = forms.modelform_factory(NotificationTemplate, fields='__all__', widgets={ + 'subject_template': AceEditorWidget(mode='django', hide_label=False), + 'body_template': AceEditorWidget(mode='django', hide_label=False), + }) + save_on_top = True + + +@admin.register(NotificationGroup) +class NotificationGroupAdmin(admin.ModelAdmin): + list_display = ( + 'code', + 'name', + ) + search_fields = ( + 'code', + 'name', + ) + + +@admin.register(NotificationType) +class NotificationTypeAdmin(admin.ModelAdmin): + list_display = ( + 'code', + 'name', + 'group', + 'is_active', + ) + list_filter = ( + 'is_active', + 'group', + ) + search_fields = ( + 'code', + 'name', + ) + + +@admin.register(NotificationChannelPreference) +class NotificationChannelPreferenceAdmin(admin.ModelAdmin): + list_display = ( + 'user', + 'type', + 'channel', + 'enabled', + ) + list_filter = ( + 'channel', + 'enabled', + ) + + +class NotificationAttachmentInline(admin.TabularInline): + model = NotificationAttachment + extra = 0 + can_delete = False + fields = ("name", "content_type", "size", "created_at") + readonly_fields = ("name", "content_type", "size", "created_at") + + def has_add_permission(self, request, obj=None): + return False + + +class NotificationRecipientInline(admin.TabularInline): + model = NotificationRecipient + extra = 0 + + +@admin.register(Notification) +class NotificationAdmin(admin.ModelAdmin): + list_display = ( + 'verb', + 'description', + 'expires_at', + 'created_at' + ) + search_fields = ( + 'id', + 'type__code', + 'verb' + ) + inlines = [NotificationAttachmentInline, NotificationRecipientInline] + + def has_change_permission(self, request, obj = ...): + return False + + +@admin.register(NotificationRecipient) +class NotificationRecipientAdmin(admin.ModelAdmin): + list_display = ( + 'user', + 'notification', + 'unread', + 'delivery_channel', + 'delivery_status', + 'attempts', + ) + list_filter = ( + 'delivery_channel', + 'delivery_status', + 'unread' + ) + ordering = ( + '-notification__created_at', + ) + + def get_search_fields(self, request): + username_field = get_user_model().USERNAME_FIELD + return ( + 'id', + f'user__{username_field}', + 'notification__verb', + ) + + def has_change_permission(self, request, obj = ...): + return False + + +@admin.register(VerificationCode) +class VerificationCodeAdmin(admin.ModelAdmin): + list_display = ( + 'purpose', + 'channel', + 'target_key', + 'user', + 'attempts', + 'max_attempts', + 'expires_at', + 'consumed_at', + 'created_at', + ) + list_filter = ( + 'channel', + 'purpose', + ) + search_fields = ( + 'target_key', + 'purpose', + ) + exclude = ('code_hash',) + + def has_add_permission(self, request): + return False + + def has_change_permission(self, request, obj=None): + return False diff --git a/notify/admin_views.py b/notify/admin_views.py new file mode 100644 index 0000000..3abb7ad --- /dev/null +++ b/notify/admin_views.py @@ -0,0 +1,106 @@ +from django.core.mail import EmailMessage, get_connection +from django.core.exceptions import PermissionDenied +from django.http import Http404, HttpResponse +from django.views.decorators.http import require_POST + +from .models import DeliveryEmailConfig + +__all__ = [ + "delivery_email_test_connection", + "delivery_email_send_test_message", +] + + +def _load_email_config(request, object_id): + try: + email_config = DeliveryEmailConfig.objects.get(pk=object_id) + except DeliveryEmailConfig.DoesNotExist: + raise Http404 + + if not request.user.has_perm("notify.change_deliveryemailconfig"): + raise PermissionDenied + return email_config + + +@require_POST +def delivery_email_test_connection(request, object_id): + email_config = _load_email_config(request, object_id) + + header = "\n".join([ + f"Host: {email_config.host}:{email_config.port}", + f"Login: {email_config.username}", + f"SSL: {email_config.use_ssl}, TLS: {email_config.use_tls}", + f"From: {email_config.from_email or '-'}", + "", + "--- smtp connection test ---", + "", + ]) + + err = None + try: + connection = get_connection(**email_config.get_connection_config()) + test_message = EmailMessage( + subject="SMTP connection test", + body="Connection check only. Message is not sent.", + from_email=email_config.from_email or email_config.username or "no-reply@example.com", + to=[email_config.from_email or email_config.username] if (email_config.from_email or email_config.username) else [], + connection=connection, + ) + test_message.connection.open() + test_message.connection.close() + except Exception as exc: + err = exc + + log = header + if err is not None: + log += f"\n\nОшибка: {type(err).__name__}" + else: + log += "\n---\nПодключение к SMTP успешно (OPEN, LOGIN, CLOSE)." + + return HttpResponse(log, content_type="text/plain; charset=utf-8") + + +@require_POST +def delivery_email_send_test_message(request, object_id): + email_config = _load_email_config(request, object_id) + + header = "\n".join([ + f"Host: {email_config.host}:{email_config.port}", + f"Login: {email_config.username}", + f"SSL: {email_config.use_ssl}, TLS: {email_config.use_tls}", + f"From: {email_config.from_email or '-'}", + f"Test email: {email_config.test_email or '-'}", + "", + "--- smtp test message ---", + "", + ]) + + if not email_config.test_email: + return HttpResponse( + header + '\nОшибка: поле "Test email" не заполнено.', + content_type="text/plain; charset=utf-8", + ) + + err = None + try: + connection = get_connection(**email_config.get_connection_config()) + test_message = EmailMessage( + subject="SMTP test message", + body="Это тестовое письмо из админки notify.", + from_email=email_config.from_email or email_config.username or "no-reply@example.com", + to=[email_config.test_email], + connection=connection, + ) + test_message.content_subtype = "plain" + sent_count = test_message.send(fail_silently=False) + except Exception as exc: + err = exc + sent_count = 0 + + log = header + if err is not None: + log += f"\n\nОшибка: {type(err).__name__}" + else: + log += f"\n---\nТестовое письмо отправлено. Отправлено сообщений: {sent_count}." + + return HttpResponse(log, content_type="text/plain; charset=utf-8") diff --git a/notify/api.py b/notify/api.py new file mode 100644 index 0000000..98ce51f --- /dev/null +++ b/notify/api.py @@ -0,0 +1,149 @@ +import logging +from typing import List + +from django.core.exceptions import ObjectDoesNotExist +from django.http import FileResponse, Http404 +from django.utils import timezone +from ninja import NinjaAPI, Path, Query, Schema +from ninja.errors import ValidationError +from ninja.pagination import paginate +from ninja.security import django_auth + +from .api_filters import NotificationFilterSchema +from .api_pagination import CustomPagination +from .api_schema import NotificationResponseSchema +from .models import DeliveryChannel, NotificationAttachment, NotificationRecipient + +__all__ = [ + "api", +] + +api = NinjaAPI( + title="Notifications API", + version="1.0.0", + urls_namespace="notify", + docs_url="docs/", + auth=django_auth, +) +logger = logging.getLogger(__name__) + + +@api.exception_handler(Http404) +def not_found(request, exc): + return api.create_response( + request, + {"message": "Not found"}, + status=404, + ) + + +@api.exception_handler(ObjectDoesNotExist) +def object_not_found(request, exc): + return api.create_response( + request, + {"message": "Object not found"}, + status=404, + ) + + +@api.exception_handler(ValidationError) +def validation_errors(request, exc): + logger.error(f"Validation Error: {exc.errors}") + return api.create_response(request, {"detail": exc.errors}, status=422) + + +class DetailPath(Schema): + id: str + + +def _base_user_queryset(user): + return NotificationRecipient.objects.filter( + user=user, + delivery_channel=DeliveryChannel.BROWSER, + notification__expires_at__gte=timezone.now(), + ).select_related("notification", "notification__type").prefetch_related("notification__attachments") + + +def _parse_pk(raw_id: str) -> int: + try: + value = int(str(raw_id)) + except (ValueError, TypeError, AttributeError): + raise Http404 + if value < 1: + raise Http404 + return value + + +def _get_user_attachment(user, raw_id: str) -> NotificationAttachment: + attachment_id = _parse_pk(raw_id) + attachment = ( + NotificationAttachment.objects.filter( + id=attachment_id, + notification__expires_at__gte=timezone.now(), + notification__recipients__user=user, + ) + .distinct() + .first() + ) + if attachment is None: + raise Http404 + return attachment + + +def _get_user_recipient(user, raw_id: str) -> NotificationRecipient: + return _base_user_queryset(user).get(id=_parse_pk(raw_id)) + + +@api.get("unread-count/") +def unread_count(request): + count = _base_user_queryset(request.user).filter(unread=True).count() + return { + "result": count, + } + + +@api.post("make-read/{id}/", response=NotificationResponseSchema) +def make_read(request, path: Path[DetailPath]): + recipient = _get_user_recipient(request.user, path.id) + recipient.make_read() + return recipient + + +@api.post("make-unread/{id}/", response=NotificationResponseSchema) +def make_unread(request, path: Path[DetailPath]): + recipient = _get_user_recipient(request.user, path.id) + recipient.make_unread() + return recipient + + +@api.post("make-all-read/") +def make_all_read(request, filters: NotificationFilterSchema = Query(...)): + qs = filters.filter(_base_user_queryset(request.user)) + qs.filter(unread=True).update(unread=False) + return {} + + +@api.get("count/") +def count(request, filters: NotificationFilterSchema = Query(...)): + qs = filters.filter(_base_user_queryset(request.user)) + return dict(result=qs.count()) + + +@api.get("attachments/{id}/") +def download_attachment(request, path: Path[DetailPath]): + attachment = _get_user_attachment(request.user, path.id) + uploaded = attachment.file.open("rb") + return FileResponse( + uploaded, + as_attachment=True, + filename=attachment.name, + content_type=attachment.content_type or "application/octet-stream", + ) + + +@api.get("list/", response=List[NotificationResponseSchema]) +@paginate(CustomPagination) +def list(request, filters: NotificationFilterSchema = Query(...)): + qs = filters.filter(_base_user_queryset(request.user)) + qs = qs.order_by("-created_at") + return qs diff --git a/notify/api_filters.py b/notify/api_filters.py new file mode 100644 index 0000000..dddf330 --- /dev/null +++ b/notify/api_filters.py @@ -0,0 +1,35 @@ + +from typing import Optional, List, Annotated +from django.db.models import Q +from ninja import ( + FilterSchema, + FilterLookup +) + +__all__ = [ + "NotificationFilterSchema", +] + + +class NotificationFilterSchema(FilterSchema): + unread: Optional[bool] = None + type: Annotated[Optional[str], FilterLookup("notification__type__code")] = None + type__startswith: Annotated[Optional[str], FilterLookup("notification__type__code__startswith")] = None + object_id: Annotated[Optional[str], FilterLookup("notification__object_id")] = None + search: Annotated[ + Optional[str], + FilterLookup( + ["notification__verb__icontains", "notification__description__icontains"], + expression_connector="OR" + ) + ] = None + object_id__ne: Optional[List[str]] = None + object_id__ne__in: Optional[str] = None + + def filter_object_id__ne(self, value: List[str]) -> Q: + return ~Q(notification__object_id__in=value) + + def filter_object_id__ne__in(self, value: str) -> Q: + if value: + value = value.split(',') + return ~Q(notification__object_id__in=value) diff --git a/notify/api_pagination.py b/notify/api_pagination.py new file mode 100644 index 0000000..9782932 --- /dev/null +++ b/notify/api_pagination.py @@ -0,0 +1,45 @@ + +import math +from typing import List, Any + +from django.db.models import QuerySet +from ninja import ( + Schema, + Field, +) +from ninja.pagination import PageNumberPagination + +__all__ = [ + "CustomPagination", +] + + +class CustomPagination(PageNumberPagination): + + class Input(Schema): + page: int = Field(1, ge=1) + + items_attribute: str = "results" + + class Output(Schema): + results: List[Any] + total: int + pagination: Any + + def paginate_queryset( + self, + queryset: QuerySet, + pagination: Input, + **params: Any, + ) -> Any: + offset = (pagination.page - 1) * self.page_size + paginated_qs = queryset[offset: offset + self.page_size] + total = self._items_count(queryset) + return { + "results": list(paginated_qs), + "total": total, + "pagination": { + "page": pagination.page, + "total_pages": math.ceil(total / self.page_size), + } + } diff --git a/notify/api_schema.py b/notify/api_schema.py new file mode 100644 index 0000000..f18c41a --- /dev/null +++ b/notify/api_schema.py @@ -0,0 +1,58 @@ +from typing import Optional + +from django.urls import reverse +from ninja import Field, ModelSchema, Schema + +from .models import NotificationRecipient + +__all__ = [ + "AttachmentSchema", + "NotificationResponseSchema", +] + + +class AttachmentSchema(Schema): + id: int + name: str + size: int + content_type: str + url: str + + +class NotificationResponseSchema(ModelSchema): + url: Optional[str] = Field(alias="notification.url") + type: Optional[str] = None + level: Optional[str] = Field(alias="notification.level") + verb: Optional[str] = Field(alias="notification.verb") + object_id: Optional[str] = Field(alias="notification.object_id") + description: Optional[str] = Field(alias="notification.description") + data: dict = Field(alias="notification.data") + attachments: list[AttachmentSchema] + + class Meta: + model = NotificationRecipient + fields = [ + "id", + "unread", + "created_at", + ] + + @staticmethod + def resolve_type(obj): + notification_type = obj.notification.type + if notification_type is None: + return None + return notification_type.code + + @staticmethod + def resolve_attachments(obj): + return [ + { + "id": attachment.id, + "name": attachment.name, + "size": attachment.size, + "content_type": attachment.content_type, + "url": reverse("notify:download_attachment", kwargs={"id": attachment.id}), + } + for attachment in obj.notification.attachments.all() + ] diff --git a/notify/apps.py b/notify/apps.py new file mode 100644 index 0000000..9e4ecc3 --- /dev/null +++ b/notify/apps.py @@ -0,0 +1,17 @@ +from django.apps import AppConfig + +__all__ = [ + "NotifyConfig", +] + + +class NotifyConfig(AppConfig): + default_auto_field = "django.db.models.BigAutoField" + name = "notify" + verbose_name = "Notifications" + + def ready(self): + from notify.delivery.providers import register_builtin_providers + + register_builtin_providers() + import notify.receivers # noqa: F401 diff --git a/notify/attachments.py b/notify/attachments.py new file mode 100644 index 0000000..7d2b3b9 --- /dev/null +++ b/notify/attachments.py @@ -0,0 +1,95 @@ +import mimetypes +import os + +from django.conf import settings +from django.core.files.base import ContentFile + +from notify.models import NotificationAttachment + +__all__ = [ + "DEFAULT_MAX_ATTACHMENT_BYTES", + "DEFAULT_MAX_ATTACHMENTS", + "discard_attachments", + "max_attachment_bytes", + "max_attachments", + "prepare_attachments", + "store_attachments", +] + +DEFAULT_MAX_ATTACHMENTS = 10 +DEFAULT_MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024 + + +def max_attachments(): + return int(getattr(settings, "NOTIFY_MAX_ATTACHMENTS", DEFAULT_MAX_ATTACHMENTS)) + + +def max_attachment_bytes(): + return int(getattr(settings, "NOTIFY_MAX_ATTACHMENT_BYTES", DEFAULT_MAX_ATTACHMENT_BYTES)) + + +def clean_filename(raw): + name = os.path.basename(str(raw).replace("\\", "/")).replace("\x00", "").strip() + if name in {"", ".", ".."}: + return "" + return name[:255] + + +def prepare_attachments(attachments): + if not attachments: + return [] + files = list(attachments) + limit = max_attachments() + if len(files) > limit: + raise ValueError(f"At most {limit} attachments are allowed") + return [_read_attachment(uploaded) for uploaded in files] + + +def store_attachments(notification, prepared, stored): + for item in prepared: + row = NotificationAttachment( + notification=notification, + name=item["name"], + content_type=item["content_type"], + size=item["size"], + ) + row.file.save(item["name"], ContentFile(item["content"]), save=False) + stored.append(row) + row.save() + + +def discard_attachments(stored): + for row in stored: + if row.file: + row.file.delete(save=False) + + +def _read_attachment(uploaded): + if not hasattr(uploaded, "read"): + raise ValueError("Attachment must be a file") + name = clean_filename(getattr(uploaded, "name", "") or "") + if not name: + raise ValueError("Attachment must have a file name") + declared = getattr(uploaded, "size", None) + if declared is not None and declared > max_attachment_bytes(): + raise ValueError(f"Attachment {name} exceeds the size limit") + if hasattr(uploaded, "seek"): + try: + uploaded.seek(0) + except (OSError, ValueError): + pass + content = uploaded.read() + if isinstance(content, str): + content = content.encode() + if content is None: + content = b"" + if len(content) > max_attachment_bytes(): + raise ValueError(f"Attachment {name} exceeds the size limit") + content_type = getattr(uploaded, "content_type", None) or mimetypes.guess_type(name)[0] + content_type = (content_type or "application/octet-stream").split(";", 1)[0].strip() + return { + "name": name, + "content": content, + "size": len(content), + "content_type": content_type[:255] or "application/octet-stream", + } diff --git a/notify/codes.py b/notify/codes.py new file mode 100644 index 0000000..d73abbc --- /dev/null +++ b/notify/codes.py @@ -0,0 +1,179 @@ +import math +import secrets +from datetime import timedelta + +from django.conf import settings +from django.db import transaction +from django.utils import timezone +from django.utils.html import escape + +from notify.delivery import get_provider +from notify.models import NotificationTemplate, NotificationType, VerificationCode + +__all__ = [ + "CodeThrottled", + "send_code", + "verify_code", +] + +DEFAULT_CODE_LENGTH = 6 +DEFAULT_CODE_TTL = 300 +DEFAULT_CODE_MAX_ATTEMPTS = 5 +DEFAULT_CODE_RESEND_INTERVAL = 60 + +DEFAULT_SUBJECT = "Код подтверждения" + + +class CodeThrottled(Exception): + def __init__(self, retry_after: int): + self.retry_after = retry_after + super().__init__(f"Code was sent recently, retry after {retry_after} seconds") + + +def _code_length(): + return int(getattr(settings, "NOTIFY_CODE_LENGTH", DEFAULT_CODE_LENGTH)) + + +def _code_ttl(): + return int(getattr(settings, "NOTIFY_CODE_TTL", DEFAULT_CODE_TTL)) + + +def _code_max_attempts(): + return int(getattr(settings, "NOTIFY_CODE_MAX_ATTEMPTS", DEFAULT_CODE_MAX_ATTEMPTS)) + + +def _code_resend_interval(): + return int(getattr(settings, "NOTIFY_CODE_RESEND_INTERVAL", DEFAULT_CODE_RESEND_INTERVAL)) + + +def _resolve_target(channel, target): + provider = get_provider(channel) + if provider is None or not provider.supports_codes: + raise ValueError(f"Channel {channel} does not support codes") + target = provider.validate_target(target) + return provider, target, provider.target_key(target) + + +def _resolve_type(notification_type): + if notification_type is None or isinstance(notification_type, NotificationType): + return notification_type + return NotificationType.objects.get(code=notification_type) + + +def _generate_code(length): + return str(secrets.randbelow(10**length)).zfill(length) + + +def _ttl_minutes(ttl): + return max(1, math.ceil(ttl / 60)) + + +def _render(channel, notification_type, code, ttl, purpose, user): + template = None + if notification_type is not None: + template = ( + NotificationTemplate.objects.filter(channel=channel, type=notification_type) + .order_by("id") + .first() + ) + ttl_minutes = _ttl_minutes(ttl) + if template is not None: + context = { + "code": code, + "ttl_minutes": ttl_minutes, + "purpose": purpose, + "user": {"id": user.pk, "username": user.get_username()} if user is not None else None, + } + subject = " ".join(template.render_subject(context).split()) or DEFAULT_SUBJECT + return subject, template.render_body(context) + text = f"Код подтверждения: {code}. Действует {ttl_minutes} мин." + if channel == "email": + return DEFAULT_SUBJECT, f"

{escape(text)}

" + return DEFAULT_SUBJECT, text + + +def _active_codes(purpose, channel, target_key): + return VerificationCode.objects.filter( + purpose=purpose, + channel=channel, + target_key=target_key, + consumed_at__isnull=True, + ) + + +def send_code( + *, + purpose: str, + channel: str, + target: dict | None = None, + user=None, + type: NotificationType | str | None = None, +) -> VerificationCode: + if not purpose: + raise ValueError("purpose is required") + provider, target, target_key = _resolve_target(channel, target) + notification_type = _resolve_type(type) + now = timezone.now() + ttl = _code_ttl() + resend_interval = _code_resend_interval() + + with transaction.atomic(): + last = ( + VerificationCode.objects.select_for_update() + .filter(purpose=purpose, channel=channel, target_key=target_key) + .order_by("-created_at") + .first() + ) + if last is not None and resend_interval > 0: + elapsed = (now - last.created_at).total_seconds() + if elapsed < resend_interval: + raise CodeThrottled(math.ceil(resend_interval - elapsed)) + + _active_codes(purpose, channel, target_key).update(consumed_at=now) + + code = _generate_code(_code_length()) + verification = VerificationCode( + user=user, + purpose=purpose, + channel=channel, + target_key=target_key, + delivery_target=target.model_dump(), + expires_at=now + timedelta(seconds=ttl), + max_attempts=_code_max_attempts(), + ) + verification.set_code(code) + verification.save() + + subject, body = _render(channel, notification_type, code, ttl, purpose, user) + provider.send_message(target, subject, body) + return verification + + +def verify_code( + *, + purpose: str, + channel: str, + code: str, + target: dict | None = None, +) -> bool: + _, _, target_key = _resolve_target(channel, target) + code = "".join(str(code or "").split()) + if not code: + return False + with transaction.atomic(): + verification = ( + _active_codes(purpose, channel, target_key) + .select_for_update() + .order_by("-created_at") + .first() + ) + if verification is None or verification.is_expired: + return False + if verification.attempts >= verification.max_attempts: + return False + verification.attempts += 1 + matched = verification.check_code(code) + if matched: + verification.consumed_at = timezone.now() + verification.save(update_fields=["attempts", "consumed_at"]) + return matched diff --git a/notify/delivery/__init__.py b/notify/delivery/__init__.py new file mode 100644 index 0000000..deef6ff --- /dev/null +++ b/notify/delivery/__init__.py @@ -0,0 +1,13 @@ +from .base import DeliveryProvider, render_notification_template +from .registry import get_provider, get_provider_or_raise, register, registered_channels +from .providers import register_builtin_providers + +__all__ = [ + 'DeliveryProvider', + 'render_notification_template', + 'get_provider', + 'get_provider_or_raise', + 'register', + 'registered_channels', + 'register_builtin_providers', +] diff --git a/notify/delivery/base.py b/notify/delivery/base.py new file mode 100644 index 0000000..0fdd8da --- /dev/null +++ b/notify/delivery/base.py @@ -0,0 +1,121 @@ +from abc import ABC, abstractmethod +from typing import Optional + +from django.utils import timezone +from django.utils.html import linebreaks +from pydantic import BaseModel +from pydantic import ValidationError as PydanticValidationError + +from notify.delivery.exceptions import PermanentDeliveryError +from notify.models import ( + DeliveryChannel, + DeliveryStatus, + NotificationRecipient, + NotificationTemplate, +) + +__all__ = [ + "template_context", + "render_notification_template", + "DeliveryProvider", +] + + +def _single_line(value: str | None) -> str: + return " ".join((value or "").split()) + + +def template_context(notification_recipient: NotificationRecipient) -> dict: + notification = notification_recipient.notification + user = notification_recipient.user + username_field = user.__class__.USERNAME_FIELD + return { + "recipient": { + "id": str(notification_recipient.id), + "delivery_channel": notification_recipient.delivery_channel, + "delivery_target": notification_recipient.delivery_target, + }, + "notification": { + "id": str(notification.id), + "url": notification.url, + "level": notification.level, + "verb": notification.verb, + "object_id": notification.object_id, + "description": notification.description, + "data": notification.data, + }, + "user": { + "id": user.pk, + "username": getattr(user, username_field, ""), + }, + } + + +def render_notification_template( + delivery_channel: DeliveryChannel, + notification_recipient: NotificationRecipient, +) -> tuple[str, str | None]: + notification = notification_recipient.notification + template = NotificationTemplate.for_delivery(delivery_channel, notification.type) + if template: + context = template_context(notification_recipient) + subject = _single_line(template.render_subject(context)) + body = template.render_body(context) + else: + subject = _single_line(notification.verb) + body = linebreaks(notification.description or "", autoescape=True) + return subject, body + + +class DeliveryProvider(ABC): + channel: DeliveryChannel + target_schema: Optional[type[BaseModel]] = None + requires_async_delivery: bool = True + supports_codes: bool = False + + def validate_target(self, raw: Optional[dict]) -> Optional[BaseModel]: + if self.target_schema is None: + if raw: + raise ValueError(f"target is not supported when channel is {self.channel}") + return None + if not raw: + raise ValueError(f"target is required when channel is {self.channel}") + try: + return self.target_schema.model_validate(raw) + except PydanticValidationError as exc: + raise ValueError(exc.errors()[0]["msg"]) from exc + + def parse_target(self, raw: Optional[dict]) -> Optional[BaseModel]: + if self.target_schema is None or raw is None: + return None + try: + return self.target_schema.model_validate(raw) + except PydanticValidationError as exc: + raise PermanentDeliveryError(f"Invalid {self.channel} target: {exc.errors()[0]['msg']}") from exc + + @abstractmethod + def send(self, recipient: NotificationRecipient) -> None: + pass + + def send_message( + self, + target: Optional[BaseModel], + subject: str, + body: str, + attachments=(), + ) -> None: + raise NotImplementedError(f"{type(self).__name__} does not support direct messages") + + def target_key(self, target: BaseModel) -> str: + raise NotImplementedError(f"{type(self).__name__} does not support codes") + + def mark_sent(self, recipient: NotificationRecipient) -> None: + recipient.delivery_status = DeliveryStatus.SENT + recipient.sent_at = timezone.now() + recipient.last_error = "" + recipient.save(update_fields=["delivery_status", "sent_at", "last_error"]) + + def enqueue(self, recipient_id) -> None: + from notify.tasks import deliver_notification + + deliver_notification.apply_async(args=(str(recipient_id),)) diff --git a/notify/delivery/exceptions.py b/notify/delivery/exceptions.py new file mode 100644 index 0000000..e296c54 --- /dev/null +++ b/notify/delivery/exceptions.py @@ -0,0 +1,12 @@ +__all__ = [ + "DeliveryError", + "PermanentDeliveryError", +] + + +class DeliveryError(Exception): + """Temporary delivery failure. The worker may retry.""" + + +class PermanentDeliveryError(DeliveryError): + """Delivery cannot succeed on another attempt.""" diff --git a/notify/delivery/providers/__init__.py b/notify/delivery/providers/__init__.py new file mode 100644 index 0000000..e37dd45 --- /dev/null +++ b/notify/delivery/providers/__init__.py @@ -0,0 +1,23 @@ +from notify.delivery.registry import register +from .browser import BrowserDeliveryProvider +from .email import EmailDeliveryProvider +from .max import MaxDeliveryProvider +from .telegram import TelegramDeliveryProvider + +__all__ = [ + 'register_builtin_providers', + 'BrowserDeliveryProvider', + 'EmailDeliveryProvider', + 'MaxDeliveryProvider', + 'TelegramDeliveryProvider', +] + + +def register_builtin_providers() -> None: + for provider in ( + BrowserDeliveryProvider(), + EmailDeliveryProvider(), + MaxDeliveryProvider(), + TelegramDeliveryProvider(), + ): + register(provider) diff --git a/notify/delivery/providers/browser.py b/notify/delivery/providers/browser.py new file mode 100644 index 0000000..60f44ce --- /dev/null +++ b/notify/delivery/providers/browser.py @@ -0,0 +1,14 @@ +from notify.delivery.base import DeliveryProvider +from notify.models import DeliveryChannel, NotificationRecipient + +__all__ = [ + 'BrowserDeliveryProvider', +] + + +class BrowserDeliveryProvider(DeliveryProvider): + channel = DeliveryChannel.BROWSER + requires_async_delivery = False + + def send(self, recipient: NotificationRecipient) -> None: + self.mark_sent(recipient) diff --git a/notify/delivery/providers/email.py b/notify/delivery/providers/email.py new file mode 100644 index 0000000..fbe4d56 --- /dev/null +++ b/notify/delivery/providers/email.py @@ -0,0 +1,73 @@ +from typing import Optional + +from django.core.mail import EmailMessage, get_connection +from pydantic import BaseModel, EmailStr + +from notify.delivery.base import DeliveryProvider, render_notification_template +from notify.delivery.exceptions import DeliveryError, PermanentDeliveryError +from notify.models import DeliveryChannel, DeliveryEmailConfig, NotificationRecipient + +__all__ = [ + 'EmailTargetSchema', + 'EmailDeliveryProvider', +] + + +class EmailTargetSchema(BaseModel): + email: EmailStr + + +class EmailDeliveryProvider(DeliveryProvider): + channel = DeliveryChannel.EMAIL + target_schema = EmailTargetSchema + supports_codes = True + + def target_key(self, target: EmailTargetSchema) -> str: + return target.email.lower() + + def send(self, recipient: NotificationRecipient) -> None: + subject, body = render_notification_template(DeliveryChannel.EMAIL, recipient) + self.send_message( + self.parse_target(recipient.delivery_target), + subject, + body, + attachments=recipient.notification.attachments.all(), + ) + self.mark_sent(recipient) + + def send_message( + self, + target: Optional[EmailTargetSchema], + subject: str, + body: str, + attachments=(), + ) -> None: + delivery_config = DeliveryEmailConfig.get_default() + if delivery_config is None: + raise DeliveryError("No default email delivery config") + if target is None: + raise PermanentDeliveryError("Email recipient has no email") + + try: + email_connection = get_connection(**delivery_config.get_connection_config()) + msg = EmailMessage( + subject, + body=body, + from_email=delivery_config.from_email, + to=[target.email], + connection=email_connection, + ) + msg.content_subtype = "html" + for attachment in attachments: + with attachment.file.open("rb") as uploaded: + payload = uploaded.read() + msg.attach(attachment.name, payload, attachment.content_type) + sent = msg.send(fail_silently=False) + except ValueError as exc: + raise PermanentDeliveryError(str(exc)) from exc + except DeliveryError: + raise + except Exception as exc: + raise DeliveryError("Email delivery failed") from exc + if not sent: + raise DeliveryError("Email was not accepted for delivery") diff --git a/notify/delivery/providers/max.py b/notify/delivery/providers/max.py new file mode 100644 index 0000000..af05a39 --- /dev/null +++ b/notify/delivery/providers/max.py @@ -0,0 +1,87 @@ +from typing import Optional + +import requests +from pydantic import BaseModel, model_validator + +from notify.delivery.base import DeliveryProvider, render_notification_template +from notify.delivery.exceptions import DeliveryError, PermanentDeliveryError +from notify.models import DeliveryChannel, DeliveryTokenConfig, NotificationRecipient + +__all__ = [ + 'MAX_API_TIMEOUT', + 'MaxTargetSchema', + 'MaxDeliveryProvider', +] + +MAX_API_TIMEOUT = 10 + + +class MaxTargetSchema(BaseModel): + chat_id: int + user_id: Optional[int] = None + + @model_validator(mode="after") + def validate_ids(self): + if self.user_id is None: + if self.chat_id >= 0: + raise ValueError("chat_id must be negative when user_id is not specified") + elif self.chat_id <= 0 or self.user_id <= 0: + raise ValueError("chat_id and user_id must be positive when both are specified") + return self + + +class MaxDeliveryProvider(DeliveryProvider): + channel = DeliveryChannel.MAX + target_schema = MaxTargetSchema + supports_codes = True + + def target_key(self, target: MaxTargetSchema) -> str: + if target.user_id: + return f"user:{target.user_id}" + return f"chat:{target.chat_id}" + + def send(self, recipient: NotificationRecipient) -> None: + _, body = render_notification_template(DeliveryChannel.MAX, recipient) + self.send_message(self.parse_target(recipient.delivery_target), "", body) + self.mark_sent(recipient) + + def send_message( + self, + target: Optional[MaxTargetSchema], + subject: str, + body: str, + attachments=(), + ) -> None: + delivery_config = DeliveryTokenConfig.get_default(DeliveryChannel.MAX) + if delivery_config is None: + raise DeliveryError("No default MAX delivery config") + if target is None: + raise PermanentDeliveryError("MAX recipient has no chat_id") + + request_params = {} + if target.user_id: + request_params["user_id"] = target.user_id + else: + request_params["chat_id"] = target.chat_id + + try: + response = requests.post( + "https://platform-api.max.ru/messages", + params=request_params, + headers={"Authorization": delivery_config.token}, + json={ + "chat_id": target.chat_id, + "text": body, + }, + timeout=MAX_API_TIMEOUT, + ) + response.raise_for_status() + except requests.Timeout as exc: + raise DeliveryError("MAX request timed out") from exc + except requests.HTTPError as exc: + status = exc.response.status_code if exc.response is not None else 0 + if status == 429 or status >= 500: + raise DeliveryError(f"MAX API temporary error: {status}") from exc + raise PermanentDeliveryError(f"MAX API rejected the message: {status}") from exc + except requests.RequestException as exc: + raise DeliveryError("MAX request failed") from exc diff --git a/notify/delivery/providers/telegram.py b/notify/delivery/providers/telegram.py new file mode 100644 index 0000000..dfd1d85 --- /dev/null +++ b/notify/delivery/providers/telegram.py @@ -0,0 +1,64 @@ +from typing import Optional + +import requests +from pydantic import BaseModel + +from notify.delivery.base import DeliveryProvider, render_notification_template +from notify.delivery.exceptions import DeliveryError, PermanentDeliveryError +from notify.models import DeliveryChannel, DeliveryTokenConfig, NotificationRecipient + +__all__ = [ + "TELEGRAM_API_TIMEOUT", + "TelegramTargetSchema", + "TelegramDeliveryProvider", +] + +TELEGRAM_API_TIMEOUT = 10 + + +class TelegramTargetSchema(BaseModel): + chat_id: int + + +class TelegramDeliveryProvider(DeliveryProvider): + channel = DeliveryChannel.TELEGRAM + target_schema = TelegramTargetSchema + supports_codes = True + + def target_key(self, target: TelegramTargetSchema) -> str: + return str(target.chat_id) + + def send(self, recipient: NotificationRecipient) -> None: + _, body = render_notification_template(DeliveryChannel.TELEGRAM, recipient) + self.send_message(self.parse_target(recipient.delivery_target), "", body) + self.mark_sent(recipient) + + def send_message( + self, + target: Optional[TelegramTargetSchema], + subject: str, + body: str, + attachments=(), + ) -> None: + delivery_config = DeliveryTokenConfig.get_default(DeliveryChannel.TELEGRAM) + if delivery_config is None: + raise DeliveryError("No default Telegram delivery config") + if target is None: + raise PermanentDeliveryError("Telegram recipient has no chat_id") + + try: + response = requests.post( + f"https://api.telegram.org/bot{delivery_config.token}/sendMessage", + json={"chat_id": target.chat_id, "text": body}, + timeout=TELEGRAM_API_TIMEOUT, + ) + response.raise_for_status() + except requests.Timeout as exc: + raise DeliveryError("Telegram request timed out") from exc + except requests.HTTPError as exc: + status = exc.response.status_code if exc.response is not None else 0 + if status == 429 or status >= 500: + raise DeliveryError(f"Telegram API temporary error: {status}") from exc + raise PermanentDeliveryError(f"Telegram API rejected the message: {status}") from exc + except requests.RequestException as exc: + raise DeliveryError("Telegram request failed") from exc diff --git a/notify/delivery/registry.py b/notify/delivery/registry.py new file mode 100644 index 0000000..cec6d9a --- /dev/null +++ b/notify/delivery/registry.py @@ -0,0 +1,35 @@ +from typing import Iterable + +from .base import DeliveryProvider + +__all__ = [ + 'register', + 'get_provider', + 'get_provider_or_raise', + 'registered_channels', +] + +_providers: dict[str, DeliveryProvider] = {} + + +def _channel_key(channel) -> str: + return str(channel) + + +def register(provider: DeliveryProvider) -> None: + _providers[_channel_key(provider.channel)] = provider + + +def get_provider(channel: str) -> DeliveryProvider | None: + return _providers.get(_channel_key(channel)) + + +def get_provider_or_raise(channel: str) -> DeliveryProvider: + provider = get_provider(channel) + if provider is None: + raise KeyError(f'No delivery provider registered for channel: {channel}') + return provider + + +def registered_channels() -> Iterable[str]: + return _providers.keys() diff --git a/notify/migrations/0001_initial.py b/notify/migrations/0001_initial.py new file mode 100644 index 0000000..9f23d18 --- /dev/null +++ b/notify/migrations/0001_initial.py @@ -0,0 +1,236 @@ +# Generated by Django 5.0.6 on 2026-10-09 01:15 + +import django.db.models.deletion +import notify.models +import uuid +from django.conf import settings +from django.db import migrations, models + + +class Migration(migrations.Migration): + + initial = True + + dependencies = [ + migrations.swappable_dependency(settings.AUTH_USER_MODEL), + ] + + operations = [ + migrations.CreateModel( + name='DeliveryConfig', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('name', models.CharField(max_length=255, unique=True)), + ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max')], max_length=20)), + ('is_default', models.BooleanField(default=False)), + ], + ), + migrations.CreateModel( + name='Notification', + fields=[ + ('id', models.BigAutoField(primary_key=True, serialize=False)), + ('url', models.TextField(null=True)), + ('level', models.CharField(choices=[('SUCCESS', 'Success'), ('INFO', 'Info'), ('WARNING', 'Warning'), ('ERROR', 'Error')], default='INFO', max_length=20)), + ('verb', models.CharField(max_length=255)), + ('object_id', models.CharField(default='', max_length=255)), + ('description', models.TextField(blank=True, null=True)), + ('data', models.JSONField(blank=True, default=dict)), + ('idempotency_key', models.CharField(blank=True, max_length=255, null=True, unique=True)), + ('expires_at', models.DateTimeField(db_index=True, default=notify.models.default_expires_at)), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ], + options={ + 'ordering': ('-created_at',), + }, + ), + migrations.CreateModel( + name='NotificationAttachment', + fields=[ + ('id', models.BigAutoField(primary_key=True, serialize=False)), + ('file', models.FileField(upload_to='notify/attachments/%Y/%m/%d')), + ('name', models.CharField(max_length=255)), + ('content_type', models.CharField(default='application/octet-stream', max_length=255)), + ('size', models.PositiveIntegerField()), + ('created_at', models.DateTimeField(auto_now_add=True)), + ], + options={ + 'ordering': ('created_at', 'id'), + }, + ), + migrations.CreateModel( + name='NotificationChannelPreference', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max')], max_length=20)), + ('enabled', models.BooleanField(default=True)), + ], + ), + migrations.CreateModel( + name='NotificationGroup', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('code', models.CharField(max_length=100, unique=True)), + ('name', models.CharField(max_length=100)), + ], + options={ + 'ordering': ('code',), + }, + ), + migrations.CreateModel( + name='NotificationRecipient', + fields=[ + ('id', models.BigAutoField(primary_key=True, serialize=False)), + ('delivery_channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max')], max_length=20)), + ('delivery_address', models.CharField(blank=True, max_length=255, null=True)), + ('delivery_data', models.JSONField(blank=True, default=None, null=True)), + ('delivery_status', models.CharField(choices=[('UNSENT', 'Unsent'), ('SENT', 'Sent'), ('FAILED', 'Failed')], default='UNSENT', max_length=10)), + ('sent_at', models.DateTimeField(blank=True, null=True)), + ('attempts', models.PositiveSmallIntegerField(default=0)), + ('last_error', models.TextField(blank=True, default='')), + ('unread', models.BooleanField(db_index=True, default=True)), + ('created_at', models.DateTimeField(auto_now_add=True, db_index=True)), + ], + ), + migrations.CreateModel( + name='NotificationTemplate', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max')], max_length=20)), + ('name', models.CharField(max_length=255, unique=True)), + ('is_default', models.BooleanField(default=False)), + ('subject_template', models.TextField(blank=True, default='')), + ('body_template', models.TextField()), + ], + ), + migrations.CreateModel( + name='NotificationType', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('code', models.CharField(max_length=100, unique=True)), + ('name', models.CharField(max_length=100)), + ('channels', models.JSONField(blank=True, default=list, validators=[notify.models.validate_delivery_channels])), + ('verb', models.CharField(blank=True, max_length=255, null=True)), + ('position', models.IntegerField(default=0)), + ('is_active', models.BooleanField(default=True)), + ('can_switch', models.BooleanField(default=True)), + ], + options={ + 'ordering': ('position', 'code'), + }, + ), + migrations.CreateModel( + name='VerificationCode', + fields=[ + ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), + ('purpose', models.CharField(max_length=100)), + ('channel', models.CharField(choices=[('email', 'Email'), ('telegram', 'Telegram'), ('browser', 'Browser'), ('max', 'Max')], max_length=20)), + ('target', models.CharField(max_length=255)), + ('delivery_data', models.JSONField(blank=True, default=None, null=True)), + ('code_hash', models.CharField(max_length=128)), + ('expires_at', models.DateTimeField(db_index=True)), + ('attempts', models.PositiveSmallIntegerField(default=0)), + ('max_attempts', models.PositiveSmallIntegerField()), + ('consumed_at', models.DateTimeField(blank=True, null=True)), + ('created_at', models.DateTimeField(auto_now_add=True)), + ], + options={ + 'ordering': ('-created_at',), + }, + ), + migrations.CreateModel( + name='DeliveryEmailConfig', + fields=[ + ('deliveryconfig_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='notify.deliveryconfig')), + ('host', models.CharField(max_length=100)), + ('port', models.IntegerField(default=587)), + ('username', models.CharField(blank=True, default='', max_length=100)), + ('password', models.CharField(blank=True, default='', max_length=100)), + ('from_email', models.CharField(blank=True, default='', max_length=100)), + ('test_email', models.EmailField(blank=True, default='', max_length=100)), + ('use_ssl', models.BooleanField(default=False)), + ('use_tls', models.BooleanField(default=True)), + ], + bases=('notify.deliveryconfig',), + ), + migrations.CreateModel( + name='DeliveryTokenConfig', + fields=[ + ('deliveryconfig_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='notify.deliveryconfig')), + ('token', models.CharField(blank=True, max_length=500)), + ], + bases=('notify.deliveryconfig',), + ), + migrations.AddConstraint( + model_name='deliveryconfig', + constraint=models.UniqueConstraint(condition=models.Q(('is_default', True)), fields=('channel',), name='uniq_default_delivery_cfg'), + ), + migrations.AddField( + model_name='notificationattachment', + name='notification', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='attachments', to='notify.notification'), + ), + migrations.AddField( + model_name='notificationchannelpreference', + name='user', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notification_channel_preferences', to=settings.AUTH_USER_MODEL), + ), + migrations.AddField( + model_name='notificationrecipient', + name='notification', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='recipients', to='notify.notification'), + ), + migrations.AddField( + model_name='notificationrecipient', + name='user', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='notification_recipients', to=settings.AUTH_USER_MODEL), + ), + migrations.AddField( + model_name='notificationtype', + name='group', + field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='types', to='notify.notificationgroup'), + ), + migrations.AddField( + model_name='notificationtemplate', + name='type', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='templates', to='notify.notificationtype'), + ), + migrations.AddField( + model_name='notificationchannelpreference', + name='type', + field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='channel_preferences', to='notify.notificationtype'), + ), + migrations.AddField( + model_name='notification', + name='type', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='notifications', to='notify.notificationtype'), + ), + migrations.AddField( + model_name='verificationcode', + name='user', + field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='verification_codes', to=settings.AUTH_USER_MODEL), + ), + migrations.AddIndex( + model_name='notificationrecipient', + index=models.Index(fields=['user', 'delivery_channel', 'created_at'], name='idx_recipient_inbox'), + ), + migrations.AddConstraint( + model_name='notificationrecipient', + constraint=models.UniqueConstraint(fields=('notification', 'user', 'delivery_channel'), name='uniq_recipient_channel'), + ), + migrations.AddConstraint( + model_name='notificationtemplate', + constraint=models.UniqueConstraint(condition=models.Q(('is_default', True), ('type__isnull', True)), fields=('channel',), name='uniq_default_template_channel'), + ), + migrations.AddConstraint( + model_name='notificationtemplate', + constraint=models.UniqueConstraint(condition=models.Q(('type__isnull', False)), fields=('type', 'channel'), name='uniq_template_type_channel'), + ), + migrations.AddConstraint( + model_name='notificationchannelpreference', + constraint=models.UniqueConstraint(fields=('user', 'type', 'channel'), name='uniq_user_type_channel_pref'), + ), + migrations.AddIndex( + model_name='verificationcode', + index=models.Index(fields=['purpose', 'channel', 'target', 'created_at'], name='idx_code_lookup'), + ), + ] diff --git a/notify/migrations/0002_delivery_target.py b/notify/migrations/0002_delivery_target.py new file mode 100644 index 0000000..c55025a --- /dev/null +++ b/notify/migrations/0002_delivery_target.py @@ -0,0 +1,65 @@ +from django.db import migrations, models + + +def forwards(apps, schema_editor): + NotificationRecipient = apps.get_model("notify", "NotificationRecipient") + for recipient in NotificationRecipient.objects.all().iterator(): + if recipient.delivery_channel == "email": + target = {"email": recipient.delivery_address} if recipient.delivery_address else None + else: + target = recipient.delivery_data + if target is not None: + recipient.delivery_target = target + recipient.save(update_fields=["delivery_target"]) + + +def backwards(apps, schema_editor): + NotificationRecipient = apps.get_model("notify", "NotificationRecipient") + for recipient in NotificationRecipient.objects.exclude(delivery_target=None).iterator(): + if recipient.delivery_channel == "email": + recipient.delivery_address = recipient.delivery_target.get("email") + else: + recipient.delivery_data = recipient.delivery_target + recipient.save(update_fields=["delivery_address", "delivery_data"]) + + +class Migration(migrations.Migration): + + dependencies = [ + ("notify", "0001_initial"), + ] + + operations = [ + migrations.AddField( + model_name="notificationrecipient", + name="delivery_target", + field=models.JSONField(blank=True, default=None, null=True), + ), + migrations.RunPython(forwards, backwards), + migrations.RemoveField( + model_name="notificationrecipient", + name="delivery_address", + ), + migrations.RemoveField( + model_name="notificationrecipient", + name="delivery_data", + ), + migrations.RemoveIndex( + model_name="verificationcode", + name="idx_code_lookup", + ), + migrations.RenameField( + model_name="verificationcode", + old_name="target", + new_name="target_key", + ), + migrations.RenameField( + model_name="verificationcode", + old_name="delivery_data", + new_name="delivery_target", + ), + migrations.AddIndex( + model_name="verificationcode", + index=models.Index(fields=["purpose", "channel", "target_key", "created_at"], name="idx_code_lookup"), + ), + ] diff --git a/notify/migrations/__init__.py b/notify/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/notify/models/__init__.py b/notify/models/__init__.py new file mode 100644 index 0000000..9933a5d --- /dev/null +++ b/notify/models/__init__.py @@ -0,0 +1,46 @@ +from notify.models.choices import ( + DeliveryChannel, + DeliveryStatus, + NotificationLevel, + validate_delivery_channels, +) +from notify.models.code import VerificationCode +from notify.models.delivery import ( + DeliveryConfig, + DeliveryEmailConfig, + DeliveryTokenConfig, +) +from notify.models.group import NotificationGroup +from notify.models.managers import NotificationGroupManager, NotificationTypeManager +from notify.models.notification import ( + Notification, + NotificationAttachment, + NotificationRecipient, + default_expires_at, +) +from notify.models.notification_type import NotificationChannelPreference, NotificationType +from notify.models.template import NotificationTemplate + +default_expires_at.__module__ = "notify.models" +validate_delivery_channels.__module__ = "notify.models" + +__all__ = [ + "DeliveryChannel", + "DeliveryStatus", + "NotificationLevel", + "default_expires_at", + "validate_delivery_channels", + "NotificationGroupManager", + "NotificationTypeManager", + "NotificationGroup", + "NotificationType", + "DeliveryConfig", + "DeliveryEmailConfig", + "DeliveryTokenConfig", + "NotificationTemplate", + "NotificationChannelPreference", + "Notification", + "NotificationAttachment", + "NotificationRecipient", + "VerificationCode", +] diff --git a/notify/models/choices.py b/notify/models/choices.py new file mode 100644 index 0000000..6a793f3 --- /dev/null +++ b/notify/models/choices.py @@ -0,0 +1,38 @@ +from django.core.exceptions import ValidationError +from django.db import models + +__all__ = [ + "DeliveryChannel", + "DeliveryStatus", + "NotificationLevel", + "validate_delivery_channels", +] + + +class DeliveryChannel(models.TextChoices): + EMAIL = "email" + TELEGRAM = "telegram" + BROWSER = "browser" + MAX = "max" + + +class DeliveryStatus(models.TextChoices): + UNSENT = "UNSENT" + SENT = "SENT" + FAILED = "FAILED" + + +class NotificationLevel(models.TextChoices): + SUCCESS = "SUCCESS" + INFO = "INFO" + WARNING = "WARNING" + ERROR = "ERROR" + + +def validate_delivery_channels(value): + if not isinstance(value, list): + raise ValidationError("channels must be a list") + allowed = set(DeliveryChannel.values) + unknown = [item for item in value if item not in allowed] + if unknown: + raise ValidationError(f"Unknown channels: {', '.join(map(str, unknown))}") diff --git a/notify/models/code.py b/notify/models/code.py new file mode 100644 index 0000000..84a29d7 --- /dev/null +++ b/notify/models/code.py @@ -0,0 +1,57 @@ +import uuid + +from django.conf import settings +from django.db import models +from django.utils import timezone +from django.utils.crypto import constant_time_compare, salted_hmac + +from notify.models.choices import DeliveryChannel + +__all__ = [ + "VerificationCode", +] + +CODE_HASH_SALT = "notify.code" + + +class VerificationCode(models.Model): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + user = models.ForeignKey( + settings.AUTH_USER_MODEL, + null=True, + blank=True, + on_delete=models.CASCADE, + related_name="verification_codes", + ) + purpose = models.CharField(max_length=100) + channel = models.CharField(max_length=20, choices=DeliveryChannel) + target_key = models.CharField(max_length=255) + delivery_target = models.JSONField(null=True, blank=True, default=None) + code_hash = models.CharField(max_length=128) + expires_at = models.DateTimeField(db_index=True) + attempts = models.PositiveSmallIntegerField(default=0) + max_attempts = models.PositiveSmallIntegerField() + consumed_at = models.DateTimeField(null=True, blank=True) + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + ordering = ("-created_at",) + indexes = [ + models.Index(fields=["purpose", "channel", "target_key", "created_at"], name="idx_code_lookup"), + ] + + def __str__(self): + return f"{self.purpose} via {self.channel} to {self.target_key}" + + def _hash(self, code: str) -> str: + return salted_hmac(CODE_HASH_SALT, f"{self.id}:{code}", algorithm="sha256").hexdigest() + + def set_code(self, code: str) -> None: + self.code_hash = self._hash(code) + + def check_code(self, code: str) -> bool: + return constant_time_compare(self.code_hash, self._hash(code)) + + @property + def is_expired(self) -> bool: + return self.expires_at <= timezone.now() diff --git a/notify/models/delivery.py b/notify/models/delivery.py new file mode 100644 index 0000000..5ab5d18 --- /dev/null +++ b/notify/models/delivery.py @@ -0,0 +1,92 @@ +import uuid + +from django.core.exceptions import ValidationError +from django.db import models, transaction + +from notify.models.choices import DeliveryChannel + +__all__ = [ + "EMAIL_TIMEOUT", + "DeliveryConfig", + "DeliveryEmailConfig", + "DeliveryTokenConfig", +] + +EMAIL_TIMEOUT = 10 + + +class DeliveryConfig(models.Model): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + name = models.CharField(unique=True, max_length=255) + channel = models.CharField(max_length=20, choices=DeliveryChannel) + is_default = models.BooleanField(default=False) + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=["channel"], + condition=models.Q(is_default=True), + name="uniq_default_delivery_cfg", + ), + ] + + def __str__(self): + return self.name + + def save(self, *args, **kwargs): + update_fields = kwargs.get("update_fields") + touches_default = update_fields is None or "is_default" in update_fields + with transaction.atomic(): + if self.is_default and touches_default: + others = type(self).objects.filter(channel=self.channel, is_default=True) + if self.pk: + others = others.exclude(pk=self.pk) + others.update(is_default=False) + super().save(*args, **kwargs) + + @classmethod + def get_default(cls): + return cls.objects.filter(is_default=True).order_by("id").first() + + +class DeliveryEmailConfig(DeliveryConfig): + host = models.CharField(max_length=100) + port = models.IntegerField(default=587) + username = models.CharField(max_length=100, default="", blank=True) + password = models.CharField(max_length=100, default="", blank=True) + from_email = models.CharField(max_length=100, default="", blank=True) + test_email = models.EmailField(max_length=100, default="", blank=True) + use_ssl = models.BooleanField(default=False) + use_tls = models.BooleanField(default=True) + + def __str__(self): + return f"{self.username} ({self.host})" + + def clean(self): + super().clean() + if self.use_ssl and self.use_tls: + raise ValidationError("use_ssl and use_tls cannot both be enabled") + + def save(self, *args, **kwargs): + if self.use_ssl and self.use_tls: + raise ValidationError("use_ssl and use_tls cannot both be enabled") + super().save(*args, **kwargs) + + def get_connection_config(self): + return dict( + host=self.host, + port=self.port, + username=self.username, + password=self.password, + use_ssl=self.use_ssl, + use_tls=self.use_tls, + timeout=EMAIL_TIMEOUT, + ) + + +class DeliveryTokenConfig(DeliveryConfig): + token = models.CharField(max_length=500, blank=True) + + @classmethod + def get_default(cls, channel): + return cls.objects.filter(channel=channel, is_default=True).order_by("id").first() diff --git a/notify/models/group.py b/notify/models/group.py new file mode 100644 index 0000000..c758f9d --- /dev/null +++ b/notify/models/group.py @@ -0,0 +1,26 @@ +import uuid + +from django.db import models + +from notify.models.managers import NotificationGroupManager + +__all__ = [ + "NotificationGroup", +] + + +class NotificationGroup(models.Model): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + code = models.CharField(max_length=100, unique=True) + name = models.CharField(max_length=100) + + objects = NotificationGroupManager() + + class Meta: + ordering = ("code",) + + def __str__(self): + return self.name + + def natural_key(self): + return (self.code,) diff --git a/notify/models/managers.py b/notify/models/managers.py new file mode 100644 index 0000000..7713901 --- /dev/null +++ b/notify/models/managers.py @@ -0,0 +1,16 @@ +from django.db import models + +__all__ = [ + "NotificationGroupManager", + "NotificationTypeManager", +] + + +class NotificationGroupManager(models.Manager): + def get_by_natural_key(self, code): + return self.get(code=code) + + +class NotificationTypeManager(models.Manager): + def get_by_natural_key(self, code): + return self.get(code=code) diff --git a/notify/models/notification.py b/notify/models/notification.py new file mode 100644 index 0000000..f794d16 --- /dev/null +++ b/notify/models/notification.py @@ -0,0 +1,120 @@ +from datetime import timedelta +from urllib.parse import urlparse + +from django.conf import settings +from django.db import models +from django.utils import timezone + +from notify.models.choices import DeliveryChannel, DeliveryStatus, NotificationLevel +from notify.models.notification_type import NotificationType + +__all__ = [ + "default_expires_at", + "Notification", + "NotificationAttachment", + "NotificationRecipient", +] + + +def default_expires_at(): + return timezone.now() + timedelta(days=30) + + +class Notification(models.Model): + id = models.BigAutoField(primary_key=True) + url = models.TextField(null=True) + type = models.ForeignKey( + NotificationType, + null=True, + blank=True, + on_delete=models.SET_NULL, + related_name="notifications", + ) + level = models.CharField(max_length=20, choices=NotificationLevel, default=NotificationLevel.INFO) + verb = models.CharField(max_length=255) + object_id = models.CharField(max_length=255, default="") + description = models.TextField(blank=True, null=True) + data = models.JSONField(blank=True, default=dict) + idempotency_key = models.CharField(max_length=255, null=True, blank=True, unique=True) + expires_at = models.DateTimeField(default=default_expires_at, db_index=True) + created_at = models.DateTimeField(db_index=True, auto_now_add=True) + + class Meta: + ordering = ("-created_at",) + + def __str__(self): + return self.verb + + @property + def relative_url(self): + if self.url: + parsed = urlparse(self.url) + return parsed.path + return None + + +class NotificationAttachment(models.Model): + id = models.BigAutoField(primary_key=True) + notification = models.ForeignKey(Notification, on_delete=models.CASCADE, related_name="attachments") + file = models.FileField(upload_to="notify/attachments/%Y/%m/%d") + name = models.CharField(max_length=255) + content_type = models.CharField(max_length=255, default="application/octet-stream") + size = models.PositiveIntegerField() + created_at = models.DateTimeField(auto_now_add=True) + + class Meta: + ordering = ("created_at", "id") + + def __str__(self): + return self.name + + +class NotificationRecipient(models.Model): + id = models.BigAutoField(primary_key=True) + notification = models.ForeignKey(Notification, on_delete=models.CASCADE, related_name="recipients") + user = models.ForeignKey( + settings.AUTH_USER_MODEL, + on_delete=models.CASCADE, + related_name="notification_recipients", + ) + delivery_channel = models.CharField(max_length=20, choices=DeliveryChannel) + delivery_target = models.JSONField(null=True, blank=True, default=None) + delivery_status = models.CharField(max_length=10, choices=DeliveryStatus, default=DeliveryStatus.UNSENT) + sent_at = models.DateTimeField(null=True, blank=True) + attempts = models.PositiveSmallIntegerField(default=0) + last_error = models.TextField(blank=True, default="") + unread = models.BooleanField(default=True, db_index=True) + created_at = models.DateTimeField(db_index=True, auto_now_add=True) + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=["notification", "user", "delivery_channel"], + name="uniq_recipient_channel", + ), + ] + indexes = [ + models.Index(fields=["user", "delivery_channel", "created_at"], name="idx_recipient_inbox"), + ] + + def __str__(self): + target = self.delivery_target + if isinstance(target, dict) and target.get("email"): + target = target["email"] + target_info = f" to {target}" if target else "" + return f"{self.delivery_channel}{target_info} ({self.delivery_status})" + + def save(self, *args, **kwargs): + if self.delivery_channel == DeliveryChannel.BROWSER: + self.delivery_status = DeliveryStatus.SENT + if self.sent_at is None: + self.sent_at = timezone.now() + super().save(*args, **kwargs) + + def make_read(self): + self.unread = False + self.save(update_fields=["unread"]) + + def make_unread(self): + self.unread = True + self.save(update_fields=["unread"]) diff --git a/notify/models/notification_type.py b/notify/models/notification_type.py new file mode 100644 index 0000000..4b105cc --- /dev/null +++ b/notify/models/notification_type.py @@ -0,0 +1,64 @@ +import uuid + +from django.conf import settings +from django.db import models + +from notify.models.choices import DeliveryChannel, validate_delivery_channels +from notify.models.group import NotificationGroup +from notify.models.managers import NotificationTypeManager + +__all__ = [ + "NotificationType", + "NotificationChannelPreference", +] + + +class NotificationType(models.Model): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + code = models.CharField(max_length=100, unique=True) + name = models.CharField(max_length=100) + channels = models.JSONField(default=list, blank=True, validators=[validate_delivery_channels]) + group = models.ForeignKey(NotificationGroup, on_delete=models.PROTECT, related_name="types") + verb = models.CharField(max_length=255, null=True, blank=True) + position = models.IntegerField(default=0) + is_active = models.BooleanField(default=True) + can_switch = models.BooleanField(default=True) + + objects = NotificationTypeManager() + + class Meta: + ordering = ("position", "code") + + def __str__(self): + return self.name + + def natural_key(self): + return (self.code,) + + +class NotificationChannelPreference(models.Model): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + user = models.ForeignKey( + settings.AUTH_USER_MODEL, + on_delete=models.CASCADE, + related_name="notification_channel_preferences", + ) + type = models.ForeignKey( + NotificationType, + on_delete=models.CASCADE, + related_name="channel_preferences", + ) + channel = models.CharField(max_length=20, choices=DeliveryChannel) + enabled = models.BooleanField(default=True) + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=["user", "type", "channel"], + name="uniq_user_type_channel_pref", + ), + ] + + def __str__(self): + state = "on" if self.enabled else "off" + return f"{self.user_id} {self.channel} {state}" diff --git a/notify/models/template.py b/notify/models/template.py new file mode 100644 index 0000000..fff4864 --- /dev/null +++ b/notify/models/template.py @@ -0,0 +1,80 @@ +import uuid + +from django.db import models, transaction + +from notify.models.choices import DeliveryChannel +from notify.rendering import render + +__all__ = [ + "NotificationTemplate", +] + + +class NotificationTemplate(models.Model): + id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) + channel = models.CharField(max_length=20, choices=DeliveryChannel) + type = models.ForeignKey( + "notify.NotificationType", + null=True, + blank=True, + on_delete=models.CASCADE, + related_name="templates", + ) + name = models.CharField(unique=True, max_length=255) + is_default = models.BooleanField(default=False) + subject_template = models.TextField(default="", blank=True) + body_template = models.TextField() + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=["channel"], + condition=models.Q(is_default=True, type__isnull=True), + name="uniq_default_template_channel", + ), + models.UniqueConstraint( + fields=["type", "channel"], + condition=models.Q(type__isnull=False), + name="uniq_template_type_channel", + ), + ] + + def __str__(self): + return self.name + + def save(self, *args, **kwargs): + update_fields = kwargs.get("update_fields") + touches_default = update_fields is None or "is_default" in update_fields + with transaction.atomic(): + if self.is_default and touches_default and self.type_id is None: + others = type(self).objects.filter( + channel=self.channel, + type__isnull=True, + is_default=True, + ) + if self.pk: + others = others.exclude(pk=self.pk) + others.update(is_default=False) + super().save(*args, **kwargs) + + @classmethod + def default(cls, channel): + return ( + cls.objects.filter(channel=channel, type__isnull=True, is_default=True) + .order_by("id") + .first() + ) + + @classmethod + def for_delivery(cls, channel, notification_type): + if notification_type is not None: + typed = cls.objects.filter(channel=channel, type=notification_type).order_by("id").first() + if typed is not None: + return typed + return cls.default(channel) + + def render_subject(self, context): + return render(self.subject_template, context) + + def render_body(self, context): + return render(self.body_template, context) diff --git a/notify/receivers.py b/notify/receivers.py new file mode 100644 index 0000000..12ceb7f --- /dev/null +++ b/notify/receivers.py @@ -0,0 +1,34 @@ +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 NotificationAttachment, NotificationRecipient + +__all__ = [ + "delete_attachment_file", + "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.delivery_channel) + if provider is None or not provider.requires_async_delivery: + return + recipient_id = instance.id + + def enqueue(): + current = get_provider(instance.delivery_channel) + if current is not None: + current.enqueue(recipient_id) + + transaction.on_commit(enqueue) + + +@receiver(post_delete, sender=NotificationAttachment) +def delete_attachment_file(sender, instance: NotificationAttachment, **kwargs): + if instance.file: + instance.file.delete(save=False) diff --git a/notify/rendering.py b/notify/rendering.py new file mode 100644 index 0000000..3133166 --- /dev/null +++ b/notify/rendering.py @@ -0,0 +1,26 @@ +import markdown as md +from django.utils.html import escape +from jinja2 import ChainableUndefined, Environment +from markupsafe import Markup + +__all__ = [ + "render", +] + + +def markdown(value): + if value is None: + value = "" + html_output = md.markdown( + escape(str(value)), + extensions=["markdown.extensions.fenced_code"], + ) + return Markup(html_output) + + +_env = Environment(autoescape=True, undefined=ChainableUndefined) +_env.filters["markdown"] = markdown + + +def render(source, context): + return _env.from_string(source or "").render(context) diff --git a/notify/services.py b/notify/services.py new file mode 100644 index 0000000..5af4837 --- /dev/null +++ b/notify/services.py @@ -0,0 +1,255 @@ +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.can_switch: + 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, True): + 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, can_switch=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), True), + } + 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"], can_switch=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"]}, + ) diff --git a/notify/tasks.py b/notify/tasks.py new file mode 100644 index 0000000..f212829 --- /dev/null +++ b/notify/tasks.py @@ -0,0 +1,117 @@ +import logging +import random + +from celery import shared_task +from celery.schedules import crontab +from django.db import transaction +from django.db.models import F +from django.utils import timezone + +from notify.delivery.exceptions import PermanentDeliveryError +from notify.delivery.registry import get_provider_or_raise +from notify.models import DeliveryStatus, Notification, NotificationRecipient, VerificationCode + +__all__ = [ + "BEAT_SCHEDULE", + "deliver_notification", + "delete_expired_codes", + "delete_expired_notifications", + "retry_countdown", +] + +logger = logging.getLogger(__name__) + +RETRY_BASE_DELAY = 60 + +BEAT_SCHEDULE = { + "notify-delete-expired-notifications": { + "task": "notify.tasks.delete_expired_notifications", + "schedule": crontab(minute=0), + }, + "notify-delete-expired-codes": { + "task": "notify.tasks.delete_expired_codes", + "schedule": crontab(minute=30), + }, +} + + +def _mark_failed(notification_recipient_id: str, error: str) -> None: + NotificationRecipient.objects.filter( + id=notification_recipient_id, + delivery_status=DeliveryStatus.UNSENT, + ).update( + delivery_status=DeliveryStatus.FAILED, + last_error=error[:2000], + ) + + +def _deliver_notification(notification_recipient_id: str) -> None: + error = None + with transaction.atomic(): + recipient = ( + NotificationRecipient.objects.select_for_update(of=("self",)) + .select_related("notification__type", "user") + .filter(id=notification_recipient_id) + .first() + ) + if recipient is None or recipient.delivery_status != DeliveryStatus.UNSENT: + return + NotificationRecipient.objects.filter(pk=recipient.pk).update( + attempts=F("attempts") + 1, + ) + recipient.refresh_from_db(fields=["attempts"]) + try: + provider = get_provider_or_raise(recipient.delivery_channel) + provider.send(recipient) + except Exception as exc: + if isinstance(exc, KeyError): + exc = PermanentDeliveryError(str(exc)) + NotificationRecipient.objects.filter(pk=recipient.pk).update( + last_error=str(exc)[:2000], + ) + error = exc + if error is not None: + raise error + + +def retry_countdown(retries: int) -> int: + delay = RETRY_BASE_DELAY * 2 ** retries + return delay + random.randint(0, delay // 10) + + +@shared_task( + bind=True, + max_retries=5, +) +def deliver_notification(self, notification_recipient_id: str): + try: + _deliver_notification(notification_recipient_id) + except PermanentDeliveryError as exc: + logger.error( + "Permanent delivery failure for recipient %s: %s", + notification_recipient_id, + exc, + ) + _mark_failed(notification_recipient_id, str(exc)) + except Exception as exc: + if self.request.retries >= self.max_retries: + logger.error( + "Delivery failed after retries for recipient %s: %s", + notification_recipient_id, + exc, + ) + _mark_failed(notification_recipient_id, str(exc)) + raise + raise self.retry(exc=exc, countdown=retry_countdown(self.request.retries)) from exc + + +@shared_task +def delete_expired_notifications(): + deleted_count, _ = Notification.objects.filter(expires_at__lt=timezone.now()).delete() + return deleted_count + + +@shared_task +def delete_expired_codes(): + deleted_count, _ = VerificationCode.objects.filter(expires_at__lt=timezone.now()).delete() + return deleted_count diff --git a/notify/templates/admin/notify/deliveryemailconfig/change_form.html b/notify/templates/admin/notify/deliveryemailconfig/change_form.html new file mode 100644 index 0000000..610735b --- /dev/null +++ b/notify/templates/admin/notify/deliveryemailconfig/change_form.html @@ -0,0 +1,55 @@ +{% extends "admin/change_form.html" %} +{% load i18n %} + +{% block after_related_objects %} +{{ block.super }} +{% if original %} +
+

{% trans "Проверка подключения" %}

+
+ + +
+
+

+    
+
+ +{% endif %} +{% endblock %} diff --git a/notify/urls.py b/notify/urls.py new file mode 100644 index 0000000..8f1047a --- /dev/null +++ b/notify/urls.py @@ -0,0 +1,11 @@ +from django.urls import path + +from notify.api import api + +__all__ = [ + "urlpatterns", +] + +urlpatterns = [ + path("", api.urls), +] diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..cf21791 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,27 @@ +[project] +name = "notify" +version = "0.1.0" +description = "Django app for user notifications" +requires-python = ">=3.10" +dependencies = [ + "celery>=5.6.3", + "django>=5.0.6,<6", + "django-ace-editor>=0.1.0", + "django-ninja>=1.6.2", + "jinja2>=3.1", + "markdown>=3.10", + "pydantic[email]>=2.13", + "requests>=2.34.2", +] + +[dependency-groups] +dev = [ + "redis>=5", +] + +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[tool.hatch.build.targets.wheel] +packages = ["notify"] diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/settings.py b/tests/settings.py new file mode 100644 index 0000000..9b7717a --- /dev/null +++ b/tests/settings.py @@ -0,0 +1,51 @@ +SECRET_KEY = "test-secret" +USE_TZ = True +DEBUG = True +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" +ROOT_URLCONF = "tests.urls" +EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend" +INSTALLED_APPS = [ + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + "notify", +] + +MIDDLEWARE = [ + "django.middleware.security.SecurityMiddleware", + "django.contrib.sessions.middleware.SessionMiddleware", + "django.middleware.common.CommonMiddleware", + "django.middleware.csrf.CsrfViewMiddleware", + "django.contrib.auth.middleware.AuthenticationMiddleware", + "django.contrib.messages.middleware.MessageMiddleware", +] + +TEMPLATES = [ + { + "BACKEND": "django.template.backends.django.DjangoTemplates", + "APP_DIRS": True, + "OPTIONS": { + "context_processors": [ + "django.template.context_processors.request", + "django.contrib.auth.context_processors.auth", + "django.contrib.messages.context_processors.messages", + ], + }, + } +] + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": ":memory:", + } +} + +PASSWORD_HASHERS = [ + "django.contrib.auth.hashers.MD5PasswordHasher", +] + +STATIC_URL = "/static/" diff --git a/tests/test_admin.py b/tests/test_admin.py new file mode 100644 index 0000000..9c9e592 --- /dev/null +++ b/tests/test_admin.py @@ -0,0 +1,221 @@ +import uuid +from unittest.mock import patch + +from django.contrib import admin +from django.contrib.auth import get_user_model +from django.core import mail +from django.test import RequestFactory, TestCase +from django.urls import reverse + +from notify.admin import ( + DeliveryEmailConfigAdmin, + DeliveryEmailConfigForm, + DeliveryTokenConfigForm, + NotificationAdmin, + NotificationRecipientAdmin, +) +from notify.models import ( + DeliveryChannel, + DeliveryEmailConfig, + DeliveryTokenConfig, + Notification, + NotificationRecipient, +) + +User = get_user_model() + + +class EmailAdminTests(TestCase): + def setUp(self): + self.admin = User.objects.create_superuser("admin", "admin@example.com", "pass") + self.config = DeliveryEmailConfig.objects.create( + name="smtp", + channel=DeliveryChannel.EMAIL, + host="smtp.example.com", + port=587, + username="mailbox", + password="s3cret-smtp", + from_email="noreply@example.com", + test_email="qa@example.com", + use_ssl=False, + use_tls=False, + ) + self.client.force_login(self.admin) + self.connection_url = reverse( + "admin:notify_deliveryemailconfig_test_connection", + args=[self.config.pk], + ) + self.send_url = reverse( + "admin:notify_deliveryemailconfig_send_test_email", + args=[self.config.pk], + ) + + def test_email_admin_uses_the_email_form(self): + self.assertIs(DeliveryEmailConfigAdmin.form, DeliveryEmailConfigForm) + self.assertIs(DeliveryEmailConfigForm._meta.model, DeliveryEmailConfig) + self.assertIs(DeliveryTokenConfigForm._meta.model, DeliveryTokenConfig) + + def test_password_is_not_rendered_and_empty_submit_keeps_it(self): + html = DeliveryEmailConfigForm(instance=self.config).as_p() + self.assertNotIn("s3cret-smtp", html) + form = DeliveryEmailConfigForm( + data={ + "name": self.config.name, + "channel": self.config.channel, + "host": self.config.host, + "port": self.config.port, + "username": self.config.username, + "password": "", + "from_email": self.config.from_email, + "test_email": self.config.test_email, + "use_tls": "on", + }, + instance=self.config, + ) + self.assertTrue(form.is_valid(), form.errors) + self.assertEqual(form.cleaned_data["password"], "s3cret-smtp") + + def test_connection_check_is_post_and_hides_the_secret(self): + response = self.client.get(self.connection_url) + self.assertEqual(response.status_code, 405) + + with patch("notify.admin_views.get_connection", side_effect=RuntimeError("password=s3cret-smtp")): + response = self.client.post(self.connection_url) + body = response.content.decode() + self.assertEqual(response.status_code, 200) + self.assertIn("RuntimeError", body) + self.assertNotIn("Traceback", body) + self.assertNotIn("s3cret-smtp", body) + + def test_token_is_not_rendered(self): + config = DeliveryTokenConfig.objects.create( + name="max", + channel=DeliveryChannel.MAX, + token="max-token-value", + ) + html = DeliveryTokenConfigForm(instance=config).as_p() + self.assertNotIn("max-token-value", html) + channel_values = [choice[0] for choice in DeliveryTokenConfigForm().fields["channel"].choices] + self.assertEqual(channel_values, [DeliveryChannel.TELEGRAM, DeliveryChannel.MAX]) + + def test_empty_token_keeps_the_stored_value_and_a_new_one_replaces_it(self): + config = DeliveryTokenConfig.objects.create( + name="max", + channel=DeliveryChannel.MAX, + token="max-token-value", + ) + kept = DeliveryTokenConfigForm( + data={"name": config.name, "channel": config.channel, "token": ""}, + instance=config, + ) + self.assertTrue(kept.is_valid(), kept.errors) + self.assertEqual(kept.cleaned_data["token"], "max-token-value") + + replaced = DeliveryTokenConfigForm( + data={"name": config.name, "channel": config.channel, "token": "next-token"}, + instance=config, + ) + self.assertTrue(replaced.is_valid(), replaced.errors) + self.assertEqual(replaced.cleaned_data["token"], "next-token") + + def test_new_password_replaces_the_stored_one(self): + form = DeliveryEmailConfigForm( + data={ + "name": self.config.name, + "channel": self.config.channel, + "host": self.config.host, + "port": self.config.port, + "username": self.config.username, + "password": "next-secret", + "from_email": self.config.from_email, + "test_email": self.config.test_email, + "use_tls": "on", + }, + instance=self.config, + ) + self.assertTrue(form.is_valid(), form.errors) + self.assertEqual(form.cleaned_data["password"], "next-secret") + + def test_change_page_links_the_smtp_actions(self): + url = reverse("admin:notify_deliveryemailconfig_change", args=[self.config.pk]) + response = self.client.get(url) + self.assertContains(response, self.connection_url) + self.assertContains(response, self.send_url) + + def test_connection_check_reports_success_without_the_secret(self): + response = self.client.post(self.connection_url) + body = response.content.decode() + self.assertEqual(response.status_code, 200) + self.assertIn("Подключение к SMTP успешно", body) + self.assertNotIn(self.config.password, body) + + def test_send_test_email_uses_the_configured_address(self): + response = self.client.post(self.send_url) + body = response.content.decode() + self.assertEqual(response.status_code, 200) + self.assertIn("Тестовое письмо отправлено", body) + self.assertNotIn(self.config.password, body) + self.assertEqual(len(mail.outbox), 1) + self.assertEqual(mail.outbox[0].to, ["qa@example.com"]) + self.assertEqual(mail.outbox[0].subject, "SMTP test message") + + def test_send_test_email_requires_post_and_an_address(self): + self.assertEqual(self.client.get(self.send_url).status_code, 405) + self.config.test_email = "" + self.config.save(update_fields=["test_email"]) + response = self.client.post(self.send_url) + self.assertIn("Test email", response.content.decode()) + self.assertEqual(len(mail.outbox), 0) + + def test_send_test_email_hides_the_secret(self): + with patch( + "notify.admin_views.get_connection", + side_effect=RuntimeError("password=s3cret-smtp"), + ): + response = self.client.post(self.send_url) + body = response.content.decode() + self.assertIn("RuntimeError", body) + self.assertNotIn("Traceback", body) + self.assertNotIn("s3cret-smtp", body) + + def test_missing_config_is_not_found(self): + missing = uuid.uuid4() + connection = reverse("admin:notify_deliveryemailconfig_test_connection", args=[missing]) + send = reverse("admin:notify_deliveryemailconfig_send_test_email", args=[missing]) + self.assertEqual(self.client.post(connection).status_code, 404) + self.assertEqual(self.client.post(send).status_code, 404) + + def test_staff_without_permission_is_forbidden(self): + staff = User.objects.create_user("staff", "staff@example.com", "pass", is_staff=True) + self.client.force_login(staff) + self.assertEqual(self.client.post(self.connection_url).status_code, 403) + self.assertEqual(self.client.post(self.send_url).status_code, 403) + + +class NotificationAdminTests(TestCase): + def setUp(self): + self.admin_user = User.objects.create_superuser("admin", "admin@example.com", "pass") + self.client.force_login(self.admin_user) + self.note = Notification.objects.create(verb="Hello") + + def test_notifications_are_read_only(self): + request = RequestFactory().get("/") + request.user = self.admin_user + self.assertFalse(NotificationAdmin(Notification, admin.site).has_change_permission(request)) + self.assertFalse( + NotificationRecipientAdmin(NotificationRecipient, admin.site).has_change_permission(request) + ) + self.assertIn( + "user__username", + NotificationRecipientAdmin(NotificationRecipient, admin.site).get_search_fields(request), + ) + + change = reverse("admin:notify_notification_change", args=[self.note.pk]) + response = self.client.get(change) + self.assertEqual(response.status_code, 200) + self.assertFalse(response.context["has_change_permission"]) + self.assertEqual(self.client.post(change, {"verb": "Changed"}).status_code, 403) + self.note.refresh_from_db() + self.assertEqual(self.note.verb, "Hello") + listing = reverse("admin:notify_notification_changelist") + self.assertEqual(self.client.get(listing).status_code, 200) diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000..f338f8e --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,303 @@ +from datetime import timedelta + +from django.contrib.auth import get_user_model +from django.test import TestCase +from django.utils import timezone + +from notify.api_pagination import CustomPagination +from notify.models import DeliveryChannel, NotificationGroup, NotificationRecipient, NotificationType +from notify.services import create_notification + +User = get_user_model() + + +class ApiTests(TestCase): + def setUp(self): + self.user = User.objects.create_user("alice", "alice@example.com", "pass") + self.other = User.objects.create_user("bob", "bob@example.com", "pass") + self.client.force_login(self.user) + + def _browser(self, user, verb, expires_at=None, **extra): + if expires_at is not None: + extra["expires_at"] = expires_at + return create_notification( + verb=verb, + recipients=[{"user": user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + **extra, + ) + + def _type(self, code): + group, _ = NotificationGroup.objects.get_or_create( + code="catalog", + defaults={"name": "Catalog"}, + ) + return NotificationType.objects.create( + code=code, + name=code, + group=group, + channels=[DeliveryChannel.BROWSER, DeliveryChannel.EMAIL], + verb=code, + ) + + def test_expired_notifications_are_hidden(self): + self._browser(self.user, "fresh") + self._browser(self.user, "stale", expires_at=timezone.now() - timedelta(minutes=1)) + self._browser(self.other, "foreign") + + unread = self.client.get("/api/unread-count/") + self.assertEqual(unread.status_code, 200) + self.assertEqual(unread.json()["result"], 1) + + listing = self.client.get("/api/list/") + self.assertEqual(listing.status_code, 200) + verbs = [item["verb"] for item in listing.json()["results"]] + self.assertEqual(verbs, ["fresh"]) + + def test_invalid_recipient_id_is_not_found(self): + response = self.client.post("/api/make-read/not-a-number/") + self.assertEqual(response.status_code, 404) + self.assertEqual(response.json()["message"], "Not found") + + missing = self.client.post("/api/make-read/999999/") + self.assertEqual(missing.status_code, 404) + self.assertEqual(missing.json()["message"], "Object not found") + + def test_anonymous_requests_are_rejected(self): + self.client.logout() + recipient_id = 1 + for url in ("/api/unread-count/", "/api/count/", "/api/list/"): + with self.subTest(url=url): + self.assertEqual(self.client.get(url).status_code, 401) + for url in ( + f"/api/make-read/{recipient_id}/", + f"/api/make-unread/{recipient_id}/", + "/api/make-all-read/", + ): + with self.subTest(url=url): + self.assertEqual(self.client.post(url).status_code, 401) + + def test_list_returns_the_browser_inbox(self): + kind = self._type("orders.approved") + when = timezone.now() + timedelta(days=3) + notification = self._browser( + self.user, + "Invoice paid", + expires_at=when, + type=kind, + url="https://example.com/orders/1?x=1", + object_id="1", + description="wire", + data={"n": 1}, + level="SUCCESS", + ) + self._browser(self.other, "foreign") + older = notification.recipients.get() + older.created_at = timezone.now() - timedelta(hours=1) + older.save(update_fields=["created_at"]) + self._browser(self.user, "Newer") + + listing = self.client.get("/api/list/") + self.assertEqual(listing.status_code, 200) + body = listing.json() + self.assertEqual(body["total"], 2) + self.assertEqual(body["pagination"], {"page": 1, "total_pages": 1}) + self.assertEqual([item["verb"] for item in body["results"]], ["Newer", "Invoice paid"]) + + item = body["results"][1] + self.assertEqual(item["id"], older.id) + self.assertEqual(item["type"], "orders.approved") + self.assertEqual(item["level"], "SUCCESS") + self.assertEqual(item["url"], "https://example.com/orders/1?x=1") + self.assertEqual(item["object_id"], "1") + self.assertEqual(item["description"], "wire") + self.assertEqual(item["data"], {"n": 1}) + self.assertTrue(item["unread"]) + self.assertNotIn("delivery_channel", item) + self.assertNotIn("delivery_target", item) + + count = self.client.get("/api/count/") + self.assertEqual(count.json()["result"], 2) + + def test_other_channels_and_other_users_stay_out_of_the_inbox(self): + create_notification( + verb="mail", + recipients=[ + { + "user": self.user, + "channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}], + } + ], + ) + foreign = self._browser(self.other, "foreign") + self._browser(self.user, "mine") + + listing = self.client.get("/api/list/") + self.assertEqual([item["verb"] for item in listing.json()["results"]], ["mine"]) + + foreign_id = foreign.recipients.get().id + denied = self.client.post(f"/api/make-read/{foreign_id}/") + self.assertEqual(denied.status_code, 404) + foreign.recipients.get().refresh_from_db() + self.assertTrue(foreign.recipients.get().unread) + + email_id = NotificationRecipient.objects.get(delivery_channel=DeliveryChannel.EMAIL).id + self.assertEqual(self.client.post(f"/api/make-read/{email_id}/").status_code, 404) + + def test_expired_recipient_cannot_be_marked(self): + stale = self._browser(self.user, "stale", expires_at=timezone.now() - timedelta(minutes=1)) + response = self.client.post(f"/api/make-read/{stale.recipients.get().id}/") + self.assertEqual(response.status_code, 404) + stale.recipients.get().refresh_from_db() + self.assertTrue(stale.recipients.get().unread) + + def test_make_read_and_make_unread(self): + notification = self._browser(self.user, "fresh") + recipient = notification.recipients.get() + + read = self.client.post(f"/api/make-read/{recipient.id}/") + self.assertEqual(read.status_code, 200) + self.assertFalse(read.json()["unread"]) + self.assertEqual(read.json()["verb"], "fresh") + self.assertEqual(self.client.get("/api/unread-count/").json()["result"], 0) + + again = self.client.post(f"/api/make-unread/{recipient.id}/") + self.assertEqual(again.status_code, 200) + self.assertTrue(again.json()["unread"]) + recipient.refresh_from_db() + self.assertTrue(recipient.unread) + + def test_filters_narrow_the_inbox(self): + approved = self._type("orders.approved") + rejected = self._type("orders.rejected") + billing = self._type("billing.due") + self._browser( + self.user, + "Invoice paid", + type=approved, + object_id="1", + description="wire", + ) + self._browser(self.user, "Nope", type=rejected, object_id="2", description="card") + self._browser( + self.user, + "Due", + type=billing, + object_id="3", + description="Invoice reminder", + ) + paid = NotificationRecipient.objects.get(notification__object_id="1") + paid.make_read() + + def verbs(response): + return [item["verb"] for item in response.json()["results"]] + + self.assertEqual( + verbs(self.client.get("/api/list/", {"type": "orders.approved"})), + ["Invoice paid"], + ) + self.assertCountEqual( + verbs(self.client.get("/api/list/", {"type__startswith": "orders"})), + ["Invoice paid", "Nope"], + ) + self.assertEqual( + verbs(self.client.get("/api/list/", {"object_id": "2"})), + ["Nope"], + ) + self.assertCountEqual( + verbs(self.client.get("/api/list/", {"search": "invoice"})), + ["Invoice paid", "Due"], + ) + self.assertCountEqual( + verbs(self.client.get("/api/list/", {"unread": "true"})), + ["Nope", "Due"], + ) + self.assertEqual( + verbs(self.client.get("/api/list/", {"unread": "false"})), + ["Invoice paid"], + ) + self.assertCountEqual( + verbs(self.client.get("/api/list/", {"object_id__ne": ["2"]})), + ["Invoice paid", "Due"], + ) + self.assertEqual( + verbs(self.client.get("/api/list/", {"object_id__ne__in": "1,3"})), + ["Nope"], + ) + self.assertEqual( + self.client.get("/api/count/", {"type__startswith": "orders"}).json()["result"], + 2, + ) + + def test_make_all_read_respects_filters(self): + orders = self._type("orders.approved") + billing = self._type("billing.due") + self._browser(self.user, "order", type=orders) + self._browser(self.user, "bill", type=billing) + self._browser(self.other, "foreign", type=orders) + self._browser( + self.user, + "old order", + type=orders, + expires_at=timezone.now() - timedelta(minutes=1), + ) + mailed = create_notification( + type=orders, + recipients=[ + { + "user": self.user, + "channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}], + } + ], + ) + + response = self.client.post("/api/make-all-read/?type=orders.approved") + self.assertEqual(response.status_code, 200) + self.assertEqual(response.json(), {}) + + def unread(verb): + return NotificationRecipient.objects.get(notification__verb=verb).unread + + self.assertFalse(unread("order")) + self.assertTrue(unread("bill")) + self.assertTrue(unread("foreign")) + self.assertTrue(unread("old order")) + self.assertTrue(mailed.recipients.get().unread) + self.assertEqual(self.client.get("/api/unread-count/").json()["result"], 1) + + def test_invalid_page_is_rejected(self): + self._browser(self.user, "fresh") + response = self.client.get("/api/list/", {"page": "0"}) + self.assertEqual(response.status_code, 422) + self.assertIn("detail", response.json()) + + +class PaginationTests(TestCase): + def setUp(self): + self.user = User.objects.create_user("alice", "alice@example.com", "pass") + + def test_pages_are_counted_from_the_queryset(self): + for verb in ("a", "b", "c"): + create_notification( + verb=verb, + recipients=[ + {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, + ], + ) + paginator = CustomPagination(page_size=2) + queryset = NotificationRecipient.objects.order_by("notification__verb") + + first = paginator.paginate_queryset(queryset, CustomPagination.Input(page=1)) + self.assertEqual(first["total"], 3) + self.assertEqual(first["pagination"], {"page": 1, "total_pages": 2}) + self.assertEqual([item.notification.verb for item in first["results"]], ["a", "b"]) + + second = paginator.paginate_queryset(queryset, CustomPagination.Input(page=2)) + self.assertEqual([item.notification.verb for item in second["results"]], ["c"]) + + empty = paginator.paginate_queryset( + NotificationRecipient.objects.none(), + CustomPagination.Input(page=1), + ) + self.assertEqual(empty["results"], []) + self.assertEqual(empty["total"], 0) + self.assertEqual(empty["pagination"]["total_pages"], 0) diff --git a/tests/test_attachments.py b/tests/test_attachments.py new file mode 100644 index 0000000..e64d013 --- /dev/null +++ b/tests/test_attachments.py @@ -0,0 +1,290 @@ +from datetime import timedelta +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.core import mail +from django.core.files.base import ContentFile +from django.core.files.storage import default_storage +from django.core.files.uploadedfile import SimpleUploadedFile +from django.test import TestCase, override_settings +from django.utils import timezone + +from notify.models import ( + DeliveryChannel, + DeliveryEmailConfig, + Notification, + NotificationAttachment, + NotificationGroup, + NotificationType, +) +from notify.services import create_notification +from notify.tasks import deliver_notification + +User = get_user_model() + +MEMORY_STORAGES = { + "default": {"BACKEND": "django.core.files.storage.memory.InMemoryStorage"}, + "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"}, +} + + +@override_settings(STORAGES=MEMORY_STORAGES) +class AttachmentServiceTests(TestCase): + def setUp(self): + self.user = User.objects.create_user("alice", "alice@example.com", "pass") + self.other = User.objects.create_user("bob", "bob@example.com", "pass") + self.group = NotificationGroup.objects.create(code="orders", name="Orders") + self.kind = NotificationType.objects.create( + code="approved", + name="Approved", + group=self.group, + channels=[DeliveryChannel.BROWSER, DeliveryChannel.EMAIL], + verb="Approved", + ) + + def _browser(self, user, **extra): + return create_notification( + verb=extra.pop("verb", "Hello"), + recipients=[{"user": user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + **extra, + ) + + def test_files_are_stored_with_a_cleaned_name(self): + uploaded = SimpleUploadedFile("notes.txt", b"abc", content_type="text/plain; charset=utf-8") + notification = self._browser( + self.user, + attachments=[ + uploaded, + ContentFile(b"%PDF", name="../../secret/report.pdf"), + ], + ) + stored = list(notification.attachments.order_by("name")) + self.assertEqual([item.name for item in stored], ["notes.txt", "report.pdf"]) + self.assertEqual(stored[0].content_type, "text/plain") + self.assertEqual(stored[0].size, 3) + self.assertEqual(stored[0].file.read(), b"abc") + self.assertEqual(stored[1].content_type, "application/pdf") + self.assertEqual(stored[1].size, 4) + self.assertTrue(default_storage.exists(stored[1].file.name)) + + def test_limits_reject_the_notification(self): + with override_settings(NOTIFY_MAX_ATTACHMENTS=1): + with self.assertRaisesMessage(ValueError, "At most 1 attachments are allowed"): + self._browser( + self.user, + attachments=[ + ContentFile(b"a", name="a.txt"), + ContentFile(b"b", name="b.txt"), + ], + ) + with override_settings(NOTIFY_MAX_ATTACHMENT_BYTES=4): + with self.assertRaisesMessage(ValueError, "exceeds the size limit"): + self._browser(self.user, attachments=[ContentFile(b"hello", name="a.txt")]) + with self.assertRaisesMessage(ValueError, "Attachment must have a file name"): + self._browser(self.user, attachments=[ContentFile(b"x", name="")]) + with self.assertRaisesMessage(ValueError, "Attachment must be a file"): + self._browser(self.user, attachments=["nope"]) + self.assertEqual(Notification.objects.count(), 0) + + def test_oversized_declared_size_is_not_read(self): + class BigFile: + name = "big.bin" + size = 100 + + def read(self): + raise AssertionError("should not read") + + with override_settings(NOTIFY_MAX_ATTACHMENT_BYTES=10): + with self.assertRaisesMessage(ValueError, "exceeds the size limit"): + self._browser(self.user, attachments=[BigFile()]) + self.assertEqual(Notification.objects.count(), 0) + + def test_failed_save_removes_stored_files(self): + real_save = NotificationAttachment.save + names = [] + + def fail_second(row, *args, **kwargs): + names.append(row.file.name) + if len(names) == 2: + raise RuntimeError("disk") + return real_save(row, *args, **kwargs) + + with patch("notify.attachments.NotificationAttachment.save", fail_second): + with self.assertRaisesMessage(RuntimeError, "disk"): + self._browser( + self.user, + attachments=[ + ContentFile(b"one", name="first.txt"), + ContentFile(b"two", name="second.txt"), + ], + ) + self.assertEqual(Notification.objects.count(), 0) + self.assertEqual(NotificationAttachment.objects.count(), 0) + self.assertEqual(len(names), 2) + for name in names: + self.assertFalse(default_storage.exists(name)) + + def test_same_idempotency_key_does_not_add_files(self): + first = self._browser(self.user, idempotency_key="approved:9") + with override_settings(NOTIFY_MAX_ATTACHMENT_BYTES=1): + second = self._browser( + self.user, + verb="Other", + idempotency_key="approved:9", + attachments=[ContentFile(b"hello", name="late.txt")], + ) + self.assertEqual(second.pk, first.pk) + self.assertEqual(first.attachments.count(), 0) + + def test_group_copies_files_onto_collapsed_and_new_notifications(self): + first = create_notification( + type=self.kind, + object_id="post-9", + group=True, + recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + ) + second = create_notification( + type=self.kind, + object_id="post-9", + verb="Ещё", + group=True, + attachments=[ContentFile(b"note", name="note.txt")], + recipients=[ + {"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}, + {"user": self.other, "channels": [{"channel": DeliveryChannel.BROWSER}]}, + ], + ) + self.assertNotEqual(second.pk, first.pk) + self.assertEqual(Notification.objects.count(), 2) + self.assertEqual(first.attachments.get().name, "note.txt") + self.assertEqual(second.attachments.get().file.read(), b"note") + self.assertNotEqual(first.attachments.get().file.name, second.attachments.get().file.name) + + collapsed = create_notification( + type=self.kind, + object_id="post-9", + group=True, + attachments=[ContentFile(b"more", name="more.txt")], + recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + ) + self.assertEqual(collapsed.pk, first.pk) + self.assertEqual(set(first.attachments.values_list("name", flat=True)), {"note.txt", "more.txt"}) + self.assertEqual(Notification.objects.count(), 2) + + def test_deleting_a_notification_deletes_its_file(self): + notification = self._browser(self.user, attachments=[ContentFile(b"gone", name="gone.txt")]) + other = self._browser(self.other, attachments=[ContentFile(b"stay", name="stay.txt")]) + removed = notification.attachments.get().file.name + kept = other.attachments.get().file.name + Notification.objects.filter(pk=notification.pk).delete() + self.assertFalse(default_storage.exists(removed)) + self.assertTrue(default_storage.exists(kept)) + self.assertEqual(other.attachments.get().file.read(), b"stay") + + +@override_settings(STORAGES=MEMORY_STORAGES) +class AttachmentApiTests(TestCase): + def setUp(self): + self.user = User.objects.create_user("alice", "alice@example.com", "pass") + self.other = User.objects.create_user("bob", "bob@example.com", "pass") + self.client.force_login(self.user) + + def test_list_and_download_are_limited_to_the_recipient(self): + create_notification( + verb="With file", + attachments=[ContentFile(b"hello", name="report.txt")], + recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + ) + create_notification( + verb="Foreign", + attachments=[ContentFile(b"secret", name="secret.txt")], + recipients=[{"user": self.other, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + ) + listing = self.client.get("/api/list/") + self.assertEqual(listing.status_code, 200) + item = listing.json()["results"][0] + self.assertEqual(item["verb"], "With file") + self.assertEqual(len(item["attachments"]), 1) + attachment = item["attachments"][0] + self.assertEqual(attachment["name"], "report.txt") + self.assertEqual(attachment["size"], 5) + self.assertEqual(attachment["content_type"], "text/plain") + self.assertIn("/api/attachments/", attachment["url"]) + + downloaded = self.client.get(attachment["url"]) + self.assertEqual(downloaded.status_code, 200) + self.assertEqual(b"".join(downloaded.streaming_content), b"hello") + self.assertIn("report.txt", downloaded["Content-Disposition"]) + + foreign = NotificationAttachment.objects.get(name="secret.txt") + hidden = self.client.get(f"/api/attachments/{foreign.id}/") + self.assertEqual(hidden.status_code, 404) + self.assertEqual(hidden.json()["message"], "Not found") + + self.client.logout() + anonymous = self.client.get(attachment["url"]) + self.assertEqual(anonymous.status_code, 401) + + def test_expired_and_invalid_ids_are_hidden(self): + notification = create_notification( + verb="Stale", + expires_at=timezone.now() - timedelta(minutes=1), + attachments=[ContentFile(b"old", name="old.txt")], + recipients=[{"user": self.user, "channels": [{"channel": DeliveryChannel.BROWSER}]}], + ) + attachment = notification.attachments.get() + missing = self.client.get(f"/api/attachments/{attachment.id}/") + self.assertEqual(missing.status_code, 404) + invalid = self.client.get("/api/attachments/not-a-number/") + self.assertEqual(invalid.status_code, 404) + + def test_email_recipient_can_download(self): + notification = create_notification( + verb="Mail", + attachments=[ContentFile(b"body", name="body.txt")], + recipients=[ + { + "user": self.user, + "channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}], + } + ], + ) + attachment = notification.attachments.get() + downloaded = self.client.get(f"/api/attachments/{attachment.id}/") + self.assertEqual(downloaded.status_code, 200) + self.assertEqual(b"".join(downloaded.streaming_content), b"body") + + +@override_settings(STORAGES=MEMORY_STORAGES) +class AttachmentEmailTests(TestCase): + def setUp(self): + self.user = User.objects.create_user("alice", "alice@example.com", "pass") + DeliveryEmailConfig.objects.create( + name="default-smtp", + channel=DeliveryChannel.EMAIL, + is_default=True, + host="smtp.example.com", + port=587, + from_email="noreply@example.com", + use_ssl=False, + use_tls=False, + ) + + def test_email_includes_the_file(self): + notification = create_notification( + verb="Hello", + description="Body", + attachments=[ContentFile(b"pdf-bytes", name="report.pdf")], + recipients=[ + { + "user": self.user, + "channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}], + } + ], + ) + recipient = notification.recipients.get() + deliver_notification.apply(args=[str(recipient.id)], throw=True) + self.assertEqual( + mail.outbox[0].attachments, + [("report.pdf", b"pdf-bytes", "application/pdf")], + ) diff --git a/tests/test_codes.py b/tests/test_codes.py new file mode 100644 index 0000000..d398e26 --- /dev/null +++ b/tests/test_codes.py @@ -0,0 +1,214 @@ +import re +from datetime import timedelta +from unittest.mock import patch + +import requests +from django.contrib.auth import get_user_model +from django.core import mail +from django.test import TestCase, override_settings +from django.utils import timezone + +from notify.codes import CodeThrottled, send_code, verify_code +from notify.delivery.exceptions import DeliveryError, PermanentDeliveryError +from notify.models import ( + DeliveryChannel, + DeliveryEmailConfig, + DeliveryTokenConfig, + NotificationGroup, + NotificationTemplate, + NotificationType, + VerificationCode, +) +from notify.tasks import delete_expired_codes + +User = get_user_model() + +CODE_RE = re.compile(r"\b(\d{6})\b") + + +class FakeResponse: + def __init__(self, status_code=200): + self.status_code = status_code + + def raise_for_status(self): + if self.status_code >= 400: + raise requests.HTTPError(response=self) + + +@override_settings(NOTIFY_CODE_RESEND_INTERVAL=0) +class CodeTests(TestCase): + def setUp(self): + self.user = User.objects.create_user("alice", "alice@example.com", "pass") + DeliveryEmailConfig.objects.create( + name="smtp", + channel=DeliveryChannel.EMAIL, + is_default=True, + host="smtp.example.com", + from_email="noreply@example.com", + use_tls=False, + ) + DeliveryTokenConfig.objects.create( + name="tg", channel=DeliveryChannel.TELEGRAM, is_default=True, token="tg-token" + ) + DeliveryTokenConfig.objects.create( + name="max", channel=DeliveryChannel.MAX, is_default=True, token="max-token" + ) + + def _send_email(self, **kwargs): + kwargs.setdefault("purpose", "login") + kwargs.setdefault("target", {"email": "Alice@Example.com"}) + send_code(channel=DeliveryChannel.EMAIL, **kwargs) + return CODE_RE.search(mail.outbox[-1].body).group(1) + + def _send_messenger(self, channel, target, **kwargs): + with patch("requests.post", return_value=FakeResponse()) as post: + send_code(purpose="login", channel=channel, target=target, **kwargs) + return post, CODE_RE.search(post.call_args.kwargs["json"]["text"]).group(1) + + def test_email_send_and_verify(self): + code = self._send_email(user=self.user) + verification = VerificationCode.objects.get() + self.assertEqual(verification.target_key, "alice@example.com") + self.assertEqual(verification.user, self.user) + self.assertNotIn(code, verification.code_hash) + self.assertEqual(mail.outbox[0].to, ["Alice@example.com"]) + self.assertTrue( + verify_code(purpose="login", channel="email", target={"email": "alice@example.com"}, code=code) + ) + verification.refresh_from_db() + self.assertIsNotNone(verification.consumed_at) + + def test_telegram_send_and_verify(self): + post, code = self._send_messenger(DeliveryChannel.TELEGRAM, {"chat_id": 42}) + self.assertEqual(post.call_args.kwargs["json"]["chat_id"], 42) + self.assertTrue(verify_code(purpose="login", channel="telegram", target={"chat_id": 42}, code=code)) + + def test_max_send_and_verify(self): + target = {"chat_id": 5, "user_id": 7} + post, code = self._send_messenger(DeliveryChannel.MAX, target) + self.assertEqual(post.call_args.kwargs["params"], {"user_id": 7}) + verification = VerificationCode.objects.get() + self.assertEqual(verification.target_key, "user:7") + self.assertEqual(verification.delivery_target, target) + self.assertTrue(verify_code(purpose="login", channel="max", target=target, code=code)) + + def test_wrong_code_counts_attempt(self): + code = self._send_email() + wrong = "000000" if code != "000000" else "111111" + self.assertFalse(verify_code(purpose="login", channel="email", target={"email": "alice@example.com"}, code=wrong)) + self.assertEqual(VerificationCode.objects.get().attempts, 1) + self.assertTrue(verify_code(purpose="login", channel="email", target={"email": "alice@example.com"}, code=code)) + + @override_settings(NOTIFY_CODE_MAX_ATTEMPTS=2) + def test_attempts_exhausted(self): + code = self._send_email() + wrong = "000000" if code != "000000" else "111111" + for _ in range(2): + verify_code(purpose="login", channel="email", target={"email": "alice@example.com"}, code=wrong) + self.assertFalse(verify_code(purpose="login", channel="email", target={"email": "alice@example.com"}, code=code)) + self.assertEqual(VerificationCode.objects.get().attempts, 2) + + def test_expired_code_rejected(self): + code = self._send_email() + VerificationCode.objects.update(expires_at=timezone.now() - timedelta(seconds=1)) + self.assertFalse(verify_code(purpose="login", channel="email", target={"email": "alice@example.com"}, code=code)) + + def test_code_is_single_use(self): + code = self._send_email() + self.assertTrue(verify_code(purpose="login", channel="email", target={"email": "alice@example.com"}, code=code)) + self.assertFalse(verify_code(purpose="login", channel="email", target={"email": "alice@example.com"}, code=code)) + + def test_purpose_is_isolated(self): + code = self._send_email(purpose="login") + self.assertFalse( + verify_code(purpose="email_change", channel="email", target={"email": "alice@example.com"}, code=code) + ) + + def test_new_code_invalidates_previous(self): + first = self._send_email() + second = self._send_email() + if first != second: + self.assertFalse( + verify_code(purpose="login", channel="email", target={"email": "alice@example.com"}, code=first) + ) + self.assertEqual(VerificationCode.objects.filter(consumed_at__isnull=True).count(), 1) + self.assertTrue(verify_code(purpose="login", channel="email", target={"email": "alice@example.com"}, code=second)) + + @override_settings(NOTIFY_CODE_RESEND_INTERVAL=60) + def test_resend_is_throttled(self): + self._send_email() + with self.assertRaises(CodeThrottled) as ctx: + self._send_email() + self.assertGreater(ctx.exception.retry_after, 0) + self.assertEqual(VerificationCode.objects.count(), 1) + self.assertEqual(len(mail.outbox), 1) + + def test_delivery_failure_rolls_back(self): + with patch("requests.post", return_value=FakeResponse(503)) as post: + with self.assertRaises(DeliveryError) as ctx: + send_code(purpose="login", channel="telegram", target={"chat_id": 42}) + code = CODE_RE.search(post.call_args.kwargs["json"]["text"]).group(1) + self.assertNotIn(code, str(ctx.exception)) + self.assertFalse(VerificationCode.objects.exists()) + + @override_settings(NOTIFY_CODE_RESEND_INTERVAL=60) + def test_failure_keeps_previous_code_and_allows_retry(self): + _, first = self._send_messenger(DeliveryChannel.TELEGRAM, {"chat_id": 42}) + VerificationCode.objects.update(created_at=timezone.now() - timedelta(seconds=61)) + with patch("requests.post", return_value=FakeResponse(400)): + with self.assertRaises(PermanentDeliveryError): + send_code(purpose="login", channel="telegram", target={"chat_id": 42}) + self.assertTrue(verify_code(purpose="login", channel="telegram", target={"chat_id": 42}, code=first)) + + def test_browser_channel_rejected(self): + with self.assertRaises(ValueError): + send_code(purpose="login", channel="browser") + + def test_invalid_recipient_rejected(self): + with self.assertRaises(ValueError): + send_code(purpose="login", channel="email", target={"email": "not-an-email"}) + with self.assertRaises(ValueError): + send_code(purpose="login", channel="telegram") + + def test_custom_template_by_type(self): + group = NotificationGroup.objects.create(code="auth", name="Auth") + notification_type = NotificationType.objects.create( + code="otp", name="OTP", verb="OTP", channels=["email"], group=group + ) + NotificationTemplate.objects.create( + name="otp-email", + channel="email", + type=notification_type, + subject_template="Вход для {{ user.username }}", + body_template="{{ code }} на {{ ttl_minutes }} мин ({{ purpose }})", + ) + code = self._send_email(user=self.user, type="otp") + message = mail.outbox[-1] + self.assertEqual(message.subject, "Вход для alice") + self.assertEqual(message.body, f"{code} на 5 мин (login)") + + def test_default_channel_template_is_not_used(self): + NotificationTemplate.objects.create( + name="default-email", + channel="email", + is_default=True, + subject_template="{{ notification.verb }}", + body_template="{{ notification.description }}", + ) + code = self._send_email() + self.assertIn(code, mail.outbox[-1].body) + + @override_settings(NOTIFY_CODE_LENGTH=8) + def test_code_length_setting(self): + with patch("requests.post", return_value=FakeResponse()) as post: + send_code(purpose="login", channel="telegram", target={"chat_id": 1}) + self.assertRegex(post.call_args.kwargs["json"]["text"], r"\b\d{8}\b") + + def test_delete_expired_codes(self): + self._send_email() + self._send_email(purpose="other") + VerificationCode.objects.filter(purpose="other").update( + expires_at=timezone.now() - timedelta(seconds=1) + ) + self.assertEqual(delete_expired_codes(), 1) + self.assertEqual(VerificationCode.objects.get().purpose, "login") diff --git a/tests/test_delivery.py b/tests/test_delivery.py new file mode 100644 index 0000000..8d6ccac --- /dev/null +++ b/tests/test_delivery.py @@ -0,0 +1,626 @@ +from datetime import timedelta +from unittest.mock import patch + +import requests +from django.contrib.auth import get_user_model +from django.core import mail +from django.core.exceptions import ValidationError +from django.db import IntegrityError, transaction +from django.test import TestCase +from django.utils import timezone + +from notify.delivery import get_provider, get_provider_or_raise, registered_channels +from notify.delivery.providers.max import MAX_API_TIMEOUT +from notify.delivery.providers.telegram import TELEGRAM_API_TIMEOUT +from notify.models import ( + DeliveryChannel, + DeliveryEmailConfig, + DeliveryStatus, + DeliveryTokenConfig, + Notification, + NotificationGroup, + NotificationRecipient, + NotificationTemplate, + NotificationType, +) +from notify.rendering import render +from notify.services import create_notification +from notify.tasks import RETRY_BASE_DELAY, deliver_notification, retry_countdown + +User = get_user_model() + + +class RetryCountdownTests(TestCase): + def test_delay_doubles_with_bounded_jitter(self): + for retries in range(5): + expected = RETRY_BASE_DELAY * 2 ** retries + for _ in range(20): + delay = retry_countdown(retries) + self.assertGreaterEqual(delay, expected) + self.assertLessEqual(delay, expected + expected // 10) + + +class DeliveryTests(TestCase): + def setUp(self): + self.user = User.objects.create_user("alice", "alice@example.com", "pass") + self.email_config = DeliveryEmailConfig.objects.create( + name="default-smtp", + channel=DeliveryChannel.EMAIL, + is_default=True, + host="smtp.example.com", + port=587, + from_email="noreply@example.com", + use_ssl=False, + use_tls=False, + ) + + def _email_recipient(self, **notification_kwargs): + notification = create_notification( + verb=notification_kwargs.pop("verb", "Hello"), + description=notification_kwargs.pop("description", "Body"), + recipients=[ + { + "user": self.user, + "channels": [{"channel": DeliveryChannel.EMAIL, "target": {"email": "alice@example.com"}}], + } + ], + **notification_kwargs, + ) + return notification.recipients.get() + + def _max_recipient(self, delivery_target=None): + DeliveryTokenConfig.objects.create( + name="max", + channel=DeliveryChannel.MAX, + is_default=True, + token="token", + ) + notification = Notification.objects.create(verb="Hello", description="Body") + return NotificationRecipient.objects.create( + notification=notification, + user=self.user, + delivery_channel=DeliveryChannel.MAX, + delivery_target={"chat_id": -10} if delivery_target is None else delivery_target, + ) + + def test_email_failure_is_not_marked_sent(self): + recipient = self._email_recipient() + with patch( + "notify.delivery.providers.email.EmailMessage.send", + side_effect=OSError("smtp down"), + ): + result = deliver_notification.apply(args=[str(recipient.id)], throw=False) + self.assertEqual(result.state, "FAILURE") + recipient.refresh_from_db() + self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) + self.assertEqual(recipient.attempts, 6) + self.assertIn("Email delivery failed", recipient.last_error) + self.assertIsNone(recipient.sent_at) + self.assertEqual(len(mail.outbox), 0) + + def test_missing_email_config_fails_explicitly(self): + recipient = self._email_recipient() + self.email_config.delete() + result = deliver_notification.apply(args=[str(recipient.id)], throw=False) + self.assertEqual(result.state, "FAILURE") + recipient.refresh_from_db() + self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) + + def test_missing_address_is_permanent_failure(self): + notification = Notification.objects.create(verb="Hello", description="Body") + recipient = NotificationRecipient.objects.create( + notification=notification, + user=self.user, + delivery_channel=DeliveryChannel.EMAIL, + delivery_target=None, + ) + deliver_notification.apply(args=[str(recipient.id)], throw=True) + recipient.refresh_from_db() + self.assertEqual(recipient.delivery_status, DeliveryStatus.FAILED) + + def test_successful_email_is_sent_once_and_escapes_html(self): + recipient = self._email_recipient( + verb="Hello\r\nBcc: leak", + description="", + ) + deliver_notification.apply(args=[str(recipient.id)], throw=True) + deliver_notification.apply(args=[str(recipient.id)], throw=True) + recipient.refresh_from_db() + self.assertEqual(recipient.delivery_status, DeliveryStatus.SENT) + self.assertEqual(recipient.attempts, 1) + self.assertEqual(recipient.last_error, "") + self.assertIsNotNone(recipient.sent_at) + self.assertEqual(len(mail.outbox), 1) + self.assertNotIn("\n", mail.outbox[0].subject) + self.assertNotIn(""}) + self.assertNotIn(""}}) + self.assertNotIn("