Compare commits

..
Author SHA1 Message Date
Trenton H 7f80f4608c Fix: close the temp file descriptor when saving mail as eml 2026-11-26 14:07:12 -08:00
3 changed files with 34 additions and 14 deletions

No files matched your search

+21 -10
View File
@@ -6,6 +6,7 @@ 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
@@ -896,25 +897,26 @@ 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():
with TemporaryDirectory(dir=settings.SCRATCH_DIR) as tmp_dir: final_path.unlink()
temp_zip_path = Path(tmp_dir) / "bundle.zip" shutil.move(temp_zip_path, final_path)
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
@@ -945,7 +947,16 @@ 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
+10 -2
View File
@@ -434,9 +434,13 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
"documents.tasks.OriginalsOnlyStrategy.add_document", "documents.tasks.OriginalsOnlyStrategy.add_document",
side_effect=RuntimeError("zip failure"), side_effect=RuntimeError("zip failure"),
), ),
self.assertRaises(RuntimeError), mock.patch("pathlib.Path.unlink") as unlink_mock,
): ):
build_share_link_bundle(bundle.pk) unlink_mock.side_effect = [OSError("unlink"), OSError("unlink-finally")] + [
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)
@@ -444,6 +448,10 @@ 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
+3 -2
View File
@@ -2,6 +2,7 @@ import datetime
import imaplib import imaplib
import itertools import itertools
import logging import logging
import os
import socket import socket
import ssl import ssl
import tempfile import tempfile
@@ -1135,12 +1136,12 @@ class MailAccountHandler(LoggingMixin):
doc_type, doc_type,
): ):
settings.SCRATCH_DIR.mkdir(parents=True, exist_ok=True) settings.SCRATCH_DIR.mkdir(parents=True, exist_ok=True)
_, temp_filename = tempfile.mkstemp( fd, temp_filename = tempfile.mkstemp(
prefix="paperless-mail-", prefix="paperless-mail-",
dir=settings.SCRATCH_DIR, dir=settings.SCRATCH_DIR,
suffix=".eml", suffix=".eml",
) )
with Path(temp_filename).open("wb") as f: with os.fdopen(fd, "wb") as f:
# Move "From"-header to beginning of file # Move "From"-header to beginning of file
# TODO: This ugly workaround is needed because the parser is # TODO: This ugly workaround is needed because the parser is
# chosen only by the mime_type detected via magic # chosen only by the mime_type detected via magic