"""
Smarter Journal api views.
They are mounted at ``/api/v1/journal/``, and only superusers may call them: a journal entry's
documents hold every user's content, e.g. prompts and manifests. Each read is
signaled, with :data:`smarter.lib.journal.signals.journal_entry_accessed` or
:data:`smarter.lib.journal.signals.journal_entries_listed`.
"""
from django.db.models import QuerySet
from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from rest_framework.request import Request
from rest_framework.response import Response
from smarter.lib import logging
from smarter.lib.django.pagination import ListViewPagination, paginate_listview
from smarter.lib.django.waffle import SmarterWaffleSwitches
from smarter.lib.drf.views.token_authentication_helpers import (
SmarterAdminAPIView,
SmarterAdminListAPIView,
)
from smarter.lib.journal.contract.models import (
SAMJournalApiEntry,
SAMJournalApiEntrySummary,
SAMJournalApiPage,
)
from smarter.lib.journal.models import DOCUMENT_FIELDS, SAMJournal
from smarter.lib.journal.serializers import (
SAMJournalMiniSerializer,
SAMJournalSerializer,
)
from smarter.lib.journal.signals import journal_entries_listed, journal_entry_accessed
logger = logging.getSmarterLogger(__name__, any_switches=[SmarterWaffleSwitches.API_LOGGING])
SEARCH_FIELDS = ("key", "thing", "command")
"""The fields that a search of the list matches."""
SORT_FIELDS = {
"createdAt": "created_at",
"user": "user__username",
"thing": "thing",
"command": "command",
"statusCode": "status_code",
}
"""
The columns that the list may be sorted by.
See :data:`smarter.lib.django.pagination.DEFAULT_SORT_FIELDS`.
"""
[docs]
def journal_entries() -> QuerySet[SAMJournal]:
"""
Return every journal entry, newest first, with its user.
:returns: The journal entries, with each entry's user fetched in the same query.
"""
entries = SAMJournal.objects.select_related("user").order_by("-created_at")
return entries
[docs]
class SAMJournalView(SmarterAdminAPIView):
"""A journal entry, by its key, with its request and response documents: a :class:`SAMJournalApiEntry`."""
serializer_class = SAMJournalSerializer
[docs]
def get_queryset(self) -> QuerySet[SAMJournal]:
"""Return every journal entry with its user, newest first."""
return journal_entries()
# *args and **kwargs are a view's, which post() passes on.
# pylint: disable=unused-argument
[docs]
def get(self, request: Request, key: str, *args, **kwargs):
"""
Return the journal entry, and send the ``journal_entry_accessed`` signal.
:param request: The request.
:param key: The journal entry's key.
:param args: Unused.
:param kwargs: Unused.
:returns: The entry as a :class:`SAMJournalApiEntry` dict.
:raises Http404: If there is no entry with this key.
"""
journal = get_object_or_404(self.get_queryset(), key=key)
journal_entry_accessed.send(sender=self.__class__, journal=journal, user=request.user)
return Response(SAMJournalApiEntry.from_model(journal).model_dump(mode="json"))
[docs]
def post(self, request: Request, key: str, *args, **kwargs):
"""
Same as ``get()``: Smarter detail views are also served by POST.
:param request: The request.
:param key: The journal entry's key.
:param args: Unused.
:param kwargs: Unused.
:returns: The entry as a :class:`SAMJournalApiEntry` dict.
:raises Http404: If there is no entry with this key.
"""
return self.get(request, key, *args, **kwargs)
[docs]
class SAMJournalListView(SmarterAdminListAPIView):
"""
One page of the journal entries, newest first, without their request and response documents.
The response is a :class:`SAMJournalApiPage`. The query parameters ``page``, ``page_size``, ``search`` and ``ordering`` are those of
:func:`smarter.lib.django.pagination.paginate_listview`. A search matches an entry's key, thing or
command.
"""
serializer_class = SAMJournalMiniSerializer
[docs]
def get_queryset(self) -> QuerySet[SAMJournal]:
"""Return every journal entry with its user, newest first, without its documents."""
entries = journal_entries()
return entries.defer(*DOCUMENT_FIELDS)
[docs]
def list(self, request: Request, *args, **kwargs):
"""
Return one page of the journal entries, and a description of the page.
Sends the ``journal_entries_listed`` signal.
:param request: The request, whose query parameters choose the page, search and ordering.
:param args: Unused.
:param kwargs: Unused.
:returns: A :class:`SAMJournalApiPage`, as JSON.
"""
page, pagination = paginate_listview(
request, self.get_queryset(), search_fields=SEARCH_FIELDS, sort_fields=SORT_FIELDS
)
journal_entries_listed.send(sender=self.__class__, user=request.user, count=pagination["count"])
logger.debug("user: %s, pagination: %s", request.user, pagination)
summaries = [SAMJournalApiEntrySummary.from_model(journal) for journal in page]
response = SAMJournalApiPage(
objects=summaries,
pagination=ListViewPagination.model_validate(pagination),
)
return JsonResponse(response.model_dump(mode="json"))
[docs]
def post(self, request: Request, *args, **kwargs):
"""
Same as ``get()``: Smarter list views are also served by POST.
:param request: The request.
:param args: Passed to :meth:`list`.
:param kwargs: Passed to :meth:`list`.
:returns: A :class:`SAMJournalApiPage`, as JSON.
"""
return self.list(request, *args, **kwargs)