mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-12-01 09:00:25 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
373d1ea600 | ||
|
|
56a77ed914 | ||
|
|
970aab73ea | ||
|
|
d1251aaef6 | ||
|
|
fca95bc821 | ||
|
|
f684baaea8 | ||
|
|
e7ead755d3 | ||
|
|
be4c4cdbfe | ||
|
|
3e6e1e6efd |
No files matched your search
@@ -1,8 +1,6 @@
|
||||
# Please see the documentation for all configuration options:
|
||||
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||
version: 2
|
||||
# Required for uv support for now
|
||||
enable-beta-ecosystems: true
|
||||
updates:
|
||||
# Enable version updates for pnpm
|
||||
- package-ecosystem: "npm"
|
||||
|
||||
@@ -38,7 +38,7 @@ repos:
|
||||
- json
|
||||
# See https://github.com/prettier/prettier/issues/15742 for the fork reason
|
||||
- repo: https://github.com/rbubley/mirrors-prettier
|
||||
rev: 'v3.9.10'
|
||||
rev: 'v3.10.1'
|
||||
hooks:
|
||||
- id: prettier
|
||||
types_or:
|
||||
@@ -46,7 +46,7 @@ repos:
|
||||
- ts
|
||||
- markdown
|
||||
additional_dependencies:
|
||||
- prettier@3.9.10
|
||||
- prettier@3.10.1
|
||||
- 'prettier-plugin-organize-imports@4.3.0'
|
||||
# Python hooks
|
||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||
@@ -55,7 +55,7 @@ repos:
|
||||
- id: ruff-check
|
||||
- id: ruff-format
|
||||
- repo: https://github.com/tox-dev/pyproject-fmt
|
||||
rev: "v2.30.3"
|
||||
rev: "v2.31.2"
|
||||
hooks:
|
||||
- id: pyproject-fmt
|
||||
additional_dependencies: [tomli]
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from django.core.management import call_command
|
||||
from django.core.management.base import CommandError
|
||||
@@ -337,3 +339,41 @@ 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"]
|
||||
+104
-15
@@ -942,7 +942,7 @@ class EmailDocumentDetailSchema(EmailSerializer):
|
||||
parameters=[
|
||||
OpenApiParameter(
|
||||
name="id",
|
||||
type=OpenApiTypes.STR,
|
||||
type=OpenApiTypes.INT,
|
||||
location=OpenApiParameter.PATH,
|
||||
),
|
||||
],
|
||||
@@ -1036,6 +1036,14 @@ class DocumentViewSet(
|
||||
# Bound the IN clauses used for search results and through-table lookups.
|
||||
selection_data_batch_size = 10_000
|
||||
|
||||
def initial(self, request, *args, **kwargs):
|
||||
super().initial(request, *args, **kwargs)
|
||||
# Only ASCII digits can be a document id, reject anything else here, before
|
||||
# any action calls int() on it
|
||||
pk = kwargs.get("pk")
|
||||
if pk is not None and not (pk.isascii() and pk.isdigit()):
|
||||
raise Http404
|
||||
|
||||
def _get_selection_data_for_queryset(
|
||||
self,
|
||||
queryset: QuerySet[Document],
|
||||
@@ -2886,6 +2894,13 @@ 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",
|
||||
@@ -2903,6 +2918,7 @@ class UnifiedSearchViewSet(DocumentViewSet):
|
||||
name="id",
|
||||
type=OpenApiTypes.STR,
|
||||
location=OpenApiParameter.PATH,
|
||||
enum=list(LOG_FILES),
|
||||
),
|
||||
OpenApiParameter(
|
||||
name="limit",
|
||||
@@ -2923,18 +2939,12 @@ class UnifiedSearchViewSet(DocumentViewSet):
|
||||
class LogViewSet(ViewSet):
|
||||
permission_classes = (IsAuthenticated, PaperlessAdminPermissions)
|
||||
|
||||
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]
|
||||
return Path(settings.LOGGING_DIR) / LOG_FILES[log_key]
|
||||
|
||||
def retrieve(self, request, *args, **kwargs):
|
||||
log_key = kwargs.get("pk")
|
||||
if log_key not in self.ALLOWED_LOG_FILES:
|
||||
if log_key not in LOG_FILES:
|
||||
raise Http404
|
||||
|
||||
log_file = self.get_log_file(log_key)
|
||||
@@ -2963,9 +2973,7 @@ class LogViewSet(ViewSet):
|
||||
|
||||
def list(self, request, *args, **kwargs):
|
||||
existing_logs = [
|
||||
log_key
|
||||
for log_key in self.ALLOWED_LOG_FILES
|
||||
if self.get_log_file(log_key).is_file()
|
||||
log_key for log_key in LOG_FILES if self.get_log_file(log_key).is_file()
|
||||
]
|
||||
return Response(existing_logs)
|
||||
|
||||
@@ -4016,7 +4024,36 @@ class GlobalSearchView(PassUserMixin):
|
||||
get=extend_schema(
|
||||
description="Get statistics for the current user",
|
||||
responses={
|
||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
||||
(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(),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
@@ -4501,7 +4538,13 @@ def get_github_stars() -> int | None:
|
||||
get=extend_schema(
|
||||
description="Get the current version of the Paperless-NGX server",
|
||||
responses={
|
||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
||||
(200, "application/json"): inline_serializer(
|
||||
name="RemoteVersion",
|
||||
fields={
|
||||
"version": serializers.CharField(),
|
||||
"update_available": serializers.BooleanField(),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
@@ -4566,7 +4609,17 @@ class RemoteVersionView(GenericAPIView[Any]):
|
||||
),
|
||||
],
|
||||
responses={
|
||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
||||
(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),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
@@ -5830,6 +5883,26 @@ 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
|
||||
@@ -5978,6 +6051,22 @@ 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"],
|
||||
|
||||
@@ -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-30 18:39+0000\n"
|
||||
"PO-Revision-Date: 2022-02-17 04:17\n"
|
||||
"Last-Translator: \n"
|
||||
"Language-Team: English\n"
|
||||
@@ -1881,7 +1881,7 @@ 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/views.py:2878 paperless_mail/serialisers.py:145
|
||||
msgid "Insufficient permissions."
|
||||
msgstr ""
|
||||
|
||||
@@ -1921,7 +1921,7 @@ msgstr ""
|
||||
msgid "Duplicate document identifiers are not allowed."
|
||||
msgstr ""
|
||||
|
||||
#: documents/serialisers.py:3004 documents/views.py:5008
|
||||
#: documents/serialisers.py:3004 documents/views.py:5061
|
||||
#, python-format
|
||||
msgid "Documents not found: %(ids)s"
|
||||
msgstr ""
|
||||
@@ -2192,36 +2192,36 @@ 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:2875
|
||||
msgid "Invalid more_like_id"
|
||||
msgstr ""
|
||||
|
||||
#: documents/views.py:1697
|
||||
#: documents/views.py:1705
|
||||
msgid "Invalid AI configuration."
|
||||
msgstr ""
|
||||
|
||||
#: documents/views.py:1708
|
||||
#: documents/views.py:1716
|
||||
msgid "AI backend request timed out."
|
||||
msgstr ""
|
||||
|
||||
#: documents/views.py:1720
|
||||
#: documents/views.py:1728
|
||||
msgid "AI backend rejected the request. Check logs for details."
|
||||
msgstr ""
|
||||
|
||||
#: documents/views.py:5024
|
||||
#: documents/views.py:5077
|
||||
#, python-format
|
||||
msgid "Insufficient permissions to share document %(id)s."
|
||||
msgstr ""
|
||||
|
||||
#: documents/views.py:5071
|
||||
#: documents/views.py:5124
|
||||
msgid "Bundle is already being processed."
|
||||
msgstr ""
|
||||
|
||||
#: documents/views.py:5137
|
||||
#: documents/views.py:5190
|
||||
msgid "The share link bundle is still being prepared. Please try again later."
|
||||
msgstr ""
|
||||
|
||||
#: documents/views.py:5151
|
||||
#: documents/views.py:5204
|
||||
msgid "The share link bundle is unavailable."
|
||||
msgstr ""
|
||||
|
||||
@@ -2661,7 +2661,7 @@ msgstr ""
|
||||
msgid "Chinese Traditional"
|
||||
msgstr ""
|
||||
|
||||
#: paperless/urls.py:452
|
||||
#: paperless/urls.py:455
|
||||
msgid "Paperless-ngx administration"
|
||||
msgstr ""
|
||||
|
||||
|
||||
@@ -374,15 +374,19 @@ class TikaDocumentParser:
|
||||
|
||||
try:
|
||||
parsed = self._tika_client.metadata.from_file(document_path, mime_type)
|
||||
return [
|
||||
{
|
||||
"namespace": "",
|
||||
"prefix": "",
|
||||
"key": key,
|
||||
"value": parsed.data[key],
|
||||
}
|
||||
for key in parsed.data
|
||||
]
|
||||
metadata: list[MetadataEntry] = []
|
||||
for key, value in parsed.data.items():
|
||||
if isinstance(value, list):
|
||||
value = " ".join(str(item) for item in value)
|
||||
metadata.append(
|
||||
{
|
||||
"namespace": "",
|
||||
"prefix": "",
|
||||
"key": key,
|
||||
"value": str(value),
|
||||
},
|
||||
)
|
||||
return metadata
|
||||
except Exception as e:
|
||||
logger.warning(
|
||||
"Error while fetching document metadata for %s: %s",
|
||||
|
||||
@@ -365,3 +365,8 @@ class ApplicationConfigurationSerializer(
|
||||
class Meta:
|
||||
model = ApplicationConfiguration
|
||||
fields = "__all__"
|
||||
|
||||
|
||||
class TOTPActivationSerializer(serializers.Serializer[dict[str, str]]):
|
||||
secret = serializers.CharField()
|
||||
code = serializers.CharField()
|
||||
@@ -131,8 +131,10 @@ class TestTikaParser:
|
||||
httpx_mock.add_response(
|
||||
json={
|
||||
"Content-Type": "application/vnd.oasis.opendocument.text",
|
||||
"X-TIKA:Parsed-By": [],
|
||||
"X-TIKA:Parsed-By": ["ParserA", "ParserB"],
|
||||
"X-TIKA:Parsed-By-Full-Set": [],
|
||||
"Some-key": "value",
|
||||
"meta:page-count": 2,
|
||||
"dcterms:created": "2020-11-21T00:00:00",
|
||||
},
|
||||
)
|
||||
@@ -144,6 +146,11 @@ class TestTikaParser:
|
||||
|
||||
assert "dcterms:created" in [m["key"] for m in metadata]
|
||||
assert "Some-key" in [m["key"] for m in metadata]
|
||||
values = {entry["key"]: entry["value"] for entry in metadata}
|
||||
assert values["X-TIKA:Parsed-By"] == "ParserA ParserB"
|
||||
assert values["X-TIKA:Parsed-By-Full-Set"] == ""
|
||||
assert values["meta:page-count"] == "2"
|
||||
assert all(isinstance(value, str) for value in values.values())
|
||||
|
||||
def test_convert_failure(
|
||||
self,
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import pytest
|
||||
from django.test import Client
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
|
||||
class TestUnmatchedApiPaths:
|
||||
@pytest.mark.parametrize("method", ["get", "post", "put", "patch", "delete"])
|
||||
def test_unmatched_api_path_is_a_json_404(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
method: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An unauthenticated client
|
||||
WHEN:
|
||||
- Any method is sent to an /api/ URL that no route matches
|
||||
THEN:
|
||||
- The response is a JSON 404, not a redirect to the login page
|
||||
"""
|
||||
response = getattr(rest_api_client, method)("/api/this_does_not_exist/")
|
||||
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
assert response["Content-Type"].startswith("application/json")
|
||||
|
||||
def test_unmatched_api_path_is_a_json_404_when_authenticated(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- An /api/ URL that no route matches is requested
|
||||
THEN:
|
||||
- The response is a JSON 404, not the frontend page
|
||||
"""
|
||||
response = admin_client.get("/api/this/is/nested/and/missing/")
|
||||
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
assert response["Content-Type"].startswith("application/json")
|
||||
|
||||
def test_other_paths_still_reach_the_frontend_catch_all(
|
||||
self,
|
||||
client: Client,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An anonymous browser request
|
||||
WHEN:
|
||||
- A non-API path is requested
|
||||
THEN:
|
||||
- The frontend catch-all still applies, which sends the user to log in
|
||||
"""
|
||||
response = client.get("/documents/")
|
||||
|
||||
assert response.status_code == status.HTTP_302_FOUND
|
||||
assert "login" in response["Location"]
|
||||
|
||||
|
||||
class TestDocumentRouteIds:
|
||||
@pytest.mark.parametrize(
|
||||
"action",
|
||||
[
|
||||
"download",
|
||||
"history",
|
||||
"metadata",
|
||||
"notes",
|
||||
"preview",
|
||||
"root",
|
||||
"share_links",
|
||||
"suggestions",
|
||||
"thumb",
|
||||
],
|
||||
)
|
||||
@pytest.mark.parametrize("pk", ["null", "true", "abc", "0.5", "%20"])
|
||||
def test_non_numeric_document_id_is_a_json_404(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
action: str,
|
||||
pk: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A document sub-route is requested with an id that is not a number
|
||||
THEN:
|
||||
- The response is a JSON 404, not a server error
|
||||
"""
|
||||
response = admin_client.get(f"/api/documents/{pk}/{action}/")
|
||||
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
assert response["Content-Type"].startswith("application/json")
|
||||
@@ -0,0 +1,39 @@
|
||||
import pytest
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
|
||||
class TestTotpView:
|
||||
def test_options_does_not_fail(self, admin_client: APIClient) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- OPTIONS is sent to the TOTP endpoint
|
||||
THEN:
|
||||
- The request succeeds, DRF's metadata needs a serializer on the view
|
||||
"""
|
||||
response = admin_client.options("/api/profile/totp/")
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[{}, {"secret": "abc"}, {"code": "123456"}, {"secret": None, "code": None}],
|
||||
)
|
||||
def test_activation_with_missing_fields_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
body: dict[str, str | None],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- TOTP is activated without both the secret and the code
|
||||
THEN:
|
||||
- The response is a 400, not a server error
|
||||
"""
|
||||
response = admin_client.post("/api/profile/totp/", body, format="json")
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
@@ -57,6 +57,7 @@ from documents.views import WorkflowTriggerViewSet
|
||||
from documents.views import WorkflowViewSet
|
||||
from documents.views import serve_logo
|
||||
from paperless.consumers import StatusConsumer
|
||||
from paperless.views import ApiNotFoundView
|
||||
from paperless.views import ApplicationConfigurationViewSet
|
||||
from paperless.views import DisconnectSocialAccountView
|
||||
from paperless.views import FaviconView
|
||||
@@ -309,6 +310,8 @@ urlpatterns = [
|
||||
RedirectView.as_view(url="schema/view/"),
|
||||
),
|
||||
*api_router.urls,
|
||||
# Must stay last, anything unmatched under /api/ is a JSON 404
|
||||
re_path(r"^.*$", ApiNotFoundView.as_view(), name="api_not_found"),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
+55
-6
@@ -24,9 +24,12 @@ 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
|
||||
from rest_framework.exceptions import NotFound
|
||||
from rest_framework.exceptions import ValidationError
|
||||
from rest_framework.fields import BooleanField
|
||||
from rest_framework.filters import OrderingFilter
|
||||
@@ -35,6 +38,7 @@ from rest_framework.pagination import PageNumberPagination
|
||||
from rest_framework.permissions import IsAuthenticated
|
||||
from rest_framework.response import Response
|
||||
from rest_framework.throttling import ScopedRateThrottle
|
||||
from rest_framework.views import APIView
|
||||
from rest_framework.viewsets import ModelViewSet
|
||||
|
||||
from documents.models import PaperlessTask
|
||||
@@ -49,6 +53,7 @@ from paperless.serialisers import ApplicationConfigurationSerializer
|
||||
from paperless.serialisers import GroupSerializer
|
||||
from paperless.serialisers import PaperlessAuthTokenSerializer
|
||||
from paperless.serialisers import ProfileSerializer
|
||||
from paperless.serialisers import TOTPActivationSerializer
|
||||
from paperless.serialisers import UserSerializer
|
||||
|
||||
|
||||
@@ -274,8 +279,16 @@ 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"): OpenApiTypes.OBJECT,
|
||||
(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(),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
post=extend_schema(
|
||||
@@ -290,7 +303,17 @@ class ProfileView(GenericAPIView[Any]):
|
||||
},
|
||||
},
|
||||
responses={
|
||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
||||
(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",
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
delete=extend_schema(
|
||||
@@ -306,6 +329,7 @@ class TOTPView(GenericAPIView[Any]):
|
||||
"""
|
||||
|
||||
permission_classes = [IsAuthenticated]
|
||||
serializer_class = TOTPActivationSerializer
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
"""
|
||||
@@ -328,15 +352,18 @@ class TOTPView(GenericAPIView[Any]):
|
||||
"""
|
||||
Validates a TOTP code and activates the TOTP authenticator
|
||||
"""
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
secret = serializer.validated_data["secret"]
|
||||
valid = totp_auth.validate_totp_code(
|
||||
request.data["secret"],
|
||||
request.data["code"],
|
||||
secret,
|
||||
serializer.validated_data["code"],
|
||||
)
|
||||
recovery_codes = None
|
||||
if valid:
|
||||
auth = totp_auth.TOTP.activate(
|
||||
request.user,
|
||||
request.data["secret"],
|
||||
secret,
|
||||
).instance
|
||||
signals.authenticator_added.send(
|
||||
sender=Authenticator,
|
||||
@@ -523,7 +550,14 @@ class DisconnectSocialAccountView(GenericAPIView[Any]):
|
||||
@extend_schema_view(
|
||||
get=extend_schema(
|
||||
responses={
|
||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
||||
(200, "application/json"): inline_serializer(
|
||||
name="SocialAccountProvider",
|
||||
fields={
|
||||
"name": serializers.CharField(),
|
||||
"login_url": serializers.CharField(),
|
||||
},
|
||||
many=True,
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
@@ -557,3 +591,18 @@ class SocialAccountProvidersView(GenericAPIView[Any]):
|
||||
]
|
||||
|
||||
return Response(sorted(resp, key=lambda p: p["name"]))
|
||||
|
||||
|
||||
@extend_schema(exclude=True)
|
||||
class ApiNotFoundView(APIView):
|
||||
"""
|
||||
A JSON 404 for any /api/ URL that no other route matches. Without this, those
|
||||
URLs fall through to the frontend catch-all, which answers a redirect to the
|
||||
login page or the single page app, never an error an API client can read.
|
||||
"""
|
||||
|
||||
authentication_classes = ()
|
||||
permission_classes = ()
|
||||
|
||||
def initial(self, request, *args, **kwargs):
|
||||
raise NotFound
|
||||
+37
-46
@@ -894,8 +894,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 +901,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 +912,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 +1011,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 +1119,6 @@ class MailAccountHandler(LoggingMixin):
|
||||
)
|
||||
|
||||
consume_tasks.append(consume_task)
|
||||
|
||||
processed_attachments += 1
|
||||
else:
|
||||
self.log.debug(
|
||||
f"Rule {rule}: "
|
||||
@@ -1115,26 +1127,15 @@ 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(
|
||||
prefix="paperless-mail-",
|
||||
@@ -1192,17 +1193,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
|
||||
@@ -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"},
|
||||
],
|
||||
|
||||
@@ -10,6 +10,7 @@ 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
|
||||
@@ -254,8 +255,39 @@ class MailRuleViewSet(PassUserMixin, ModelViewSet[MailRule]):
|
||||
|
||||
@extend_schema_view(
|
||||
get=extend_schema(
|
||||
description="Callback view for OAuth2 authentication",
|
||||
responses={200: None},
|
||||
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,
|
||||
},
|
||||
),
|
||||
)
|
||||
class OauthCallbackView(GenericAPIView[Any]):
|
||||
|
||||
Reference in new issue
Block a user