199 lines
5.3 KiB
Python
199 lines
5.3 KiB
Python
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 (
|
|
ChannelPreferenceSaveSchema,
|
|
DetailSchema,
|
|
NotificationResponseSchema,
|
|
OkSchema,
|
|
Preference,
|
|
)
|
|
from .models import (
|
|
DeliveryChannel,
|
|
NotificationAttachment,
|
|
NotificationRecipient,
|
|
NotificationType,
|
|
)
|
|
from .services import channel_preferences, save_channel_preferences
|
|
|
|
__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,
|
|
channel=DeliveryChannel.BROWSER,
|
|
notification__expires_at__gte=timezone.now(),
|
|
).select_related(
|
|
"notification",
|
|
"notification__notification_type",
|
|
"notification__content_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
|
|
|
|
|
|
@api.get("preferences/", response=List[Preference])
|
|
def preferences(request):
|
|
saved = {
|
|
item["code"]: item["channels"]
|
|
for item in channel_preferences(request.user)
|
|
}
|
|
types = NotificationType.objects.filter(
|
|
is_active=True,
|
|
is_configurable=True,
|
|
).select_related("group")
|
|
return [
|
|
{
|
|
"code": notification_type.code,
|
|
"name": notification_type.name,
|
|
"group_name": notification_type.group.name,
|
|
"channels": saved.get(notification_type.code, []),
|
|
}
|
|
for notification_type in types
|
|
]
|
|
|
|
|
|
@api.post("preferences/", response={200: OkSchema, 400: DetailSchema})
|
|
def save_preferences(request, payload: ChannelPreferenceSaveSchema):
|
|
try:
|
|
save_channel_preferences(
|
|
request.user,
|
|
[item.model_dump() for item in payload.items],
|
|
)
|
|
except (ValueError, NotificationType.DoesNotExist) as exc:
|
|
return 400, {"detail": str(exc)}
|
|
return {"ok": True}
|