mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-11-29 00:11:59 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
afbdd07145 | ||
|
|
9a2a50d23f | ||
|
|
d4617d8177 | ||
|
|
155a118f0d | ||
|
|
bc9d45cecc | ||
|
|
1655a844e3 |
No files matched your search
@@ -87,7 +87,6 @@ src/documents/classifier.py:0: error: Incompatible types in assignment (expressi
|
|||||||
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
|
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
|
||||||
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
|
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
|
||||||
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "str", variable has type "None") [assignment]
|
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "str", variable has type "None") [assignment]
|
||||||
src/documents/classifier.py:0: error: Item "None" of "str | None" has no attribute "encode" [union-attr]
|
|
||||||
src/documents/classifier.py:0: error: List comprehension has incompatible type List[int]; expected List[list[int]] [misc]
|
src/documents/classifier.py:0: error: List comprehension has incompatible type List[int]; expected List[list[int]] [misc]
|
||||||
src/documents/classifier.py:0: error: Module "sklearn.exceptions" has no attribute "InconsistentVersionWarning" [attr-defined]
|
src/documents/classifier.py:0: error: Module "sklearn.exceptions" has no attribute "InconsistentVersionWarning" [attr-defined]
|
||||||
src/documents/classifier.py:0: error: Unsupported operand types for >= ("datetime" and "None") [operator]
|
src/documents/classifier.py:0: error: Unsupported operand types for >= ("datetime" and "None") [operator]
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ dependencies = [
|
|||||||
"channels~=4.2",
|
"channels~=4.2",
|
||||||
"channels-redis~=4.2",
|
"channels-redis~=4.2",
|
||||||
"concurrent-log-handler~=0.9.25",
|
"concurrent-log-handler~=0.9.25",
|
||||||
|
"cryptography>=50",
|
||||||
"dateparser~=1.4",
|
"dateparser~=1.4",
|
||||||
# WARNING: django does not use semver.
|
# WARNING: django does not use semver.
|
||||||
# Only patch versions are guaranteed to not introduce breaking changes.
|
# Only patch versions are guaranteed to not introduce breaking changes.
|
||||||
@@ -46,6 +47,7 @@ dependencies = [
|
|||||||
"flower>=2.0.1,<2.3",
|
"flower>=2.0.1,<2.3",
|
||||||
"gotenberg-client[httpx]~=1.0",
|
"gotenberg-client[httpx]~=1.0",
|
||||||
"httpx-oauth~=0.17",
|
"httpx-oauth~=0.17",
|
||||||
|
"humanize>=4.15",
|
||||||
"ijson>=3.5.1",
|
"ijson>=3.5.1",
|
||||||
"imap-tools>=1.14,<1.16",
|
"imap-tools>=1.14,<1.16",
|
||||||
"jinja2~=3.1.6",
|
"jinja2~=3.1.6",
|
||||||
@@ -56,10 +58,13 @@ dependencies = [
|
|||||||
"llama-index-embeddings-openai-like>=0.2.2",
|
"llama-index-embeddings-openai-like>=0.2.2",
|
||||||
"llama-index-llms-ollama>=0.9.1",
|
"llama-index-llms-ollama>=0.9.1",
|
||||||
"llama-index-llms-openai-like>=0.7.1",
|
"llama-index-llms-openai-like>=0.7.1",
|
||||||
|
"lxml>=6.1",
|
||||||
"ocrmypdf[heic]>=17.12,<17.13",
|
"ocrmypdf[heic]>=17.12,<17.13",
|
||||||
|
"ollama>=0.6.1",
|
||||||
"openai>=2.48",
|
"openai>=2.48",
|
||||||
"pathvalidate~=3.3.1",
|
"pathvalidate~=3.3.1",
|
||||||
"pdf2image~=1.17.0",
|
"pdf2image~=1.17.0",
|
||||||
|
"pikepdf>=10.13",
|
||||||
"python-dateutil~=2.9.0",
|
"python-dateutil~=2.9.0",
|
||||||
"python-dotenv~=1.2.1",
|
"python-dotenv~=1.2.1",
|
||||||
"python-gnupg~=0.5.4",
|
"python-gnupg~=0.5.4",
|
||||||
|
|||||||
+11
-73
@@ -1,7 +1,6 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import functools
|
import functools
|
||||||
import hmac
|
|
||||||
import logging
|
import logging
|
||||||
import pickle
|
import pickle
|
||||||
import re
|
import re
|
||||||
@@ -15,9 +14,6 @@ if TYPE_CHECKING:
|
|||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from collections.abc import Iterator
|
from collections.abc import Iterator
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from types import TracebackType
|
|
||||||
from typing import BinaryIO
|
|
||||||
from typing import Self
|
|
||||||
|
|
||||||
import tantivy
|
import tantivy
|
||||||
from numpy import ndarray
|
from numpy import ndarray
|
||||||
@@ -37,9 +33,11 @@ from documents.caching import CLASSIFIER_VERSION_KEY
|
|||||||
from documents.models import Document
|
from documents.models import Document
|
||||||
from documents.models import MatchingModel
|
from documents.models import MatchingModel
|
||||||
from documents.models import Tag
|
from documents.models import Tag
|
||||||
|
from paperless.signed_pickle import SignedFileWriter
|
||||||
from paperless.signed_pickle import SignedPickleError
|
from paperless.signed_pickle import SignedPickleError
|
||||||
from paperless.signed_pickle import signed_pickle_dumps
|
from paperless.signed_pickle import signed_pickle_dumps
|
||||||
from paperless.signed_pickle import signed_pickle_loads
|
from paperless.signed_pickle import signed_pickle_loads
|
||||||
|
from paperless.signed_pickle import verify_signed
|
||||||
|
|
||||||
logger = logging.getLogger("paperless.classifier")
|
logger = logging.getLogger("paperless.classifier")
|
||||||
|
|
||||||
@@ -77,49 +75,6 @@ RE_WORD = re.compile(r"\b[\w]+\b") # words that may contain digits
|
|||||||
_CONTENT_CHUNK_SIZE = 1000
|
_CONTENT_CHUNK_SIZE = 1000
|
||||||
|
|
||||||
|
|
||||||
class _SignedFileWriter:
|
|
||||||
"""
|
|
||||||
Atomically writes a file made of an HMAC signature followed by the data,
|
|
||||||
signing the data as it streams to disk rather than holding it in memory.
|
|
||||||
|
|
||||||
The signature is only known once everything is written, so its space is
|
|
||||||
reserved at the start of the file and filled in on exit. The target is only
|
|
||||||
replaced once the file is complete; on error the partial file is removed.
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, target: Path, mac: hmac.HMAC) -> None:
|
|
||||||
self._target = target
|
|
||||||
self._temp = target.with_name(f"{target.name}.part")
|
|
||||||
self._mac = mac
|
|
||||||
self._file: BinaryIO
|
|
||||||
|
|
||||||
def __enter__(self) -> Self:
|
|
||||||
self._file = self._temp.open("wb")
|
|
||||||
self._file.write(bytes(self._mac.digest_size))
|
|
||||||
return self
|
|
||||||
|
|
||||||
def write(self, data: bytes | memoryview) -> int:
|
|
||||||
self._mac.update(data)
|
|
||||||
return self._file.write(data)
|
|
||||||
|
|
||||||
def __exit__(
|
|
||||||
self,
|
|
||||||
exc_type: type[BaseException] | None,
|
|
||||||
exc_value: BaseException | None,
|
|
||||||
traceback: TracebackType | None,
|
|
||||||
) -> None:
|
|
||||||
try:
|
|
||||||
with self._file:
|
|
||||||
if exc_type is None:
|
|
||||||
self._file.seek(0)
|
|
||||||
self._file.write(self._mac.digest())
|
|
||||||
if exc_type is None:
|
|
||||||
self._temp.rename(self._target)
|
|
||||||
finally:
|
|
||||||
# A no-op after a successful rename, otherwise removes the partial file
|
|
||||||
self._temp.unlink(missing_ok=True)
|
|
||||||
|
|
||||||
|
|
||||||
@functools.cache
|
@functools.cache
|
||||||
def _text_analyzer(language: str) -> tantivy.TextAnalyzer:
|
def _text_analyzer(language: str) -> tantivy.TextAnalyzer:
|
||||||
"""
|
"""
|
||||||
@@ -209,8 +164,6 @@ class DocumentClassifier:
|
|||||||
# Tantivy text preprocessing
|
# Tantivy text preprocessing
|
||||||
FORMAT_VERSION = 11
|
FORMAT_VERSION = 11
|
||||||
|
|
||||||
HMAC_SIZE = 32 # SHA-256 digest length
|
|
||||||
|
|
||||||
def __init__(self) -> None:
|
def __init__(self) -> None:
|
||||||
# last time a document changed and therefore training might be required
|
# last time a document changed and therefore training might be required
|
||||||
self.last_doc_change_time: datetime | None = None
|
self.last_doc_change_time: datetime | None = None
|
||||||
@@ -230,10 +183,6 @@ class DocumentClassifier:
|
|||||||
pickle.dumps(self.data_vectorizer),
|
pickle.dumps(self.data_vectorizer),
|
||||||
).hexdigest()
|
).hexdigest()
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _new_hmac() -> hmac.HMAC:
|
|
||||||
return hmac.new(settings.SECRET_KEY.encode(), digestmod=sha256)
|
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _strip_training_state(classifier: MLPClassifier) -> None:
|
def _strip_training_state(classifier: MLPClassifier) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -248,30 +197,19 @@ class DocumentClassifier:
|
|||||||
del classifier._best_coefs
|
del classifier._best_coefs
|
||||||
del classifier._best_intercepts
|
del classifier._best_intercepts
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _compute_hmac(data: bytes | memoryview) -> bytes:
|
|
||||||
mac = DocumentClassifier._new_hmac()
|
|
||||||
mac.update(data)
|
|
||||||
return mac.digest()
|
|
||||||
|
|
||||||
def load(self) -> None:
|
def load(self) -> None:
|
||||||
from sklearn.exceptions import InconsistentVersionWarning
|
from sklearn.exceptions import InconsistentVersionWarning
|
||||||
|
|
||||||
raw = Path(settings.MODEL_FILE).read_bytes()
|
raw = Path(settings.MODEL_FILE).read_bytes()
|
||||||
|
|
||||||
if len(raw) <= self.HMAC_SIZE:
|
# The whole file is verified from memory before unpickling, rather than
|
||||||
raise ClassifierModelCorruptError
|
# streamed from disk, so it cannot change between check and load.
|
||||||
|
# verify_signed returns a view of the data without copying the
|
||||||
# Slice through a memoryview so the (potentially multi-GB) payload is
|
# (potentially multi-GB) payload.
|
||||||
# not copied; hmac and pickle both accept buffers directly.
|
try:
|
||||||
# The whole file is still verified from memory before unpickling, rather
|
data = verify_signed(raw)
|
||||||
# than streamed from disk, so it cannot change between check and load.
|
except SignedPickleError as err:
|
||||||
view = memoryview(raw)
|
raise ClassifierModelCorruptError from err
|
||||||
signature = view[: self.HMAC_SIZE]
|
|
||||||
data = view[self.HMAC_SIZE :]
|
|
||||||
|
|
||||||
if not hmac.compare_digest(signature, self._compute_hmac(data)):
|
|
||||||
raise ClassifierModelCorruptError
|
|
||||||
|
|
||||||
# Catch warnings for processing
|
# Catch warnings for processing
|
||||||
with warnings.catch_warnings(record=True) as w:
|
with warnings.catch_warnings(record=True) as w:
|
||||||
@@ -315,7 +253,7 @@ class DocumentClassifier:
|
|||||||
def save(self) -> None:
|
def save(self) -> None:
|
||||||
# Stream to disk instead of building the payload in memory. Protocol 5+
|
# Stream to disk instead of building the payload in memory. Protocol 5+
|
||||||
# pickles numpy arrays without copying them (the default is 4 before 3.14).
|
# pickles numpy arrays without copying them (the default is 4 before 3.14).
|
||||||
with _SignedFileWriter(settings.MODEL_FILE, self._new_hmac()) as f:
|
with SignedFileWriter(settings.MODEL_FILE) as f:
|
||||||
pickle.dump(
|
pickle.dump(
|
||||||
(
|
(
|
||||||
self.FORMAT_VERSION,
|
self.FORMAT_VERSION,
|
||||||
|
|||||||
+10
-21
@@ -6,7 +6,6 @@ import zipfile
|
|||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tempfile import TemporaryDirectory
|
from tempfile import TemporaryDirectory
|
||||||
from tempfile import mkstemp
|
|
||||||
|
|
||||||
from celery import Task
|
from celery import Task
|
||||||
from celery import shared_task
|
from celery import shared_task
|
||||||
@@ -897,26 +896,25 @@ def build_share_link_bundle(bundle_id: int) -> None:
|
|||||||
|
|
||||||
documents = list(bundle.documents.all().order_by("pk"))
|
documents = list(bundle.documents.all().order_by("pk"))
|
||||||
|
|
||||||
_, temp_zip_path_str = mkstemp(suffix=".zip", dir=settings.SCRATCH_DIR)
|
|
||||||
temp_zip_path = Path(temp_zip_path_str)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
strategy_class = (
|
strategy_class = (
|
||||||
ArchiveOnlyStrategy
|
ArchiveOnlyStrategy
|
||||||
if bundle.file_version == ShareLink.FileVersion.ARCHIVE
|
if bundle.file_version == ShareLink.FileVersion.ARCHIVE
|
||||||
else OriginalsOnlyStrategy
|
else OriginalsOnlyStrategy
|
||||||
)
|
)
|
||||||
with zipfile.ZipFile(temp_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
|
|
||||||
strategy = strategy_class(zipf)
|
|
||||||
for document in documents:
|
|
||||||
strategy.add_document(document)
|
|
||||||
|
|
||||||
output_dir = settings.SHARE_LINK_BUNDLE_DIR
|
output_dir = settings.SHARE_LINK_BUNDLE_DIR
|
||||||
output_dir.mkdir(parents=True, exist_ok=True)
|
output_dir.mkdir(parents=True, exist_ok=True)
|
||||||
final_path = (output_dir / f"{bundle.slug}.zip").resolve()
|
final_path = (output_dir / f"{bundle.slug}.zip").resolve()
|
||||||
if final_path.exists():
|
|
||||||
final_path.unlink()
|
with TemporaryDirectory(dir=settings.SCRATCH_DIR) as tmp_dir:
|
||||||
shutil.move(temp_zip_path, final_path)
|
temp_zip_path = Path(tmp_dir) / "bundle.zip"
|
||||||
|
with zipfile.ZipFile(temp_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
|
||||||
|
strategy = strategy_class(zipf)
|
||||||
|
for document in documents:
|
||||||
|
strategy.add_document(document)
|
||||||
|
|
||||||
|
final_path.unlink(missing_ok=True)
|
||||||
|
shutil.move(temp_zip_path, final_path)
|
||||||
|
|
||||||
bundle.file_path = f"{bundle.slug}.zip"
|
bundle.file_path = f"{bundle.slug}.zip"
|
||||||
bundle.size_bytes = final_path.stat().st_size
|
bundle.size_bytes = final_path.stat().st_size
|
||||||
@@ -947,16 +945,7 @@ def build_share_link_bundle(bundle_id: int) -> None:
|
|||||||
"timestamp": timezone.now().isoformat(),
|
"timestamp": timezone.now().isoformat(),
|
||||||
}
|
}
|
||||||
bundle.save(update_fields=["status", "last_error"])
|
bundle.save(update_fields=["status", "last_error"])
|
||||||
try:
|
|
||||||
temp_zip_path.unlink()
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
raise
|
raise
|
||||||
finally:
|
|
||||||
try:
|
|
||||||
temp_zip_path.unlink(missing_ok=True)
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
@shared_task
|
@shared_task
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
import pickle
|
import pickle
|
||||||
import warnings
|
import warnings
|
||||||
from datetime import UTC
|
from datetime import UTC
|
||||||
@@ -31,6 +33,7 @@ from documents.models import Tag
|
|||||||
from documents.tests.helpers import dummy_preprocess
|
from documents.tests.helpers import dummy_preprocess
|
||||||
from paperless.settings import CLASSIFIER_LANGUAGES
|
from paperless.settings import CLASSIFIER_LANGUAGES
|
||||||
from paperless.signed_pickle import HMAC_SIZE
|
from paperless.signed_pickle import HMAC_SIZE
|
||||||
|
from paperless.signed_pickle import compute_signature
|
||||||
from paperless.signed_pickle import signed_pickle_dumps
|
from paperless.signed_pickle import signed_pickle_dumps
|
||||||
from paperless_testing.dirs import DirectoriesMixin
|
from paperless_testing.dirs import DirectoriesMixin
|
||||||
from paperless_testing.factories import DocumentFactory
|
from paperless_testing.factories import DocumentFactory
|
||||||
@@ -423,7 +426,7 @@ class TestClassifier(DirectoriesMixin, TestCase):
|
|||||||
- The ClassifierModelCorruptError is raised
|
- The ClassifierModelCorruptError is raised
|
||||||
"""
|
"""
|
||||||
garbage_data = b"this is not valid pickle data"
|
garbage_data = b"this is not valid pickle data"
|
||||||
signature = DocumentClassifier._compute_hmac(garbage_data)
|
signature = compute_signature(garbage_data)
|
||||||
Path(settings.MODEL_FILE).write_bytes(signature + garbage_data)
|
Path(settings.MODEL_FILE).write_bytes(signature + garbage_data)
|
||||||
|
|
||||||
with self.assertRaises(ClassifierModelCorruptError):
|
with self.assertRaises(ClassifierModelCorruptError):
|
||||||
@@ -944,9 +947,17 @@ class TestClassifierSave:
|
|||||||
classifier.save()
|
classifier.save()
|
||||||
|
|
||||||
raw = model_file.read_bytes()
|
raw = model_file.read_bytes()
|
||||||
signature = raw[: DocumentClassifier.HMAC_SIZE]
|
signature = raw[:HMAC_SIZE]
|
||||||
data = raw[DocumentClassifier.HMAC_SIZE :]
|
data = raw[HMAC_SIZE:]
|
||||||
assert signature == DocumentClassifier._compute_hmac(data)
|
# Computed independently so the on-disk format stays what is documented
|
||||||
|
assert (
|
||||||
|
signature
|
||||||
|
== hmac.new(
|
||||||
|
settings.SECRET_KEY.encode(),
|
||||||
|
data,
|
||||||
|
hashlib.sha256,
|
||||||
|
).digest()
|
||||||
|
)
|
||||||
# A pickle opens with the PROTO opcode followed by the protocol number
|
# A pickle opens with the PROTO opcode followed by the protocol number
|
||||||
assert data[:2] == bytes([pickle.PROTO[0], pickle.HIGHEST_PROTOCOL])
|
assert data[:2] == bytes([pickle.PROTO[0], pickle.HIGHEST_PROTOCOL])
|
||||||
assert pickle.loads(data)[:3] == (
|
assert pickle.loads(data)[:3] == (
|
||||||
|
|||||||
@@ -434,13 +434,9 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
|
|||||||
"documents.tasks.OriginalsOnlyStrategy.add_document",
|
"documents.tasks.OriginalsOnlyStrategy.add_document",
|
||||||
side_effect=RuntimeError("zip failure"),
|
side_effect=RuntimeError("zip failure"),
|
||||||
),
|
),
|
||||||
mock.patch("pathlib.Path.unlink") as unlink_mock,
|
self.assertRaises(RuntimeError),
|
||||||
):
|
):
|
||||||
unlink_mock.side_effect = [OSError("unlink"), OSError("unlink-finally")] + [
|
build_share_link_bundle(bundle.pk)
|
||||||
None,
|
|
||||||
] * 5
|
|
||||||
with self.assertRaises(RuntimeError):
|
|
||||||
build_share_link_bundle(bundle.pk)
|
|
||||||
|
|
||||||
bundle.refresh_from_db()
|
bundle.refresh_from_db()
|
||||||
self.assertEqual(bundle.status, ShareLinkBundle.Status.FAILED)
|
self.assertEqual(bundle.status, ShareLinkBundle.Status.FAILED)
|
||||||
@@ -448,10 +444,6 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
|
|||||||
assert isinstance(bundle.last_error, dict)
|
assert isinstance(bundle.last_error, dict)
|
||||||
self.assertEqual(bundle.last_error.get("message"), "zip failure")
|
self.assertEqual(bundle.last_error.get("message"), "zip failure")
|
||||||
self.assertEqual(bundle.last_error.get("exception_type"), "RuntimeError")
|
self.assertEqual(bundle.last_error.get("exception_type"), "RuntimeError")
|
||||||
scratch_zips = list(Path(settings.SCRATCH_DIR).glob("*.zip"))
|
|
||||||
self.assertTrue(scratch_zips)
|
|
||||||
for path in scratch_zips:
|
|
||||||
path.unlink(missing_ok=True)
|
|
||||||
|
|
||||||
def test_build_share_link_bundle_missing_bundle_noop(self) -> None:
|
def test_build_share_link_bundle_missing_bundle_noop(self) -> None:
|
||||||
# Should not raise when bundle does not exist
|
# Should not raise when bundle does not exist
|
||||||
|
|||||||
@@ -364,13 +364,14 @@ def extract_pdf_metadata(
|
|||||||
namespace_pattern = re.compile(r"\{(.*)\}(.*)")
|
namespace_pattern = re.compile(r"\{(.*)\}(.*)")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
pdf = pikepdf.open(document_path)
|
with pikepdf.open(document_path) as pdf:
|
||||||
meta = pdf.open_metadata()
|
meta = pdf.open_metadata()
|
||||||
|
items = list(meta.items())
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
_log.warning("Could not open PDF metadata for %s: %s", document_path, e)
|
_log.warning("Could not open PDF metadata for %s: %s", document_path, e)
|
||||||
return []
|
return []
|
||||||
|
|
||||||
for key, value in meta.items():
|
for key, value in items:
|
||||||
if isinstance(value, list):
|
if isinstance(value, list):
|
||||||
value = " ".join(str(e) for e in value)
|
value = " ".join(str(e) for e in value)
|
||||||
value = str(value)
|
value = str(value)
|
||||||
|
|||||||
@@ -3,10 +3,17 @@ from __future__ import annotations
|
|||||||
import hmac
|
import hmac
|
||||||
import pickle
|
import pickle
|
||||||
from hashlib import sha256
|
from hashlib import sha256
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from pathlib import Path
|
||||||
|
from types import TracebackType
|
||||||
|
from typing import BinaryIO
|
||||||
|
from typing import Self
|
||||||
|
|
||||||
HMAC_SIZE = sha256().digest_size
|
HMAC_SIZE = sha256().digest_size
|
||||||
|
|
||||||
|
|
||||||
@@ -14,26 +21,91 @@ class SignedPickleError(ValueError):
|
|||||||
"""Raised when a signed pickle payload cannot be authenticated."""
|
"""Raised when a signed pickle payload cannot be authenticated."""
|
||||||
|
|
||||||
|
|
||||||
def _get_signing_key() -> bytes:
|
def new_mac() -> hmac.HMAC:
|
||||||
return settings.SECRET_KEY.encode()
|
"""
|
||||||
|
A new HMAC-SHA256 keyed with the SECRET_KEY, for signing incrementally.
|
||||||
|
"""
|
||||||
|
return hmac.new(settings.SECRET_KEY.encode(), digestmod=sha256)
|
||||||
|
|
||||||
|
|
||||||
def signed_pickle_dumps(obj: object) -> bytes:
|
def compute_signature(data: bytes | memoryview) -> bytes:
|
||||||
data = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
|
mac = new_mac()
|
||||||
signature = hmac.new(_get_signing_key(), data, sha256).digest()
|
mac.update(data)
|
||||||
return signature + data
|
return mac.digest()
|
||||||
|
|
||||||
|
|
||||||
def signed_pickle_loads(payload: bytes) -> Any:
|
def verify_signed(payload: bytes | memoryview) -> memoryview:
|
||||||
|
"""
|
||||||
|
Verifies a payload made of an HMAC signature followed by the data, returning
|
||||||
|
a view of the data.
|
||||||
|
|
||||||
|
The data is sliced through a memoryview, so a (potentially multi-GB) payload
|
||||||
|
is not copied. The view is only returned once the whole payload has been
|
||||||
|
verified, and callers should unpickle from it rather than from the source,
|
||||||
|
so what is loaded is exactly what was checked.
|
||||||
|
"""
|
||||||
if len(payload) <= HMAC_SIZE:
|
if len(payload) <= HMAC_SIZE:
|
||||||
msg = "Signed-pickle payload too short"
|
msg = "Signed-pickle payload too short"
|
||||||
raise SignedPickleError(msg)
|
raise SignedPickleError(msg)
|
||||||
|
|
||||||
signature = payload[:HMAC_SIZE]
|
view = memoryview(payload)
|
||||||
data = payload[HMAC_SIZE:]
|
signature = view[:HMAC_SIZE]
|
||||||
expected = hmac.new(_get_signing_key(), data, sha256).digest()
|
data = view[HMAC_SIZE:]
|
||||||
if not hmac.compare_digest(signature, expected):
|
if not hmac.compare_digest(signature, compute_signature(data)):
|
||||||
msg = "Signed-pickle HMAC verification failed; payload may have been tampered with"
|
msg = "Signed-pickle HMAC verification failed; payload may have been tampered with"
|
||||||
raise SignedPickleError(msg)
|
raise SignedPickleError(msg)
|
||||||
|
|
||||||
return pickle.loads(data)
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def signed_pickle_dumps(obj: object) -> bytes:
|
||||||
|
data = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
|
||||||
|
return compute_signature(data) + data
|
||||||
|
|
||||||
|
|
||||||
|
def signed_pickle_loads(payload: bytes) -> Any:
|
||||||
|
return pickle.loads(verify_signed(payload))
|
||||||
|
|
||||||
|
|
||||||
|
class SignedFileWriter:
|
||||||
|
"""
|
||||||
|
Atomically writes a file made of an HMAC signature followed by the data,
|
||||||
|
signing the data as it streams to disk rather than holding it in memory.
|
||||||
|
The result can be read back with verify_signed.
|
||||||
|
|
||||||
|
The signature is only known once everything is written, so its space is
|
||||||
|
reserved at the start of the file and filled in on exit. The target is only
|
||||||
|
replaced once the file is complete; on error the partial file is removed.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, target: Path) -> None:
|
||||||
|
self._target = target
|
||||||
|
self._temp = target.with_name(f"{target.name}.part")
|
||||||
|
self._mac = new_mac()
|
||||||
|
self._file: BinaryIO
|
||||||
|
|
||||||
|
def __enter__(self) -> Self:
|
||||||
|
self._file = self._temp.open("wb")
|
||||||
|
self._file.write(bytes(HMAC_SIZE))
|
||||||
|
return self
|
||||||
|
|
||||||
|
def write(self, data: bytes | memoryview) -> int:
|
||||||
|
self._mac.update(data)
|
||||||
|
return self._file.write(data)
|
||||||
|
|
||||||
|
def __exit__(
|
||||||
|
self,
|
||||||
|
exc_type: type[BaseException] | None,
|
||||||
|
exc_value: BaseException | None,
|
||||||
|
traceback: TracebackType | None,
|
||||||
|
) -> None:
|
||||||
|
try:
|
||||||
|
with self._file:
|
||||||
|
if exc_type is None:
|
||||||
|
self._file.seek(0)
|
||||||
|
self._file.write(self._mac.digest())
|
||||||
|
if exc_type is None:
|
||||||
|
self._temp.rename(self._target)
|
||||||
|
finally:
|
||||||
|
# A no-op after a successful rename, otherwise removes the partial file
|
||||||
|
self._temp.unlink(missing_ok=True)
|
||||||
@@ -12,6 +12,8 @@ from django.test import override_settings
|
|||||||
from paperless.celery import signed_pickle_dumps
|
from paperless.celery import signed_pickle_dumps
|
||||||
from paperless.celery import signed_pickle_loads
|
from paperless.celery import signed_pickle_loads
|
||||||
from paperless.signed_pickle import HMAC_SIZE
|
from paperless.signed_pickle import HMAC_SIZE
|
||||||
|
from paperless.signed_pickle import compute_signature
|
||||||
|
from paperless.signed_pickle import verify_signed
|
||||||
|
|
||||||
|
|
||||||
def test_tasks_registered_without_system_checks() -> None:
|
def test_tasks_registered_without_system_checks() -> None:
|
||||||
@@ -80,6 +82,14 @@ class TestSignedPickleSerializer:
|
|||||||
with pytest.raises(ValueError, match="HMAC verification failed"):
|
with pytest.raises(ValueError, match="HMAC verification failed"):
|
||||||
signed_pickle_loads(bytes(tampered))
|
signed_pickle_loads(bytes(tampered))
|
||||||
|
|
||||||
|
def test_verified_data_is_a_view_not_a_copy(self) -> None:
|
||||||
|
"""Verified data is a view of the payload, so large payloads aren't copied."""
|
||||||
|
data = b"x" * 1024
|
||||||
|
payload = compute_signature(data) + data
|
||||||
|
verified = verify_signed(payload)
|
||||||
|
assert verified.obj is payload
|
||||||
|
assert bytes(verified) == data
|
||||||
|
|
||||||
def test_truncated_payload_rejected(self) -> None:
|
def test_truncated_payload_rejected(self) -> None:
|
||||||
"""A payload shorter than HMAC_SIZE is rejected."""
|
"""A payload shorter than HMAC_SIZE is rejected."""
|
||||||
with pytest.raises(ValueError, match="too short"):
|
with pytest.raises(ValueError, match="too short"):
|
||||||
|
|||||||
@@ -12,6 +12,11 @@ from paperless.utils import ocr_to_dateparser_languages
|
|||||||
pytest.param("eng", ["en"], id="single-language"),
|
pytest.param("eng", ["en"], id="single-language"),
|
||||||
pytest.param("fra+ita+lao", ["fr", "it", "lo"], id="multiple-languages"),
|
pytest.param("fra+ita+lao", ["fr", "it", "lo"], id="multiple-languages"),
|
||||||
pytest.param("fil", ["fil"], id="no-two-letter-equivalent"),
|
pytest.param("fil", ["fil"], id="no-two-letter-equivalent"),
|
||||||
|
pytest.param(
|
||||||
|
"afr+vie+kan+chr+mkd", # codespell:ignore
|
||||||
|
["af", "vi", "kn", "chr", "mk"],
|
||||||
|
id="previously-unmapped-languages",
|
||||||
|
),
|
||||||
pytest.param(
|
pytest.param(
|
||||||
"aze_cyrl+srp_latn",
|
"aze_cyrl+srp_latn",
|
||||||
["az-Cyrl", "sr-Latn"],
|
["az-Cyrl", "sr-Latn"],
|
||||||
@@ -49,6 +54,19 @@ def test_ocr_to_dateparser_languages(ocr_language: str, expected: list[str]) ->
|
|||||||
assert sorted(ocr_to_dateparser_languages(ocr_language)) == sorted(expected)
|
assert sorted(ocr_to_dateparser_languages(ocr_language)) == sorted(expected)
|
||||||
|
|
||||||
|
|
||||||
|
def test_ocr_to_dateparser_map_values_supported_by_dateparser() -> None:
|
||||||
|
from dateparser.languages.loader import LocaleDataLoader
|
||||||
|
|
||||||
|
loader = LocaleDataLoader()
|
||||||
|
unsupported = []
|
||||||
|
for ocr_code, dateparser_code in utils.OCR_TO_DATEPARSER_LANGUAGES.items():
|
||||||
|
try:
|
||||||
|
loader.get_locale_map(locales=[dateparser_code])
|
||||||
|
except Exception:
|
||||||
|
unsupported.append((ocr_code, dateparser_code))
|
||||||
|
assert unsupported == []
|
||||||
|
|
||||||
|
|
||||||
def test_ocr_to_dateparser_languages_exception(
|
def test_ocr_to_dateparser_languages_exception(
|
||||||
monkeypatch: pytest.MonkeyPatch,
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
caplog: pytest.LogCaptureFixture,
|
caplog: pytest.LogCaptureFixture,
|
||||||
|
|||||||
+16
-16
@@ -2,19 +2,18 @@ import logging
|
|||||||
|
|
||||||
logger = logging.getLogger("paperless.utils")
|
logger = logging.getLogger("paperless.utils")
|
||||||
|
|
||||||
|
# Translation map from languages supported by Tesseract OCR
|
||||||
|
# to languages supported by dateparser.
|
||||||
|
# To add a language, make sure it is supported by both libraries.
|
||||||
|
# The ISO 639-2 will help you link a 3-char to 2-char language code.
|
||||||
|
# Links:
|
||||||
|
# - Tesseract languages: https://tesseract-ocr.github.io/tessdoc/Data-Files-in-different-versions.html
|
||||||
|
# - Python dateparser languages: https://dateparser.readthedocs.io/en/latest/supported_locales.html
|
||||||
|
# - ISO 639-2: https://www.loc.gov/standards/iso639-2/php/code_list.php
|
||||||
OCR_TO_DATEPARSER_LANGUAGES = {
|
OCR_TO_DATEPARSER_LANGUAGES = {
|
||||||
"""
|
# These dateparser languages have no equivalent in any Tesseract release
|
||||||
Translation map from languages supported by Tesseract OCR
|
# (checked against tessdata, tessdata_best and tessdata_fast), so they cannot
|
||||||
to languages supported by dateparser.
|
# be reached from the OCR language. Set PAPERLESS_DATE_PARSER_LANGUAGES to use them:
|
||||||
To add a language, make sure it is supported by both libraries.
|
|
||||||
The ISO 639-2 will help you link a 3-char to 2-char language code.
|
|
||||||
Links:
|
|
||||||
- Tesseract languages: https://tesseract-ocr.github.io/tessdoc/Data-Files-in-different-versions.html
|
|
||||||
- Python dateparser languages: https://dateparser.readthedocs.io/en/latest/supported_locales.html
|
|
||||||
- ISO 639-2: https://www.loc.gov/standards/iso639-2/php/code_list.php
|
|
||||||
"""
|
|
||||||
# TODO check these Dateparser languages as they are not referenced on the ISO639-2 standard,
|
|
||||||
# so we didn't find the equivalent in Tesseract:
|
|
||||||
# agq, asa, bez, brx, cgg, ckb, dav, dje, dyo, ebu, guz, jgo, jmc, kde, kea, khq, kln,
|
# agq, asa, bez, brx, cgg, ckb, dav, dje, dyo, ebu, guz, jgo, jmc, kde, kea, khq, kln,
|
||||||
# ksb, ksf, ksh, lag, lkt, lrc, luy, mer, mfe, mgh, mgo, mua, mzn, naq, nmg, nnh, nus,
|
# ksb, ksf, ksh, lag, lkt, lrc, luy, mer, mfe, mgh, mgo, mua, mzn, naq, nmg, nnh, nus,
|
||||||
# rof, rwk, saq, sbp, she, ses, shi, teo, twq, tzm, vun, wae, xog, yav, yue
|
# rof, rwk, saq, sbp, she, ses, shi, teo, twq, tzm, vun, wae, xog, yav, yue
|
||||||
@@ -22,7 +21,6 @@ OCR_TO_DATEPARSER_LANGUAGES = {
|
|||||||
"amh": "am",
|
"amh": "am",
|
||||||
"ara": "ar",
|
"ara": "ar",
|
||||||
"asm": "as",
|
"asm": "as",
|
||||||
"ast": "ast",
|
|
||||||
"aze": "az",
|
"aze": "az",
|
||||||
"bel": "be",
|
"bel": "be",
|
||||||
"bul": "bg",
|
"bul": "bg",
|
||||||
@@ -31,7 +29,7 @@ OCR_TO_DATEPARSER_LANGUAGES = {
|
|||||||
"bre": "br",
|
"bre": "br",
|
||||||
"bos": "bs",
|
"bos": "bs",
|
||||||
"cat": "ca",
|
"cat": "ca",
|
||||||
"cher": "chr",
|
"chr": "chr",
|
||||||
"ces": "cs",
|
"ces": "cs",
|
||||||
"cym": "cy",
|
"cym": "cy",
|
||||||
"dan": "da",
|
"dan": "da",
|
||||||
@@ -65,19 +63,21 @@ OCR_TO_DATEPARSER_LANGUAGES = {
|
|||||||
"kat": "ka",
|
"kat": "ka",
|
||||||
"kaz": "kk",
|
"kaz": "kk",
|
||||||
"khm": "km",
|
"khm": "km",
|
||||||
"knda": "kn",
|
"kan": "kn",
|
||||||
"kor": "ko",
|
"kor": "ko",
|
||||||
"kir": "ky",
|
"kir": "ky",
|
||||||
"ltz": "lb",
|
"ltz": "lb",
|
||||||
"lao": "lo",
|
"lao": "lo",
|
||||||
"lit": "lt",
|
"lit": "lt",
|
||||||
"lav": "lv",
|
"lav": "lv",
|
||||||
|
"mkd": "mk",
|
||||||
"mal": "ml",
|
"mal": "ml",
|
||||||
"mon": "mn",
|
"mon": "mn",
|
||||||
"mar": "mr",
|
"mar": "mr",
|
||||||
"msa": "ms",
|
"msa": "ms",
|
||||||
"mlt": "mt",
|
"mlt": "mt",
|
||||||
"mya": "my",
|
"mya": "my",
|
||||||
|
"nor": "nb",
|
||||||
"nep": "ne",
|
"nep": "ne",
|
||||||
"nld": "nl",
|
"nld": "nl",
|
||||||
"ori": "or",
|
"ori": "or",
|
||||||
@@ -106,7 +106,7 @@ OCR_TO_DATEPARSER_LANGUAGES = {
|
|||||||
"ukr": "uk",
|
"ukr": "uk",
|
||||||
"urd": "ur",
|
"urd": "ur",
|
||||||
"uzb": "uz",
|
"uzb": "uz",
|
||||||
"via": "vi",
|
"vie": "vi", # codespell:ignore
|
||||||
"yid": "yi",
|
"yid": "yi",
|
||||||
"yor": "yo",
|
"yor": "yo",
|
||||||
"chi": "zh",
|
"chi": "zh",
|
||||||
|
|||||||
+37
-46
@@ -893,8 +893,6 @@ class MailAccountHandler(LoggingMixin):
|
|||||||
def _handle_message(self, message, rule: MailRule) -> int:
|
def _handle_message(self, message, rule: MailRule) -> int:
|
||||||
message = self._preprocess_message(message)
|
message = self._preprocess_message(message)
|
||||||
|
|
||||||
processed_elements = 0
|
|
||||||
|
|
||||||
# Skip Message handling when only attachments are to be processed but
|
# Skip Message handling when only attachments are to be processed but
|
||||||
# message doesn't have any.
|
# message doesn't have any.
|
||||||
if (
|
if (
|
||||||
@@ -902,7 +900,7 @@ class MailAccountHandler(LoggingMixin):
|
|||||||
and rule.consumption_scope == MailRule.ConsumptionScope.ATTACHMENTS_ONLY
|
and rule.consumption_scope == MailRule.ConsumptionScope.ATTACHMENTS_ONLY
|
||||||
):
|
):
|
||||||
self._record_processed_without_consumption(message, rule)
|
self._record_processed_without_consumption(message, rule)
|
||||||
return processed_elements
|
return 0
|
||||||
|
|
||||||
self.log.debug(
|
self.log.debug(
|
||||||
f"Rule {rule}: "
|
f"Rule {rule}: "
|
||||||
@@ -913,29 +911,47 @@ class MailAccountHandler(LoggingMixin):
|
|||||||
tag_ids: list[int] = [tag.id for tag in rule.assign_tags.all()]
|
tag_ids: list[int] = [tag.id for tag in rule.assign_tags.all()]
|
||||||
doc_type = rule.assign_document_type
|
doc_type = rule.assign_document_type
|
||||||
|
|
||||||
|
consume_tasks: list[Signature] = []
|
||||||
|
|
||||||
if (
|
if (
|
||||||
rule.consumption_scope == MailRule.ConsumptionScope.EML_ONLY
|
rule.consumption_scope == MailRule.ConsumptionScope.EML_ONLY
|
||||||
or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING
|
or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING
|
||||||
):
|
):
|
||||||
processed_elements += self._process_eml(
|
consume_tasks.append(
|
||||||
message,
|
self._build_eml_task(
|
||||||
rule,
|
message,
|
||||||
tag_ids,
|
rule,
|
||||||
doc_type,
|
tag_ids,
|
||||||
|
doc_type,
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
if (
|
if (
|
||||||
rule.consumption_scope == MailRule.ConsumptionScope.ATTACHMENTS_ONLY
|
rule.consumption_scope == MailRule.ConsumptionScope.ATTACHMENTS_ONLY
|
||||||
or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING
|
or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING
|
||||||
):
|
):
|
||||||
processed_elements += self._process_attachments(
|
consume_tasks.extend(
|
||||||
message,
|
self._build_attachment_tasks(
|
||||||
rule,
|
message,
|
||||||
tag_ids,
|
rule,
|
||||||
doc_type,
|
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(
|
def _record_processed_without_consumption(
|
||||||
self,
|
self,
|
||||||
@@ -994,16 +1010,14 @@ class MailAccountHandler(LoggingMixin):
|
|||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _process_attachments(
|
def _build_attachment_tasks(
|
||||||
self,
|
self,
|
||||||
message: MailMessage,
|
message: MailMessage,
|
||||||
rule: MailRule,
|
rule: MailRule,
|
||||||
tag_ids,
|
tag_ids,
|
||||||
doc_type,
|
doc_type,
|
||||||
):
|
) -> list[Signature]:
|
||||||
processed_attachments = 0
|
consume_tasks: list[Signature] = []
|
||||||
|
|
||||||
consume_tasks = []
|
|
||||||
|
|
||||||
for att in message.attachments:
|
for att in message.attachments:
|
||||||
if (
|
if (
|
||||||
@@ -1104,8 +1118,6 @@ class MailAccountHandler(LoggingMixin):
|
|||||||
)
|
)
|
||||||
|
|
||||||
consume_tasks.append(consume_task)
|
consume_tasks.append(consume_task)
|
||||||
|
|
||||||
processed_attachments += 1
|
|
||||||
else:
|
else:
|
||||||
self.log.debug(
|
self.log.debug(
|
||||||
f"Rule {rule}: "
|
f"Rule {rule}: "
|
||||||
@@ -1114,26 +1126,15 @@ class MailAccountHandler(LoggingMixin):
|
|||||||
f"by paperless",
|
f"by paperless",
|
||||||
)
|
)
|
||||||
|
|
||||||
if len(consume_tasks) > 0:
|
return consume_tasks
|
||||||
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 processed_attachments
|
def _build_eml_task(
|
||||||
|
|
||||||
def _process_eml(
|
|
||||||
self,
|
self,
|
||||||
message: MailMessage,
|
message: MailMessage,
|
||||||
rule: MailRule,
|
rule: MailRule,
|
||||||
tag_ids,
|
tag_ids,
|
||||||
doc_type,
|
doc_type,
|
||||||
):
|
) -> Signature:
|
||||||
settings.SCRATCH_DIR.mkdir(parents=True, exist_ok=True)
|
settings.SCRATCH_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
_, temp_filename = tempfile.mkstemp(
|
_, temp_filename = tempfile.mkstemp(
|
||||||
prefix="paperless-mail-",
|
prefix="paperless-mail-",
|
||||||
@@ -1191,17 +1192,7 @@ class MailAccountHandler(LoggingMixin):
|
|||||||
owner_id=rule.owner.id if rule.owner else None,
|
owner_id=rule.owner.id if rule.owner else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
consume_task = consume_file.s(
|
return consume_file.s(
|
||||||
input_doc=input_doc,
|
input_doc=input_doc,
|
||||||
overrides=doc_overrides,
|
overrides=doc_overrides,
|
||||||
).set(headers={"trigger_source": PaperlessTask.TriggerSource.EMAIL_CONSUME})
|
).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,
|
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:
|
def test_handle_empty_message_long_subject(self) -> None:
|
||||||
"""
|
"""
|
||||||
GIVEN:
|
GIVEN:
|
||||||
|
|||||||
@@ -272,8 +272,6 @@ class TestMailMessageGpgDecryptor(TestMail):
|
|||||||
"override_title": message.subject,
|
"override_title": message.subject,
|
||||||
"override_filename": f"{message.subject}.eml",
|
"override_filename": f"{message.subject}.eml",
|
||||||
},
|
},
|
||||||
],
|
|
||||||
[
|
|
||||||
{"override_title": "file_0", "override_filename": "file_0.pdf"},
|
{"override_title": "file_0", "override_filename": "file_0.pdf"},
|
||||||
{"override_title": "file_1", "override_filename": "file_1.pdf"},
|
{"override_title": "file_1", "override_filename": "file_1.pdf"},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -2516,6 +2516,7 @@ dependencies = [
|
|||||||
{ name = "channels" },
|
{ name = "channels" },
|
||||||
{ name = "channels-redis" },
|
{ name = "channels-redis" },
|
||||||
{ name = "concurrent-log-handler" },
|
{ name = "concurrent-log-handler" },
|
||||||
|
{ name = "cryptography" },
|
||||||
{ name = "dateparser" },
|
{ name = "dateparser" },
|
||||||
{ name = "django" },
|
{ name = "django" },
|
||||||
{ name = "django-allauth", extra = ["mfa", "socialaccount"] },
|
{ name = "django-allauth", extra = ["mfa", "socialaccount"] },
|
||||||
@@ -2537,6 +2538,7 @@ dependencies = [
|
|||||||
{ name = "flower" },
|
{ name = "flower" },
|
||||||
{ name = "gotenberg-client", extra = ["httpx"] },
|
{ name = "gotenberg-client", extra = ["httpx"] },
|
||||||
{ name = "httpx-oauth" },
|
{ name = "httpx-oauth" },
|
||||||
|
{ name = "humanize" },
|
||||||
{ name = "ijson" },
|
{ name = "ijson" },
|
||||||
{ name = "imap-tools" },
|
{ name = "imap-tools" },
|
||||||
{ name = "jinja2" },
|
{ name = "jinja2" },
|
||||||
@@ -2547,10 +2549,13 @@ dependencies = [
|
|||||||
{ name = "llama-index-embeddings-openai-like" },
|
{ name = "llama-index-embeddings-openai-like" },
|
||||||
{ name = "llama-index-llms-ollama" },
|
{ name = "llama-index-llms-ollama" },
|
||||||
{ name = "llama-index-llms-openai-like" },
|
{ name = "llama-index-llms-openai-like" },
|
||||||
|
{ name = "lxml" },
|
||||||
{ name = "ocrmypdf", extra = ["heic"] },
|
{ name = "ocrmypdf", extra = ["heic"] },
|
||||||
|
{ name = "ollama" },
|
||||||
{ name = "openai" },
|
{ name = "openai" },
|
||||||
{ name = "pathvalidate" },
|
{ name = "pathvalidate" },
|
||||||
{ name = "pdf2image" },
|
{ name = "pdf2image" },
|
||||||
|
{ name = "pikepdf" },
|
||||||
{ name = "python-dateutil" },
|
{ name = "python-dateutil" },
|
||||||
{ name = "python-dotenv" },
|
{ name = "python-dotenv" },
|
||||||
{ name = "python-gnupg" },
|
{ name = "python-gnupg" },
|
||||||
@@ -2668,6 +2673,7 @@ requires-dist = [
|
|||||||
{ name = "channels", specifier = "~=4.2" },
|
{ name = "channels", specifier = "~=4.2" },
|
||||||
{ name = "channels-redis", specifier = "~=4.2" },
|
{ name = "channels-redis", specifier = "~=4.2" },
|
||||||
{ name = "concurrent-log-handler", specifier = "~=0.9.25" },
|
{ name = "concurrent-log-handler", specifier = "~=0.9.25" },
|
||||||
|
{ name = "cryptography", specifier = ">=50.0.0" },
|
||||||
{ name = "dateparser", specifier = "~=1.4" },
|
{ name = "dateparser", specifier = "~=1.4" },
|
||||||
{ name = "django", specifier = "~=5.2.18" },
|
{ name = "django", specifier = "~=5.2.18" },
|
||||||
{ name = "django-allauth", extras = ["mfa", "socialaccount"], specifier = "~=65.21.1" },
|
{ name = "django-allauth", extras = ["mfa", "socialaccount"], specifier = "~=65.21.1" },
|
||||||
@@ -2690,6 +2696,7 @@ requires-dist = [
|
|||||||
{ name = "gotenberg-client", extras = ["httpx"], specifier = "~=1.0" },
|
{ name = "gotenberg-client", extras = ["httpx"], specifier = "~=1.0" },
|
||||||
{ name = "granian", extras = ["uvloop"], marker = "extra == 'webserver'", specifier = ">=2.7,<2.9" },
|
{ name = "granian", extras = ["uvloop"], marker = "extra == 'webserver'", specifier = ">=2.7,<2.9" },
|
||||||
{ name = "httpx-oauth", specifier = "~=0.17" },
|
{ name = "httpx-oauth", specifier = "~=0.17" },
|
||||||
|
{ name = "humanize", specifier = ">=4.15.0" },
|
||||||
{ name = "ijson", specifier = ">=3.5.1" },
|
{ name = "ijson", specifier = ">=3.5.1" },
|
||||||
{ name = "imap-tools", specifier = ">=1.14,<1.16" },
|
{ name = "imap-tools", specifier = ">=1.14,<1.16" },
|
||||||
{ name = "jinja2", specifier = "~=3.1.6" },
|
{ name = "jinja2", specifier = "~=3.1.6" },
|
||||||
@@ -2700,11 +2707,14 @@ requires-dist = [
|
|||||||
{ name = "llama-index-embeddings-openai-like", specifier = ">=0.2.2" },
|
{ name = "llama-index-embeddings-openai-like", specifier = ">=0.2.2" },
|
||||||
{ name = "llama-index-llms-ollama", specifier = ">=0.9.1" },
|
{ name = "llama-index-llms-ollama", specifier = ">=0.9.1" },
|
||||||
{ name = "llama-index-llms-openai-like", specifier = ">=0.7.1" },
|
{ name = "llama-index-llms-openai-like", specifier = ">=0.7.1" },
|
||||||
|
{ name = "lxml", specifier = ">=6.1.0" },
|
||||||
{ name = "mysqlclient", marker = "extra == 'mariadb'", specifier = ">=2.2.7,<2.4" },
|
{ name = "mysqlclient", marker = "extra == 'mariadb'", specifier = ">=2.2.7,<2.4" },
|
||||||
{ name = "ocrmypdf", extras = ["heic"], specifier = ">=17.12,<17.13" },
|
{ name = "ocrmypdf", extras = ["heic"], specifier = ">=17.12,<17.13" },
|
||||||
|
{ name = "ollama", specifier = ">=0.6.1" },
|
||||||
{ name = "openai", specifier = ">=2.48" },
|
{ name = "openai", specifier = ">=2.48" },
|
||||||
{ name = "pathvalidate", specifier = "~=3.3.1" },
|
{ name = "pathvalidate", specifier = "~=3.3.1" },
|
||||||
{ name = "pdf2image", specifier = "~=1.17.0" },
|
{ name = "pdf2image", specifier = "~=1.17.0" },
|
||||||
|
{ name = "pikepdf", specifier = ">=10.13" },
|
||||||
{ name = "psycopg", extras = ["c", "pool"], marker = "extra == 'postgres'", specifier = "==3.3.8" },
|
{ name = "psycopg", extras = ["c", "pool"], marker = "extra == 'postgres'", specifier = "==3.3.8" },
|
||||||
{ name = "psycopg-c", marker = "python_full_version == '3.12.*' and platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'postgres'", url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp312-cp312-manylinux_2_38_aarch64.whl" },
|
{ name = "psycopg-c", marker = "python_full_version == '3.12.*' and platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'postgres'", url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp312-cp312-manylinux_2_38_aarch64.whl" },
|
||||||
{ name = "psycopg-c", marker = "python_full_version == '3.14.*' and platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'postgres'", url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp314-cp314-manylinux_2_38_aarch64.whl" },
|
{ name = "psycopg-c", marker = "python_full_version == '3.14.*' and platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'postgres'", url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp314-cp314-manylinux_2_38_aarch64.whl" },
|
||||||
|
|||||||
Reference in new issue
Block a user