Compare commits

..
4 changed files with 95 additions and 126 deletions

No files matched your search

+12 -5
View File
@@ -1330,6 +1330,11 @@ class SavedViewFilterRuleSerializer(serializers.ModelSerializer[SavedViewFilterR
class SavedViewSerializer(OwnedObjectSerializer):
filter_rules = SavedViewFilterRuleSerializer(many=True)
display_fields = serializers.ListField(
child=serializers.CharField(),
required=False,
allow_null=True,
)
class Meta:
model = SavedView
@@ -1471,11 +1476,13 @@ class SavedViewSerializer(OwnedObjectSerializer):
attrs = super().validate(attrs)
if "display_fields" in attrs and attrs["display_fields"] is not None:
for field in attrs["display_fields"]:
if (
SavedView.DisplayFields.CUSTOM_FIELD[:-2] in field
): # i.e. check for 'custom_field_' prefix
field_id = int(re.search(r"\d+", field)[0])
if not CustomField.objects.filter(id=field_id).exists():
# i.e. 'custom_field_' followed by the id of a custom field
custom_field = re.fullmatch(
rf"{re.escape(SavedView.DisplayFields.CUSTOM_FIELD[:-2])}(\d+)",
field,
)
if custom_field:
if not CustomField.objects.filter(id=custom_field[1]).exists():
raise serializers.ValidationError(
f"Invalid field: {field}",
)
@@ -1,114 +0,0 @@
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import Document
from paperless_testing.dirs import PaperlessDirs
from paperless_testing.factories import DocumentFactory
@pytest.fixture
def archived_document(paperless_dirs: PaperlessDirs) -> Document:
document = DocumentFactory.create(
title="title",
filename="source.pdf",
archive_filename="archived.pdf",
mime_type="application/pdf",
)
document.source_path.write_bytes(b"source")
document.archive_path.write_bytes(b"archive")
return document
class TestDownloadFollowFormatting:
@pytest.mark.parametrize("value", ["false", "0", "no", "off"])
def test_false_values_use_the_public_filename(
self,
admin_client: APIClient,
archived_document: Document,
value: str,
) -> None:
"""
GIVEN:
- A document whose name on disk differs from its public name
WHEN:
- It is downloaded with follow_formatting set to a false value
THEN:
- The public name is used, the string "false" is not true
"""
response = admin_client.get(
f"/api/documents/{archived_document.pk}/download/?follow_formatting={value}",
)
assert response.status_code == status.HTTP_200_OK
assert "title.pdf" in response["Content-Disposition"]
response.close()
@pytest.mark.parametrize("value", ["true", "True", "1", "yes", "on"])
def test_true_values_use_the_name_on_disk(
self,
admin_client: APIClient,
archived_document: Document,
value: str,
) -> None:
"""
GIVEN:
- A document whose name on disk differs from its public name
WHEN:
- It is downloaded with follow_formatting set to a true value
THEN:
- The name on disk is used
"""
response = admin_client.get(
f"/api/documents/{archived_document.pk}/download/?follow_formatting={value}",
)
assert "archived.pdf" in response["Content-Disposition"]
response.close()
def test_a_value_that_is_not_a_boolean_is_a_400(
self,
admin_client: APIClient,
archived_document: Document,
) -> None:
response = admin_client.get(
f"/api/documents/{archived_document.pk}/download/?follow_formatting=maybe",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
class TestDownloadFilenameControlCharacters:
def test_control_characters_do_not_fail_the_download(
self,
admin_client: APIClient,
paperless_dirs: PaperlessDirs,
) -> None:
"""
GIVEN:
- A document whose name on disk holds control characters, a title can
WHEN:
- It is downloaded following the name on disk
THEN:
- The download works and no control character is in the header
"""
document = DocumentFactory.create(
filename="source.pdf",
archive_filename="ar\r\nchi\x12ved.pdf",
mime_type="application/pdf",
)
document.source_path.write_bytes(b"source")
document.archive_path.parent.mkdir(parents=True, exist_ok=True)
document.archive_path.write_bytes(b"archive")
response = admin_client.get(
f"/api/documents/{document.pk}/download/?follow_formatting=true",
)
assert response.status_code == status.HTTP_200_OK
assert 'filename="archived.pdf"' in response["Content-Disposition"]
assert not any(
ord(char) < 32 or ord(char) == 127
for char in response["Content-Disposition"]
)
response.close()
@@ -0,0 +1,82 @@
import pytest
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import CustomField
from documents.models import SavedView
class TestSavedViewDisplayFields:
@pytest.mark.parametrize(
"value",
[
pytest.param(["custom_field_abc"], id="no-id"),
pytest.param(["custom_field_"], id="empty-id"),
pytest.param(["xcustom_field_{id}"], id="prefixed"),
pytest.param(["custom_field_{id}x"], id="suffixed"),
pytest.param([1], id="not-a-string"),
],
)
def test_malformed_display_fields_are_a_400(
self,
admin_client: APIClient,
admin_user: User,
value: object,
) -> None:
"""
GIVEN:
- A saved view and a custom field
WHEN:
- Its display fields are patched to something that names no field
THEN:
- The response is a 400 and the stored display fields are unchanged
"""
custom_field = CustomField.objects.create(
name="cf",
data_type=CustomField.FieldDataType.STRING,
)
view = SavedView.objects.create(
name="view",
owner=admin_user,
sort_field="created",
display_fields=["title"],
)
if isinstance(value, list):
value = [
item.format(id=custom_field.pk) if isinstance(item, str) else item
for item in value
]
response = admin_client.patch(
f"/api/saved_views/{view.pk}/",
{"display_fields": value},
format="json",
)
assert response.status_code == status.HTTP_400_BAD_REQUEST
view.refresh_from_db()
assert view.display_fields == ["title"]
def test_a_custom_field_display_name_is_accepted(
self,
admin_client: APIClient,
admin_user: User,
) -> None:
custom_field = CustomField.objects.create(
name="cf",
data_type=CustomField.FieldDataType.STRING,
)
view = SavedView.objects.create(
name="view",
owner=admin_user,
sort_field="created",
)
response = admin_client.patch(
f"/api/saved_views/{view.pk}/",
{"display_fields": ["title", f"custom_field_{custom_field.pk}"]},
format="json",
)
assert response.status_code == status.HTTP_200_OK
+1 -7
View File
@@ -1461,10 +1461,7 @@ class DocumentViewSet(
use_archive=not self.original_requested(request)
and file_doc.has_archive_version,
disposition=disposition,
# The query value is a string, "false" must not count as true
follow_formatting=serializers.BooleanField(default=False).run_validation(
request.query_params.get("follow_formatting", serializers.empty),
),
follow_formatting=request.query_params.get("follow_formatting", False),
)
def get_metadata(self, file, mime_type):
@@ -5275,9 +5272,6 @@ def serve_file(
.replace("\\", "_")
.replace('"', "_")
)
# A name can hold control characters, which a header cannot carry. The encoded
# form below percent encodes them, only this plain fallback needs them removed
filename_normalized = "".join(c for c in filename_normalized if c.isprintable())
filename_encoded = quote(filename)
content_disposition = (
f"{disposition}; "