From 098694c6e497ff3347d10e5b57015233ffdd4d72 Mon Sep 17 00:00:00 2001 From: Trenton H <797416+stumpylog@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:46:34 -0800 Subject: [PATCH] Chore: Remove dead code (#14817) * Chore: remove unused is_file_ext_supported Nothing in production called it, only its own test. * Chore: remove unused Tag.parent_pk It was an alias of tn_parent_id used only by two test asserts, which now use tn_parent_id directly. * Chore: remove unused SanityCheckMessages summary properties has_global_issues was never referenced and total_issue_count was only asserted in tests. The two private issue counters that fed it are removed as well, and the tests assert on has_error and has_warning instead. * Chore: remove unused DocumentViewSet._has_document_permissions It duplicated has_document_operation_permissions and had no callers. * Chore: remove legacy DocumentParser base class Parsers are resolved through the parser registry and ParserProtocol now, and nothing referenced this class. Its now unused imports are removed too. * Chore: remove unused ColorField and DeprecatedColors No serializer used ColorField, and DeprecatedColors was only referenced by it. * Chore: remove unused RtlLanguageException A leftover from the old tesseract parser, nothing referenced it. * Chore: remove unused TASK_WORKERS setting An alias of CELERY_WORKER_CONCURRENCY that nothing read. PAPERLESS_TASK_WORKERS is unchanged. * Chore: remove unused GNUPG_HOME setting Nothing read it. The mail GPG code uses EMAIL_GNUPG_HOME. * Chore: remove unused test helpers Drops the shared_samples_dir fixture, MailAttachmentMock, _SHORT_TEXT and _make_extract_text, none of which any test used. --- src/conftest.py | 6 -- src/documents/models.py | 4 - src/documents/parsers.py | 93 ------------------ src/documents/sanity_checker.py | 27 +----- src/documents/serialisers.py | 37 -------- .../tests/test_management_exporter.py | 3 +- src/documents/tests/test_parsers.py | 6 -- src/documents/tests/test_sanity_check.py | 3 - src/documents/tests/test_tag_hierarchy.py | 4 +- src/documents/views.py | 94 ------------------- src/paperless/parsers/tesseract.py | 4 - src/paperless/settings/__init__.py | 4 - .../tests/parsers/test_mail_parser_live.py | 7 -- .../tests/parsers/test_parse_modes.py | 10 -- 14 files changed, 9 insertions(+), 293 deletions(-) diff --git a/src/conftest.py b/src/conftest.py index 91f5635a2f..5f53c25a6f 100644 --- a/src/conftest.py +++ b/src/conftest.py @@ -153,12 +153,6 @@ def fake_progress_manager( return FakeProgressManager -@pytest.fixture(scope="session") -def shared_samples_dir() -> Path: - """Directory of sample files used by more than one app's tests.""" - return samples.SHARED_SAMPLES_DIR - - @pytest.fixture(scope="session") def simple_digital_pdf_file() -> Path: """One-page PDF with a text layer.""" diff --git a/src/documents/models.py b/src/documents/models.py index 12444a8de5..1045a20825 100644 --- a/src/documents/models.py +++ b/src/documents/models.py @@ -138,10 +138,6 @@ class Tag(MatchingModel): return TagHierarchy(cls.objects.values_list("pk", "tn_parent_id")) - @property - def parent_pk(self) -> int | None: - return self.tn_parent_id - def get_parent(self) -> "Tag | None": return self.tn_parent diff --git a/src/documents/parsers.py b/src/documents/parsers.py index 48983bb232..58ffd0c939 100644 --- a/src/documents/parsers.py +++ b/src/documents/parsers.py @@ -4,21 +4,13 @@ import logging import mimetypes import shutil import subprocess -import tempfile from pathlib import Path -from typing import TYPE_CHECKING from typing import Final -from django.conf import settings - -from documents.loggers import LoggingMixin from documents.utils import copy_file_with_basic_stats from documents.utils import run_subprocess from paperless.parsers.registry import get_parser_registry -if TYPE_CHECKING: - import datetime - logger = logging.getLogger("paperless.parsing") @@ -44,17 +36,6 @@ def get_default_file_extension(mime_type: str) -> str: return ext if ext else "" -def is_file_ext_supported(ext: str) -> bool: - """ - Returns True if the file extension is supported, False otherwise - TODO: Investigate why this really exists, why not use mimetype - """ - if ext: - return ext.lower() in get_supported_file_extensions() - else: - return False - - def get_supported_file_extensions() -> set[str]: extensions = set() for parser_class in get_parser_registry().all_parsers(): @@ -276,77 +257,3 @@ def make_thumbnail_from_pdf(in_path: Path, temp_dir: Path, logging_group=None) - class ParseError(Exception): pass - - -class DocumentParser(LoggingMixin): - """ - Subclass this to make your own parser. Have a look at - `paperless_tesseract.parsers` for inspiration. - """ - - logging_name = "paperless.parsing" - - def __init__(self, logging_group, progress_callback=None) -> None: - super().__init__() - self.renew_logging_group() - self.logging_group = logging_group - self.settings = self.get_settings() - settings.SCRATCH_DIR.mkdir(parents=True, exist_ok=True) - self.tempdir = Path( - tempfile.mkdtemp(prefix="paperless-", dir=settings.SCRATCH_DIR), - ) - - self.archive_path = None - self.text = None - self.date: datetime.datetime | None = None - self.progress_callback = progress_callback - - def progress(self, current_progress, max_progress) -> None: - if self.progress_callback: - self.progress_callback(current_progress, max_progress) - - def get_settings(self): # pragma: no cover - """ - A parser must implement this - """ - raise NotImplementedError - - def read_file_handle_unicode_errors(self, filepath: Path) -> str: - """ - Helper utility for reading from a file, and handling a problem with its - unicode, falling back to ignoring the error to remove the invalid bytes - """ - try: - text = filepath.read_text(encoding="utf-8") - except UnicodeDecodeError as e: - self.log.warning(f"Unicode error during text reading, continuing: {e}") - text = filepath.read_bytes().decode("utf-8", errors="replace") - return text - - def extract_metadata(self, document_path, mime_type): - return [] - - def get_page_count(self, document_path, mime_type) -> None: - return None - - def parse(self, document_path, mime_type, file_name=None): - raise NotImplementedError - - def get_archive_path(self): - return self.archive_path - - def get_thumbnail(self, document_path, mime_type, file_name=None): - """ - Returns the path to a file we can use as a thumbnail for this document. - """ - raise NotImplementedError - - def get_text(self): - return self.text - - def get_date(self) -> datetime.datetime | None: - return self.date - - def cleanup(self) -> None: - self.log.debug(f"Deleting directory {self.tempdir}") - shutil.rmtree(self.tempdir) diff --git a/src/documents/sanity_checker.py b/src/documents/sanity_checker.py index 413ebff32b..7949641ac3 100644 --- a/src/documents/sanity_checker.py +++ b/src/documents/sanity_checker.py @@ -49,8 +49,6 @@ class SanityCheckMessages: self._document_error_pks: set[int] = set() self._document_warning_pks: set[int] = set() self._document_info_pks: set[int] = set() - self._document_error_issue_count: int = 0 - self._document_warning_issue_count: int = 0 self.has_error: bool = False self.has_warning: bool = False self.has_info: bool = False @@ -76,17 +74,17 @@ class SanityCheckMessages: def error(self, doc_pk: int | None, message: str) -> None: self._messages[doc_pk].append({"level": logging.ERROR, "message": message}) self.has_error = True - if doc_pk is not None: - self._document_error_issue_count += 1 - if self._add_document_issue(doc_pk, self._document_error_pks): - self.document_error_count += 1 + if doc_pk is not None and self._add_document_issue( + doc_pk, + self._document_error_pks, + ): + self.document_error_count += 1 def warning(self, doc_pk: int | None, message: str) -> None: self._messages[doc_pk].append({"level": logging.WARNING, "message": message}) self.has_warning = True if doc_pk is not None: - self._document_warning_issue_count += 1 if self._add_document_issue(doc_pk, self._document_warning_pks): self.document_warning_count += 1 else: @@ -116,21 +114,6 @@ class SanityCheckMessages: def __getitem__(self, item: int | None) -> list[MessageEntry]: return self._messages[item] - # -- Summarize Helpers -------------------------------------------------- - - @property - def has_global_issues(self) -> bool: - return None in self._messages - - @property - def total_issue_count(self) -> int: - """Total number of error and warning messages across all documents and global.""" - return ( - self._document_error_issue_count - + self._document_warning_issue_count - + self.global_warning_count - ) - # -- Logging output (used by Celery task path) -------------------------- def log_messages(self) -> None: diff --git a/src/documents/serialisers.py b/src/documents/serialisers.py index 70d1f894de..f4b171f95d 100644 --- a/src/documents/serialisers.py +++ b/src/documents/serialisers.py @@ -536,43 +536,6 @@ class DocumentTypeSerializer(MatchingModelSerializer, OwnedObjectSerializer): ) -class DeprecatedColors: - COLOURS = ( - (1, "#a6cee3"), - (2, "#1f78b4"), - (3, "#b2df8a"), - (4, "#33a02c"), - (5, "#fb9a99"), - (6, "#e31a1c"), - (7, "#fdbf6f"), - (8, "#ff7f00"), - (9, "#cab2d6"), - (10, "#6a3d9a"), - (11, "#b15928"), - (12, "#000000"), - (13, "#cccccc"), - ) - - -@extend_schema_field( - serializers.ChoiceField( - choices=DeprecatedColors.COLOURS, - ), -) -class ColorField(serializers.Field): - def to_internal_value(self, data): - for id, color in DeprecatedColors.COLOURS: - if id == data: - return color - raise serializers.ValidationError - - def to_representation(self, value): - for id, color in DeprecatedColors.COLOURS: - if color == value: - return id - return 1 - - class TagSerializer(MatchingModelSerializer, OwnedObjectSerializer): def get_text_color(self, obj) -> str: try: diff --git a/src/documents/tests/test_management_exporter.py b/src/documents/tests/test_management_exporter.py index ec6a21b772..9419f24fed 100644 --- a/src/documents/tests/test_management_exporter.py +++ b/src/documents/tests/test_management_exporter.py @@ -305,7 +305,8 @@ class TestExportImport( self.assertEqual(Permission.objects.count(), num_permission_objects) messages = check_sanity() # everything is alright after the test - self.assertEqual(messages.total_issue_count, 0) + self.assertFalse(messages.has_error) + self.assertFalse(messages.has_warning) def test_exporter_with_filename_format(self) -> None: shutil.rmtree(Path(self.dirs.media_dir) / "documents") diff --git a/src/documents/tests/test_parsers.py b/src/documents/tests/test_parsers.py index cf27994c10..16fe5d14e6 100644 --- a/src/documents/tests/test_parsers.py +++ b/src/documents/tests/test_parsers.py @@ -14,7 +14,6 @@ from documents.parsers import encode_thumbnail_webp from documents.parsers import get_default_file_extension from documents.parsers import get_default_thumbnail from documents.parsers import get_supported_file_extensions -from documents.parsers import is_file_ext_supported from documents.parsers import make_thumbnail_from_pdf from documents.parsers import rasterize_pdf_page_to_png from paperless.parsers.registry import get_parser_registry @@ -132,11 +131,6 @@ class TestParserAvailability: # Test invalid mimetype returns no extension assert get_default_file_extension("aasdasd/dgfgf") == "" - def test_file_extension_support(self) -> None: - assert is_file_ext_supported(".pdf") - assert not is_file_ext_supported(".hsdfh") - assert not is_file_ext_supported("") - class TestComputeThumbnailDpi: @pytest.mark.parametrize( diff --git a/src/documents/tests/test_sanity_check.py b/src/documents/tests/test_sanity_check.py index e04367f7b3..b78feef5ab 100644 --- a/src/documents/tests/test_sanity_check.py +++ b/src/documents/tests/test_sanity_check.py @@ -39,7 +39,6 @@ class TestSanityCheckMessages: assert messages.document_warning_count == 1 assert messages.document_info_count == 1 assert messages.global_warning_count == 1 - assert messages.total_issue_count == 5 @pytest.mark.django_db @@ -51,7 +50,6 @@ class TestCheckSanityNoDocuments: messages = check_sanity() assert not messages.has_error assert not messages.has_warning - assert messages.total_issue_count == 0 @pytest.mark.usefixtures("paperless_dirs") def test_no_issues_logs_clean(self, caplog: pytest.LogCaptureFixture) -> None: @@ -67,7 +65,6 @@ class TestCheckSanityHealthyDocument: messages = check_sanity() assert not messages.has_error assert not messages.has_warning - assert messages.total_issue_count == 0 @pytest.mark.django_db diff --git a/src/documents/tests/test_tag_hierarchy.py b/src/documents/tests/test_tag_hierarchy.py index b7416c1424..1275551c08 100644 --- a/src/documents/tests/test_tag_hierarchy.py +++ b/src/documents/tests/test_tag_hierarchy.py @@ -362,7 +362,7 @@ class TestTagHierarchy(DirectoriesMixin, APITestCase): x = Tag.objects.create(name="X2") y = Tag.objects.create(name="Y2", tn_parent=x) - assert y.parent_pk == x.pk + assert y.tn_parent_id == x.pk # Moving X under D would make deepest node Y exceed depth 5 -> reject resp_fail = self.client.patch( @@ -383,7 +383,7 @@ class TestTagHierarchy(DirectoriesMixin, APITestCase): ) assert resp_ok.status_code in (200, 202) x.refresh_from_db() - assert x.parent_pk == c.id + assert x.tn_parent_id == c.id def test_is_root_filter_returns_only_root_tags(self) -> None: other_root = Tag.objects.create(name="Other parent") diff --git a/src/documents/views.py b/src/documents/views.py index 722b5bea9c..4d34a03aa8 100644 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -3023,100 +3023,6 @@ class DocumentOperationPermissionMixin(PassUserMixin, DocumentSelectionMixin): ) return Response({"result": "OK", "task_id": task.id}) - def _has_document_permissions( - self, - *, - user: User, - documents: list[int], - method, - parameters: dict[str, Any], - ) -> bool: - if user.is_superuser: - return True - - root_docs = { - get_root_document(doc) - for doc in Document.objects.select_related( - "owner", - "root_document__owner", - ).filter(pk__in=documents) - } - user_is_owner_of_all_documents = all( - (doc.owner == user or doc.owner is None) for doc in root_docs - ) - - # check global and object permissions for all documents - has_perms = ( - user.has_perm( - "documents.change_document", - ) - and not Document.global_objects.filter(pk__in=documents) - .exclude(pk__in=permitted_document_ids(user, perm="change_document")) - .exists() - ) - - # check ownership for methods that change original document - if ( - ( - has_perms - and method - in [ - bulk_edit.set_permissions, - bulk_edit.delete, - bulk_edit.rotate, - bulk_edit.delete_pages, - bulk_edit.edit_pdf, - bulk_edit.merge_as_versions, - bulk_edit.remove_password, - bulk_edit.run_workflow, - ] - ) - or ( - method in [bulk_edit.merge, bulk_edit.split] - and parameters.get("delete_originals") - ) - or (method == bulk_edit.edit_pdf and parameters.get("update_document")) - ): - has_perms = has_perms and user_is_owner_of_all_documents - - # check global add permissions for methods that create documents - if ( - has_perms - and ( - method in [bulk_edit.split, bulk_edit.merge] - or ( - method in [bulk_edit.edit_pdf, bulk_edit.remove_password] - and not parameters.get("update_document") - ) - ) - and not user.has_perm("documents.add_document") - ): - has_perms = False - - # check global delete permissions for methods that delete documents - if ( - has_perms - and ( - method == bulk_edit.delete - # Sources stop being documents of their own, and removing one - # again afterwards needs delete_document - or method == bulk_edit.merge_as_versions - or ( - method in [bulk_edit.merge, bulk_edit.split] - and parameters.get("delete_originals") - ) - or ( - method in [bulk_edit.edit_pdf, bulk_edit.remove_password] - and parameters.get("delete_original") - and not parameters.get("update_document") - ) - ) - and not user.has_perm("documents.delete_document") - ): - has_perms = False - - return has_perms - def _execute_document_action( self, *, diff --git a/src/paperless/parsers/tesseract.py b/src/paperless/parsers/tesseract.py index 96fc60f6e8..7cae31e0a4 100644 --- a/src/paperless/parsers/tesseract.py +++ b/src/paperless/parsers/tesseract.py @@ -65,10 +65,6 @@ class NoTextFoundException(Exception): pass -class RtlLanguageException(Exception): - pass - - class RasterisedDocumentParser: """ This parser uses Tesseract to try and get some text out of a rasterised diff --git a/src/paperless/settings/__init__.py b/src/paperless/settings/__init__.py index 3db1e88d0a..5279684f12 100644 --- a/src/paperless/settings/__init__.py +++ b/src/paperless/settings/__init__.py @@ -714,7 +714,6 @@ CELERY_TIMEZONE = TIME_ZONE CELERY_WORKER_HIJACK_ROOT_LOGGER = False CELERY_WORKER_CONCURRENCY: Final[int] = get_int_from_env("PAPERLESS_TASK_WORKERS", 1) -TASK_WORKERS = CELERY_WORKER_CONCURRENCY CELERY_WORKER_MAX_TASKS_PER_CHILD = 1 CELERY_WORKER_SEND_TASK_EVENTS = True CELERY_TASK_SEND_SENT_EVENT = True @@ -996,9 +995,6 @@ MAX_IMAGE_PIXELS: Final[int | None] = get_int_from_env( "PAPERLESS_MAX_IMAGE_PIXELS", ) -# GNUPG needs a home directory for some reason -GNUPG_HOME = os.getenv("HOME", "/tmp") - # Fallback layout for .eml consumption EMAIL_PARSE_DEFAULT_LAYOUT = get_int_from_env( "PAPERLESS_EMAIL_PARSE_DEFAULT_LAYOUT", diff --git a/src/paperless/tests/parsers/test_mail_parser_live.py b/src/paperless/tests/parsers/test_mail_parser_live.py index a91b25ec30..6125a71929 100644 --- a/src/paperless/tests/parsers/test_mail_parser_live.py +++ b/src/paperless/tests/parsers/test_mail_parser_live.py @@ -37,13 +37,6 @@ def extract_text(pdf_path: Path) -> str: return tmp.read() -class MailAttachmentMock: - def __init__(self, payload: bytes, content_id: str) -> None: - self.payload = payload - self.content_id = content_id - self.content_type = "image/png" - - @pytest.mark.live @pytest.mark.nginx @pytest.mark.skipif( diff --git a/src/paperless/tests/parsers/test_parse_modes.py b/src/paperless/tests/parsers/test_parse_modes.py index 1c1f4bd48e..7f86eae885 100644 --- a/src/paperless/tests/parsers/test_parse_modes.py +++ b/src/paperless/tests/parsers/test_parse_modes.py @@ -29,16 +29,6 @@ if TYPE_CHECKING: # --------------------------------------------------------------------------- _LONG_TEXT = "This is a test document with enough text. " * 5 # >50 chars -_SHORT_TEXT = "Hi." # <50 chars - - -def _make_extract_text(text: str | None): - """Return a side_effect function for ``extract_text`` that returns *text*.""" - - def _extract(sidecar_file, pdf_file): - return text - - return _extract # ---------------------------------------------------------------------------