Compare commits

..
Author SHA1 Message Date
Trenton H afbdd07145 Fix: queue one consumption chord per mail so it produces a single ProcessedMail row
With the "everything" consumption scope the eml and the attachments were each queued
as their own chord, so each ran its own mail action and wrote its own ProcessedMail row.
A mail without attachments also got an early PROCESSED_WO_CONSUMPTION row alongside the
eml's SUCCESS row.

Build the eml and attachment tasks separately, then queue them together once per message.
2026-11-28 15:04:48 -08:00
13 changed files with 119 additions and 336 deletions

No files matched your search

+2 -7
View File
@@ -74,10 +74,6 @@ _LOCK_BACKOFF_CAP: Final[float] = 10.0 # seconds
T = TypeVar("T")
# Upper bound on autocomplete suggestions. tantivy sizes its collector from the
# requested limit, so an unbounded value aborts the whole process on allocation.
MAX_AUTOCOMPLETE_LIMIT = 1000
class ViewerGrant(NamedTuple):
"""Direct user and group view grants for a single document.
@@ -1002,8 +998,7 @@ class TantivyBackend:
Args:
term: Prefix to match against autocomplete words
limit: Maximum number of suggestions to return, capped at
MAX_AUTOCOMPLETE_LIMIT
limit: Maximum number of suggestions to return
user: User for permission filtering (None for no filtering)
Returns:
@@ -1026,7 +1021,7 @@ class TantivyBackend:
"autocomplete_word",
normalized_term,
permission_query,
min(limit, MAX_AUTOCOMPLETE_LIMIT),
limit,
)
return [x[0] for x in matches]
+3 -8
View File
@@ -112,10 +112,6 @@ if TYPE_CHECKING:
logger = logging.getLogger("paperless.serializers")
# How much of an upload is read to detect its type. libmagic examines at most
# 7 MiB (its default bytes_max), so this is more than it will ever look at.
_MIME_SNIFF_BYTES = 8 * 1024 * 1024
# https://www.django-rest-framework.org/api-guide/serializers/#example
class DynamicFieldsModelSerializer(serializers.ModelSerializer[Any]):
@@ -2367,9 +2363,8 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
)
def validate_document(self, document):
# libmagic only examines a bounded prefix, so an upload of any size is
# never read into memory just to detect its type
mime_type = magic.from_buffer(document.read(_MIME_SNIFF_BYTES), mime=True)
document_data = document.file.read()
mime_type = magic.from_buffer(document_data, mime=True)
if not is_mime_type_supported(mime_type):
if (
@@ -2385,7 +2380,7 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
_("File type %(type)s not supported") % {"type": mime_type},
)
return document.name, document
return document.name, document_data
def validate_correspondent(self, correspondent):
if correspondent:
@@ -1069,13 +1069,6 @@ class TestAutocomplete:
results = backend.autocomplete("micro", limit=10)
assert "microsoft" in results
def test_huge_limit_is_clamped(self, backend: TantivyBackend) -> None:
"""An oversized limit must be capped, not handed to tantivy as-is."""
doc = DocumentFactory.create(title="Microsoft invoice", content="payment")
backend.add_or_update(doc)
assert "microsoft" in backend.autocomplete("micro", limit=10**15)
def test_results_ordered_by_document_frequency(
self,
backend: TantivyBackend,
-32
View File
@@ -2089,38 +2089,6 @@ class TestDocumentApi(DirectoriesMixin, ConsumeTaskMixin, APITestCase):
self.assertIsNone(overrides.document_type_id)
self.assertIsNone(overrides.tag_ids)
def test_upload_type_is_detected_from_a_prefix(self) -> None:
"""
GIVEN:
- An upload larger than the prefix read to detect its type
WHEN:
- The document is posted
THEN:
- The type is detected from the prefix and the upload is accepted
- The file handed to the consumer holds the whole upload
"""
self.consume_file_mock.return_value = celery.result.AsyncResult(
id=str(uuid.uuid4()),
)
content = SIMPLE_DIGITAL_PDF.read_bytes()
with (
mock.patch("documents.serialisers._MIME_SNIFF_BYTES", 1024),
SimpleUploadedFile(
"simple.pdf",
content,
content_type="application/pdf",
) as f,
):
response = self.client.post(
"/api/documents/post_document/",
{"document": f},
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
input_doc, _ = self.assert_queue_consumption_task_call_args()
self.assertEqual(input_doc.original_file.read_bytes(), content)
def test_upload_with_path_traversal_filename_is_reduced_to_basename(self) -> None:
self.consume_file_mock.return_value = celery.result.AsyncResult(
id=str(uuid.uuid4()),
-40
View File
@@ -1,5 +1,3 @@
from typing import Any
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
@@ -339,41 +337,3 @@ class TestDocumentListObjectFilterSchema:
param = next(p for p in params if p["name"] == param_name)
assert param["schema"] == {"type": "array", "items": {"type": "integer"}}
assert param["explode"] is False
class TestOauthCallbackSchema:
@pytest.mark.parametrize("name", ["code", "state"])
def test_empty_code_and_state_are_not_schema_valid(
self,
api_schema: dict[str, Any],
name: str,
) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The code and state parameters of the OAuth callback are read
THEN:
- They are required and not empty, the view answers 400 to an empty one
"""
params = api_schema["paths"]["/api/oauth/callback/"]["get"]["parameters"]
param = next(p for p in params if p["name"] == name)
assert param["required"] is True
assert param["schema"]["minLength"] == 1
class TestOcrPageImageSchema:
def test_page_image_is_declared_as_png(self, api_schema: dict[str, Any]) -> None:
"""
GIVEN:
- The generated schema
WHEN:
- The 200 response of the OCR template page image is read
THEN:
- It is a PNG, which is what the view serves
"""
path = "/api/ocr_templates/document-page-image/{doc_id}/{page}/"
content = api_schema["paths"][path]["get"]["responses"]["200"]["content"]
assert list(content) == ["image/png"]
-3
View File
@@ -996,9 +996,6 @@ class TestDocumentSearchApi(DirectoriesMixin, APITestCase):
response = self.client.get("/api/search/autocomplete/?term=test&limit=-1")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
response = self.client.get("/api/search/autocomplete/?term=test&limit=null")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
response = self.client.get("/api/search/autocomplete/")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+14 -106
View File
@@ -942,7 +942,7 @@ class EmailDocumentDetailSchema(EmailSerializer):
parameters=[
OpenApiParameter(
name="id",
type=OpenApiTypes.INT,
type=OpenApiTypes.STR,
location=OpenApiParameter.PATH,
),
],
@@ -2205,7 +2205,7 @@ class DocumentViewSet(
raise Http404
try:
doc_name, doc_file = serializer.validated_data.get("document")
doc_name, doc_data = serializer.validated_data.get("document")
version_label = serializer.validated_data.get("version_label")
t = int(mktime(datetime.now().timetuple()))
@@ -2216,9 +2216,7 @@ class DocumentViewSet(
pathvalidate.sanitize_filename(doc_name),
)
with temp_file_path.open("wb") as scratch_file:
for chunk in doc_file.chunks():
scratch_file.write(chunk)
temp_file_path.write_bytes(doc_data)
os.utime(temp_file_path, times=(t, t))
@@ -2886,13 +2884,6 @@ class UnifiedSearchViewSet(DocumentViewSet):
return Response(max_asn + 1)
LOG_FILES = {
"paperless": "paperless.log",
"mail": "mail.log",
"celery": "celery.log",
}
@extend_schema_view(
list=extend_schema(
description="Logs view",
@@ -2910,7 +2901,6 @@ LOG_FILES = {
name="id",
type=OpenApiTypes.STR,
location=OpenApiParameter.PATH,
enum=list(LOG_FILES),
),
OpenApiParameter(
name="limit",
@@ -2931,7 +2921,11 @@ LOG_FILES = {
class LogViewSet(ViewSet):
permission_classes = (IsAuthenticated, PaperlessAdminPermissions)
ALLOWED_LOG_FILES = LOG_FILES
ALLOWED_LOG_FILES = {
"paperless": "paperless.log",
"mail": "mail.log",
"celery": "celery.log",
}
def get_log_file(self, log_key: str) -> Path:
return Path(settings.LOGGING_DIR) / self.ALLOWED_LOG_FILES[log_key]
@@ -3504,7 +3498,7 @@ class PostDocumentView(GenericAPIView[Any]):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
doc_name, doc_file = serializer.validated_data.get("document")
doc_name, doc_data = serializer.validated_data.get("document")
doc_name = normalize("NFC", doc_name)
correspondent_id = serializer.validated_data.get("correspondent")
document_type_id = serializer.validated_data.get("document_type")
@@ -3524,9 +3518,7 @@ class PostDocumentView(GenericAPIView[Any]):
pathvalidate.sanitize_filename(doc_name),
)
with temp_file_path.open("wb") as scratch_file:
for chunk in doc_file.chunks():
scratch_file.write(chunk)
temp_file_path.write_bytes(doc_data)
os.utime(temp_file_path, times=(t, t))
@@ -3741,10 +3733,7 @@ class SearchAutoCompleteView(GenericAPIView[Any]):
return HttpResponseBadRequest("Term required")
if "limit" in request.query_params:
try:
limit = int(request.query_params["limit"])
except ValueError:
return HttpResponseBadRequest("Invalid limit")
limit = int(request.query_params["limit"])
if limit <= 0:
return HttpResponseBadRequest("Invalid limit")
else:
@@ -4020,36 +4009,7 @@ class GlobalSearchView(PassUserMixin):
get=extend_schema(
description="Get statistics for the current user",
responses={
(200, "application/json"): inline_serializer(
name="Statistics",
fields={
"documents_total": serializers.IntegerField(),
"documents_inbox": serializers.IntegerField(allow_null=True),
"inbox_tag": serializers.IntegerField(
allow_null=True,
help_text="The first inbox tag, kept for backwards compatibility",
),
"inbox_tags": serializers.ListField(
child=serializers.IntegerField(),
allow_null=True,
),
"document_file_type_counts": serializers.ListField(
child=inline_serializer(
name="MimeTypeCount",
fields={
"mime_type": serializers.CharField(),
"mime_type_count": serializers.IntegerField(),
},
),
),
"character_count": serializers.IntegerField(),
"tag_count": serializers.IntegerField(),
"correspondent_count": serializers.IntegerField(),
"document_type_count": serializers.IntegerField(),
"storage_path_count": serializers.IntegerField(),
"current_asn": serializers.IntegerField(),
},
),
(200, "application/json"): OpenApiTypes.OBJECT,
},
),
)
@@ -4534,13 +4494,7 @@ def get_github_stars() -> int | None:
get=extend_schema(
description="Get the current version of the Paperless-NGX server",
responses={
(200, "application/json"): inline_serializer(
name="RemoteVersion",
fields={
"version": serializers.CharField(),
"update_available": serializers.BooleanField(),
},
),
(200, "application/json"): OpenApiTypes.OBJECT,
},
),
)
@@ -4605,17 +4559,7 @@ class RemoteVersionView(GenericAPIView[Any]):
),
],
responses={
(200, "application/json"): inline_serializer(
name="ReleaseNotes",
fields={
"version": serializers.CharField(),
"releases": serializers.ListField(
child=serializers.DictField(),
help_text="GitHub release objects",
),
"stars": serializers.IntegerField(allow_null=True),
},
),
(200, "application/json"): OpenApiTypes.OBJECT,
},
),
)
@@ -5879,26 +5823,6 @@ class SystemStatusView(PassUserMixin):
)
@extend_schema_view(
get=extend_schema(
description="List the documents in the trash",
responses={(200, "application/json"): DocumentSerializer(many=True)},
),
post=extend_schema(
description="Restore documents from the trash, or delete them permanently",
responses={
(200, "application/json"): inline_serializer(
name="TrashActionResult",
fields={
"result": serializers.CharField(),
"doc_ids": serializers.ListField(
child=serializers.IntegerField(),
),
},
),
},
),
)
class TrashView(ListModelMixin, PassUserMixin):
permission_classes = (IsAuthenticated, TrashPermissions)
serializer_class = TrashSerializer
@@ -6047,22 +5971,6 @@ class OcrTemplateViewSet(BulkPermissionMixin, PassUserMixin, ModelViewSet[OcrTem
]
return super().get_permissions()
@extend_schema(
parameters=[
OpenApiParameter(
name="doc_id",
type=OpenApiTypes.INT,
location=OpenApiParameter.PATH,
),
OpenApiParameter(
name="page",
type={"type": "integer", "minimum": 1},
location=OpenApiParameter.PATH,
description="1-based page number",
),
],
responses={(200, "image/png"): OpenApiTypes.BINARY},
)
@action(
detail=False,
methods=["get"],
+18 -18
View File
@@ -2,7 +2,7 @@ msgid ""
msgstr ""
"Project-Id-Version: paperless-ngx\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-11-28 23:01+0000\n"
"POT-Creation-Date: 2026-11-27 02:54+0000\n"
"PO-Revision-Date: 2022-02-17 04:17\n"
"Last-Translator: \n"
"Language-Team: English\n"
@@ -1879,49 +1879,49 @@ msgstr ""
msgid "OCR template zones"
msgstr ""
#: documents/serialisers.py:495 documents/serialisers.py:819
#: documents/serialisers.py:2918 documents/views.py:372 documents/views.py:638
#: documents/views.py:2870 paperless_mail/serialisers.py:145
#: documents/serialisers.py:491 documents/serialisers.py:815
#: documents/serialisers.py:2913 documents/views.py:372 documents/views.py:638
#: documents/views.py:2868 paperless_mail/serialisers.py:145
msgid "Insufficient permissions."
msgstr ""
#: documents/serialisers.py:651
#: documents/serialisers.py:647
msgid "Invalid color."
msgstr ""
#: documents/serialisers.py:2385
#: documents/serialisers.py:2380
#, python-format
msgid "File type %(type)s not supported"
msgstr ""
#: documents/serialisers.py:2429
#: documents/serialisers.py:2424
#, python-format
msgid "Custom field id must be an integer: %(id)s"
msgstr ""
#: documents/serialisers.py:2436
#: documents/serialisers.py:2431
#, python-format
msgid "Custom field with id %(id)s does not exist"
msgstr ""
#: documents/serialisers.py:2453 documents/serialisers.py:2463
#: documents/serialisers.py:2448 documents/serialisers.py:2458
msgid ""
"Custom fields must be a list of integers or an object mapping ids to values."
msgstr ""
#: documents/serialisers.py:2458
#: documents/serialisers.py:2453
msgid "Some custom fields don't exist or were specified twice."
msgstr ""
#: documents/serialisers.py:2605
#: documents/serialisers.py:2600
msgid "Invalid variable detected."
msgstr ""
#: documents/serialisers.py:2974
#: documents/serialisers.py:2969
msgid "Duplicate document identifiers are not allowed."
msgstr ""
#: documents/serialisers.py:3004 documents/views.py:5008
#: documents/serialisers.py:2999 documents/views.py:5001
#, python-format
msgid "Documents not found: %(ids)s"
msgstr ""
@@ -2192,7 +2192,7 @@ msgstr ""
msgid "Specify only one of text, title_search, query, or more_like_id."
msgstr ""
#: documents/views.py:365 documents/views.py:2867
#: documents/views.py:365 documents/views.py:2865
msgid "Invalid more_like_id"
msgstr ""
@@ -2208,20 +2208,20 @@ msgstr ""
msgid "AI backend rejected the request. Check logs for details."
msgstr ""
#: documents/views.py:5024
#: documents/views.py:5017
#, python-format
msgid "Insufficient permissions to share document %(id)s."
msgstr ""
#: documents/views.py:5071
#: documents/views.py:5064
msgid "Bundle is already being processed."
msgstr ""
#: documents/views.py:5137
#: documents/views.py:5130
msgid "The share link bundle is still being prepared. Please try again later."
msgstr ""
#: documents/views.py:5151
#: documents/views.py:5144
msgid "The share link bundle is unavailable."
msgstr ""
+3 -30
View File
@@ -24,8 +24,6 @@ from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema
from drf_spectacular.utils import extend_schema_view
from drf_spectacular.utils import inline_serializer
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.decorators import action
@@ -276,16 +274,8 @@ class ProfileView(GenericAPIView[Any]):
@extend_schema_view(
get=extend_schema(
description="Generate a new TOTP secret, its otpauth URL and a QR code",
responses={
(200, "application/json"): inline_serializer(
name="TotpSetup",
fields={
"url": serializers.CharField(),
"qr_svg": serializers.CharField(help_text="QR code as an SVG"),
"secret": serializers.CharField(),
},
),
(200, "application/json"): OpenApiTypes.OBJECT,
},
),
post=extend_schema(
@@ -300,17 +290,7 @@ class ProfileView(GenericAPIView[Any]):
},
},
responses={
(200, "application/json"): inline_serializer(
name="TotpActivation",
fields={
"success": serializers.BooleanField(),
"recovery_codes": serializers.ListField(
child=serializers.CharField(),
allow_null=True,
help_text="Only returned when the code was valid",
),
},
),
(200, "application/json"): OpenApiTypes.OBJECT,
},
),
delete=extend_schema(
@@ -543,14 +523,7 @@ class DisconnectSocialAccountView(GenericAPIView[Any]):
@extend_schema_view(
get=extend_schema(
responses={
(200, "application/json"): inline_serializer(
name="SocialAccountProvider",
fields={
"name": serializers.CharField(),
"login_url": serializers.CharField(),
},
many=True,
),
(200, "application/json"): OpenApiTypes.OBJECT,
},
),
)
+39 -49
View File
@@ -2,7 +2,6 @@ import datetime
import imaplib
import itertools
import logging
import os
import socket
import ssl
import tempfile
@@ -894,8 +893,6 @@ class MailAccountHandler(LoggingMixin):
def _handle_message(self, message, rule: MailRule) -> int:
message = self._preprocess_message(message)
processed_elements = 0
# Skip Message handling when only attachments are to be processed but
# message doesn't have any.
if (
@@ -903,7 +900,7 @@ class MailAccountHandler(LoggingMixin):
and rule.consumption_scope == MailRule.ConsumptionScope.ATTACHMENTS_ONLY
):
self._record_processed_without_consumption(message, rule)
return processed_elements
return 0
self.log.debug(
f"Rule {rule}: "
@@ -914,29 +911,47 @@ class MailAccountHandler(LoggingMixin):
tag_ids: list[int] = [tag.id for tag in rule.assign_tags.all()]
doc_type = rule.assign_document_type
consume_tasks: list[Signature] = []
if (
rule.consumption_scope == MailRule.ConsumptionScope.EML_ONLY
or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING
):
processed_elements += self._process_eml(
message,
rule,
tag_ids,
doc_type,
consume_tasks.append(
self._build_eml_task(
message,
rule,
tag_ids,
doc_type,
),
)
if (
rule.consumption_scope == MailRule.ConsumptionScope.ATTACHMENTS_ONLY
or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING
):
processed_elements += self._process_attachments(
message,
rule,
tag_ids,
doc_type,
consume_tasks.extend(
self._build_attachment_tasks(
message,
rule,
tag_ids,
doc_type,
),
)
return processed_elements
# One chord per message, so the mail action and the ProcessedMail row
# are written once, after every part of the message has been consumed
if consume_tasks:
queue_consumption_tasks(
consume_tasks=consume_tasks,
rule=rule,
message=message,
uid_validity=self._current_uid_validity,
)
else:
self._record_processed_without_consumption(message, rule)
return len(consume_tasks)
def _record_processed_without_consumption(
self,
@@ -995,16 +1010,14 @@ class MailAccountHandler(LoggingMixin):
return True
return False
def _process_attachments(
def _build_attachment_tasks(
self,
message: MailMessage,
rule: MailRule,
tag_ids,
doc_type,
):
processed_attachments = 0
consume_tasks = []
) -> list[Signature]:
consume_tasks: list[Signature] = []
for att in message.attachments:
if (
@@ -1105,8 +1118,6 @@ class MailAccountHandler(LoggingMixin):
)
consume_tasks.append(consume_task)
processed_attachments += 1
else:
self.log.debug(
f"Rule {rule}: "
@@ -1115,33 +1126,22 @@ class MailAccountHandler(LoggingMixin):
f"by paperless",
)
if len(consume_tasks) > 0:
queue_consumption_tasks(
consume_tasks=consume_tasks,
rule=rule,
message=message,
uid_validity=self._current_uid_validity,
)
else:
# No files to consume, just mark as processed if it wasn't by .eml processing
self._record_processed_without_consumption(message, rule)
return consume_tasks
return processed_attachments
def _process_eml(
def _build_eml_task(
self,
message: MailMessage,
rule: MailRule,
tag_ids,
doc_type,
):
) -> Signature:
settings.SCRATCH_DIR.mkdir(parents=True, exist_ok=True)
fd, temp_filename = tempfile.mkstemp(
_, temp_filename = tempfile.mkstemp(
prefix="paperless-mail-",
dir=settings.SCRATCH_DIR,
suffix=".eml",
)
with os.fdopen(fd, "wb") as f:
with Path(temp_filename).open("wb") as f:
# Move "From"-header to beginning of file
# TODO: This ugly workaround is needed because the parser is
# chosen only by the mime_type detected via magic
@@ -1192,17 +1192,7 @@ class MailAccountHandler(LoggingMixin):
owner_id=rule.owner.id if rule.owner else None,
)
consume_task = consume_file.s(
return consume_file.s(
input_doc=input_doc,
overrides=doc_overrides,
).set(headers={"trigger_source": PaperlessTask.TriggerSource.EMAIL_CONSUME})
queue_consumption_tasks(
consume_tasks=[consume_task],
rule=rule,
message=message,
uid_validity=self._current_uid_validity,
)
processed_elements = 1
return processed_elements
+38
View File
@@ -416,6 +416,44 @@ class TestMail(
1,
)
def test_handle_message_everything_scope_single_row(self) -> None:
"""
GIVEN:
- A rule consuming the eml and attachments, and a mail with or
without attachments
WHEN:
- The mail is handled and its queued mail action is applied
THEN:
- The eml and attachments are queued together in one call
- Exactly one ProcessedMail row exists and it is not
PROCESSED_WO_CONSUMPTION
"""
rule = MailRule.objects.create(
account=MailAccount.objects.create(
name="test",
imap_server="",
username="admin",
password="secret",
),
consumption_scope=MailRule.ConsumptionScope.EVERYTHING,
)
for attachments in (0, 2):
with self.subTest(attachments=attachments):
self.mailMocker._queue_consumption_tasks_mock.reset_mock()
message = self.mailMocker.messageBuilder.create_message(
subject=f"{attachments} attachments",
attachments=attachments,
)
result = self.mail_account_handler._handle_message(message, rule)
self.mailMocker.apply_mail_actions()
self.assertEqual(result, 1 + attachments)
self.mailMocker._queue_consumption_tasks_mock.assert_called_once()
processed = ProcessedMail.objects.get(rule=rule, uid=message.uid)
self.assertEqual(processed.status, "SUCCESS")
def test_handle_empty_message_long_subject(self) -> None:
"""
GIVEN:
@@ -272,8 +272,6 @@ class TestMailMessageGpgDecryptor(TestMail):
"override_title": message.subject,
"override_filename": f"{message.subject}.eml",
},
],
[
{"override_title": "file_0", "override_filename": "file_0.pdf"},
{"override_title": "file_1", "override_filename": "file_1.pdf"},
],
+2 -34
View File
@@ -10,7 +10,6 @@ from django.http import HttpResponseRedirect
from django.utils import timezone
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter
from drf_spectacular.utils import extend_schema
from drf_spectacular.utils import extend_schema_view
from drf_spectacular.utils import inline_serializer
@@ -255,39 +254,8 @@ class MailRuleViewSet(PassUserMixin, ModelViewSet[MailRule]):
@extend_schema_view(
get=extend_schema(
description=(
"Callback view for OAuth2 authentication. Redirects back to the "
"frontend, with the outcome in the query string"
),
parameters=[
OpenApiParameter(
name="code",
# An empty value is rejected
type={"type": "string", "minLength": 1},
location=OpenApiParameter.QUERY,
required=True,
description="Authorization code returned by the OAuth provider",
),
OpenApiParameter(
name="state",
# An empty value is rejected
type={"type": "string", "minLength": 1},
location=OpenApiParameter.QUERY,
required=True,
description="State value, must match the one stored in the session",
),
OpenApiParameter(
name="scope",
type=OpenApiTypes.STR,
location=OpenApiParameter.QUERY,
required=False,
description="Granted scopes, sent by Gmail but not by Outlook",
),
],
responses={
302: None,
(400, "text/html"): OpenApiTypes.STR,
},
description="Callback view for OAuth2 authentication",
responses={200: None},
),
)
class OauthCallbackView(GenericAPIView[Any]):