mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-11-30 08:35:24 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b150c1292 | ||
|
|
f895fd369e | ||
|
|
416161dd1e | ||
|
|
afa722ba95 | ||
|
|
b1d06e1b18 | ||
|
|
641bb83860 | ||
|
|
d35c6e6e97 | ||
|
|
8b80913d3d | ||
|
|
51822d6273 |
No files matched your search
+14
-23
@@ -11,10 +11,12 @@ from typing import Final
|
||||
import magic
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import User
|
||||
from django.core.exceptions import ValidationError as DjangoValidationError
|
||||
from django.db import transaction
|
||||
from django.db.models import Max
|
||||
from django.db.models import Q
|
||||
from django.utils import timezone
|
||||
from filelock import FileLock
|
||||
from rest_framework.reverse import reverse
|
||||
|
||||
from documents.barcodes import read_barcode_values
|
||||
@@ -26,10 +28,7 @@ from documents.file_handling import create_source_path_directory
|
||||
from documents.file_handling import generate_filename
|
||||
from documents.file_handling import generate_unique_filename
|
||||
from documents.file_handling import validate_path_in_root
|
||||
from documents.file_moves import defer_file_moves
|
||||
from documents.file_moves import flush_pending_file_moves
|
||||
from documents.loggers import LoggingMixin
|
||||
from documents.media_lock import media_lock
|
||||
from documents.models import Correspondent
|
||||
from documents.models import CustomField
|
||||
from documents.models import CustomFieldInstance
|
||||
@@ -625,13 +624,7 @@ class ConsumerPlugin(
|
||||
# now that everything is done, we can start to store the document
|
||||
# in the system. This will be a transaction and reasonably fast.
|
||||
try:
|
||||
# File moves requested in here run after commit and after
|
||||
# media.lock is released. media.lock is taken before the
|
||||
# transaction: the version path locks the root row with
|
||||
# select_for_update, and workflow email actions and file
|
||||
# placement below re-enter media.lock instead of waiting
|
||||
# on it while rows are locked.
|
||||
with defer_file_moves(), media_lock(), transaction.atomic():
|
||||
with transaction.atomic():
|
||||
# store the document.
|
||||
if self.input_doc.root_document_id:
|
||||
# If this is a new version of an existing document, we need
|
||||
@@ -722,7 +715,7 @@ class ConsumerPlugin(
|
||||
|
||||
# After everything is in the database, copy the files into
|
||||
# place. If this fails, we'll also rollback the transaction.
|
||||
with media_lock():
|
||||
with FileLock(settings.MEDIA_LOCK):
|
||||
generated_filename = generate_unique_filename(document)
|
||||
if (
|
||||
len(str(generated_filename))
|
||||
@@ -786,9 +779,10 @@ class ConsumerPlugin(
|
||||
document.archive_path,
|
||||
)
|
||||
|
||||
# Any filename follow-up from this save is deferred by
|
||||
# the scope above until after commit.
|
||||
document.save(write_file_paths=True)
|
||||
# Don't save with the lock active. Saving will cause the file
|
||||
# renaming logic to acquire the lock as well.
|
||||
# This triggers things like file renaming
|
||||
document.save()
|
||||
|
||||
if document.root_document_id:
|
||||
document_updated.send(
|
||||
@@ -829,11 +823,6 @@ class ConsumerPlugin(
|
||||
exception=e,
|
||||
)
|
||||
|
||||
# The storage scope above nests under the consume task's scope, so its
|
||||
# moves are still pending; place the file before the script reads its path.
|
||||
flush_pending_file_moves()
|
||||
document.refresh_from_db()
|
||||
|
||||
self.run_post_consume_script(document)
|
||||
|
||||
self.log.info(f"Document {document} consumption finished")
|
||||
@@ -846,6 +835,9 @@ class ConsumerPlugin(
|
||||
document.id,
|
||||
)
|
||||
|
||||
# Return the most up to date fields
|
||||
document.refresh_from_db()
|
||||
|
||||
return ConsumeFileSuccessResult(document_id=document.pk)
|
||||
|
||||
def _parse_title_placeholders(self, title: str) -> str:
|
||||
@@ -1282,10 +1274,9 @@ class AsnCheckPlugin(
|
||||
return
|
||||
# Validate the range is above zero and less than uint32_t max
|
||||
# otherwise, Whoosh can't handle it in the index
|
||||
if (
|
||||
self.metadata.asn < Document.ARCHIVE_SERIAL_NUMBER_MIN
|
||||
or self.metadata.asn > Document.ARCHIVE_SERIAL_NUMBER_MAX
|
||||
):
|
||||
try:
|
||||
Document.validate_archive_serial_number(self.metadata.asn)
|
||||
except DjangoValidationError:
|
||||
self._fail(
|
||||
ConsumerStatusShortMessage.ASN_RANGE,
|
||||
f"Not consuming {self.filename}: "
|
||||
|
||||
@@ -1,480 +0,0 @@
|
||||
"""
|
||||
Document file moves, coalesced to once per unit of work.
|
||||
|
||||
Every save that can change a document's generated filename asks for a file
|
||||
move through request_file_move(). Inside a scope opened by defer_file_moves()
|
||||
(a request, a Celery task, the consumer, or a per-item command step) the
|
||||
request is only recorded, and the outermost scope moves each recorded document
|
||||
once, after its own writes have committed. Outside any scope the move happens
|
||||
immediately.
|
||||
|
||||
The mover always takes media.lock first and then reads the document fresh, so
|
||||
it starts from the latest committed state and never waits on media.lock while
|
||||
its own transaction holds document rows.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import shutil
|
||||
import threading
|
||||
from contextlib import asynccontextmanager
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import Final
|
||||
|
||||
from asgiref.sync import sync_to_async
|
||||
from django.conf import settings
|
||||
from django.db import DatabaseError
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
from filelock import Timeout
|
||||
|
||||
from documents.caching import clear_document_caches
|
||||
from documents.file_handling import create_source_path_directory
|
||||
from documents.file_handling import delete_empty_directories
|
||||
from documents.file_handling import generate_filename
|
||||
from documents.file_handling import generate_unique_filename
|
||||
from documents.media_lock import media_lock
|
||||
from documents.models import Document
|
||||
from documents.utils import compute_checksum
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import AsyncIterator
|
||||
from collections.abc import Iterator
|
||||
|
||||
logger = logging.getLogger("paperless.handlers")
|
||||
|
||||
MEDIA_LOCK_TIMEOUT_SECONDS: Final[int] = 300
|
||||
|
||||
|
||||
class CannotMoveFilesException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def in_user_transaction() -> bool:
|
||||
"""
|
||||
True when the default connection is inside an atomic block that was not
|
||||
created by Django's test case machinery.
|
||||
|
||||
Django marks the atomic blocks TestCase (and pytest-django) wrap around
|
||||
each test with _from_testcase. Ignoring them keeps tests on the same path
|
||||
as production.
|
||||
"""
|
||||
connection = transaction.get_connection()
|
||||
return any(not block._from_testcase for block in connection.atomic_blocks)
|
||||
|
||||
|
||||
class FileMoveCollector:
|
||||
"""Pending document pks for one file move scope."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._pending: set[int] = set()
|
||||
self._lock = threading.Lock()
|
||||
self.closed = False
|
||||
|
||||
def add(self, pk: int) -> bool:
|
||||
"""Record a pending move. Returns False if the collector is closed."""
|
||||
with self._lock:
|
||||
if self.closed:
|
||||
return False
|
||||
self._pending.add(pk)
|
||||
return True
|
||||
|
||||
def take_pending(self) -> list[int]:
|
||||
"""Remove and return the pending pks, sorted, leaving the collector open."""
|
||||
with self._lock:
|
||||
pending = sorted(self._pending)
|
||||
self._pending.clear()
|
||||
return pending
|
||||
|
||||
def close(self) -> list[int]:
|
||||
"""Close the collector and return what was still pending, sorted."""
|
||||
with self._lock:
|
||||
self.closed = True
|
||||
pending = sorted(self._pending)
|
||||
self._pending.clear()
|
||||
return pending
|
||||
|
||||
|
||||
# Only the scope context managers call set() / reset(). Everything else reads
|
||||
# it and mutates the collector, so adds made in a copied context (thread or
|
||||
# task hops) are visible to the scope that flushes.
|
||||
_active_collector: ContextVar[FileMoveCollector | None] = ContextVar(
|
||||
"paperless_file_move_collector",
|
||||
default=None,
|
||||
)
|
||||
|
||||
|
||||
def _path_matches_checksum(path: Path, checksum: str | None) -> bool:
|
||||
if checksum is None or not path.is_file():
|
||||
return False
|
||||
|
||||
return compute_checksum(path) == checksum
|
||||
|
||||
|
||||
def move_files_for_document(pk: int) -> Document | None:
|
||||
"""
|
||||
Move the document's original and archive to the paths its current
|
||||
committed state generates, then do the same for its versions.
|
||||
|
||||
Returns the fresh instance with its final filename columns, or None when
|
||||
the document does not exist, has no filename yet, or the lock timed out.
|
||||
"""
|
||||
# Cheap check without the lock: most saves during consumption happen
|
||||
# before the file is placed. filename is never cleared once set, so this
|
||||
# stays true under the lock. values_list() keeps the check off
|
||||
# Document.global_objects.filter(), which tests patch to inject database
|
||||
# errors into and observe the mover's own writes.
|
||||
filename = (
|
||||
Document.global_objects.values_list("filename", flat=True).filter(pk=pk).first()
|
||||
)
|
||||
if not filename:
|
||||
return None
|
||||
|
||||
try:
|
||||
with media_lock(timeout=MEDIA_LOCK_TIMEOUT_SECONDS):
|
||||
try:
|
||||
document = Document.global_objects.get(pk=pk)
|
||||
except Document.DoesNotExist:
|
||||
logger.debug(f"Document {pk} no longer exists, skipping file move")
|
||||
return None
|
||||
_move_document_files(document)
|
||||
except Timeout:
|
||||
logger.error(
|
||||
f"Timed out after {MEDIA_LOCK_TIMEOUT_SECONDS}s waiting for "
|
||||
f"{settings.MEDIA_LOCK} to move files of document {pk}; the file "
|
||||
f"keeps its current name and will be renamed on its next save",
|
||||
)
|
||||
return None
|
||||
|
||||
# Keep version files in sync with root
|
||||
if document.root_document_id is None:
|
||||
version_pks = list(
|
||||
Document.global_objects.values_list("pk", flat=True).filter(
|
||||
root_document_id=pk,
|
||||
),
|
||||
)
|
||||
for version_pk in version_pks:
|
||||
move_files_for_document(version_pk)
|
||||
|
||||
return document
|
||||
|
||||
|
||||
def _flush(pks: list[int]) -> None:
|
||||
"""Move each document; one failure never stops the rest or raises."""
|
||||
for pk in pks:
|
||||
try:
|
||||
move_files_for_document(pk)
|
||||
except Exception:
|
||||
logger.exception(f"Unexpected error moving files of document {pk}")
|
||||
|
||||
|
||||
def _flush_after_commit(pks: list[int]) -> None:
|
||||
if not pks:
|
||||
return
|
||||
if in_user_transaction():
|
||||
transaction.on_commit(lambda: _flush(pks))
|
||||
else:
|
||||
_flush(pks)
|
||||
|
||||
|
||||
def _close_and_flush(collector: FileMoveCollector) -> None:
|
||||
_flush_after_commit(collector.close())
|
||||
|
||||
|
||||
@contextmanager
|
||||
def defer_file_moves() -> Iterator[None]:
|
||||
"""
|
||||
Collect file move requests and perform each once when the outermost scope
|
||||
exits, after its own writes have committed.
|
||||
"""
|
||||
current = _active_collector.get()
|
||||
if current is not None and not current.closed:
|
||||
yield
|
||||
return
|
||||
|
||||
collector = FileMoveCollector()
|
||||
token = _active_collector.set(collector)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_active_collector.reset(token)
|
||||
_close_and_flush(collector)
|
||||
|
||||
|
||||
def flush_pending_file_moves() -> None:
|
||||
"""
|
||||
Perform the current scope's pending moves now, keeping the scope open.
|
||||
|
||||
From an eager task inside a request this flushes the request's collector
|
||||
early, which is harmless: moves still run after commit, on fresh state.
|
||||
"""
|
||||
collector = _active_collector.get()
|
||||
if collector is None:
|
||||
return
|
||||
_flush_after_commit(collector.take_pending())
|
||||
|
||||
|
||||
def _validate_move(
|
||||
document: Document,
|
||||
old_path: Path,
|
||||
new_path: Path,
|
||||
root: Path,
|
||||
) -> None:
|
||||
if not new_path.is_relative_to(root):
|
||||
msg = (
|
||||
f"Document {document!s}: Refusing to move file outside root {root}: "
|
||||
f"{new_path}."
|
||||
)
|
||||
logger.warning(msg)
|
||||
raise CannotMoveFilesException(msg)
|
||||
|
||||
if not old_path.is_file():
|
||||
# Can't do anything if the old file does not exist anymore.
|
||||
msg = f"Document {document!s}: File {old_path} doesn't exist."
|
||||
logger.fatal(msg)
|
||||
raise CannotMoveFilesException(msg)
|
||||
|
||||
if new_path.is_file():
|
||||
# Can't do anything if the new file already exists. Skip updating file.
|
||||
msg = f"Document {document!s}: Cannot rename file since target path {new_path} already exists."
|
||||
logger.warning(msg)
|
||||
raise CannotMoveFilesException(msg)
|
||||
|
||||
|
||||
def _move_document_files(document: Document) -> None:
|
||||
try:
|
||||
old_filename = document.filename
|
||||
old_source_path = document.source_path
|
||||
move_original = False
|
||||
original_already_moved = False
|
||||
original_moved = False
|
||||
|
||||
old_archive_filename = document.archive_filename
|
||||
old_archive_path = document.archive_path
|
||||
move_archive = False
|
||||
archive_already_moved = False
|
||||
archive_moved = False
|
||||
|
||||
candidate_filename = generate_filename(document)
|
||||
if len(str(candidate_filename)) > Document.MAX_STORED_FILENAME_LENGTH:
|
||||
msg = (
|
||||
f"Document {document!s}: Generated filename exceeds db path "
|
||||
f"limit ({len(str(candidate_filename))} > "
|
||||
f"{Document.MAX_STORED_FILENAME_LENGTH}): {candidate_filename!s}"
|
||||
)
|
||||
logger.warning(msg)
|
||||
raise CannotMoveFilesException(msg)
|
||||
|
||||
candidate_source_path = (settings.ORIGINALS_DIR / candidate_filename).resolve()
|
||||
if candidate_filename == Path(old_filename):
|
||||
new_filename = Path(old_filename)
|
||||
elif (
|
||||
candidate_source_path.exists() and candidate_source_path != old_source_path
|
||||
):
|
||||
if not old_source_path.is_file() and _path_matches_checksum(
|
||||
candidate_source_path,
|
||||
document.checksum,
|
||||
):
|
||||
new_filename = candidate_filename
|
||||
original_already_moved = True
|
||||
else:
|
||||
# Only fall back to unique search when there is an actual conflict
|
||||
new_filename = generate_unique_filename(document)
|
||||
else:
|
||||
new_filename = candidate_filename
|
||||
|
||||
# Need to convert to string to be able to save it to the db
|
||||
document.filename = str(new_filename)
|
||||
move_original = old_filename != document.filename and not original_already_moved
|
||||
|
||||
if document.has_archive_version:
|
||||
archive_candidate = generate_filename(document, archive_filename=True)
|
||||
if len(str(archive_candidate)) > Document.MAX_STORED_FILENAME_LENGTH:
|
||||
msg = (
|
||||
f"Document {document!s}: Generated archive filename exceeds "
|
||||
f"db path limit ({len(str(archive_candidate))} > "
|
||||
f"{Document.MAX_STORED_FILENAME_LENGTH}): {archive_candidate!s}"
|
||||
)
|
||||
logger.warning(msg)
|
||||
raise CannotMoveFilesException(msg)
|
||||
archive_candidate_path = (
|
||||
settings.ARCHIVE_DIR / archive_candidate
|
||||
).resolve()
|
||||
if archive_candidate == Path(old_archive_filename):
|
||||
new_archive_filename = Path(old_archive_filename)
|
||||
elif (
|
||||
archive_candidate_path.exists()
|
||||
and archive_candidate_path != old_archive_path
|
||||
):
|
||||
if not old_archive_path.is_file() and _path_matches_checksum(
|
||||
archive_candidate_path,
|
||||
document.archive_checksum,
|
||||
):
|
||||
new_archive_filename = archive_candidate
|
||||
archive_already_moved = True
|
||||
else:
|
||||
new_archive_filename = generate_unique_filename(
|
||||
document,
|
||||
archive_filename=True,
|
||||
)
|
||||
else:
|
||||
new_archive_filename = archive_candidate
|
||||
|
||||
document.archive_filename = str(new_archive_filename)
|
||||
|
||||
move_archive = (
|
||||
old_archive_filename != document.archive_filename
|
||||
and not archive_already_moved
|
||||
)
|
||||
else:
|
||||
move_archive = False
|
||||
|
||||
if not move_original and not move_archive:
|
||||
updates: dict[str, object] = {}
|
||||
if old_filename != document.filename:
|
||||
updates["filename"] = document.filename
|
||||
if old_archive_filename != document.archive_filename:
|
||||
updates["archive_filename"] = document.archive_filename
|
||||
if updates:
|
||||
# global_objects so a trashed document's path is fixed too.
|
||||
updates["modified"] = timezone.now()
|
||||
# Don't save() here to prevent infinite recursion.
|
||||
Document.global_objects.filter(pk=document.pk).update(**updates)
|
||||
return
|
||||
|
||||
if move_original:
|
||||
_validate_move(
|
||||
document,
|
||||
old_source_path,
|
||||
document.source_path,
|
||||
settings.ORIGINALS_DIR,
|
||||
)
|
||||
create_source_path_directory(document.source_path)
|
||||
shutil.move(old_source_path, document.source_path)
|
||||
original_moved = True
|
||||
|
||||
if move_archive:
|
||||
_validate_move(
|
||||
document,
|
||||
old_archive_path,
|
||||
document.archive_path,
|
||||
settings.ARCHIVE_DIR,
|
||||
)
|
||||
create_source_path_directory(document.archive_path)
|
||||
shutil.move(old_archive_path, document.archive_path)
|
||||
archive_moved = True
|
||||
|
||||
# Don't save() here to prevent infinite recursion.
|
||||
Document.global_objects.filter(pk=document.pk).update(
|
||||
filename=document.filename,
|
||||
archive_filename=document.archive_filename,
|
||||
modified=timezone.now(),
|
||||
)
|
||||
# Clear any caching for this document. Slightly overkill, but not terrible
|
||||
clear_document_caches(document.pk)
|
||||
|
||||
except (OSError, DatabaseError, CannotMoveFilesException) as e:
|
||||
logger.warning(f"Exception during file handling: {e}")
|
||||
# This happens when either:
|
||||
# - moving the files failed due to file system errors
|
||||
# - saving to the database failed due to database errors
|
||||
# In both cases, we need to revert to the original state.
|
||||
|
||||
# Try to move files to their original location.
|
||||
try:
|
||||
# Only undo moves this call made. A refused move leaves a file at
|
||||
# the target that is not ours, and moving it back would overwrite
|
||||
# the original.
|
||||
if original_moved and document.source_path.is_file():
|
||||
logger.info("Restoring previous original path")
|
||||
shutil.move(document.source_path, old_source_path)
|
||||
|
||||
if archive_moved and document.archive_path.is_file():
|
||||
logger.info("Restoring previous archive path")
|
||||
shutil.move(document.archive_path, old_archive_path)
|
||||
|
||||
except Exception:
|
||||
# This is fine, since:
|
||||
# A: if we managed to move source from A to B, we will also
|
||||
# manage to move it from B to A. If not, we have a serious
|
||||
# issue that's going to get caught by the santiy checker.
|
||||
# All files remain in place and will never be overwritten,
|
||||
# so this is not the end of the world.
|
||||
# B: if moving the original file failed, nothing has changed
|
||||
# anyway.
|
||||
pass
|
||||
|
||||
# restore old values on the document
|
||||
document.filename = old_filename
|
||||
document.archive_filename = old_archive_filename
|
||||
|
||||
# finally, remove any empty sub folders. This will do nothing if
|
||||
# something has failed above.
|
||||
if not old_source_path.is_file():
|
||||
delete_empty_directories(
|
||||
Path(old_source_path).parent,
|
||||
root=settings.ORIGINALS_DIR,
|
||||
)
|
||||
|
||||
if document.has_archive_version and not old_archive_path.is_file():
|
||||
delete_empty_directories(
|
||||
Path(old_archive_path).parent,
|
||||
root=settings.ARCHIVE_DIR,
|
||||
)
|
||||
|
||||
|
||||
def request_file_move(document: Document) -> None:
|
||||
"""
|
||||
Ask for the document's files to follow its committed state.
|
||||
|
||||
Inside an open scope the request is recorded and performed when the scope
|
||||
ends. Inside a user transaction with no scope it runs on commit. Otherwise
|
||||
the move happens now and only the final filename columns are copied onto
|
||||
the caller's instance, so source_path is current after save() while other
|
||||
in-memory fields are left alone.
|
||||
"""
|
||||
collector = _active_collector.get()
|
||||
if collector is not None and collector.add(document.pk):
|
||||
return
|
||||
|
||||
if in_user_transaction():
|
||||
# An enclosing transaction can still roll back the filename columns,
|
||||
# and the move would take media.lock while it holds document rows.
|
||||
# Wait for the commit, so the caller's instance keeps its old paths.
|
||||
pk = document.pk
|
||||
transaction.on_commit(lambda: _flush([pk]))
|
||||
return
|
||||
|
||||
moved = move_files_for_document(document.pk)
|
||||
if moved is not None:
|
||||
document.filename = moved.filename
|
||||
document.archive_filename = moved.archive_filename
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def adefer_file_moves() -> AsyncIterator[None]:
|
||||
"""
|
||||
Async twin of defer_file_moves().
|
||||
|
||||
When something was collected, the flush runs through sync_to_async: its
|
||||
transaction check needs the thread owning the DB connection, and the
|
||||
blocking media.lock must never run on the event loop.
|
||||
"""
|
||||
current = _active_collector.get()
|
||||
if current is not None and not current.closed:
|
||||
yield
|
||||
return
|
||||
|
||||
collector = FileMoveCollector()
|
||||
token = _active_collector.set(collector)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
_active_collector.reset(token)
|
||||
pks = collector.close()
|
||||
if pks:
|
||||
await sync_to_async(_flush_after_commit, thread_sensitive=True)(pks)
|
||||
+177
-24
@@ -6,13 +6,17 @@ import json
|
||||
import logging
|
||||
import operator
|
||||
from contextlib import contextmanager
|
||||
from datetime import UTC
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
from decimal import InvalidOperation
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import Any
|
||||
|
||||
from django import forms
|
||||
from django.conf import settings
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.db import models
|
||||
from django.db.models import Case
|
||||
from django.db.models import CharField
|
||||
from django.db.models import Count
|
||||
@@ -29,6 +33,7 @@ from django.db.models.functions import NullIf
|
||||
from django.utils import timezone
|
||||
from django.utils.translation import gettext_lazy as _
|
||||
from django_filters import DateFilter
|
||||
from django_filters.filterset import FILTER_FOR_DBFIELD_DEFAULTS
|
||||
from django_filters.rest_framework import BooleanFilter
|
||||
from django_filters.rest_framework import CharFilter
|
||||
from django_filters.rest_framework import DateTimeFilter
|
||||
@@ -61,6 +66,7 @@ from documents.versioning import annotate_effective_content
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Callable
|
||||
from collections.abc import Iterable
|
||||
from datetime import datetime
|
||||
|
||||
CHAR_KWARGS = ["istartswith", "iendswith", "icontains", "iexact"]
|
||||
@@ -95,7 +101,115 @@ CUSTOM_FIELD_QUERY_MAX_ATOMS = 20
|
||||
logger = logging.getLogger("paperless.api")
|
||||
|
||||
|
||||
class CorrespondentFilterSet(FilterSet):
|
||||
# The smallest and largest values a 64 bit integer column can hold. Nothing outside can
|
||||
# match a row, and handing it to the database raises an error on some backends.
|
||||
INT64_MIN = -(2**63)
|
||||
INT64_MAX = 2**63 - 1
|
||||
# SmallIntegerField and IntegerField columns, the same size on every supported database
|
||||
INT16_MIN = -(2**15)
|
||||
INT16_MAX = 2**15 - 1
|
||||
INT32_MIN = -(2**31)
|
||||
INT32_MAX = 2**31 - 1
|
||||
# Real UTC offsets run from -12:00 to +14:00, databases reject anything much larger.
|
||||
MAX_UTC_OFFSET = timedelta(hours=14)
|
||||
DATE_PART_BOUNDS = {"year": (1, 9999), "month": (1, 12), "day": (1, 31)}
|
||||
|
||||
|
||||
def in_id_range(value: int) -> bool:
|
||||
return INT64_MIN <= value <= INT64_MAX
|
||||
|
||||
|
||||
def in_range_ids(ids: Iterable[int]) -> list[int]:
|
||||
"""
|
||||
The ids a row could have. Any other id cannot match, and some databases raise an
|
||||
error instead of finding nothing when asked for one.
|
||||
"""
|
||||
return [i for i in ids if in_id_range(i)]
|
||||
|
||||
|
||||
class BoundedDecimalField(forms.DecimalField):
|
||||
"""
|
||||
django-filter only bounds numbers at 1e50, which is far past any integer column
|
||||
"""
|
||||
|
||||
def __init__(self, **kwargs: Any) -> None:
|
||||
kwargs.setdefault("min_value", INT64_MIN)
|
||||
kwargs.setdefault("max_value", INT64_MAX)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class BoundedNumberFilter(NumberFilter):
|
||||
field_class = BoundedDecimalField
|
||||
|
||||
|
||||
class BoundedIntegerField(forms.IntegerField):
|
||||
def __init__(self, **kwargs: Any) -> None:
|
||||
kwargs.setdefault("min_value", INT64_MIN)
|
||||
kwargs.setdefault("max_value", INT64_MAX)
|
||||
super().__init__(**kwargs)
|
||||
|
||||
|
||||
class BoundedDateTimeField(forms.DateTimeField):
|
||||
def clean(self, value: Any) -> Any:
|
||||
value = super().clean(value)
|
||||
if value is not None and timezone.is_aware(value):
|
||||
offset = value.utcoffset()
|
||||
if offset is not None and abs(offset) > MAX_UTC_OFFSET:
|
||||
raise forms.ValidationError(
|
||||
_("Enter a valid UTC offset."),
|
||||
code="invalid",
|
||||
)
|
||||
try:
|
||||
value.astimezone(UTC)
|
||||
except OverflowError:
|
||||
raise forms.ValidationError(
|
||||
_("Enter a valid date and time."),
|
||||
code="invalid",
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
class BoundedDateTimeFilter(DateTimeFilter):
|
||||
field_class = BoundedDateTimeField
|
||||
|
||||
|
||||
class BoundedFilterSet(FilterSet):
|
||||
"""
|
||||
A FilterSet whose generated number and datetime filters reject values the database
|
||||
cannot hold, as a 400, instead of failing later as a server error
|
||||
"""
|
||||
|
||||
FILTER_DEFAULTS = {
|
||||
**FILTER_FOR_DBFIELD_DEFAULTS,
|
||||
**{
|
||||
field: {"filter_class": BoundedNumberFilter}
|
||||
for field in (
|
||||
models.AutoField,
|
||||
models.BigAutoField,
|
||||
models.SmallAutoField,
|
||||
models.IntegerField,
|
||||
models.BigIntegerField,
|
||||
models.SmallIntegerField,
|
||||
models.PositiveIntegerField,
|
||||
models.PositiveSmallIntegerField,
|
||||
models.PositiveBigIntegerField,
|
||||
)
|
||||
},
|
||||
models.DateTimeField: {"filter_class": BoundedDateTimeFilter},
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def filter_for_field(cls, field, field_name, lookup_expr=None):
|
||||
filter_ = super().filter_for_field(field, field_name, lookup_expr)
|
||||
# The lookup resolves to a plain integer field, so only here is it known to be
|
||||
# a year, month or day
|
||||
bounds = DATE_PART_BOUNDS.get(lookup_expr)
|
||||
if bounds is not None and isinstance(filter_, NumberFilter):
|
||||
filter_.extra["min_value"], filter_.extra["max_value"] = bounds
|
||||
return filter_
|
||||
|
||||
|
||||
class CorrespondentFilterSet(BoundedFilterSet):
|
||||
class Meta:
|
||||
model = Correspondent
|
||||
fields = {
|
||||
@@ -104,7 +218,7 @@ class CorrespondentFilterSet(FilterSet):
|
||||
}
|
||||
|
||||
|
||||
class TagFilterSet(FilterSet):
|
||||
class TagFilterSet(BoundedFilterSet):
|
||||
class Meta:
|
||||
model = Tag
|
||||
fields = {
|
||||
@@ -119,7 +233,7 @@ class TagFilterSet(FilterSet):
|
||||
)
|
||||
|
||||
|
||||
class DocumentTypeFilterSet(FilterSet):
|
||||
class DocumentTypeFilterSet(BoundedFilterSet):
|
||||
class Meta:
|
||||
model = DocumentType
|
||||
fields = {
|
||||
@@ -128,7 +242,7 @@ class DocumentTypeFilterSet(FilterSet):
|
||||
}
|
||||
|
||||
|
||||
class StoragePathFilterSet(FilterSet):
|
||||
class StoragePathFilterSet(BoundedFilterSet):
|
||||
class Meta:
|
||||
model = StoragePath
|
||||
fields = {
|
||||
@@ -155,9 +269,21 @@ class ObjectFilter(Filter):
|
||||
return qs
|
||||
|
||||
if self.in_list:
|
||||
qs = qs.filter(**{f"{self.field_name}__id__in": object_ids}).distinct()
|
||||
qs = qs.filter(
|
||||
**{
|
||||
f"{self.field_name}__id__in": [
|
||||
obj_id for obj_id in object_ids if in_id_range(obj_id)
|
||||
],
|
||||
},
|
||||
).distinct()
|
||||
else:
|
||||
for obj_id in object_ids:
|
||||
if not in_id_range(obj_id):
|
||||
# No row has this id: excluding it changes nothing, requiring it
|
||||
# matches nothing
|
||||
if self.exclude:
|
||||
continue
|
||||
return qs.none()
|
||||
if self.exclude:
|
||||
qs = qs.exclude(**{f"{self.field_name}__id": obj_id})
|
||||
else:
|
||||
@@ -206,8 +332,14 @@ class EffectiveContentFilter(Filter):
|
||||
)
|
||||
|
||||
|
||||
@extend_schema_field(serializers.BooleanField)
|
||||
@extend_schema_field(serializers.IntegerField)
|
||||
class SharedByUser(Filter):
|
||||
"""
|
||||
Documents owned by the given user id that are shared with someone
|
||||
"""
|
||||
|
||||
field_class = BoundedIntegerField
|
||||
|
||||
def filter(self, qs, value):
|
||||
ctype = ContentType.objects.get_for_model(self.model)
|
||||
UserObjectPermission = get_user_obj_perms_model()
|
||||
@@ -242,7 +374,7 @@ class SharedByUser(Filter):
|
||||
)
|
||||
|
||||
|
||||
class CustomFieldFilterSet(FilterSet):
|
||||
class CustomFieldFilterSet(BoundedFilterSet):
|
||||
class Meta:
|
||||
model = CustomField
|
||||
fields = {
|
||||
@@ -251,8 +383,8 @@ class CustomFieldFilterSet(FilterSet):
|
||||
}
|
||||
|
||||
|
||||
class WorkflowFilterSet(FilterSet):
|
||||
trigger_type = NumberFilter(field_name="triggers__type", distinct=True)
|
||||
class WorkflowFilterSet(BoundedFilterSet):
|
||||
trigger_type = BoundedNumberFilter(field_name="triggers__type", distinct=True)
|
||||
|
||||
class Meta:
|
||||
model = Workflow
|
||||
@@ -276,9 +408,25 @@ class CustomFieldsFilter(Filter):
|
||||
option_ids = []
|
||||
if fields_with_matching_selects.count() > 0:
|
||||
for field in fields_with_matching_selects:
|
||||
options = field.extra_data.get("select_options", [])
|
||||
for _, option in enumerate(options):
|
||||
if option.get("label").lower().find(value.lower()) != -1:
|
||||
# Extra data saved by older versions may not be an object
|
||||
options = (
|
||||
field.extra_data.get("select_options")
|
||||
if isinstance(field.extra_data, dict)
|
||||
else None
|
||||
)
|
||||
if not isinstance(options, list):
|
||||
options = []
|
||||
for option in options:
|
||||
label = (
|
||||
option.get("label") if isinstance(option, dict) else None
|
||||
)
|
||||
if (
|
||||
isinstance(label, str)
|
||||
and label.lower().find(
|
||||
value.lower(),
|
||||
)
|
||||
!= -1
|
||||
):
|
||||
option_ids.extend([option.get("id")])
|
||||
# A document with multiple custom field instances can match more
|
||||
# than one of these OR-ed branches (or the same branch via
|
||||
@@ -852,7 +1000,7 @@ class CustomFieldQueryFilter(Filter):
|
||||
return qs.filter(pk__in=matching_ids)
|
||||
|
||||
|
||||
class DocumentFilterSet(FilterSet):
|
||||
class DocumentFilterSet(BoundedFilterSet):
|
||||
has_duplicates = BooleanFilter(method="filter_has_duplicates")
|
||||
|
||||
def __init__(self, *args: Any, user: Any = None, **kwargs: Any) -> None:
|
||||
@@ -984,7 +1132,7 @@ class DocumentFilterSet(FilterSet):
|
||||
}
|
||||
|
||||
|
||||
class ShareLinkFilterSet(FilterSet):
|
||||
class ShareLinkFilterSet(BoundedFilterSet):
|
||||
class Meta:
|
||||
model = ShareLink
|
||||
fields = {
|
||||
@@ -993,7 +1141,7 @@ class ShareLinkFilterSet(FilterSet):
|
||||
}
|
||||
|
||||
|
||||
class ShareLinkBundleFilterSet(FilterSet):
|
||||
class ShareLinkBundleFilterSet(BoundedFilterSet):
|
||||
documents = Filter(method="filter_documents")
|
||||
|
||||
class Meta:
|
||||
@@ -1013,10 +1161,13 @@ class ShareLinkBundleFilterSet(FilterSet):
|
||||
return queryset.none()
|
||||
if not ids:
|
||||
return queryset
|
||||
ids = [item for item in ids if in_id_range(item)]
|
||||
if not ids:
|
||||
return queryset.none()
|
||||
return queryset.filter(documents__in=ids).distinct()
|
||||
|
||||
|
||||
class PaperlessTaskFilterSet(FilterSet):
|
||||
class PaperlessTaskFilterSet(BoundedFilterSet):
|
||||
name = CharFilter(
|
||||
method="filter_name",
|
||||
label="Name",
|
||||
@@ -1052,13 +1203,13 @@ class PaperlessTaskFilterSet(FilterSet):
|
||||
field_name="acknowledged",
|
||||
)
|
||||
|
||||
date_created_after = DateTimeFilter(
|
||||
date_created_after = BoundedDateTimeFilter(
|
||||
field_name="date_created",
|
||||
lookup_expr="gte",
|
||||
label="Created After",
|
||||
)
|
||||
|
||||
date_created_before = DateTimeFilter(
|
||||
date_created_before = BoundedDateTimeFilter(
|
||||
field_name="date_created",
|
||||
lookup_expr="lte",
|
||||
label="Created Before",
|
||||
@@ -1110,9 +1261,10 @@ class PaperlessTaskFilterSet(FilterSet):
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
else:
|
||||
query |= Q(result_data__document_id=numeric_value) | Q(
|
||||
result_data__duplicate_of=numeric_value,
|
||||
)
|
||||
if in_id_range(numeric_value):
|
||||
query |= Q(result_data__document_id=numeric_value) | Q(
|
||||
result_data__duplicate_of=numeric_value,
|
||||
)
|
||||
|
||||
if "duplicate" in value.lower():
|
||||
query |= Q(result_data__duplicate_of__isnull=False)
|
||||
@@ -1184,12 +1336,13 @@ class DocumentsOrderingFilter(OrderingFilter):
|
||||
def filter_queryset(self, request, queryset, view):
|
||||
param = request.query_params.get("ordering")
|
||||
if param and self.prefix in param:
|
||||
custom_field_id = int(param.split(self.prefix)[1])
|
||||
custom_field_suffix = param.split(self.prefix)[1]
|
||||
try:
|
||||
custom_field_id = int(custom_field_suffix)
|
||||
field = CustomField.objects.get(pk=custom_field_id)
|
||||
except CustomField.DoesNotExist:
|
||||
except (ValueError, CustomField.DoesNotExist):
|
||||
raise serializers.ValidationError(
|
||||
{self.prefix + str(custom_field_id): [_("Custom field not found")]},
|
||||
{self.prefix + custom_field_suffix: [_("Custom field not found")]},
|
||||
)
|
||||
|
||||
annotation = None
|
||||
|
||||
@@ -4,9 +4,9 @@ from dataclasses import dataclass
|
||||
from email import message_from_bytes
|
||||
from pathlib import Path
|
||||
|
||||
from django.conf import settings
|
||||
from django.core.mail import EmailMessage
|
||||
|
||||
from documents.media_lock import media_lock
|
||||
from filelock import FileLock
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -48,7 +48,7 @@ def send_email(
|
||||
used_filenames: set[str] = set()
|
||||
|
||||
# Something could be renaming the file concurrently so it can't be attached
|
||||
with media_lock():
|
||||
with FileLock(settings.MEDIA_LOCK):
|
||||
for attachment in attachments:
|
||||
filename = _get_unique_filename(
|
||||
attachment.friendly_name,
|
||||
|
||||
@@ -18,11 +18,10 @@ from django.core import serializers
|
||||
from django.core.management.base import CommandError
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
from filelock import FileLock
|
||||
from guardian.models import GroupObjectPermission
|
||||
from guardian.models import UserObjectPermission
|
||||
|
||||
from documents.media_lock import media_lock
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Generator
|
||||
|
||||
@@ -331,7 +330,7 @@ class Command(CryptMixin, PaperlessCommand):
|
||||
)
|
||||
|
||||
# Prevent any ongoing changes in the documents while exporting
|
||||
with media_lock(), sink:
|
||||
with FileLock(settings.MEDIA_LOCK), sink:
|
||||
self.dump(sink)
|
||||
|
||||
def dump(self, sink: ExportSink) -> None:
|
||||
|
||||
@@ -29,6 +29,7 @@ from django.db.models import GeneratedField
|
||||
from django.db.models import Model
|
||||
from django.db.models.signals import m2m_changed
|
||||
from django.db.models.signals import post_save
|
||||
from filelock import FileLock
|
||||
from guardian.shortcuts import clear_ct_cache
|
||||
|
||||
from documents.export.compression import compress_type_readable
|
||||
@@ -36,7 +37,6 @@ from documents.export.compression import unreadable_method_names
|
||||
from documents.file_handling import create_source_path_directory
|
||||
from documents.management.commands.base import PaperlessCommand
|
||||
from documents.management.commands.mixins import CryptMixin
|
||||
from documents.media_lock import media_lock
|
||||
from documents.models import Correspondent
|
||||
from documents.models import CustomField
|
||||
from documents.models import CustomFieldInstance
|
||||
@@ -662,7 +662,7 @@ class Command(CryptMixin, PaperlessCommand):
|
||||
else:
|
||||
archive_path = None
|
||||
|
||||
with media_lock():
|
||||
with FileLock(settings.MEDIA_LOCK):
|
||||
if Path(document.source_path).is_file():
|
||||
raise FileExistsError(document.source_path)
|
||||
|
||||
@@ -696,7 +696,7 @@ class Command(CryptMixin, PaperlessCommand):
|
||||
f"Share link bundle {bundle.pk} does not have a valid file path.",
|
||||
)
|
||||
|
||||
with media_lock():
|
||||
with FileLock(settings.MEDIA_LOCK):
|
||||
bundle_target_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
copy_file_with_basic_stats(
|
||||
bundle_source_path,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
from documents.file_moves import move_files_for_document
|
||||
from django.db.models.signals import post_save
|
||||
|
||||
from documents.management.commands.base import PaperlessCommand
|
||||
from documents.models import Document
|
||||
|
||||
@@ -10,9 +11,5 @@ class Command(PaperlessCommand):
|
||||
supports_multiprocessing = False
|
||||
|
||||
def handle(self, *args, **options):
|
||||
for document in self.track(
|
||||
# move_files_for_document handles a root's versions itself
|
||||
Document.objects.filter(root_document__isnull=True).only("pk"),
|
||||
description="Renaming...",
|
||||
):
|
||||
move_files_for_document(document.pk)
|
||||
for document in self.track(Document.objects.all(), description="Renaming..."):
|
||||
post_save.send(Document, instance=document, created=False)
|
||||
@@ -9,7 +9,6 @@ from rich.table import Table
|
||||
from rich.text import Text
|
||||
|
||||
from documents.classifier import load_classifier
|
||||
from documents.file_moves import defer_file_moves
|
||||
from documents.management.commands.base import PaperlessCommand
|
||||
from documents.models import Document
|
||||
from documents.signals.handlers import set_correspondent
|
||||
@@ -274,63 +273,61 @@ class Command(PaperlessCommand):
|
||||
description="Retagging...",
|
||||
stats_renderer=render_stats,
|
||||
):
|
||||
# One file move per document, after all of its assignments.
|
||||
with defer_file_moves():
|
||||
suggestion = DocumentSuggestion(document=document)
|
||||
suggestion = DocumentSuggestion(document=document)
|
||||
|
||||
if do_correspondent:
|
||||
correspondent = set_correspondent(
|
||||
None,
|
||||
document,
|
||||
classifier=classifier,
|
||||
replace=overwrite,
|
||||
use_first=use_first,
|
||||
dry_run=suggest,
|
||||
)
|
||||
if correspondent is not None:
|
||||
stats.correspondents += 1
|
||||
suggestion.correspondent = correspondent
|
||||
if do_correspondent:
|
||||
correspondent = set_correspondent(
|
||||
None,
|
||||
document,
|
||||
classifier=classifier,
|
||||
replace=overwrite,
|
||||
use_first=use_first,
|
||||
dry_run=suggest,
|
||||
)
|
||||
if correspondent is not None:
|
||||
stats.correspondents += 1
|
||||
suggestion.correspondent = correspondent
|
||||
|
||||
if do_document_type:
|
||||
document_type = set_document_type(
|
||||
None,
|
||||
document,
|
||||
classifier=classifier,
|
||||
replace=overwrite,
|
||||
use_first=use_first,
|
||||
dry_run=suggest,
|
||||
)
|
||||
if document_type is not None:
|
||||
stats.document_types += 1
|
||||
suggestion.document_type = document_type
|
||||
if do_document_type:
|
||||
document_type = set_document_type(
|
||||
None,
|
||||
document,
|
||||
classifier=classifier,
|
||||
replace=overwrite,
|
||||
use_first=use_first,
|
||||
dry_run=suggest,
|
||||
)
|
||||
if document_type is not None:
|
||||
stats.document_types += 1
|
||||
suggestion.document_type = document_type
|
||||
|
||||
if do_tags:
|
||||
tags_to_add, tags_to_remove = set_tags(
|
||||
None,
|
||||
document,
|
||||
classifier=classifier,
|
||||
replace=overwrite,
|
||||
dry_run=suggest,
|
||||
)
|
||||
stats.tags_added += len(tags_to_add)
|
||||
stats.tags_removed += len(tags_to_remove)
|
||||
suggestion.tags_to_add = frozenset(tags_to_add)
|
||||
suggestion.tags_to_remove = frozenset(tags_to_remove)
|
||||
if do_tags:
|
||||
tags_to_add, tags_to_remove = set_tags(
|
||||
None,
|
||||
document,
|
||||
classifier=classifier,
|
||||
replace=overwrite,
|
||||
dry_run=suggest,
|
||||
)
|
||||
stats.tags_added += len(tags_to_add)
|
||||
stats.tags_removed += len(tags_to_remove)
|
||||
suggestion.tags_to_add = frozenset(tags_to_add)
|
||||
suggestion.tags_to_remove = frozenset(tags_to_remove)
|
||||
|
||||
if do_storage_path:
|
||||
storage_path = set_storage_path(
|
||||
None,
|
||||
document,
|
||||
classifier=classifier,
|
||||
replace=overwrite,
|
||||
use_first=use_first,
|
||||
dry_run=suggest,
|
||||
)
|
||||
if storage_path is not None:
|
||||
stats.storage_paths += 1
|
||||
suggestion.storage_path = storage_path
|
||||
if do_storage_path:
|
||||
storage_path = set_storage_path(
|
||||
None,
|
||||
document,
|
||||
classifier=classifier,
|
||||
replace=overwrite,
|
||||
use_first=use_first,
|
||||
dry_run=suggest,
|
||||
)
|
||||
if storage_path is not None:
|
||||
stats.storage_paths += 1
|
||||
suggestion.storage_path = storage_path
|
||||
|
||||
stats.documents_processed += 1
|
||||
stats.documents_processed += 1
|
||||
|
||||
if suggest:
|
||||
suggestions.append(suggestion)
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
"""
|
||||
The global media lock, reentrant within a thread.
|
||||
|
||||
Code that both needs media.lock and opens a transaction that locks document
|
||||
rows must take media.lock first, so no transaction ever waits on it while
|
||||
holding rows. Reentrancy lets code already holding the lock (for example the
|
||||
consumer) call into code that takes it again (for example a workflow email
|
||||
action attaching files) without blocking itself.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from django.conf import settings
|
||||
from filelock import FileLock
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
|
||||
@contextmanager
|
||||
def media_lock(timeout: float = -1) -> Iterator[None]:
|
||||
"""
|
||||
Hold settings.MEDIA_LOCK for the block.
|
||||
|
||||
is_singleton returns one FileLock instance per path in this process, and
|
||||
the default thread_local=True keeps the hold count per thread, so the
|
||||
same thread re-enters while other threads and processes are excluded.
|
||||
The timeout goes to acquire() because a singleton rejects construction
|
||||
with different parameters. A negative timeout waits forever.
|
||||
"""
|
||||
lock = FileLock(settings.MEDIA_LOCK, is_singleton=True)
|
||||
with lock.acquire(timeout=timeout):
|
||||
yield
|
||||
+6
-29
@@ -2,7 +2,6 @@ import datetime
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
from typing import Any
|
||||
from typing import Final
|
||||
|
||||
import pathvalidate
|
||||
@@ -212,12 +211,6 @@ class StoragePath(MatchingModel):
|
||||
|
||||
class Document(SoftDeleteModel, ModelWithOwner): # type: ignore[django-manager-missing]
|
||||
MAX_STORED_FILENAME_LENGTH: Final[int] = 1024
|
||||
# Written only by the file mover, the consumer's file placement and the
|
||||
# archiver. A full save() of a stale instance must never write them, or
|
||||
# the DB can point at a path the file has already been moved away from.
|
||||
FILE_PATH_FIELDS: Final[frozenset[str]] = frozenset(
|
||||
{"filename", "archive_filename"},
|
||||
)
|
||||
# Per-component limit of common filesystems (ext4, XFS, btrfs, ZFS, APFS)
|
||||
MAX_PUBLIC_FILENAME_BYTES: Final[int] = 255
|
||||
|
||||
@@ -429,30 +422,14 @@ class Document(SoftDeleteModel, ModelWithOwner): # type: ignore[django-manager-
|
||||
res += f" {self.title}"
|
||||
return res
|
||||
|
||||
def save(self, *, write_file_paths: bool = False, **kwargs: Any) -> None:
|
||||
@classmethod
|
||||
def validate_archive_serial_number(cls, value: int) -> None:
|
||||
"""
|
||||
Save the document without writing filename / archive_filename on an
|
||||
existing row, unless write_file_paths=True or update_fields names them.
|
||||
|
||||
This mirrors how Django narrows a save on a deferred instance: only the
|
||||
loaded, concrete, non-generated, non-primary-key fields are written.
|
||||
Run every validator of the ASN field. Besides the fixed range above, Django
|
||||
adds the range of the column for the database in use (a signed 32 bit
|
||||
integer on PostgreSQL), which a serializer built from the field does not apply
|
||||
"""
|
||||
if (
|
||||
not write_file_paths
|
||||
and not self._state.adding
|
||||
and kwargs.get("update_fields") is None
|
||||
and not kwargs.get("force_insert", False)
|
||||
):
|
||||
deferred = self.get_deferred_fields()
|
||||
kwargs["update_fields"] = [
|
||||
field.attname
|
||||
for field in self._meta.concrete_fields
|
||||
if not field.primary_key
|
||||
and not field.generated
|
||||
and field.name not in self.FILE_PATH_FIELDS
|
||||
and field.attname not in deferred
|
||||
]
|
||||
super().save(**kwargs)
|
||||
cls._meta.get_field("archive_serial_number").run_validators(value)
|
||||
|
||||
def get_effective_barcodes(self) -> list["DocumentBarcode"]:
|
||||
"""
|
||||
|
||||
@@ -2,6 +2,8 @@ from drf_spectacular.extensions import OpenApiAuthenticationExtension
|
||||
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_field
|
||||
from rest_framework import serializers
|
||||
|
||||
|
||||
class AngularApiAuthenticationOverrideScheme(OpenApiAuthenticationExtension):
|
||||
@@ -42,3 +44,89 @@ def generate_object_with_permissions_schema(serializer_class):
|
||||
)
|
||||
for operation in ["list", "retrieve"]
|
||||
}
|
||||
|
||||
|
||||
HTTP_METHODS = {"get", "put", "post", "patch", "delete"}
|
||||
|
||||
|
||||
def add_common_error_responses(result, generator, request, public):
|
||||
"""
|
||||
Document the errors nearly every operation can answer, so they do not have to be
|
||||
declared on each view: a 400 when validation of the input fails, and a 404 when
|
||||
the object named in the path, or the requested page of a list, does not exist.
|
||||
Responses a view declares itself are kept as they are.
|
||||
"""
|
||||
for item in result.get("paths", {}).values():
|
||||
for method, operation in item.items():
|
||||
if method not in HTTP_METHODS:
|
||||
continue
|
||||
parameters = [*item.get("parameters", []), *operation.get("parameters", [])]
|
||||
has_path_parameter = any(p.get("in") == "path" for p in parameters)
|
||||
has_input = (
|
||||
"requestBody" in operation
|
||||
or has_path_parameter
|
||||
or any(p.get("in") == "query" for p in parameters)
|
||||
)
|
||||
paginated = any(
|
||||
p.get("in") == "query" and p.get("name") == "page" for p in parameters
|
||||
)
|
||||
responses = operation.setdefault("responses", {})
|
||||
if has_input:
|
||||
responses.setdefault("400", {"description": "Invalid input"})
|
||||
if has_path_parameter or paginated:
|
||||
responses.setdefault(
|
||||
"404",
|
||||
{"description": "The object or page does not exist"},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
# Fields of the objects with an owner that a response only carries sometimes: the
|
||||
# permissions or the flags that replace them (see OwnedObjectSerializer), and counts a
|
||||
# queryset annotates, which a response to a create or an update does not have.
|
||||
CONDITIONAL_RESPONSE_FIELDS = (
|
||||
"permissions",
|
||||
"user_can_change",
|
||||
"is_shared_by_requester",
|
||||
"document_count",
|
||||
"last_correspondence",
|
||||
)
|
||||
|
||||
|
||||
# Components without an owner that still carry an annotated count
|
||||
COMPONENTS_WITH_ANNOTATED_COUNTS = {"CustomField"}
|
||||
|
||||
|
||||
def make_conditional_fields_optional(result, generator, request, public):
|
||||
"""
|
||||
drf-spectacular lists every read only field as required in a response. For the
|
||||
objects built on OwnedObjectSerializer that is wrong for the fields above, so they
|
||||
are taken out of the required list of those components.
|
||||
"""
|
||||
for name, component in result.get("components", {}).get("schemas", {}).items():
|
||||
properties = component.get("properties", {})
|
||||
required = component.get("required")
|
||||
owned = {"permissions", "user_can_change"} & set(properties)
|
||||
if not required or not (owned or name in COMPONENTS_WITH_ANNOTATED_COUNTS):
|
||||
continue
|
||||
remaining = [
|
||||
name for name in required if name not in CONDITIONAL_RESPONSE_FIELDS
|
||||
]
|
||||
if remaining:
|
||||
component["required"] = remaining
|
||||
else:
|
||||
del component["required"]
|
||||
return result
|
||||
|
||||
|
||||
@extend_schema_field({"type": "integer", "format": "int64"})
|
||||
class Int64Field(serializers.IntegerField):
|
||||
"""An integer that does not fit 32 bits, for example a size in bytes."""
|
||||
|
||||
|
||||
@extend_schema_field({"type": "string", "format": "date", "nullable": True})
|
||||
class NullableDateField(serializers.DateField):
|
||||
"""
|
||||
A date the schema documents as nullable. allow_null would also make a response
|
||||
carry an explicit null where the field is left out today.
|
||||
"""
|
||||
+196
-57
@@ -20,6 +20,7 @@ from django.core.validators import EmailValidator
|
||||
from django.core.validators import MaxLengthValidator
|
||||
from django.core.validators import MaxValueValidator
|
||||
from django.core.validators import MinValueValidator
|
||||
from django.core.validators import RegexValidator
|
||||
from django.core.validators import integer_validator
|
||||
from django.db import transaction
|
||||
from django.db.models import Count
|
||||
@@ -52,7 +53,10 @@ if settings.AUDIT_LOG_ENABLED:
|
||||
|
||||
from documents import bulk_edit
|
||||
from documents.data_models import DocumentSource
|
||||
from documents.filters import INT32_MAX
|
||||
from documents.filters import INT32_MIN
|
||||
from documents.filters import CustomFieldQueryParser
|
||||
from documents.filters import in_range_ids
|
||||
from documents.models import Correspondent
|
||||
from documents.models import CustomField
|
||||
from documents.models import CustomFieldInstance
|
||||
@@ -90,6 +94,7 @@ from documents.permissions import permitted_object_ids
|
||||
from documents.permissions import restrict_queryset_to_visible
|
||||
from documents.permissions import set_permissions_for_objects
|
||||
from documents.regex import validate_regex_pattern
|
||||
from documents.schema import NullableDateField
|
||||
from documents.templating.filepath import validate_filepath_template_and_render
|
||||
from documents.templating.utils import convert_format_str_to_template_format
|
||||
from documents.templating.workflows import validate_workflow_template
|
||||
@@ -230,7 +235,7 @@ class SetPermissionsMixin:
|
||||
def _validate_user_ids(self, user_ids):
|
||||
users = User.objects.none()
|
||||
if user_ids is not None:
|
||||
users = User.objects.filter(id__in=user_ids)
|
||||
users = User.objects.filter(id__in=in_range_ids(user_ids))
|
||||
if not users.count() == len(user_ids):
|
||||
raise serializers.ValidationError(
|
||||
"Some users in don't exist or were specified twice.",
|
||||
@@ -240,7 +245,7 @@ class SetPermissionsMixin:
|
||||
def _validate_group_ids(self, group_ids):
|
||||
groups = Group.objects.none()
|
||||
if group_ids is not None:
|
||||
groups = Group.objects.filter(id__in=group_ids)
|
||||
groups = Group.objects.filter(id__in=in_range_ids(group_ids))
|
||||
if not groups.count() == len(group_ids):
|
||||
raise serializers.ValidationError(
|
||||
"Some groups in don't exist or were specified twice.",
|
||||
@@ -448,6 +453,10 @@ class OwnedObjectSerializer(
|
||||
|
||||
def validate_unique_together(self, validated_data, instance=None) -> None:
|
||||
# workaround for https://github.com/encode/django-rest-framework/issues/9358
|
||||
# An update that does not mention the owner keeps the current one, which
|
||||
# still has to be unique with the new name
|
||||
if instance is not None and "owner" not in validated_data:
|
||||
validated_data = {**validated_data, "owner": instance.owner}
|
||||
if "owner" in validated_data and "name" in self.Meta.fields:
|
||||
name = validated_data.get("name", instance.name if instance else None)
|
||||
objects = (
|
||||
@@ -510,7 +519,7 @@ class OwnedObjectListSerializer(serializers.ListSerializer[Any]):
|
||||
|
||||
|
||||
class CorrespondentSerializer(MatchingModelSerializer, OwnedObjectSerializer):
|
||||
last_correspondence = serializers.DateField(read_only=True, required=False)
|
||||
last_correspondence = NullableDateField(read_only=True, required=False)
|
||||
|
||||
class Meta:
|
||||
model = Correspondent
|
||||
@@ -573,11 +582,8 @@ class TagSerializer(MatchingModelSerializer, OwnedObjectSerializer):
|
||||
)
|
||||
|
||||
@extend_schema_field(
|
||||
field=serializers.ListSerializer(
|
||||
child=serializers.PrimaryKeyRelatedField(
|
||||
queryset=Tag.objects.all(),
|
||||
),
|
||||
),
|
||||
# The children are nested tags, not ids
|
||||
field={"type": "array", "items": {"$ref": "#/components/schemas/Tag"}},
|
||||
)
|
||||
def get_children(self, obj):
|
||||
children_map = self.context.get("children_map")
|
||||
@@ -644,12 +650,14 @@ class TagSerializer(MatchingModelSerializer, OwnedObjectSerializer):
|
||||
"parent",
|
||||
"children",
|
||||
)
|
||||
|
||||
def validate_color(self, color):
|
||||
regex = r"#[0-9a-fA-F]{6}"
|
||||
if not re.match(regex, color):
|
||||
raise serializers.ValidationError(_("Invalid color."))
|
||||
return color
|
||||
# A validator, so the schema publishes it as a pattern
|
||||
extra_kwargs = {
|
||||
"color": {
|
||||
"validators": [
|
||||
RegexValidator(r"^#[0-9a-fA-F]{6}$", message=_("Invalid color.")),
|
||||
],
|
||||
},
|
||||
}
|
||||
|
||||
def validate(self, attrs):
|
||||
# Validate when changing parent
|
||||
@@ -725,6 +733,15 @@ class CustomFieldSerializer(serializers.ModelSerializer[CustomField]):
|
||||
]
|
||||
|
||||
def validate(self, attrs):
|
||||
# Extra data is read as an object everywhere, any other JSON would be stored
|
||||
# to fail on the next read
|
||||
if attrs.get("extra_data") is not None and not isinstance(
|
||||
attrs["extra_data"],
|
||||
dict,
|
||||
):
|
||||
raise serializers.ValidationError(
|
||||
{"extra_data": "Must be an object"},
|
||||
)
|
||||
# TODO: remove pending https://github.com/encode/django-rest-framework/issues/7173
|
||||
name = attrs.get(
|
||||
"name",
|
||||
@@ -750,14 +767,19 @@ class CustomFieldSerializer(serializers.ModelSerializer[CustomField]):
|
||||
self.instance
|
||||
and self.instance.data_type == CustomField.FieldDataType.SELECT
|
||||
):
|
||||
select_options = (
|
||||
attrs["extra_data"].get("select_options")
|
||||
if isinstance(attrs.get("extra_data"), dict)
|
||||
else None
|
||||
)
|
||||
if (
|
||||
"extra_data" not in attrs
|
||||
or "select_options" not in attrs["extra_data"]
|
||||
or not isinstance(attrs["extra_data"]["select_options"], list)
|
||||
or len(attrs["extra_data"]["select_options"]) == 0
|
||||
not isinstance(select_options, list)
|
||||
or len(select_options) == 0
|
||||
or not all(
|
||||
len(option.get("label", "")) > 0
|
||||
for option in attrs["extra_data"]["select_options"]
|
||||
isinstance(option, dict)
|
||||
and isinstance(option.get("label", ""), str)
|
||||
and len(option.get("label", "")) > 0
|
||||
for option in select_options
|
||||
)
|
||||
):
|
||||
raise serializers.ValidationError(
|
||||
@@ -770,7 +792,7 @@ class CustomFieldSerializer(serializers.ModelSerializer[CustomField]):
|
||||
elif (
|
||||
"data_type" in attrs
|
||||
and attrs["data_type"] == CustomField.FieldDataType.MONETARY
|
||||
and "extra_data" in attrs
|
||||
and isinstance(attrs.get("extra_data"), dict)
|
||||
and "default_currency" in attrs["extra_data"]
|
||||
and attrs["extra_data"]["default_currency"] is not None
|
||||
and (
|
||||
@@ -802,7 +824,7 @@ class ReadWriteSerializerMethodField(serializers.SerializerMethodField):
|
||||
|
||||
|
||||
def validate_documentlink_targets(user, doc_ids):
|
||||
if Document.objects.filter(id__in=doc_ids).count() != len(doc_ids):
|
||||
if Document.objects.filter(id__in=in_range_ids(doc_ids)).count() != len(doc_ids):
|
||||
raise serializers.ValidationError(
|
||||
"Some documents in value don't exist or were specified twice.",
|
||||
)
|
||||
@@ -1008,7 +1030,7 @@ class DocumentSerializer(
|
||||
|
||||
notes = NotesSerializer(many=True, required=False, read_only=True)
|
||||
root_document: RelatedField[Document, Document, Any] | ManyRelatedField = (
|
||||
serializers.PrimaryKeyRelatedField(read_only=True)
|
||||
serializers.PrimaryKeyRelatedField(read_only=True, allow_null=True)
|
||||
)
|
||||
versions = SerializerMethodField()
|
||||
|
||||
@@ -1131,6 +1153,11 @@ class DocumentSerializer(
|
||||
data["created"] = parsed.astimezone().date()
|
||||
return super().to_internal_value(data)
|
||||
|
||||
def validate_archive_serial_number(self, value):
|
||||
if value is not None:
|
||||
Document.validate_archive_serial_number(value)
|
||||
return value
|
||||
|
||||
def validate(self, attrs):
|
||||
if (
|
||||
"archive_serial_number" in attrs
|
||||
@@ -1469,12 +1496,29 @@ class SavedViewSerializer(OwnedObjectSerializer):
|
||||
|
||||
def validate(self, attrs):
|
||||
attrs = super().validate(attrs)
|
||||
# On a PATCH the nested rules are validated as partial, but a stored rule
|
||||
# always needs its type
|
||||
for rule in attrs.get("filter_rules") or []:
|
||||
if "rule_type" not in rule:
|
||||
raise serializers.ValidationError(
|
||||
{"filter_rules": "Every rule needs a rule_type"},
|
||||
)
|
||||
if "display_fields" in attrs and attrs["display_fields"] is not None:
|
||||
if not isinstance(attrs["display_fields"], list):
|
||||
raise serializers.ValidationError(
|
||||
{"display_fields": "Must be a list"},
|
||||
)
|
||||
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 isinstance(field, str):
|
||||
raise serializers.ValidationError(
|
||||
f"Invalid field: {field}",
|
||||
)
|
||||
custom_field = re.fullmatch(
|
||||
rf"{re.escape(SavedView.DisplayFields.CUSTOM_FIELD[:-2])}(\d+)",
|
||||
field,
|
||||
) # i.e. 'custom_field_' followed by an id
|
||||
if custom_field:
|
||||
field_id = int(custom_field[1])
|
||||
if not CustomField.objects.filter(id=field_id).exists():
|
||||
raise serializers.ValidationError(
|
||||
f"Invalid field: {field}",
|
||||
@@ -1553,7 +1597,9 @@ class DocumentListSerializer(serializers.Serializer[dict[str, list[int]]]):
|
||||
raise serializers.ValidationError(f"{name} must be a list")
|
||||
if not all(isinstance(i, int) for i in documents):
|
||||
raise serializers.ValidationError(f"{name} must be a list of integers")
|
||||
count = Document.objects.filter(id__in=documents).count()
|
||||
# An id beyond what a database column holds can't exist, and some backends raise
|
||||
# an error instead of finding nothing
|
||||
count = Document.objects.filter(id__in=in_range_ids(documents)).count()
|
||||
if not count == len(documents):
|
||||
raise serializers.ValidationError(
|
||||
f"Some documents in {name} don't exist or were specified twice.",
|
||||
@@ -1726,6 +1772,10 @@ class EditPdfDocumentsSerializer(DocumentListSerializer, SourceModeValidationMix
|
||||
raise serializers.ValidationError(
|
||||
"Edit PDF method only supports one document",
|
||||
)
|
||||
if len(documents) == 0:
|
||||
raise serializers.ValidationError(
|
||||
"Edit PDF method requires a document",
|
||||
)
|
||||
|
||||
operations = attrs["operations"]
|
||||
|
||||
@@ -1809,14 +1859,13 @@ class RunZoneOcrResponseSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
read_only=True,
|
||||
help_text="OK when the run was queued, skipped when it was not.",
|
||||
)
|
||||
# Not read only: spectacular lists every read only field of a response as required
|
||||
task_id = serializers.CharField(
|
||||
read_only=True,
|
||||
required=False,
|
||||
help_text="The queued task. Absent when the run was skipped.",
|
||||
)
|
||||
reason = serializers.ChoiceField(
|
||||
choices=[reason.value for reason in ZoneOcrSkipReason],
|
||||
read_only=True,
|
||||
required=False,
|
||||
help_text="Present only when the run was skipped.",
|
||||
)
|
||||
@@ -1825,7 +1874,10 @@ class RunZoneOcrResponseSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
class OcrErrorSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
"""The body of an error response from the OCR template actions."""
|
||||
|
||||
error = serializers.CharField(read_only=True)
|
||||
# Not read only: spectacular lists every read only field of a response as required.
|
||||
# A 404 from a missing document has a detail instead of an error.
|
||||
error = serializers.CharField(required=False)
|
||||
detail = serializers.CharField(required=False)
|
||||
|
||||
|
||||
class RunZoneOcrDocumentsSerializer(DocumentSelectionSerializer, RunZoneOcrSerializer):
|
||||
@@ -1877,7 +1929,7 @@ class BulkEditSerializer(
|
||||
raise serializers.ValidationError(f"{name} must be a list")
|
||||
if not all(isinstance(i, int) for i in tags):
|
||||
raise serializers.ValidationError(f"{name} must be a list of integers")
|
||||
count = Tag.objects.filter(id__in=tags).count()
|
||||
count = Tag.objects.filter(id__in=in_range_ids(tags)).count()
|
||||
if not count == len(tags):
|
||||
raise serializers.ValidationError(
|
||||
f"Some tags in {name} don't exist or were specified twice.",
|
||||
@@ -1903,7 +1955,7 @@ class BulkEditSerializer(
|
||||
raise serializers.ValidationError(
|
||||
f"{name} must be a list of integers or a dict of id:value pairs",
|
||||
)
|
||||
count = CustomField.objects.filter(id__in=ids).count()
|
||||
count = CustomField.objects.filter(id__in=in_range_ids(ids)).count()
|
||||
if not count == len(ids):
|
||||
raise serializers.ValidationError(
|
||||
f"Some custom fields in {name} don't exist or were specified twice.",
|
||||
@@ -2269,12 +2321,20 @@ class BulkEditSerializer(
|
||||
raise serializers.ValidationError(
|
||||
"Split method only supports one document",
|
||||
)
|
||||
if len(attrs["documents"]) == 0:
|
||||
raise serializers.ValidationError(
|
||||
"Split method requires a document",
|
||||
)
|
||||
self._validate_parameters_split(parameters, attrs["documents"][0])
|
||||
elif method == bulk_edit.delete_pages:
|
||||
if len(attrs["documents"]) > 1:
|
||||
raise serializers.ValidationError(
|
||||
"Delete pages method only supports one document",
|
||||
)
|
||||
if len(attrs["documents"]) == 0:
|
||||
raise serializers.ValidationError(
|
||||
"Delete pages method requires a document",
|
||||
)
|
||||
self._validate_parameters_delete_pages(parameters)
|
||||
elif method == bulk_edit.merge:
|
||||
self._validate_parameters_merge(parameters)
|
||||
@@ -2283,6 +2343,10 @@ class BulkEditSerializer(
|
||||
raise serializers.ValidationError(
|
||||
"Edit PDF method only supports one document",
|
||||
)
|
||||
if len(attrs["documents"]) == 0:
|
||||
raise serializers.ValidationError(
|
||||
"Edit PDF method requires a document",
|
||||
)
|
||||
self._validate_parameters_edit_pdf(parameters, attrs["documents"][0])
|
||||
elif method == bulk_edit.remove_password:
|
||||
self.validate_parameters_remove_password(parameters)
|
||||
@@ -2351,6 +2415,7 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
required=False,
|
||||
min_value=Document.ARCHIVE_SERIAL_NUMBER_MIN,
|
||||
max_value=Document.ARCHIVE_SERIAL_NUMBER_MAX,
|
||||
validators=[Document.validate_archive_serial_number],
|
||||
)
|
||||
|
||||
# Accept either a list of custom field ids or a dict mapping id -> value
|
||||
@@ -2453,7 +2518,9 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
"Custom fields must be a list of integers or an object mapping ids to values.",
|
||||
),
|
||||
)
|
||||
if CustomField.objects.filter(id__in=ids).count() != len(set(ids)):
|
||||
if CustomField.objects.filter(id__in=in_range_ids(ids)).count() != len(
|
||||
set(ids),
|
||||
):
|
||||
raise serializers.ValidationError(
|
||||
_("Some custom fields don't exist or were specified twice."),
|
||||
)
|
||||
@@ -2633,12 +2700,17 @@ class UiSettingsViewSerializer(serializers.ModelSerializer[UiSettings]):
|
||||
]
|
||||
|
||||
def validate_settings(self, settings):
|
||||
if settings is None:
|
||||
return settings
|
||||
if not isinstance(settings, dict):
|
||||
raise serializers.ValidationError("Settings must be an object")
|
||||
# we never save update checking backend setting
|
||||
if "update_checking" in settings:
|
||||
try:
|
||||
settings["update_checking"].pop("backend_setting")
|
||||
except KeyError:
|
||||
pass
|
||||
if not isinstance(settings["update_checking"], dict):
|
||||
raise serializers.ValidationError(
|
||||
{"update_checking": "Must be an object"},
|
||||
)
|
||||
settings["update_checking"].pop("backend_setting", None)
|
||||
return settings
|
||||
|
||||
def create(self, validated_data):
|
||||
@@ -2855,7 +2927,7 @@ class AcknowledgeTasksViewSerializer(serializers.Serializer[dict[str, Any]]):
|
||||
if not all(isinstance(i, int) for i in tasks):
|
||||
raise serializers.ValidationError(f"{name} must be a list of integers")
|
||||
queryset = self.context.get("queryset", PaperlessTask.objects.all())
|
||||
count = queryset.filter(id__in=tasks).count()
|
||||
count = queryset.filter(id__in=in_range_ids(tasks)).count()
|
||||
if not count == len(tasks):
|
||||
raise serializers.ValidationError(
|
||||
f"Some tasks in {name} don't exist or were specified twice.",
|
||||
@@ -2898,6 +2970,8 @@ class ShareLinkSerializer(OwnedObjectSerializer):
|
||||
"document_title",
|
||||
"file_version",
|
||||
)
|
||||
# The model field is blank=True but not nullable, so it would be optional
|
||||
extra_kwargs = {"document": {"required": True}}
|
||||
|
||||
def create(self, validated_data):
|
||||
validated_data["slug"] = get_random_string(50)
|
||||
@@ -2989,7 +3063,7 @@ class ShareLinkBundleSerializer(OwnedObjectSerializer):
|
||||
share_link_bundle = super().create(validated_data)
|
||||
|
||||
documents = list(
|
||||
Document.objects.filter(pk__in=document_ids).only(
|
||||
Document.objects.filter(pk__in=in_range_ids(document_ids)).only(
|
||||
"pk",
|
||||
),
|
||||
)
|
||||
@@ -3095,7 +3169,7 @@ class BulkEditObjectsSerializer(SerializerWithPerms, SetPermissionsMixin):
|
||||
if not all(isinstance(i, int) for i in objects):
|
||||
raise serializers.ValidationError("objects must be a list of integers")
|
||||
object_class = self.get_object_class(object_type)
|
||||
count = object_class.objects.filter(id__in=objects).count()
|
||||
count = object_class.objects.filter(id__in=in_range_ids(objects)).count()
|
||||
if not count == len(objects):
|
||||
raise serializers.ValidationError(
|
||||
"Some ids in objects don't exist or were specified twice.",
|
||||
@@ -3238,10 +3312,14 @@ class WorkflowTriggerSerializer(serializers.ModelSerializer[WorkflowTrigger]):
|
||||
]
|
||||
|
||||
def create(self, validated_data):
|
||||
# The id is only meaningful when this is nested in a workflow. On its own
|
||||
# a client chosen id would collide with, or overwrite, another row
|
||||
validated_data.pop("id", None)
|
||||
WorkflowTriggerSerializer.normalize_workflow_trigger_sources(validated_data)
|
||||
return super().create(validated_data)
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
validated_data.pop("id", None)
|
||||
WorkflowTriggerSerializer.normalize_workflow_trigger_sources(validated_data)
|
||||
return super().update(instance, validated_data)
|
||||
|
||||
@@ -3283,6 +3361,34 @@ class WorkflowActionWebhookSerializer(
|
||||
]
|
||||
|
||||
|
||||
def save_action_email_and_webhook(action, email_data, webhook_data) -> None:
|
||||
"""
|
||||
Store the nested email and webhook of a workflow action on the action's own rows.
|
||||
An id in the payload is never used, it could name a row that belongs to another
|
||||
action. An action with no row of that kind gets a new one. The data must already
|
||||
be cleaned by the nested serializers, an unknown key would be a model error.
|
||||
"""
|
||||
created = False
|
||||
for data, model, attribute in (
|
||||
(email_data, WorkflowActionEmail, "email"),
|
||||
(webhook_data, WorkflowActionWebhook, "webhook"),
|
||||
):
|
||||
if data is None:
|
||||
continue
|
||||
values = {key: value for key, value in data.items() if key != "id"}
|
||||
existing = getattr(action, attribute)
|
||||
if existing is not None:
|
||||
# Change the loaded row, a response is built from it
|
||||
for key, value in values.items():
|
||||
setattr(existing, key, value)
|
||||
existing.save()
|
||||
else:
|
||||
setattr(action, attribute, model.objects.create(**values))
|
||||
created = True
|
||||
if created:
|
||||
action.save()
|
||||
|
||||
|
||||
class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
|
||||
id = serializers.IntegerField(required=False, allow_null=True)
|
||||
assign_correspondent = CorrespondentField(allow_null=True, required=False)
|
||||
@@ -3334,6 +3440,22 @@ class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
|
||||
"ai_overwrite_existing",
|
||||
]
|
||||
|
||||
def create(self, validated_data):
|
||||
validated_data.pop("id", None)
|
||||
email_data = validated_data.pop("email", None)
|
||||
webhook_data = validated_data.pop("webhook", None)
|
||||
instance = super().create(validated_data)
|
||||
save_action_email_and_webhook(instance, email_data, webhook_data)
|
||||
return instance
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
validated_data.pop("id", None)
|
||||
email_data = validated_data.pop("email", None)
|
||||
webhook_data = validated_data.pop("webhook", None)
|
||||
instance = super().update(instance, validated_data)
|
||||
save_action_email_and_webhook(instance, email_data, webhook_data)
|
||||
return instance
|
||||
|
||||
def validate(self, attrs):
|
||||
if "assign_title" in attrs and attrs["assign_title"] is not None:
|
||||
if len(attrs["assign_title"]) == 0:
|
||||
@@ -3348,6 +3470,10 @@ class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
|
||||
)
|
||||
|
||||
if attrs.get("assign_custom_fields_values"):
|
||||
if not isinstance(attrs["assign_custom_fields_values"], dict):
|
||||
raise serializers.ValidationError(
|
||||
{"assign_custom_fields_values": "Must be an object"},
|
||||
)
|
||||
# Empty strings treated as None to avoid unexpected behavior
|
||||
attrs["assign_custom_fields_values"] = {
|
||||
field_id: (None if value == "" else value)
|
||||
@@ -3410,7 +3536,11 @@ class WorkflowActionSerializer(serializers.ModelSerializer[WorkflowAction]):
|
||||
|
||||
|
||||
class WorkflowSerializer(serializers.ModelSerializer[Workflow]):
|
||||
order = serializers.IntegerField(required=False)
|
||||
order = serializers.IntegerField(
|
||||
required=False,
|
||||
min_value=INT32_MIN,
|
||||
max_value=INT32_MAX,
|
||||
)
|
||||
|
||||
triggers = WorkflowTriggerSerializer(many=True)
|
||||
actions = WorkflowActionSerializer(many=True)
|
||||
@@ -3496,6 +3626,10 @@ class WorkflowSerializer(serializers.ModelSerializer[Workflow]):
|
||||
) -> None:
|
||||
set_triggers = []
|
||||
set_actions = []
|
||||
# Only rows already attached to this workflow may be updated by id, an id
|
||||
# from anywhere else would take over or overwrite another workflow's row
|
||||
own_trigger_ids = set(instance.triggers.values_list("pk", flat=True))
|
||||
own_action_ids = set(instance.actions.values_list("pk", flat=True))
|
||||
|
||||
if triggers is not None and triggers is not serializers.empty:
|
||||
for trigger in triggers:
|
||||
@@ -3528,8 +3662,10 @@ class WorkflowSerializer(serializers.ModelSerializer[Workflow]):
|
||||
)
|
||||
# Convert sources to strings to handle django-multiselectfield v1.0 changes
|
||||
WorkflowTriggerSerializer.normalize_workflow_trigger_sources(trigger)
|
||||
trigger_id = trigger.pop("id", None)
|
||||
trigger_instance, _ = WorkflowTrigger.objects.update_or_create(
|
||||
id=trigger.get("id"),
|
||||
# A row that is not already part of this workflow is never reused
|
||||
id=trigger_id if trigger_id in own_trigger_ids else None,
|
||||
defaults=trigger,
|
||||
)
|
||||
if filter_has_tags is not None:
|
||||
@@ -3587,30 +3723,24 @@ class WorkflowSerializer(serializers.ModelSerializer[Workflow]):
|
||||
email_data = action.pop("email", None)
|
||||
webhook_data = action.pop("webhook", None)
|
||||
|
||||
action_id = action.pop("id", None)
|
||||
action_instance, _ = WorkflowAction.objects.update_or_create(
|
||||
id=action.get("id"),
|
||||
# A row that is not already part of this workflow is never reused
|
||||
id=action_id if action_id in own_action_ids else None,
|
||||
defaults=action,
|
||||
)
|
||||
|
||||
if email_data is not None:
|
||||
serializer = WorkflowActionEmailSerializer(data=email_data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
email, _ = WorkflowActionEmail.objects.update_or_create(
|
||||
id=email_data.get("id"),
|
||||
defaults=serializer.validated_data,
|
||||
)
|
||||
action_instance.email = email
|
||||
action_instance.save()
|
||||
email_data = serializer.validated_data
|
||||
|
||||
if webhook_data is not None:
|
||||
serializer = WorkflowActionWebhookSerializer(data=webhook_data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
webhook, _ = WorkflowActionWebhook.objects.update_or_create(
|
||||
id=webhook_data.get("id"),
|
||||
defaults=serializer.validated_data,
|
||||
)
|
||||
action_instance.webhook = webhook
|
||||
action_instance.save()
|
||||
webhook_data = serializer.validated_data
|
||||
|
||||
save_action_email_and_webhook(action_instance, email_data, webhook_data)
|
||||
|
||||
if assign_tags is not None:
|
||||
action_instance.assign_tags.set(assign_tags)
|
||||
@@ -3711,13 +3841,22 @@ class TrashSerializer(SerializerWithPerms):
|
||||
)
|
||||
|
||||
def validate_documents(self, documents: list[int]) -> list[int]:
|
||||
count = Document.deleted_objects.filter(id__in=documents).count()
|
||||
count = Document.deleted_objects.filter(
|
||||
id__in=in_range_ids(documents),
|
||||
).count()
|
||||
if not count == len(documents):
|
||||
raise serializers.ValidationError(
|
||||
"Some documents in the list have not yet been deleted.",
|
||||
)
|
||||
return documents
|
||||
|
||||
def validate(self, attrs):
|
||||
if attrs.get("action") == "restore" and "documents" not in attrs:
|
||||
raise serializers.ValidationError(
|
||||
{"documents": "This field is required to restore documents."},
|
||||
)
|
||||
return attrs
|
||||
|
||||
|
||||
class StoragePathTestSerializer(SerializerWithPerms):
|
||||
path = serializers.CharField(
|
||||
|
||||
@@ -21,22 +21,25 @@ from channels.layers import get_channel_layer
|
||||
from django.conf import settings
|
||||
from django.contrib.auth.models import Group
|
||||
from django.contrib.auth.models import User
|
||||
from django.db import DatabaseError
|
||||
from django.db import close_old_connections
|
||||
from django.db import connections
|
||||
from django.db import models
|
||||
from django.db.models import Q
|
||||
from django.dispatch import receiver
|
||||
from django.utils import timezone
|
||||
from filelock import FileLock
|
||||
from rest_framework import serializers
|
||||
|
||||
from documents import matching
|
||||
from documents.caching import clear_document_caches
|
||||
from documents.caching import invalidate_llm_suggestions_cache
|
||||
from documents.caching import invalidate_suggestions_cache
|
||||
from documents.data_models import ConsumableDocument
|
||||
from documents.file_handling import create_source_path_directory
|
||||
from documents.file_handling import delete_empty_directories
|
||||
from documents.file_moves import move_files_for_document
|
||||
from documents.file_moves import request_file_move
|
||||
from documents.media_lock import media_lock
|
||||
from documents.file_handling import generate_filename
|
||||
from documents.file_handling import generate_unique_filename
|
||||
from documents.models import Correspondent
|
||||
from documents.models import CustomField
|
||||
from documents.models import CustomFieldInstance
|
||||
@@ -56,6 +59,7 @@ from documents.models import WorkflowTrigger
|
||||
from documents.permissions import restrict_queryset_to_visible
|
||||
from documents.plugins.helpers import DocumentsStatusManager
|
||||
from documents.templating.utils import convert_format_str_to_template_format
|
||||
from documents.utils import compute_checksum
|
||||
from documents.utils import copy_file_with_basic_stats
|
||||
from documents.workflows.actions import build_workflow_action_context
|
||||
from documents.workflows.actions import execute_email_action
|
||||
@@ -339,7 +343,7 @@ def set_storage_path(
|
||||
|
||||
# see empty_trash in documents/tasks.py for signal handling
|
||||
def cleanup_document_deletion(sender, instance, **kwargs) -> None:
|
||||
with media_lock():
|
||||
with FileLock(settings.MEDIA_LOCK):
|
||||
if settings.EMPTY_TRASH_DIR:
|
||||
# Find a non-conflicting filename in case a document with the same
|
||||
# name was moved to trash earlier
|
||||
@@ -405,6 +409,17 @@ def cleanup_document_deletion(sender, instance, **kwargs) -> None:
|
||||
)
|
||||
|
||||
|
||||
class CannotMoveFilesException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _path_matches_checksum(path: Path, checksum: str | None) -> bool:
|
||||
if checksum is None or not path.is_file():
|
||||
return False
|
||||
|
||||
return compute_checksum(path) == checksum
|
||||
|
||||
|
||||
def _filename_template_uses_custom_fields(doc: Document) -> bool:
|
||||
template = None
|
||||
if doc.storage_path is not None:
|
||||
@@ -427,37 +442,235 @@ def update_filename_and_move_files(
|
||||
instance: Document | CustomFieldInstance,
|
||||
**kwargs,
|
||||
) -> None:
|
||||
action = kwargs.get("action")
|
||||
|
||||
if kwargs.get("reverse") and action == "pre_clear":
|
||||
# tag.documents.clear(): Django sends pk_set=None for both clear
|
||||
# actions, and the rows are gone by post_clear. Remember the affected
|
||||
# documents here, on the instance both signals share.
|
||||
instance._cleared_document_pks = list(
|
||||
instance.documents.values_list("pk", flat=True),
|
||||
)
|
||||
return
|
||||
|
||||
if action is not None and action not in {"post_add", "post_remove", "post_clear"}:
|
||||
# m2m_changed fires pre_* and post_* actions; only post_* describe the
|
||||
# relation state the filename should follow.
|
||||
return
|
||||
|
||||
if kwargs.get("reverse"):
|
||||
# tag.documents.add(doc): instance is the Tag, pk_set holds Document pks.
|
||||
pk_set = kwargs.get("pk_set")
|
||||
if action == "post_clear":
|
||||
pk_set = instance.__dict__.pop("_cleared_document_pks", ())
|
||||
for document in Document.objects.filter(pk__in=pk_set or ()):
|
||||
request_file_move(document)
|
||||
return
|
||||
|
||||
if isinstance(instance, CustomFieldInstance):
|
||||
if not _filename_template_uses_custom_fields(instance.document):
|
||||
return
|
||||
instance = instance.document
|
||||
|
||||
request_file_move(instance)
|
||||
def validate_move(instance, old_path: Path, new_path: Path, root: Path) -> None:
|
||||
if not new_path.is_relative_to(root):
|
||||
msg = (
|
||||
f"Document {instance!s}: Refusing to move file outside root {root}: "
|
||||
f"{new_path}."
|
||||
)
|
||||
logger.warning(msg)
|
||||
raise CannotMoveFilesException(msg)
|
||||
|
||||
if not old_path.is_file():
|
||||
# Can't do anything if the old file does not exist anymore.
|
||||
msg = f"Document {instance!s}: File {old_path} doesn't exist."
|
||||
logger.fatal(msg)
|
||||
raise CannotMoveFilesException(msg)
|
||||
|
||||
if new_path.is_file():
|
||||
# Can't do anything if the new file already exists. Skip updating file.
|
||||
msg = f"Document {instance!s}: Cannot rename file since target path {new_path} already exists."
|
||||
logger.warning(msg)
|
||||
raise CannotMoveFilesException(msg)
|
||||
|
||||
if not instance.filename:
|
||||
# Can't update the filename if there is no filename to begin with
|
||||
# This happens when the consumer creates a new document.
|
||||
# The document is modified and saved multiple times, and only after
|
||||
# everything is done (i.e., the generated filename is final),
|
||||
# filename will be set to the location where the consumer has put
|
||||
# the file.
|
||||
#
|
||||
# This will in turn cause this logic to move the file where it belongs.
|
||||
return
|
||||
|
||||
with FileLock(settings.MEDIA_LOCK):
|
||||
# If this was waiting for the lock, the filename or archive_filename
|
||||
# of this document may have been updated. This happens if multiple updates
|
||||
# get queued from the UI for the same document
|
||||
# So freshen up the data before doing anything
|
||||
instance.refresh_from_db()
|
||||
|
||||
try:
|
||||
old_filename = instance.filename
|
||||
old_source_path = instance.source_path
|
||||
move_original = False
|
||||
original_already_moved = False
|
||||
|
||||
old_archive_filename = instance.archive_filename
|
||||
old_archive_path = instance.archive_path
|
||||
move_archive = False
|
||||
archive_already_moved = False
|
||||
|
||||
candidate_filename = generate_filename(instance)
|
||||
if len(str(candidate_filename)) > Document.MAX_STORED_FILENAME_LENGTH:
|
||||
msg = (
|
||||
f"Document {instance!s}: Generated filename exceeds db path "
|
||||
f"limit ({len(str(candidate_filename))} > "
|
||||
f"{Document.MAX_STORED_FILENAME_LENGTH}): {candidate_filename!s}"
|
||||
)
|
||||
logger.warning(msg)
|
||||
raise CannotMoveFilesException(msg)
|
||||
|
||||
candidate_source_path = (
|
||||
settings.ORIGINALS_DIR / candidate_filename
|
||||
).resolve()
|
||||
if candidate_filename == Path(old_filename):
|
||||
new_filename = Path(old_filename)
|
||||
elif (
|
||||
candidate_source_path.exists()
|
||||
and candidate_source_path != old_source_path
|
||||
):
|
||||
if not old_source_path.is_file() and _path_matches_checksum(
|
||||
candidate_source_path,
|
||||
instance.checksum,
|
||||
):
|
||||
new_filename = candidate_filename
|
||||
original_already_moved = True
|
||||
else:
|
||||
# Only fall back to unique search when there is an actual conflict
|
||||
new_filename = generate_unique_filename(instance)
|
||||
else:
|
||||
new_filename = candidate_filename
|
||||
|
||||
# Need to convert to string to be able to save it to the db
|
||||
instance.filename = str(new_filename)
|
||||
move_original = (
|
||||
old_filename != instance.filename and not original_already_moved
|
||||
)
|
||||
|
||||
if instance.has_archive_version:
|
||||
archive_candidate = generate_filename(instance, archive_filename=True)
|
||||
if len(str(archive_candidate)) > Document.MAX_STORED_FILENAME_LENGTH:
|
||||
msg = (
|
||||
f"Document {instance!s}: Generated archive filename exceeds "
|
||||
f"db path limit ({len(str(archive_candidate))} > "
|
||||
f"{Document.MAX_STORED_FILENAME_LENGTH}): {archive_candidate!s}"
|
||||
)
|
||||
logger.warning(msg)
|
||||
raise CannotMoveFilesException(msg)
|
||||
archive_candidate_path = (
|
||||
settings.ARCHIVE_DIR / archive_candidate
|
||||
).resolve()
|
||||
if archive_candidate == Path(old_archive_filename):
|
||||
new_archive_filename = Path(old_archive_filename)
|
||||
elif (
|
||||
archive_candidate_path.exists()
|
||||
and archive_candidate_path != old_archive_path
|
||||
):
|
||||
if not old_archive_path.is_file() and _path_matches_checksum(
|
||||
archive_candidate_path,
|
||||
instance.archive_checksum,
|
||||
):
|
||||
new_archive_filename = archive_candidate
|
||||
archive_already_moved = True
|
||||
else:
|
||||
new_archive_filename = generate_unique_filename(
|
||||
instance,
|
||||
archive_filename=True,
|
||||
)
|
||||
else:
|
||||
new_archive_filename = archive_candidate
|
||||
|
||||
instance.archive_filename = str(new_archive_filename)
|
||||
|
||||
move_archive = (
|
||||
old_archive_filename != instance.archive_filename
|
||||
and not archive_already_moved
|
||||
)
|
||||
else:
|
||||
move_archive = False
|
||||
|
||||
if not move_original and not move_archive:
|
||||
updates = {"modified": timezone.now()}
|
||||
if old_filename != instance.filename:
|
||||
updates["filename"] = instance.filename
|
||||
if old_archive_filename != instance.archive_filename:
|
||||
updates["archive_filename"] = instance.archive_filename
|
||||
|
||||
# Don't save() here to prevent infinite recursion.
|
||||
Document.objects.filter(pk=instance.pk).update(**updates)
|
||||
return
|
||||
|
||||
if move_original:
|
||||
validate_move(
|
||||
instance,
|
||||
old_source_path,
|
||||
instance.source_path,
|
||||
settings.ORIGINALS_DIR,
|
||||
)
|
||||
create_source_path_directory(instance.source_path)
|
||||
shutil.move(old_source_path, instance.source_path)
|
||||
|
||||
if move_archive:
|
||||
validate_move(
|
||||
instance,
|
||||
old_archive_path,
|
||||
instance.archive_path,
|
||||
settings.ARCHIVE_DIR,
|
||||
)
|
||||
create_source_path_directory(instance.archive_path)
|
||||
shutil.move(old_archive_path, instance.archive_path)
|
||||
|
||||
# Don't save() here to prevent infinite recursion.
|
||||
Document.global_objects.filter(pk=instance.pk).update(
|
||||
filename=instance.filename,
|
||||
archive_filename=instance.archive_filename,
|
||||
modified=timezone.now(),
|
||||
)
|
||||
# Clear any caching for this document. Slightly overkill, but not terrible
|
||||
clear_document_caches(instance.pk)
|
||||
|
||||
except (OSError, DatabaseError, CannotMoveFilesException) as e:
|
||||
logger.warning(f"Exception during file handling: {e}")
|
||||
# This happens when either:
|
||||
# - moving the files failed due to file system errors
|
||||
# - saving to the database failed due to database errors
|
||||
# In both cases, we need to revert to the original state.
|
||||
|
||||
# Try to move files to their original location.
|
||||
try:
|
||||
if move_original and instance.source_path.is_file():
|
||||
logger.info("Restoring previous original path")
|
||||
shutil.move(instance.source_path, old_source_path)
|
||||
|
||||
if move_archive and instance.archive_path.is_file():
|
||||
logger.info("Restoring previous archive path")
|
||||
shutil.move(instance.archive_path, old_archive_path)
|
||||
|
||||
except Exception:
|
||||
# This is fine, since:
|
||||
# A: if we managed to move source from A to B, we will also
|
||||
# manage to move it from B to A. If not, we have a serious
|
||||
# issue that's going to get caught by the santiy checker.
|
||||
# All files remain in place and will never be overwritten,
|
||||
# so this is not the end of the world.
|
||||
# B: if moving the original file failed, nothing has changed
|
||||
# anyway.
|
||||
pass
|
||||
|
||||
# restore old values on the instance
|
||||
instance.filename = old_filename
|
||||
instance.archive_filename = old_archive_filename
|
||||
|
||||
# finally, remove any empty sub folders. This will do nothing if
|
||||
# something has failed above.
|
||||
if not old_source_path.is_file():
|
||||
delete_empty_directories(
|
||||
Path(old_source_path).parent,
|
||||
root=settings.ORIGINALS_DIR,
|
||||
)
|
||||
|
||||
if instance.has_archive_version and not old_archive_path.is_file():
|
||||
delete_empty_directories(
|
||||
Path(old_archive_path).parent,
|
||||
root=settings.ARCHIVE_DIR,
|
||||
)
|
||||
|
||||
# Keep version files in sync with root
|
||||
if instance.root_document_id is None:
|
||||
for version_doc in Document.objects.filter(root_document_id=instance.pk).only(
|
||||
"pk",
|
||||
):
|
||||
update_filename_and_move_files(
|
||||
Document,
|
||||
version_doc,
|
||||
)
|
||||
|
||||
|
||||
@shared_task
|
||||
@@ -482,8 +695,7 @@ def process_cf_select_update(custom_field: CustomField) -> None:
|
||||
|
||||
for cf_instance in custom_field.fields.select_related("document").iterator():
|
||||
# Update the filename and move files if necessary
|
||||
if _filename_template_uses_custom_fields(cf_instance.document):
|
||||
move_files_for_document(cf_instance.document_id)
|
||||
update_filename_and_move_files(CustomFieldInstance, cf_instance)
|
||||
|
||||
|
||||
# should be disabled in /src/documents/management/commands/document_importer.py handle
|
||||
|
||||
+9
-49
@@ -16,6 +16,7 @@ from django.db import models
|
||||
from django.db import transaction
|
||||
from django.db.models.signals import post_save
|
||||
from django.utils import timezone
|
||||
from filelock import FileLock
|
||||
|
||||
from documents import sanity_checker
|
||||
from documents.barcodes import BarcodePlugin
|
||||
@@ -41,7 +42,6 @@ from documents.double_sided import CollatePlugin
|
||||
from documents.file_handling import create_source_path_directory
|
||||
from documents.file_handling import generate_unique_filename
|
||||
from documents.matching import prefilter_documents_by_workflowtrigger
|
||||
from documents.media_lock import media_lock
|
||||
from documents.models import Correspondent
|
||||
from documents.models import CustomFieldInstance
|
||||
from documents.models import Document
|
||||
@@ -311,14 +311,9 @@ def sanity_check(*, raise_on_error: bool = True) -> str:
|
||||
|
||||
@shared_task
|
||||
def bulk_update_documents(document_ids) -> None:
|
||||
from documents.file_moves import flush_pending_file_moves
|
||||
from documents.search import get_backend
|
||||
|
||||
document_ids = list(document_ids)
|
||||
# Bulk edits write through querysets and relation tables, which skip
|
||||
# auto_now, and the file mover only writes when a path changes. Record the
|
||||
# edit here, before the signals and notifications below read the documents.
|
||||
Document.objects.filter(id__in=document_ids).update(modified=timezone.now())
|
||||
# Annotated so the signal handlers below (e.g. matching) don't query the
|
||||
# versions of each document. Indexing re-queries and re-annotates its own
|
||||
# copy via add_or_update_ids() below, after these signals (and any
|
||||
@@ -329,32 +324,13 @@ def bulk_update_documents(document_ids) -> None:
|
||||
|
||||
for doc in documents:
|
||||
clear_document_caches(doc.pk)
|
||||
# The bulk edit wrote through querysets and relation tables, so this
|
||||
# post_save is what requests the move. Move before document_updated,
|
||||
# whose websocket notification must carry the final filename and
|
||||
# modified timestamp.
|
||||
post_save.send(Document, instance=doc, created=False)
|
||||
flush_pending_file_moves()
|
||||
# The move changed the stored paths. Workflows read source_path from
|
||||
# this instance, so bring it up to date. Not refresh_from_db(), which
|
||||
# would drop the effective content annotation.
|
||||
paths = (
|
||||
Document.global_objects.filter(pk=doc.pk)
|
||||
.values_list("filename", "archive_filename")
|
||||
.first()
|
||||
)
|
||||
if paths is not None:
|
||||
doc.filename, doc.archive_filename = paths
|
||||
document_updated.send(
|
||||
sender=None,
|
||||
document=doc,
|
||||
logging_group=uuid.uuid4(),
|
||||
skip_ai_index=True, # bulk path calls update_llm_index once below
|
||||
)
|
||||
# Moves requested by workflows that document_updated ran. Moving per
|
||||
# document, rather than at the end of the task, keeps a long bulk
|
||||
# edit making steady progress.
|
||||
flush_pending_file_moves()
|
||||
post_save.send(Document, instance=doc, created=False)
|
||||
|
||||
with get_backend().batch_update() as batch:
|
||||
batch.add_or_update_ids(document_ids)
|
||||
@@ -442,13 +418,7 @@ def update_document_content_maybe_archive_file(
|
||||
|
||||
thumbnail = parser.get_thumbnail(document.source_path, mime_type)
|
||||
|
||||
# media.lock first, then the transaction: never wait on media.lock
|
||||
# while this transaction holds the document row. Also keeps the
|
||||
# unique archive filename generation under the lock.
|
||||
with media_lock(), transaction.atomic():
|
||||
# Loaded before the (long) parse; read current metadata now
|
||||
# that the lock is held, for the archive filename.
|
||||
document.refresh_from_db()
|
||||
with transaction.atomic():
|
||||
oldDocument = Document.objects.get(pk=document.pk)
|
||||
if parser.get_archive_path():
|
||||
checksum = compute_checksum(parser.get_archive_path())
|
||||
@@ -513,10 +483,11 @@ def update_document_content_maybe_archive_file(
|
||||
modified=timezone.now(),
|
||||
)
|
||||
|
||||
if parser.get_archive_path():
|
||||
create_source_path_directory(document.archive_path)
|
||||
shutil.move(parser.get_archive_path(), document.archive_path)
|
||||
shutil.move(thumbnail, document.thumbnail_path)
|
||||
with FileLock(settings.MEDIA_LOCK):
|
||||
if parser.get_archive_path():
|
||||
create_source_path_directory(document.archive_path)
|
||||
shutil.move(parser.get_archive_path(), document.archive_path)
|
||||
shutil.move(thumbnail, document.thumbnail_path)
|
||||
|
||||
document.refresh_from_db()
|
||||
logger.info(
|
||||
@@ -561,11 +532,7 @@ def empty_trash(doc_ids=None) -> None:
|
||||
deleted_document_ids = list(documents.values_list("id", flat=True))
|
||||
# Temporarily connect the cleanup handler
|
||||
models.signals.post_delete.connect(cleanup_document_deletion, sender=Document)
|
||||
# media.lock before Django's delete transaction: post_delete runs
|
||||
# cleanup_document_deletion inside it while the rows are locked, and
|
||||
# that handler re-enters the lock instead of waiting.
|
||||
with media_lock():
|
||||
documents.delete() # this is effectively a hard delete
|
||||
documents.delete() # this is effectively a hard delete
|
||||
logger.info(f"Deleted {len(deleted_document_ids)} documents from trash")
|
||||
|
||||
if settings.AUDIT_LOG_ENABLED:
|
||||
@@ -595,8 +562,6 @@ def check_scheduled_workflows() -> None:
|
||||
|
||||
Once a document satisfies this condition, and recurring/non-recurring constraints are met, the workflow is run.
|
||||
"""
|
||||
from documents.file_moves import flush_pending_file_moves
|
||||
|
||||
scheduled_workflows = get_workflows_for_trigger(
|
||||
WorkflowTrigger.WorkflowTriggerType.SCHEDULED,
|
||||
)
|
||||
@@ -719,11 +684,6 @@ def check_scheduled_workflows() -> None:
|
||||
workflow_to_run=workflow,
|
||||
document=document,
|
||||
)
|
||||
# Move this document's files now rather than at the end
|
||||
# of the task, so a long run makes steady progress and
|
||||
# the notification below carries the final filename and
|
||||
# modified timestamp.
|
||||
flush_pending_file_moves()
|
||||
# Scheduled workflows dont send document_updated signal, so send a websocket update here to ensure clients are updated
|
||||
send_websocket_document_updated(
|
||||
sender=None,
|
||||
|
||||
@@ -75,3 +75,17 @@ def searchable_document(_search_index: None) -> "Document":
|
||||
def mock_zone_ocr_run(mocker: "MockerFixture") -> "MagicMock":
|
||||
"""Patch the subprocess runner used by zone OCR (tesseract and pdftoppm)."""
|
||||
return mocker.patch("documents.zone_ocr.subprocess.run")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def config_id(db: None) -> int:
|
||||
"""
|
||||
The id of the application configuration row. A migration creates it, but a test
|
||||
that flushes the database in the same worker removes it, so make sure it exists.
|
||||
"""
|
||||
from paperless.models import ApplicationConfiguration
|
||||
|
||||
config = ApplicationConfiguration.objects.first()
|
||||
if config is None:
|
||||
config = ApplicationConfiguration.objects.create()
|
||||
return config.pk
|
||||
@@ -0,0 +1,97 @@
|
||||
from collections.abc import Generator
|
||||
|
||||
import pytest
|
||||
from django.core.exceptions import ValidationError
|
||||
from django.db import connection
|
||||
from pytest_mock import MockerFixture
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import Document
|
||||
from paperless_testing.factories import DocumentFactory
|
||||
|
||||
SIGNED_INT32_RANGE = (-(2**31), 2**31 - 1)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def signed_int32_column(mocker: MockerFixture) -> Generator[None, None, None]:
|
||||
"""
|
||||
Make the database report a signed 32 bit integer range for the column, as
|
||||
PostgreSQL does. Django caches the validators of a field, so the cache is
|
||||
dropped before and after.
|
||||
"""
|
||||
field = Document._meta.get_field("archive_serial_number")
|
||||
field.__dict__.pop("validators", None)
|
||||
mocker.patch.object(
|
||||
connection.ops,
|
||||
"integer_field_range",
|
||||
return_value=SIGNED_INT32_RANGE,
|
||||
)
|
||||
yield
|
||||
field.__dict__.pop("validators", None)
|
||||
|
||||
|
||||
class TestArchiveSerialNumberRange:
|
||||
@pytest.mark.usefixtures("signed_int32_column")
|
||||
@pytest.mark.parametrize("value", [2**31, 3_000_000_000, 0xFF_FF_FF_FF])
|
||||
def test_value_beyond_the_column_is_rejected(self, value: int) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A database whose integer column stops at 2**31 - 1
|
||||
WHEN:
|
||||
- An ASN inside the fixed range but beyond the column is validated
|
||||
THEN:
|
||||
- It is rejected, the database would have raised an error
|
||||
"""
|
||||
with pytest.raises(ValidationError):
|
||||
Document.validate_archive_serial_number(value)
|
||||
|
||||
@pytest.mark.usefixtures("signed_int32_column")
|
||||
@pytest.mark.parametrize("value", [0, 1, 2**31 - 1])
|
||||
def test_value_within_the_column_is_accepted(self, value: int) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A database whose integer column stops at 2**31 - 1
|
||||
WHEN:
|
||||
- An ASN inside the column is validated
|
||||
THEN:
|
||||
- It is accepted
|
||||
"""
|
||||
Document.validate_archive_serial_number(value)
|
||||
|
||||
@pytest.mark.parametrize("value", [-1, 0xFF_FF_FF_FF + 1])
|
||||
def test_value_outside_the_fixed_range_is_rejected(self, value: int) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The fixed ASN range
|
||||
WHEN:
|
||||
- A value outside of it is validated
|
||||
THEN:
|
||||
- It is rejected whatever the database
|
||||
"""
|
||||
with pytest.raises(ValidationError):
|
||||
Document.validate_archive_serial_number(value)
|
||||
|
||||
@pytest.mark.usefixtures("signed_int32_column")
|
||||
def test_api_answers_400_for_a_value_beyond_the_column(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document and a database whose integer column stops at 2**31 - 1
|
||||
WHEN:
|
||||
- The document is patched with a larger ASN
|
||||
THEN:
|
||||
- The response is a 400 naming the field, not a database error
|
||||
"""
|
||||
document = DocumentFactory.create()
|
||||
|
||||
response = admin_client.patch(
|
||||
f"/api/documents/{document.pk}/",
|
||||
{"archive_serial_number": 3_000_000_000},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "archive_serial_number" in response.data
|
||||
@@ -0,0 +1,114 @@
|
||||
import pytest
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import CustomField
|
||||
from paperless_testing.http import send_json
|
||||
|
||||
|
||||
class TestCustomFieldExtraData:
|
||||
@pytest.mark.parametrize("extra_data", [[1], "text", 5, True])
|
||||
def test_extra_data_that_is_not_an_object_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
extra_data: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A custom field is created with extra data that is not an object
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/custom_fields/",
|
||||
{"name": "field", "data_type": "string", "extra_data": extra_data},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "extra_data" in response.data
|
||||
|
||||
@pytest.mark.parametrize("extra_data", [None, {}])
|
||||
def test_null_or_empty_extra_data_is_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
extra_data: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A string custom field has null or empty extra data
|
||||
THEN:
|
||||
- It is created
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/custom_fields/",
|
||||
{"name": "field", "data_type": "string", "extra_data": extra_data},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("extra_data", "term"),
|
||||
[
|
||||
pytest.param([1], "1", id="list"),
|
||||
pytest.param(
|
||||
{"select_options": [1, "x"]},
|
||||
"select",
|
||||
id="options-not-objects",
|
||||
),
|
||||
pytest.param(
|
||||
{"select_options": None, "note": "zzz"},
|
||||
"zzz",
|
||||
id="options-null",
|
||||
),
|
||||
pytest.param(
|
||||
{"select_options": 5, "note": "zzz"},
|
||||
"zzz",
|
||||
id="options-a-number",
|
||||
),
|
||||
pytest.param(
|
||||
{"select_options": [{"label": None, "id": "zzz"}]},
|
||||
"zzz",
|
||||
id="label-missing",
|
||||
),
|
||||
pytest.param(
|
||||
{"select_options": [{"label": 5, "id": "zzz"}]},
|
||||
"zzz",
|
||||
id="label-not-a-string",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_the_deprecated_custom_fields_filter_survives_odd_stored_data(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
db: None,
|
||||
extra_data: object,
|
||||
term: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A custom field whose stored extra data an older version allowed
|
||||
WHEN:
|
||||
- Documents are filtered with the deprecated custom_fields__icontains
|
||||
THEN:
|
||||
- The request succeeds
|
||||
"""
|
||||
CustomField.objects.create(
|
||||
name="legacy",
|
||||
data_type=CustomField.FieldDataType.SELECT,
|
||||
extra_data=extra_data,
|
||||
)
|
||||
|
||||
response = admin_client.get(
|
||||
"/api/documents/",
|
||||
{"custom_fields__icontains": term},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
@@ -0,0 +1,741 @@
|
||||
import pytest
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import UiSettings
|
||||
from documents.models import WorkflowAction
|
||||
from documents.models import WorkflowActionEmail
|
||||
from paperless_testing.http import send_json
|
||||
|
||||
EMAIL = {
|
||||
"subject": "Subject",
|
||||
"body": "Body",
|
||||
"to": "someone@example.com",
|
||||
"include_document": False,
|
||||
}
|
||||
|
||||
|
||||
class TestObjectJsonBody:
|
||||
@pytest.mark.parametrize("body", [[], [1, 2], True, 1, 1.5, None, "text"])
|
||||
@pytest.mark.parametrize(
|
||||
("method", "path"),
|
||||
[
|
||||
pytest.param("PATCH", "/api/workflow_triggers/1/", id="trigger-patch"),
|
||||
pytest.param("PATCH", "/api/workflow_actions/1/", id="action-patch"),
|
||||
pytest.param("POST", "/api/documents/bulk_edit/", id="bulk-edit"),
|
||||
pytest.param(
|
||||
"POST",
|
||||
"/api/processed_mail/bulk_delete/",
|
||||
id="processed-mail-bulk-delete",
|
||||
),
|
||||
pytest.param("POST", "/api/tags/", id="tags-create"),
|
||||
],
|
||||
)
|
||||
def test_body_that_is_not_an_object_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
method: str,
|
||||
path: str,
|
||||
body: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A JSON body that is a list or a scalar is sent
|
||||
THEN:
|
||||
- The response is a 400, never a server error
|
||||
"""
|
||||
response = send_json(admin_client, method, path, body)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
|
||||
class TestNullAndWrongTypeFields:
|
||||
@pytest.mark.parametrize("password", [["x"], 5, {"a": 1}, True])
|
||||
def test_password_that_is_not_a_string_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
password: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A user
|
||||
WHEN:
|
||||
- The password is sent as something other than a string
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/users/{admin_user.pk}/",
|
||||
{"password": password},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "password" in response.data
|
||||
|
||||
@pytest.mark.parametrize("ui_settings", [None, {}])
|
||||
def test_ui_settings_that_are_null_or_empty_are_accepted_and_readable(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
ui_settings: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- UI settings are saved as null or with an unexpected update_checking
|
||||
THEN:
|
||||
- The request does not fail with a server error
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/ui_settings/",
|
||||
{"settings": ui_settings},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
# What was saved must also be readable, null used to break the GET afterwards
|
||||
assert admin_client.get("/api/ui_settings/").status_code == status.HTTP_200_OK
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"ui_settings",
|
||||
[[1], "text", 5, {"update_checking": [1]}, {"update_checking": "x"}],
|
||||
)
|
||||
def test_ui_settings_of_the_wrong_shape_are_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
ui_settings: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- UI settings are saved that are not an object, or have a mistyped
|
||||
update_checking
|
||||
THEN:
|
||||
- The response is a 400, not stored to break the next read
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/ui_settings/",
|
||||
{"settings": ui_settings},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"stored",
|
||||
[None, [1], "text", {"update_checking": "x"}, {"update_checking": [1]}],
|
||||
)
|
||||
def test_reading_ui_settings_saved_in_an_unexpected_shape_still_works(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
stored: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- UI settings stored in a shape the API no longer accepts, as older
|
||||
versions allowed it
|
||||
WHEN:
|
||||
- The settings are read
|
||||
THEN:
|
||||
- The request succeeds
|
||||
"""
|
||||
UiSettings.objects.update_or_create(
|
||||
user=admin_user,
|
||||
defaults={"settings": stored},
|
||||
)
|
||||
|
||||
response = admin_client.get("/api/ui_settings/")
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"field",
|
||||
["llm_api_key", "llm_embedding_api_key", "remote_ocr_api_key"],
|
||||
)
|
||||
@pytest.mark.parametrize("value", [5, ["a"], {"a": 1}, True])
|
||||
def test_config_api_key_that_is_not_a_string_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
config_id: int,
|
||||
field: str,
|
||||
value: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The application configuration
|
||||
WHEN:
|
||||
- An obfuscated key field is sent as something other than a string
|
||||
THEN:
|
||||
- The response is a 400, not a server error
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/config/{config_id}/",
|
||||
{field: value},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert field in response.data
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"display_fields",
|
||||
[["custom_field_abc"], ["custom_field_"], ["xcustom_field_1"]],
|
||||
)
|
||||
def test_saved_view_custom_field_name_must_be_well_formed(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
display_fields: list,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A saved view lists a custom field display name without a numeric id
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/saved_views/",
|
||||
{
|
||||
"name": "view",
|
||||
"show_on_dashboard": False,
|
||||
"show_in_sidebar": False,
|
||||
"sort_field": "created",
|
||||
"filter_rules": [],
|
||||
"display_fields": display_fields,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize("display_fields", [5, True, {"a": 1}, "text"])
|
||||
def test_saved_view_display_fields_must_be_a_list(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
display_fields: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A saved view is created with display fields that are not a list
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/saved_views/",
|
||||
{
|
||||
"name": "view",
|
||||
"show_on_dashboard": False,
|
||||
"show_in_sidebar": False,
|
||||
"sort_field": "created",
|
||||
"filter_rules": [],
|
||||
"display_fields": display_fields,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize("display_fields", [[None], [5], [["x"]]])
|
||||
def test_saved_view_display_field_that_is_not_a_string_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
display_fields: list,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A saved view is created with display fields that are not strings
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/saved_views/",
|
||||
{
|
||||
"name": "view",
|
||||
"show_on_dashboard": False,
|
||||
"show_in_sidebar": False,
|
||||
"sort_field": "created",
|
||||
"filter_rules": [],
|
||||
"display_fields": display_fields,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"extra_data",
|
||||
[None, {}, {"select_options": None}, {"select_options": [1, 2]}, [1]],
|
||||
)
|
||||
def test_select_custom_field_without_valid_options_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
extra_data: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A select custom field is created without usable options
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/custom_fields/",
|
||||
{"name": "select", "data_type": "select", "extra_data": extra_data},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
def test_monetary_custom_field_with_null_extra_data_is_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A monetary custom field is created with null extra data
|
||||
THEN:
|
||||
- It is created
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/custom_fields/",
|
||||
{"name": "money", "data_type": "monetary", "extra_data": None},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
|
||||
@pytest.mark.parametrize("values", [[1], "text", 5])
|
||||
def test_workflow_custom_field_values_must_be_an_object(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
values: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A workflow action carries custom field values that are not an object
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflows/",
|
||||
{
|
||||
"name": "workflow",
|
||||
"order": 0,
|
||||
"enabled": True,
|
||||
"triggers": [{"type": 2, "sources": [1], "matching_algorithm": 0}],
|
||||
"actions": [{"type": 1, "assign_custom_fields_values": values}],
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
|
||||
class TestRequiredFields:
|
||||
def test_share_link_requires_a_document(self, admin_client: APIClient) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A share link is created without a document
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = send_json(admin_client, "POST", "/api/share_links/", {})
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "document" in response.data
|
||||
|
||||
def test_restoring_from_the_trash_requires_documents(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- The trash is asked to restore without saying which documents
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = send_json(admin_client, "POST", "/api/trash/", {"action": "restore"})
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "documents" in response.data
|
||||
|
||||
@pytest.mark.parametrize("action", ["restore", "empty"])
|
||||
def test_trash_document_id_beyond_the_database_range_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
action: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- The trash is given a document id no row can have
|
||||
THEN:
|
||||
- The response is a 400, as for any document that is not in the trash
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/trash/",
|
||||
{"action": action, "documents": [2**70]},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize("method", ["split", "delete_pages", "edit_pdf"])
|
||||
def test_single_document_bulk_methods_reject_an_empty_selection(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
method: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A method that works on exactly one document gets none
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/documents/bulk_edit/",
|
||||
{
|
||||
"documents": [],
|
||||
"method": method,
|
||||
"parameters": {
|
||||
"pages": "1",
|
||||
"operations": [{"page": 1}],
|
||||
"split_pages": [[1]],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
def test_edit_pdf_endpoint_rejects_an_empty_selection(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- The edit_pdf endpoint gets no documents
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/documents/edit_pdf/",
|
||||
{"documents": [], "operations": [{"page": 1}]},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
|
||||
class TestSharedByFilter:
|
||||
@pytest.mark.parametrize("value", ["false", "abc", "1.5", str(2**63)])
|
||||
def test_non_integer_user_id_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
value: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- shared_by__id is not an integer user id
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = admin_client.get("/api/documents/", {"shared_by__id": value})
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize("value", ["", "1"])
|
||||
def test_empty_or_valid_user_id_works(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
value: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- shared_by__id is empty or a user id
|
||||
THEN:
|
||||
- The request succeeds
|
||||
"""
|
||||
response = admin_client.get("/api/documents/", {"shared_by__id": value})
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
|
||||
class TestStandaloneWorkflowActions:
|
||||
def test_create_with_nested_email(self, admin_client: APIClient) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- An email action is created through the standalone endpoint
|
||||
THEN:
|
||||
- The action and its email are both stored
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflow_actions/",
|
||||
{"type": WorkflowAction.WorkflowActionType.EMAIL, "email": EMAIL},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
action = WorkflowAction.objects.get(pk=response.data["id"])
|
||||
assert action.email is not None
|
||||
assert action.email.subject == "Subject"
|
||||
|
||||
def test_update_changes_the_existing_email_row(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An email action
|
||||
WHEN:
|
||||
- Its email is changed through the standalone endpoint
|
||||
THEN:
|
||||
- The existing email row is updated, no new row is made
|
||||
"""
|
||||
created = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflow_actions/",
|
||||
{"type": WorkflowAction.WorkflowActionType.EMAIL, "email": EMAIL},
|
||||
)
|
||||
action = WorkflowAction.objects.get(pk=created.data["id"])
|
||||
email_id = action.email_id
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/workflow_actions/{action.pk}/",
|
||||
{"email": {**EMAIL, "subject": "Changed"}},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
# The response must show the saved value, not the row loaded before the update
|
||||
assert response.data["email"]["subject"] == "Changed"
|
||||
action.refresh_from_db()
|
||||
assert action.email_id == email_id
|
||||
assert WorkflowActionEmail.objects.get(pk=email_id).subject == "Changed"
|
||||
assert WorkflowActionEmail.objects.count() == 1
|
||||
|
||||
def test_null_email_leaves_the_existing_email_alone(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An email action
|
||||
WHEN:
|
||||
- It is patched with a null email
|
||||
THEN:
|
||||
- The email is kept, null is a no-op as in the nested workflow serializer
|
||||
"""
|
||||
created = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflow_actions/",
|
||||
{"type": WorkflowAction.WorkflowActionType.EMAIL, "email": EMAIL},
|
||||
)
|
||||
action = WorkflowAction.objects.get(pk=created.data["id"])
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/workflow_actions/{action.pk}/",
|
||||
{"email": None},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
action.refresh_from_db()
|
||||
assert action.email is not None
|
||||
assert action.email.subject == "Subject"
|
||||
|
||||
def test_an_id_in_the_payload_cannot_reach_another_actions_email(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An email action
|
||||
WHEN:
|
||||
- A second action is created with the first action's email id in its payload
|
||||
THEN:
|
||||
- The first email is untouched and the second action gets its own row
|
||||
"""
|
||||
first = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflow_actions/",
|
||||
{"type": WorkflowAction.WorkflowActionType.EMAIL, "email": EMAIL},
|
||||
)
|
||||
first_email = WorkflowAction.objects.get(pk=first.data["id"]).email
|
||||
|
||||
second = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflow_actions/",
|
||||
{
|
||||
"type": WorkflowAction.WorkflowActionType.EMAIL,
|
||||
"email": {**EMAIL, "id": first_email.pk, "subject": "Hijacked"},
|
||||
},
|
||||
)
|
||||
|
||||
assert second.status_code == status.HTTP_201_CREATED
|
||||
first_email.refresh_from_db()
|
||||
assert first_email.subject == "Subject"
|
||||
assert WorkflowAction.objects.get(pk=second.data["id"]).email_id != (
|
||||
first_email.pk
|
||||
)
|
||||
|
||||
|
||||
BEYOND_THE_DATABASE = 2**70
|
||||
|
||||
|
||||
class TestIdListsBeyondTheDatabaseRange:
|
||||
@pytest.mark.parametrize(
|
||||
("path", "body"),
|
||||
[
|
||||
pytest.param(
|
||||
"/api/documents/bulk_edit/",
|
||||
{"documents": [BEYOND_THE_DATABASE], "method": "delete"},
|
||||
id="bulk-edit-documents",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/bulk_edit/",
|
||||
{
|
||||
"documents": [],
|
||||
"method": "modify_tags",
|
||||
"parameters": {"add_tags": [BEYOND_THE_DATABASE]},
|
||||
},
|
||||
id="bulk-edit-tags",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/bulk_edit/",
|
||||
{
|
||||
"documents": [],
|
||||
"method": "modify_custom_fields",
|
||||
"parameters": {
|
||||
"add_custom_fields": [BEYOND_THE_DATABASE],
|
||||
"remove_custom_fields": [],
|
||||
},
|
||||
},
|
||||
id="bulk-edit-custom-fields",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/delete/",
|
||||
{"documents": [BEYOND_THE_DATABASE]},
|
||||
id="delete",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/reprocess/",
|
||||
{"documents": [BEYOND_THE_DATABASE]},
|
||||
id="reprocess",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/rotate/",
|
||||
{"documents": [BEYOND_THE_DATABASE], "degrees": 90},
|
||||
id="rotate",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/merge/",
|
||||
{"documents": [BEYOND_THE_DATABASE, BEYOND_THE_DATABASE + 1]},
|
||||
id="merge",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/bulk_download/",
|
||||
{"documents": [BEYOND_THE_DATABASE], "content": "both"},
|
||||
id="bulk-download",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/selection_data/",
|
||||
{"documents": [BEYOND_THE_DATABASE]},
|
||||
id="selection-data",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/share_link_bundles/",
|
||||
{"document_ids": [BEYOND_THE_DATABASE], "file_version": "archive"},
|
||||
id="share-link-bundle",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/bulk_edit_objects/",
|
||||
{
|
||||
"objects": [BEYOND_THE_DATABASE],
|
||||
"object_type": "tags",
|
||||
"operation": "delete",
|
||||
},
|
||||
id="bulk-edit-objects",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/tasks/acknowledge/",
|
||||
{"tasks": [BEYOND_THE_DATABASE]},
|
||||
id="acknowledge-tasks",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/trash/",
|
||||
{"action": "restore", "documents": [BEYOND_THE_DATABASE]},
|
||||
id="trash",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_id_no_row_can_have_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
path: str,
|
||||
body: dict,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A list of ids includes one larger than a database column can hold
|
||||
THEN:
|
||||
- The response is a 400 like any id that does not exist, not a server
|
||||
error
|
||||
"""
|
||||
response = send_json(admin_client, "POST", path, body)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
@@ -0,0 +1,446 @@
|
||||
import pytest
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import Correspondent
|
||||
from documents.models import WorkflowAction
|
||||
from documents.models import WorkflowTrigger
|
||||
from paperless_mail.models import MailAccount
|
||||
from paperless_testing.http import send_json
|
||||
|
||||
ACCOUNT = {
|
||||
"name": "Email",
|
||||
"username": "username",
|
||||
"password": "password",
|
||||
"imap_server": "server.example.com",
|
||||
"imap_port": 993,
|
||||
"imap_security": MailAccount.ImapSecurity.SSL,
|
||||
"character_set": "UTF-8",
|
||||
}
|
||||
|
||||
TRIGGER = {"type": 2, "sources": [1, 2, 3], "matching_algorithm": 0}
|
||||
|
||||
|
||||
def create_account(client: APIClient) -> int:
|
||||
response = send_json(client, "POST", "/api/mail_accounts/", ACCOUNT)
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
return response.data["id"]
|
||||
|
||||
|
||||
class TestMailBounds:
|
||||
@pytest.mark.parametrize("port", [-1, 0, 65536, 2**40])
|
||||
def test_imap_port_outside_the_port_range_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
port: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A mail account is created with a port that cannot exist
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/",
|
||||
{**ACCOUNT, "imap_port": port},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "imap_port" in response.data
|
||||
|
||||
@pytest.mark.parametrize("port", [1, 993, 65535])
|
||||
def test_imap_port_inside_the_range_is_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
port: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A mail account is created with a valid port
|
||||
THEN:
|
||||
- It is created
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/",
|
||||
{**ACCOUNT, "imap_port": port},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
|
||||
@pytest.mark.parametrize("method", ["PATCH", "PUT"])
|
||||
def test_updating_to_an_impossible_port_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
method: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mail account
|
||||
WHEN:
|
||||
- It is updated with a negative port
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
account_id = create_account(admin_client)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
method,
|
||||
f"/api/mail_accounts/{account_id}/",
|
||||
{**ACCOUNT, "imap_port": -5},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize("order", [2**15, -(2**15) - 1, 2**40])
|
||||
def test_mail_rule_order_beyond_a_smallint_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
order: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mail account
|
||||
WHEN:
|
||||
- A rule is created with an order its column cannot hold
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
account_id = create_account(admin_client)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_rules/",
|
||||
{"name": "rule", "account": account_id, "action": 3, "order": order},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "order" in response.data
|
||||
|
||||
@pytest.mark.parametrize("order", [2**15 - 1, -(2**15)])
|
||||
def test_mail_rule_order_at_the_limits_is_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
order: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mail account
|
||||
WHEN:
|
||||
- A rule is created with the largest or smallest order
|
||||
THEN:
|
||||
- It is created
|
||||
"""
|
||||
account_id = create_account(admin_client)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_rules/",
|
||||
{"name": "rule", "account": account_id, "action": 3, "order": order},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("length", "expected"),
|
||||
[(256, status.HTTP_201_CREATED), (257, status.HTTP_400_BAD_REQUEST)],
|
||||
)
|
||||
def test_mail_rule_action_parameter_must_fit_the_column(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
length: int,
|
||||
expected: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mail account
|
||||
WHEN:
|
||||
- A rule is created with an action parameter at, or past, the column size
|
||||
THEN:
|
||||
- It is created, or rejected, accordingly
|
||||
"""
|
||||
account_id = create_account(admin_client)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_rules/",
|
||||
{
|
||||
"name": "rule",
|
||||
"account": account_id,
|
||||
"action": 3,
|
||||
"action_parameter": "x" * length,
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == expected
|
||||
|
||||
def test_updating_a_mail_rule_to_an_impossible_order_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mail rule
|
||||
WHEN:
|
||||
- It is patched with an order beyond a smallint
|
||||
THEN:
|
||||
- The response is a 400
|
||||
"""
|
||||
account_id = create_account(admin_client)
|
||||
rule = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_rules/",
|
||||
{"name": "rule", "account": account_id, "action": 3},
|
||||
)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/mail_rules/{rule.data['id']}/",
|
||||
{"order": 2**40},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
|
||||
class TestWorkflowOrder:
|
||||
@pytest.mark.parametrize(
|
||||
("order", "expected"),
|
||||
[
|
||||
(2**31, status.HTTP_400_BAD_REQUEST),
|
||||
(-(2**31) - 1, status.HTTP_400_BAD_REQUEST),
|
||||
(2**40, status.HTTP_400_BAD_REQUEST),
|
||||
(2**31 - 1, status.HTTP_201_CREATED),
|
||||
(-(2**31), status.HTTP_201_CREATED),
|
||||
],
|
||||
)
|
||||
def test_workflow_order_must_fit_the_column(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
order: int,
|
||||
expected: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A workflow is created with an order beyond a 32 bit integer, or exactly
|
||||
at its limits
|
||||
THEN:
|
||||
- It is rejected, or created, accordingly
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflows/",
|
||||
{
|
||||
"name": "workflow",
|
||||
"order": order,
|
||||
"enabled": True,
|
||||
"triggers": [TRIGGER],
|
||||
"actions": [{"type": 1, "assign_title": "title"}],
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == expected
|
||||
|
||||
|
||||
class TestStandaloneWorkflowRowIds:
|
||||
def test_trigger_created_with_an_existing_id_gets_its_own(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An existing workflow trigger
|
||||
WHEN:
|
||||
- A new trigger is created with that trigger's id in the payload
|
||||
THEN:
|
||||
- A new row is created and the existing one is untouched
|
||||
"""
|
||||
existing = WorkflowTrigger.objects.create(
|
||||
type=2,
|
||||
sources="1",
|
||||
matching_algorithm=0,
|
||||
)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflow_triggers/",
|
||||
{**TRIGGER, "id": existing.pk},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
assert response.data["id"] != existing.pk
|
||||
assert WorkflowTrigger.objects.count() == 2
|
||||
|
||||
def test_action_created_with_an_existing_id_gets_its_own(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An existing workflow action
|
||||
WHEN:
|
||||
- A new action is created with that action's id in the payload
|
||||
THEN:
|
||||
- A new row is created and the existing one is untouched
|
||||
"""
|
||||
existing = WorkflowAction.objects.create(type=1, assign_title="original")
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflow_actions/",
|
||||
{"type": 1, "assign_title": "new", "id": existing.pk},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
assert response.data["id"] != existing.pk
|
||||
existing.refresh_from_db()
|
||||
assert existing.assign_title == "original"
|
||||
|
||||
def test_put_cannot_overwrite_another_trigger_through_the_body_id(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Two workflow triggers
|
||||
WHEN:
|
||||
- One is replaced with a body that carries the other's id
|
||||
THEN:
|
||||
- Only the trigger named in the URL changes
|
||||
"""
|
||||
target = WorkflowTrigger.objects.create(
|
||||
type=2,
|
||||
sources="1",
|
||||
matching_algorithm=0,
|
||||
)
|
||||
other = WorkflowTrigger.objects.create(
|
||||
type=2,
|
||||
sources="1",
|
||||
matching_algorithm=0,
|
||||
filter_filename="keep",
|
||||
)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflow_triggers/{target.pk}/",
|
||||
{**TRIGGER, "filter_filename": "changed", "id": other.pk},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
target.refresh_from_db()
|
||||
other.refresh_from_db()
|
||||
assert target.filter_filename == "changed"
|
||||
assert other.filter_filename == "keep"
|
||||
|
||||
|
||||
class TestUniqueNameOnUpdate:
|
||||
@pytest.mark.parametrize("owner_kind", ["owned", "unowned"])
|
||||
def test_patching_to_an_existing_name_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
owner_kind: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Two correspondents with the same owner, or none
|
||||
WHEN:
|
||||
- One is patched to the other's name without mentioning the owner
|
||||
THEN:
|
||||
- The response is a 400, as it is when creating a duplicate
|
||||
"""
|
||||
owner = admin_user if owner_kind == "owned" else None
|
||||
Correspondent.objects.create(name="taken", owner=owner)
|
||||
other = Correspondent.objects.create(name="free", owner=owner)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/correspondents/{other.pk}/",
|
||||
{"name": "taken"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
other.refresh_from_db()
|
||||
assert other.name == "free"
|
||||
|
||||
@pytest.mark.parametrize("owner_kind", ["owned", "unowned"])
|
||||
def test_renaming_to_a_free_name_or_keeping_the_name_still_works(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
owner_kind: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A correspondent
|
||||
WHEN:
|
||||
- It is renamed to a free name, then saved again under that name
|
||||
THEN:
|
||||
- Both requests succeed
|
||||
"""
|
||||
correspondent = Correspondent.objects.create(
|
||||
name="before",
|
||||
owner=admin_user if owner_kind == "owned" else None,
|
||||
)
|
||||
|
||||
first = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/correspondents/{correspondent.pk}/",
|
||||
{"name": "after"},
|
||||
)
|
||||
second = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/correspondents/{correspondent.pk}/",
|
||||
{"name": "after"},
|
||||
)
|
||||
|
||||
assert first.status_code == status.HTTP_200_OK
|
||||
assert second.status_code == status.HTTP_200_OK
|
||||
|
||||
def test_the_same_name_under_a_different_owner_is_allowed(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
regular_user: User,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Correspondents with the same name but different owners are allowed
|
||||
WHEN:
|
||||
- One correspondent is renamed to a name another owner already uses
|
||||
THEN:
|
||||
- The request succeeds
|
||||
"""
|
||||
Correspondent.objects.create(name="shared name", owner=regular_user)
|
||||
mine = Correspondent.objects.create(name="mine", owner=admin_user)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/correspondents/{mine.pk}/",
|
||||
{"name": "shared name"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
@@ -0,0 +1,139 @@
|
||||
import pytest
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from paperless_mail.models import MailAccount
|
||||
from paperless_testing.http import send_json
|
||||
|
||||
ACCOUNT = {
|
||||
"name": "Email",
|
||||
"username": "username",
|
||||
"password": "password",
|
||||
"imap_server": "server.example.com",
|
||||
"imap_port": 143,
|
||||
"imap_security": MailAccount.ImapSecurity.STARTTLS,
|
||||
"character_set": "UTF-8",
|
||||
}
|
||||
|
||||
|
||||
class TestStarttlsOnTheSslPort:
|
||||
def test_creating_a_starttls_account_on_port_993_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A mail account is created with STARTTLS on port 993
|
||||
THEN:
|
||||
- The response is a 400 naming the port, that pair can never connect
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/",
|
||||
{**ACCOUNT, "imap_port": 993},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "imap_port" in response.data
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("security", "port"),
|
||||
[
|
||||
(MailAccount.ImapSecurity.STARTTLS, 143),
|
||||
(MailAccount.ImapSecurity.SSL, 993),
|
||||
(MailAccount.ImapSecurity.NONE, 143),
|
||||
],
|
||||
)
|
||||
def test_other_combinations_are_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
security: int,
|
||||
port: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A mail account is created with a sensible security and port pair
|
||||
THEN:
|
||||
- It is created
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/",
|
||||
{**ACCOUNT, "imap_security": security, "imap_port": port},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
|
||||
def test_the_account_test_endpoint_reports_it_as_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- The account test is run with STARTTLS on port 993
|
||||
THEN:
|
||||
- The response is a 400, the mailbox class refuses that pair with an
|
||||
error that used to escape as a 500
|
||||
"""
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/test/",
|
||||
{**ACCOUNT, "imap_port": 993},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
def test_a_patch_that_creates_the_pair_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A STARTTLS account on port 143, and an SSL account on port 993
|
||||
WHEN:
|
||||
- Only the port of the first, or only the security of the second, is patched
|
||||
THEN:
|
||||
- Both requests are a 400, the stored half of the pair counts
|
||||
"""
|
||||
starttls = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/",
|
||||
ACCOUNT,
|
||||
).data["id"]
|
||||
ssl = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/",
|
||||
{
|
||||
**ACCOUNT,
|
||||
"name": "Other",
|
||||
"imap_port": 993,
|
||||
"imap_security": MailAccount.ImapSecurity.SSL,
|
||||
},
|
||||
).data["id"]
|
||||
|
||||
port_patch = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/mail_accounts/{starttls}/",
|
||||
{"imap_port": 993},
|
||||
)
|
||||
security_patch = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/mail_accounts/{ssl}/",
|
||||
{"imap_security": MailAccount.ImapSecurity.STARTTLS},
|
||||
)
|
||||
|
||||
assert port_patch.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert security_patch.status_code == status.HTTP_400_BAD_REQUEST
|
||||
@@ -0,0 +1,405 @@
|
||||
import imaplib
|
||||
import shutil
|
||||
import socket
|
||||
import ssl
|
||||
|
||||
import pytest
|
||||
from django.contrib.auth.models import User
|
||||
from django.core import mail
|
||||
from django.core.files.uploadedfile import SimpleUploadedFile
|
||||
from pytest_django.fixtures import Settings
|
||||
from pytest_mock import MockerFixture
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import Document
|
||||
from documents.models import SavedView
|
||||
from paperless_mail.mail import MailError
|
||||
from paperless_testing.dirs import PaperlessDirs
|
||||
from paperless_testing.factories import DocumentFactory
|
||||
from paperless_testing.factories import UserFactory
|
||||
from paperless_testing.http import send_json
|
||||
from paperless_testing.permissions import grant_global
|
||||
from paperless_testing.samples import SIMPLE_DIGITAL_PDF
|
||||
|
||||
EMAIL = {
|
||||
"addresses": "hello@paperless-ngx.com",
|
||||
"subject": "subject",
|
||||
"message": "message",
|
||||
"use_archive_version": False,
|
||||
}
|
||||
|
||||
MAIL_ACCOUNT = {
|
||||
"imap_server": "server.example.com",
|
||||
"imap_port": 993,
|
||||
"imap_security": 2,
|
||||
"username": "admin",
|
||||
"password": "secret",
|
||||
}
|
||||
|
||||
|
||||
class TestEmailSingleDocument:
|
||||
def _document_with_file(self, paperless_dirs: PaperlessDirs) -> Document:
|
||||
document = DocumentFactory.create(
|
||||
filename="test.pdf",
|
||||
mime_type="application/pdf",
|
||||
)
|
||||
shutil.copy(SIMPLE_DIGITAL_PDF, document.source_path)
|
||||
return document
|
||||
|
||||
def test_json_body_sends_the_email(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
paperless_dirs: PaperlessDirs,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document with a file
|
||||
WHEN:
|
||||
- The per document email endpoint gets a JSON body
|
||||
THEN:
|
||||
- The email is sent, a JSON body used to crash on a QueryDict only call
|
||||
"""
|
||||
document = self._document_with_file(paperless_dirs)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
f"/api/documents/{document.pk}/email/",
|
||||
EMAIL,
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert len(mail.outbox) == 1
|
||||
|
||||
def test_form_body_still_sends_the_email(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
paperless_dirs: PaperlessDirs,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document with a file
|
||||
WHEN:
|
||||
- The endpoint gets a form encoded body
|
||||
THEN:
|
||||
- The email is sent
|
||||
"""
|
||||
document = self._document_with_file(paperless_dirs)
|
||||
|
||||
response = admin_client.post(
|
||||
f"/api/documents/{document.pk}/email/",
|
||||
EMAIL,
|
||||
format="multipart",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert len(mail.outbox) == 1
|
||||
|
||||
def test_json_body_is_still_validated(self, admin_client: APIClient) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document
|
||||
WHEN:
|
||||
- A JSON body without addresses is sent
|
||||
THEN:
|
||||
- The response is a 400 from the serializer, not a server error
|
||||
"""
|
||||
document = DocumentFactory.create()
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
f"/api/documents/{document.pk}/email/",
|
||||
{"subject": "only a subject"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "addresses" in response.data
|
||||
|
||||
|
||||
class TestMailAccountTest:
|
||||
def test_form_encoded_body_is_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
mocker: MockerFixture,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mailbox that connects
|
||||
WHEN:
|
||||
- The account test gets a form encoded body, which is a read only QueryDict
|
||||
THEN:
|
||||
- The request succeeds, the view must not write into the request data
|
||||
"""
|
||||
mocker.patch("paperless_mail.views.get_mailbox")
|
||||
mocker.patch("paperless_mail.views.mailbox_login")
|
||||
|
||||
response = admin_client.post(
|
||||
"/api/mail_accounts/test/",
|
||||
MAIL_ACCOUNT,
|
||||
format="multipart",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data == {"success": True}
|
||||
|
||||
def test_write_only_serializer_fields_are_not_passed_to_the_model(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
mocker: MockerFixture,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mailbox that connects
|
||||
WHEN:
|
||||
- The account test body carries set_permissions, which is not a model field
|
||||
THEN:
|
||||
- The request succeeds
|
||||
"""
|
||||
mocker.patch("paperless_mail.views.get_mailbox")
|
||||
mocker.patch("paperless_mail.views.mailbox_login")
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/test/",
|
||||
{
|
||||
**MAIL_ACCOUNT,
|
||||
"set_permissions": {"view": {"users": [], "groups": []}},
|
||||
},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
def test_multipart_body_with_a_large_file_is_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
mocker: MockerFixture,
|
||||
settings: Settings,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mailbox that connects, and uploads that spill to a temporary file
|
||||
WHEN:
|
||||
- The account test gets a multipart body that carries a large file
|
||||
THEN:
|
||||
- The request succeeds, copying the request data would try to deep copy
|
||||
the temporary file and fail
|
||||
"""
|
||||
settings.FILE_UPLOAD_MAX_MEMORY_SIZE = 10
|
||||
mocker.patch("paperless_mail.views.get_mailbox")
|
||||
mocker.patch("paperless_mail.views.mailbox_login")
|
||||
|
||||
response = admin_client.post(
|
||||
"/api/mail_accounts/test/",
|
||||
{
|
||||
**MAIL_ACCOUNT,
|
||||
"attachment": SimpleUploadedFile("junk.bin", b"0" * 1000),
|
||||
},
|
||||
format="multipart",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
pytest.param(ConnectionRefusedError, id="refused"),
|
||||
pytest.param(socket.gaierror, id="unknown-host"),
|
||||
pytest.param(TimeoutError, id="timeout"),
|
||||
pytest.param(ssl.SSLError, id="tls"),
|
||||
pytest.param(imaplib.IMAP4.error, id="imap-error"),
|
||||
pytest.param(UnicodeError, id="bad-host-name"),
|
||||
pytest.param(MailError, id="mail-error"),
|
||||
],
|
||||
)
|
||||
def test_connection_failures_are_reported_as_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
mocker: MockerFixture,
|
||||
error: type[Exception],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A mailbox that cannot be reached
|
||||
WHEN:
|
||||
- The account test is run
|
||||
THEN:
|
||||
- The response is a 400 saying the server cannot be reached, that is the
|
||||
answer this endpoint exists to give
|
||||
"""
|
||||
mocker.patch("paperless_mail.views.get_mailbox", side_effect=error("boom"))
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/mail_accounts/test/",
|
||||
MAIL_ACCOUNT,
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert response.content == b"Unable to connect to server"
|
||||
|
||||
|
||||
class TestDeactivateTotp:
|
||||
def test_unknown_user_is_a_404_for_a_superuser(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A superuser
|
||||
WHEN:
|
||||
- TOTP is deactivated for a user id that does not exist
|
||||
THEN:
|
||||
- The response is a 404
|
||||
"""
|
||||
response = admin_client.post("/api/users/999999/deactivate_totp/")
|
||||
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
def test_non_numeric_user_id_is_a_404_for_a_superuser(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A superuser
|
||||
WHEN:
|
||||
- The user id is not a number
|
||||
THEN:
|
||||
- The response is a 404, not a server error
|
||||
"""
|
||||
response = admin_client.post("/api/users/abc/deactivate_totp/")
|
||||
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
def test_status_does_not_reveal_whether_another_user_exists(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
regular_user: User,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A regular user allowed to use the users API, and another user
|
||||
WHEN:
|
||||
- They deactivate TOTP for another existing user, and for one that does not
|
||||
exist
|
||||
THEN:
|
||||
- Both answers are a 403, so the status cannot be used to find user ids
|
||||
"""
|
||||
grant_global(regular_user, "add_user", "change_user")
|
||||
other = UserFactory.create(username="other")
|
||||
rest_api_client.force_authenticate(user=regular_user)
|
||||
|
||||
existing = rest_api_client.post(f"/api/users/{other.pk}/deactivate_totp/")
|
||||
missing = rest_api_client.post("/api/users/999999/deactivate_totp/")
|
||||
|
||||
assert existing.status_code == status.HTTP_403_FORBIDDEN
|
||||
assert missing.status_code == status.HTTP_403_FORBIDDEN
|
||||
|
||||
def test_a_user_can_reach_their_own_record(
|
||||
self,
|
||||
rest_api_client: APIClient,
|
||||
regular_user: User,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A regular user with no authenticator
|
||||
WHEN:
|
||||
- They deactivate TOTP for themselves
|
||||
THEN:
|
||||
- The lookup succeeds and the answer is that no TOTP was found
|
||||
"""
|
||||
grant_global(regular_user, "add_user", "change_user")
|
||||
rest_api_client.force_authenticate(user=regular_user)
|
||||
|
||||
response = rest_api_client.post(
|
||||
f"/api/users/{regular_user.pk}/deactivate_totp/",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
assert response.content == b"TOTP not found"
|
||||
|
||||
|
||||
class TestSavedViewPartialRules:
|
||||
def test_patch_with_a_rule_missing_its_type_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
admin_user: User,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A saved view
|
||||
WHEN:
|
||||
- It is patched with a filter rule that has no rule_type
|
||||
THEN:
|
||||
- The response is a 400, not a database error
|
||||
"""
|
||||
view = SavedView.objects.create(
|
||||
name="view",
|
||||
owner=admin_user,
|
||||
sort_field="created",
|
||||
)
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PATCH",
|
||||
f"/api/saved_views/{view.pk}/",
|
||||
{"filter_rules": [{"value": "1"}]},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "filter_rules" in response.data
|
||||
|
||||
|
||||
class TestConfigFormBody:
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
["language=", "llm_api_key=", "language=&llm_api_key="],
|
||||
)
|
||||
def test_form_encoded_empty_values_are_accepted(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
config_id: int,
|
||||
body: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The application configuration
|
||||
WHEN:
|
||||
- A form encoded body with empty values is patched in
|
||||
THEN:
|
||||
- The request succeeds, the serializer used to write into the read only
|
||||
QueryDict
|
||||
"""
|
||||
response = admin_client.patch(
|
||||
f"/api/config/{config_id}/",
|
||||
data=body,
|
||||
content_type="application/x-www-form-urlencoded",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
def test_form_encoded_empty_json_field_is_a_clean_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
config_id: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The application configuration
|
||||
WHEN:
|
||||
- An empty value for a JSON field arrives in a form encoded body
|
||||
THEN:
|
||||
- The response is a 400 naming the field, not a server error
|
||||
"""
|
||||
response = admin_client.patch(
|
||||
f"/api/config/{config_id}/",
|
||||
data="user_args=",
|
||||
content_type="application/x-www-form-urlencoded",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "user_args" in response.data
|
||||
@@ -1,8 +1,11 @@
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from django.core.management import call_command
|
||||
from django.core.management.base import CommandError
|
||||
from drf_spectacular.generators import SchemaGenerator
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
from rest_framework.test import APITestCase
|
||||
|
||||
|
||||
@@ -337,3 +340,505 @@ 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 TestCommonErrorResponsesSchema:
|
||||
def test_detail_operations_document_400_and_404(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The detail operations of a resource are read
|
||||
THEN:
|
||||
- A 400 and a 404 are documented, no view declares them itself
|
||||
"""
|
||||
operation = api_schema["paths"]["/api/tags/{id}/"]["patch"]
|
||||
|
||||
assert "400" in operation["responses"]
|
||||
assert "404" in operation["responses"]
|
||||
|
||||
def test_paginated_list_documents_404_for_a_missing_page(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- A paginated list operation is read
|
||||
THEN:
|
||||
- A 404 is documented, an out of range page answers one
|
||||
"""
|
||||
responses = api_schema["paths"]["/api/tags/"]["get"]["responses"]
|
||||
|
||||
assert "404" in responses
|
||||
|
||||
def test_operation_without_input_has_no_400(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An operation with no parameters and no body
|
||||
WHEN:
|
||||
- Its responses are read
|
||||
THEN:
|
||||
- No 400 is added, there is no input to reject
|
||||
"""
|
||||
responses = api_schema["paths"]["/api/status/"]["get"]["responses"]
|
||||
|
||||
assert "400" not in responses
|
||||
assert "404" not in responses
|
||||
|
||||
def test_responses_declared_by_a_view_are_kept(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An operation whose view documents its own 400
|
||||
WHEN:
|
||||
- Its responses are read
|
||||
THEN:
|
||||
- The description of the view is kept
|
||||
"""
|
||||
responses = api_schema["paths"]["/api/oauth/callback/"]["get"]["responses"]
|
||||
|
||||
assert responses["400"]["description"] != "Invalid input"
|
||||
|
||||
|
||||
class TestDocumentFileContentTypesSchema:
|
||||
@pytest.mark.parametrize(
|
||||
("path", "content_type"),
|
||||
[
|
||||
("/api/documents/{id}/download/", "*/*"),
|
||||
("/api/documents/{id}/preview/", "*/*"),
|
||||
("/api/documents/{id}/thumb/", "image/webp"),
|
||||
],
|
||||
)
|
||||
def test_file_endpoints_declare_the_real_content_type(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
path: str,
|
||||
content_type: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The 200 response of a document file endpoint is read
|
||||
THEN:
|
||||
- It declares the content type it is served with, not JSON
|
||||
"""
|
||||
content = api_schema["paths"][path]["get"]["responses"]["200"]["content"]
|
||||
|
||||
assert list(content) == [content_type]
|
||||
|
||||
|
||||
class TestConditionalResponseFieldsSchema:
|
||||
@pytest.mark.parametrize(
|
||||
"component",
|
||||
["Tag", "Correspondent", "DocumentType", "StoragePath", "Document"],
|
||||
)
|
||||
def test_fields_present_only_sometimes_are_not_required(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
component: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The response component of an owned object is read
|
||||
THEN:
|
||||
- Permissions, the permission flags and the annotated counts are not
|
||||
required, a create or update response and a response without full_perms
|
||||
do not carry them
|
||||
"""
|
||||
schema = api_schema["components"]["schemas"][component]
|
||||
required = set(schema.get("required", []))
|
||||
|
||||
assert required.isdisjoint(
|
||||
{
|
||||
"permissions",
|
||||
"user_can_change",
|
||||
"is_shared_by_requester",
|
||||
"document_count",
|
||||
"last_correspondence",
|
||||
},
|
||||
)
|
||||
assert "id" in required
|
||||
|
||||
def test_fields_of_other_components_stay_required(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A response component that is not an owned object but has a count
|
||||
WHEN:
|
||||
- Its required fields are read
|
||||
THEN:
|
||||
- The count is still required, it is always present
|
||||
"""
|
||||
schema = api_schema["components"]["schemas"]["ShareLinkBundle"]
|
||||
|
||||
assert "document_count" in schema["required"]
|
||||
|
||||
|
||||
class TestSystemStatusSchema:
|
||||
def test_status_fields_match_the_response(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The system status response is read
|
||||
THEN:
|
||||
- The index, classifier and sanity check fields are inside tasks, as the
|
||||
view returns them, and storage sizes are 64 bit
|
||||
"""
|
||||
schemas = api_schema["components"]["schemas"]
|
||||
status_schema = schemas["SystemStatus"]
|
||||
tasks = schemas["Tasks"]["properties"]
|
||||
|
||||
assert set(status_schema["properties"]) == {
|
||||
"pngx_version",
|
||||
"server_os",
|
||||
"install_type",
|
||||
"storage",
|
||||
"database",
|
||||
"tasks",
|
||||
}
|
||||
assert {
|
||||
"index_status",
|
||||
"classifier_last_trained",
|
||||
"sanity_check_error",
|
||||
"llmindex_status",
|
||||
} <= set(tasks)
|
||||
assert schemas["Storage"]["properties"]["total"]["format"] == "int64"
|
||||
|
||||
|
||||
class TestUiSettingsSchema:
|
||||
def test_get_response_has_user_settings_and_permissions(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The response of GET /api/ui_settings/ is read
|
||||
THEN:
|
||||
- It has the user, settings and permissions the view returns, and no
|
||||
request body
|
||||
"""
|
||||
operation = api_schema["paths"]["/api/ui_settings/"]["get"]
|
||||
response = operation["responses"]["200"]["content"]["application/json"]
|
||||
|
||||
assert "requestBody" not in operation
|
||||
assert response["schema"]["$ref"].endswith("/UiSettingsResponse")
|
||||
properties = api_schema["components"]["schemas"]["UiSettingsResponse"][
|
||||
"properties"
|
||||
]
|
||||
assert set(properties) == {"user", "settings", "permissions"}
|
||||
|
||||
|
||||
class TestRunZoneOcrResponseSchema:
|
||||
def test_task_id_and_reason_are_optional(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The response of run-zone-ocr is read
|
||||
THEN:
|
||||
- Only the result is required, task_id is absent when the run was
|
||||
skipped and the reason is absent when it was queued
|
||||
"""
|
||||
schema = api_schema["components"]["schemas"]["RunZoneOcrResponse"]
|
||||
|
||||
assert schema["required"] == ["result"]
|
||||
|
||||
|
||||
class TestDocumentShareLinksSchema:
|
||||
def test_response_is_a_list_of_share_links(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The response of the share links of a document is read
|
||||
THEN:
|
||||
- It is the share link serializer, which allows a null expiration
|
||||
"""
|
||||
operation = api_schema["paths"]["/api/documents/{id}/share_links/"]["get"]
|
||||
items = operation["responses"]["200"]["content"]["application/json"]["schema"][
|
||||
"items"
|
||||
]
|
||||
|
||||
assert items["$ref"].endswith("/ShareLink")
|
||||
|
||||
|
||||
class TestTagChildrenAndHistorySchema:
|
||||
def test_tag_children_are_nested_tags(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The children of a tag are read
|
||||
THEN:
|
||||
- They are tags, the API nests the objects and does not return ids
|
||||
"""
|
||||
children = api_schema["components"]["schemas"]["Tag"]["properties"]["children"]
|
||||
|
||||
assert children["items"] == {"$ref": "#/components/schemas/Tag"}
|
||||
|
||||
def test_history_is_an_unpaginated_list(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The history response of a document is read
|
||||
THEN:
|
||||
- It is a plain array of log entries, the view does not paginate
|
||||
"""
|
||||
operation = api_schema["paths"]["/api/documents/{id}/history/"]["get"]
|
||||
schema = operation["responses"]["200"]["content"]["application/json"]["schema"]
|
||||
|
||||
assert schema["type"] == "array"
|
||||
|
||||
|
||||
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 TestRemainingResponseShapesSchema:
|
||||
def test_logs_limit_must_be_positive(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The limit parameter of the log endpoint is read
|
||||
THEN:
|
||||
- It has a minimum of 1, the view rejects anything lower
|
||||
"""
|
||||
params = api_schema["paths"]["/api/logs/{id}/"]["get"]["parameters"]
|
||||
limit = next(p for p in params if p["name"] == "limit")
|
||||
|
||||
assert limit["schema"]["minimum"] == 1
|
||||
|
||||
@pytest.mark.parametrize("name", ["since", "until"])
|
||||
def test_release_notes_versions_have_a_pattern(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
name: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The version parameters of the release notes are read
|
||||
THEN:
|
||||
- They are patterned like a version, anything else answers a 400
|
||||
"""
|
||||
params = api_schema["paths"]["/api/release_notes/"]["get"]["parameters"]
|
||||
param = next(p for p in params if p["name"] == name)
|
||||
|
||||
assert "pattern" in param["schema"]
|
||||
|
||||
def test_deactivate_totp_404_is_html(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The 404 of deactivate_totp is read
|
||||
THEN:
|
||||
- It is text, the view answers with a plain not found response
|
||||
"""
|
||||
responses = api_schema["paths"]["/api/users/{id}/deactivate_totp/"]["post"][
|
||||
"responses"
|
||||
]
|
||||
|
||||
assert list(responses["404"]["content"]) == ["text/html"]
|
||||
|
||||
def test_ocr_error_body_has_no_required_fields(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The error body of the OCR actions is read
|
||||
THEN:
|
||||
- Neither error nor detail is required, a missing document answers with
|
||||
a detail and the actions answer with an error
|
||||
"""
|
||||
schema = api_schema["components"]["schemas"]["OcrError"]
|
||||
|
||||
assert "required" not in schema
|
||||
assert {"error", "detail"} <= set(schema["properties"])
|
||||
|
||||
def test_nullable_response_fields(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The root document of a document and the last correspondence of a
|
||||
correspondent are read
|
||||
THEN:
|
||||
- Both are nullable, a root document has no root and a correspondent
|
||||
may have no documents
|
||||
"""
|
||||
schemas = api_schema["components"]["schemas"]
|
||||
|
||||
assert schemas["Document"]["properties"]["root_document"]["nullable"] is True
|
||||
assert (
|
||||
schemas["Correspondent"]["properties"]["last_correspondence"]["nullable"]
|
||||
is True
|
||||
)
|
||||
|
||||
def test_custom_field_count_is_optional(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The custom field response is read
|
||||
THEN:
|
||||
- document_count is not required, a create response does not have it
|
||||
"""
|
||||
required = api_schema["components"]["schemas"]["CustomField"]["required"]
|
||||
|
||||
assert "document_count" not in required
|
||||
|
||||
|
||||
class TestSearchAndMailTestSchema:
|
||||
def test_autocomplete_term_is_required(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The term parameter of autocomplete is read
|
||||
THEN:
|
||||
- It is required, the view answers 400 without it
|
||||
"""
|
||||
params = api_schema["paths"]["/api/search/autocomplete/"]["get"]["parameters"]
|
||||
term = next(p for p in params if p["name"] == "term")
|
||||
|
||||
assert term["required"] is True
|
||||
|
||||
def test_global_search_query_has_a_minimum_length(
|
||||
self,
|
||||
api_schema: dict[str, Any],
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The query parameter of the global search is read
|
||||
THEN:
|
||||
- It has a minimum length of 3, the view answers 400 to a shorter one
|
||||
"""
|
||||
params = api_schema["paths"]["/api/search/"]["get"]["parameters"]
|
||||
query = next(p for p in params if p["name"] == "query")
|
||||
|
||||
assert query["schema"]["minLength"] == 3
|
||||
|
||||
def test_mail_account_test_400_is_html(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The 400 of the mail account test is read
|
||||
THEN:
|
||||
- It is text, the view answers with a plain bad request response
|
||||
"""
|
||||
responses = api_schema["paths"]["/api/mail_accounts/test/"]["post"]["responses"]
|
||||
|
||||
assert list(responses["400"]["content"]) == ["text/html"]
|
||||
|
||||
|
||||
class TestTagColorSchema:
|
||||
def test_color_has_a_hex_pattern(self, api_schema: dict[str, Any]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The generated schema
|
||||
WHEN:
|
||||
- The color of a tag request is read
|
||||
THEN:
|
||||
- It has a hex pattern, the serializer rejects anything else
|
||||
"""
|
||||
color = api_schema["components"]["schemas"]["TagRequest"]["properties"]["color"]
|
||||
|
||||
assert color["pattern"] == "^#[0-9a-fA-F]{6}$"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("color", "expected"),
|
||||
[
|
||||
("#a6cee3", 201),
|
||||
("#A6CEE3", 201),
|
||||
("a6cee3", 400),
|
||||
("#a6cee", 400),
|
||||
("#a6ceez", 400),
|
||||
("#a6cee3x", 400),
|
||||
],
|
||||
)
|
||||
def test_color_validation_is_unchanged(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
color: str,
|
||||
expected: int,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A tag request
|
||||
WHEN:
|
||||
- It is created with a valid or an invalid color
|
||||
THEN:
|
||||
- Only a # followed by six hex digits is accepted
|
||||
"""
|
||||
response = admin_client.post(
|
||||
"/api/tags/",
|
||||
{"name": "colored", "color": color},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == expected
|
||||
|
||||
|
||||
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"]
|
||||
@@ -0,0 +1,299 @@
|
||||
import json
|
||||
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from documents.models import WorkflowAction
|
||||
from documents.models import WorkflowActionEmail
|
||||
from documents.models import WorkflowTrigger
|
||||
from paperless_testing.http import send_json
|
||||
|
||||
EMAIL = {
|
||||
"subject": "original",
|
||||
"body": "body",
|
||||
"to": "someone@example.com",
|
||||
"include_document": False,
|
||||
}
|
||||
|
||||
|
||||
def workflow_body(name: str, *, trigger: dict, action: dict) -> dict:
|
||||
return {
|
||||
"name": name,
|
||||
"order": 0,
|
||||
"enabled": True,
|
||||
"triggers": [
|
||||
{"type": 2, "sources": [1], "matching_algorithm": 0, **trigger},
|
||||
],
|
||||
"actions": [{"type": 3, "email": EMAIL, **action}],
|
||||
}
|
||||
|
||||
|
||||
def make_workflow(client: APIClient, name: str) -> dict:
|
||||
response = send_json(
|
||||
client,
|
||||
"POST",
|
||||
"/api/workflows/",
|
||||
workflow_body(name, trigger={}, action={}),
|
||||
)
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
return response.data
|
||||
|
||||
|
||||
class TestWorkflowRowOwnership:
|
||||
def test_update_cannot_take_over_another_workflows_action(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Two workflows, each with an email action
|
||||
WHEN:
|
||||
- The first is updated with the id of the second one's action and a changed
|
||||
email
|
||||
THEN:
|
||||
- The second workflow's action and email are untouched, the first gets its
|
||||
own action
|
||||
"""
|
||||
first = make_workflow(admin_client, "first")
|
||||
second = make_workflow(admin_client, "second")
|
||||
foreign_action = second["actions"][0]
|
||||
foreign_email_id = foreign_action["email"]["id"]
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflows/{first['id']}/",
|
||||
workflow_body(
|
||||
"first",
|
||||
trigger={"id": first["triggers"][0]["id"]},
|
||||
action={
|
||||
"id": foreign_action["id"],
|
||||
"email": {**EMAIL, "subject": "taken over"},
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data["actions"][0]["id"] != foreign_action["id"]
|
||||
assert WorkflowActionEmail.objects.get(pk=foreign_email_id).subject == (
|
||||
"original"
|
||||
)
|
||||
second_actions = list(
|
||||
WorkflowAction.objects.filter(workflows__pk=second["id"]),
|
||||
)
|
||||
assert [a.pk for a in second_actions] == [foreign_action["id"]]
|
||||
|
||||
def test_update_cannot_take_over_another_workflows_trigger(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Two workflows
|
||||
WHEN:
|
||||
- The first is updated with the id of the second one's trigger and a
|
||||
different filter
|
||||
THEN:
|
||||
- The second workflow's trigger is untouched
|
||||
"""
|
||||
first = make_workflow(admin_client, "first")
|
||||
second = make_workflow(admin_client, "second")
|
||||
foreign_trigger_id = second["triggers"][0]["id"]
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflows/{first['id']}/",
|
||||
workflow_body(
|
||||
"first",
|
||||
trigger={"id": foreign_trigger_id, "filter_filename": "taken"},
|
||||
action={"id": first["actions"][0]["id"]},
|
||||
),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data["triggers"][0]["id"] != foreign_trigger_id
|
||||
assert WorkflowTrigger.objects.get(pk=foreign_trigger_id).filter_filename != (
|
||||
"taken"
|
||||
)
|
||||
assert list(
|
||||
WorkflowTrigger.objects.filter(workflows__pk=second["id"]).values_list(
|
||||
"pk",
|
||||
flat=True,
|
||||
),
|
||||
) == [foreign_trigger_id]
|
||||
|
||||
def test_nested_email_id_of_another_action_is_ignored(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Two workflows with email actions
|
||||
WHEN:
|
||||
- The first is updated, keeping its own action, with the second action's
|
||||
email id in the nested email
|
||||
THEN:
|
||||
- The other email is untouched and the action's own email is the one
|
||||
changed
|
||||
"""
|
||||
first = make_workflow(admin_client, "first")
|
||||
second = make_workflow(admin_client, "second")
|
||||
own_action = first["actions"][0]
|
||||
own_email_id = own_action["email"]["id"]
|
||||
foreign_email_id = second["actions"][0]["email"]["id"]
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflows/{first['id']}/",
|
||||
workflow_body(
|
||||
"first",
|
||||
trigger={"id": first["triggers"][0]["id"]},
|
||||
action={
|
||||
"id": own_action["id"],
|
||||
"email": {**EMAIL, "id": foreign_email_id, "subject": "mine"},
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert WorkflowActionEmail.objects.get(pk=foreign_email_id).subject == (
|
||||
"original"
|
||||
)
|
||||
assert response.data["actions"][0]["email"]["id"] == own_email_id
|
||||
assert WorkflowActionEmail.objects.get(pk=own_email_id).subject == "mine"
|
||||
|
||||
def test_nested_email_id_beyond_the_database_range_is_ignored(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A workflow with an email action
|
||||
WHEN:
|
||||
- It is updated with a nested email id larger than a column can hold
|
||||
THEN:
|
||||
- The request succeeds and the action keeps its own email row
|
||||
"""
|
||||
workflow = make_workflow(admin_client, "workflow")
|
||||
action = workflow["actions"][0]
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflows/{workflow['id']}/",
|
||||
workflow_body(
|
||||
"workflow",
|
||||
trigger={"id": workflow["triggers"][0]["id"]},
|
||||
action={
|
||||
"id": action["id"],
|
||||
"email": {**EMAIL, "id": 2**63},
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data["actions"][0]["email"]["id"] == action["email"]["id"]
|
||||
|
||||
def test_create_ignores_ids_of_existing_rows(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An existing workflow
|
||||
WHEN:
|
||||
- A new workflow is created that carries that workflow's trigger and
|
||||
action ids
|
||||
THEN:
|
||||
- New rows are created and the existing ones are untouched
|
||||
"""
|
||||
existing = make_workflow(admin_client, "existing")
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"POST",
|
||||
"/api/workflows/",
|
||||
workflow_body(
|
||||
"new",
|
||||
trigger={
|
||||
"id": existing["triggers"][0]["id"],
|
||||
"filter_filename": "taken",
|
||||
},
|
||||
action={"id": existing["actions"][0]["id"]},
|
||||
),
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_201_CREATED
|
||||
assert response.data["triggers"][0]["id"] != existing["triggers"][0]["id"]
|
||||
assert response.data["actions"][0]["id"] != existing["actions"][0]["id"]
|
||||
assert WorkflowTrigger.objects.get(
|
||||
pk=existing["triggers"][0]["id"],
|
||||
).filter_filename != ("taken")
|
||||
|
||||
def test_editing_a_workflow_keeps_its_row_ids(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A workflow read back from the API, as the UI does before an edit
|
||||
WHEN:
|
||||
- It is sent back with a changed name and email subject
|
||||
THEN:
|
||||
- Its trigger, action and email keep their ids and no rows are added
|
||||
"""
|
||||
workflow = make_workflow(admin_client, "workflow")
|
||||
body = admin_client.get(f"/api/workflows/{workflow['id']}/").data
|
||||
body = json.loads(json.dumps(body))
|
||||
body["name"] = "renamed"
|
||||
body["actions"][0]["email"]["subject"] = "edited"
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflows/{workflow['id']}/",
|
||||
body,
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data["triggers"][0]["id"] == workflow["triggers"][0]["id"]
|
||||
assert response.data["actions"][0]["id"] == workflow["actions"][0]["id"]
|
||||
assert (
|
||||
response.data["actions"][0]["email"]["id"]
|
||||
== (workflow["actions"][0]["email"]["id"])
|
||||
)
|
||||
assert response.data["actions"][0]["email"]["subject"] == "edited"
|
||||
assert WorkflowAction.objects.count() == 1
|
||||
assert WorkflowActionEmail.objects.count() == 1
|
||||
assert WorkflowTrigger.objects.count() == 1
|
||||
|
||||
def test_a_new_action_in_an_update_is_added_beside_the_existing_one(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A workflow with one action
|
||||
WHEN:
|
||||
- It is updated with that action plus a new one without an id
|
||||
THEN:
|
||||
- The first action keeps its id and a second one is created
|
||||
"""
|
||||
workflow = make_workflow(admin_client, "workflow")
|
||||
body = json.loads(
|
||||
json.dumps(admin_client.get(f"/api/workflows/{workflow['id']}/").data),
|
||||
)
|
||||
body["actions"].append({"type": 1, "assign_title": "added"})
|
||||
|
||||
response = send_json(
|
||||
admin_client,
|
||||
"PUT",
|
||||
f"/api/workflows/{workflow['id']}/",
|
||||
body,
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert len(response.data["actions"]) == 2
|
||||
assert response.data["actions"][0]["id"] == workflow["actions"][0]["id"]
|
||||
@@ -743,7 +743,7 @@ class TestPDFActions(DirectoriesMixin, TestCase):
|
||||
mime_type="application/pdf",
|
||||
)
|
||||
self.doc1.archive_filename = sample1_archive
|
||||
self.doc1.save(write_file_paths=True)
|
||||
self.doc1.save()
|
||||
self.doc2 = Document.objects.create(
|
||||
checksum="B",
|
||||
title="B",
|
||||
@@ -753,7 +753,7 @@ class TestPDFActions(DirectoriesMixin, TestCase):
|
||||
created=date(2023, 1, 2),
|
||||
)
|
||||
self.doc2.archive_filename = sample2_archive
|
||||
self.doc2.save(write_file_paths=True)
|
||||
self.doc2.save()
|
||||
self.doc3 = Document.objects.create(
|
||||
checksum="C",
|
||||
title="C",
|
||||
@@ -778,7 +778,7 @@ class TestPDFActions(DirectoriesMixin, TestCase):
|
||||
created=date(2023, 1, 3),
|
||||
)
|
||||
self.img_doc.archive_filename = img_doc_archive
|
||||
self.img_doc.save(write_file_paths=True)
|
||||
self.img_doc.save()
|
||||
|
||||
@staticmethod
|
||||
def fake_decrypt(
|
||||
|
||||
@@ -27,10 +27,6 @@ from documents.models import Document
|
||||
from documents.models import DocumentType
|
||||
from documents.models import StoragePath
|
||||
from documents.models import Tag
|
||||
from documents.models import Workflow
|
||||
from documents.models import WorkflowAction
|
||||
from documents.models import WorkflowActionEmail
|
||||
from documents.models import WorkflowTrigger
|
||||
from documents.parsers import ParseError
|
||||
from documents.plugins.helpers import ProgressStatusOptions
|
||||
from documents.tasks import sanity_check
|
||||
@@ -42,7 +38,6 @@ from paperless_testing.factories import DocumentFactory
|
||||
from paperless_testing.factories import TagFactory
|
||||
from paperless_testing.factories import UserFactory
|
||||
from paperless_testing.fakes.progress import FakeProgressManager
|
||||
from paperless_testing.locks import record_media_lock_acquisitions
|
||||
from paperless_testing.permissions import grant_object
|
||||
from paperless_testing.samples import MULTI_PAGE_DIGITAL_PDF
|
||||
from paperless_testing.samples import MULTI_PAGE_IMAGES_PDF
|
||||
@@ -226,160 +221,6 @@ class TestConsumer(
|
||||
shutil.copy(src, dst)
|
||||
return dst
|
||||
|
||||
@mock.patch("documents.consumer.load_classifier")
|
||||
def test_consume_takes_media_lock_outside_transaction(self, m) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A new document to consume
|
||||
WHEN:
|
||||
- It is consumed
|
||||
THEN:
|
||||
- media.lock is acquired
|
||||
- media.lock is never first acquired inside a transaction
|
||||
- The document's file is in place
|
||||
"""
|
||||
m.return_value = MagicMock()
|
||||
|
||||
with record_media_lock_acquisitions() as acquisitions:
|
||||
with self.get_consumer(self.get_test_file()) as consumer:
|
||||
consumer.run()
|
||||
|
||||
self.assertTrue(acquisitions)
|
||||
self.assertFalse(any(a.in_user_transaction for a in acquisitions))
|
||||
document = Document.objects.first()
|
||||
assert document is not None
|
||||
self.assertIsFile(document.source_path)
|
||||
|
||||
@mock.patch("documents.consumer.load_classifier")
|
||||
def test_consume_places_file_before_post_consume_script(self, m) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A new document to consume
|
||||
WHEN:
|
||||
- It is consumed
|
||||
THEN:
|
||||
- Pending file moves are flushed before the post-consume script runs
|
||||
"""
|
||||
m.return_value = MagicMock()
|
||||
order = MagicMock()
|
||||
|
||||
with (
|
||||
mock.patch(
|
||||
"documents.consumer.flush_pending_file_moves",
|
||||
order.flush,
|
||||
),
|
||||
mock.patch.object(
|
||||
ConsumerPlugin,
|
||||
"run_post_consume_script",
|
||||
order.script,
|
||||
),
|
||||
):
|
||||
with self.get_consumer(self.get_test_file()) as consumer:
|
||||
consumer.run()
|
||||
|
||||
self.assertEqual(
|
||||
[c[0] for c in order.mock_calls],
|
||||
["flush", "script"],
|
||||
)
|
||||
|
||||
@mock.patch("documents.consumer.load_classifier")
|
||||
def test_consume_version_takes_media_lock_outside_transaction(self, m) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An existing root document
|
||||
WHEN:
|
||||
- A new version of it is consumed (the root row is locked with
|
||||
select_for_update inside the consumer's transaction)
|
||||
THEN:
|
||||
- media.lock is never first acquired inside a transaction
|
||||
- The root's modified is bumped
|
||||
"""
|
||||
m.return_value = MagicMock()
|
||||
|
||||
with self.get_consumer(self.get_test_file()) as consumer:
|
||||
consumer.run()
|
||||
root_doc = Document.objects.first()
|
||||
assert root_doc is not None
|
||||
original_modified = timezone.now() - datetime.timedelta(days=1)
|
||||
Document.objects.filter(pk=root_doc.pk).update(modified=original_modified)
|
||||
|
||||
version_file = self.get_test_file2()
|
||||
status = FakeProgressManager(version_file.name, None)
|
||||
overrides = DocumentMetadataOverrides(version_label="v2")
|
||||
doc = ConsumableDocument(
|
||||
DocumentSource.ApiUpload,
|
||||
original_file=version_file,
|
||||
root_document_id=root_doc.pk,
|
||||
)
|
||||
preflight = ConsumerPreflightPlugin(
|
||||
doc,
|
||||
overrides,
|
||||
status, # type: ignore[arg-type]
|
||||
self.dirs.scratch_dir,
|
||||
"task-id",
|
||||
)
|
||||
preflight.setup()
|
||||
preflight.run()
|
||||
consumer = ConsumerPlugin(
|
||||
doc,
|
||||
overrides,
|
||||
status, # type: ignore[arg-type]
|
||||
self.dirs.scratch_dir,
|
||||
"task-id",
|
||||
)
|
||||
consumer.setup()
|
||||
|
||||
try:
|
||||
with record_media_lock_acquisitions() as acquisitions:
|
||||
consumer.run()
|
||||
finally:
|
||||
consumer.cleanup()
|
||||
|
||||
self.assertTrue(acquisitions)
|
||||
self.assertFalse(any(a.in_user_transaction for a in acquisitions))
|
||||
root_doc.refresh_from_db()
|
||||
self.assertGreater(root_doc.modified, original_modified)
|
||||
|
||||
@override_settings(
|
||||
PAPERLESS_EMAIL_HOST="localhost",
|
||||
EMAIL_ENABLED=True,
|
||||
PAPERLESS_URL="http://localhost:8000",
|
||||
)
|
||||
@mock.patch("documents.consumer.load_classifier")
|
||||
@mock.patch("django.core.mail.message.EmailMessage.send", return_value=1)
|
||||
def test_consumption_workflow_email_runs_under_held_lock(self, send, m) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document added workflow with an email action
|
||||
WHEN:
|
||||
- A document is consumed (the consumer holds media.lock while
|
||||
workflows run)
|
||||
THEN:
|
||||
- The email action re-enters media.lock and sends without blocking
|
||||
"""
|
||||
m.return_value = MagicMock()
|
||||
trigger = WorkflowTrigger.objects.create(
|
||||
type=WorkflowTrigger.WorkflowTriggerType.DOCUMENT_ADDED,
|
||||
)
|
||||
email = WorkflowActionEmail.objects.create(
|
||||
subject="added",
|
||||
body="body",
|
||||
to="someone@example.com",
|
||||
include_document=True,
|
||||
)
|
||||
action = WorkflowAction.objects.create(
|
||||
type=WorkflowAction.WorkflowActionType.EMAIL,
|
||||
email=email,
|
||||
)
|
||||
workflow = Workflow.objects.create(name="email on add")
|
||||
workflow.triggers.add(trigger)
|
||||
workflow.actions.add(action)
|
||||
|
||||
with self.get_consumer(self.get_test_file()) as consumer:
|
||||
consumer.run()
|
||||
|
||||
send.assert_called_once()
|
||||
|
||||
@override_settings(
|
||||
FILENAME_FORMAT=None,
|
||||
TIME_ZONE="America/Chicago",
|
||||
@@ -909,7 +750,7 @@ class TestConsumer(
|
||||
FILENAME_FORMAT="{correspondent}/{title}",
|
||||
ARCHIVE_FILE_GENERATION="always",
|
||||
)
|
||||
@mock.patch("documents.file_moves.generate_unique_filename")
|
||||
@mock.patch("documents.signals.handlers.generate_unique_filename")
|
||||
def testFilenameHandlingUnstableFormat(self, m) -> None:
|
||||
filenames = ["this", "that", "now this", "i cannot decide"]
|
||||
|
||||
|
||||
@@ -92,7 +92,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
# Ensure that filename is properly generated
|
||||
self.assertEqual(document.filename, Path("none/none.pdf"))
|
||||
|
||||
document.save(write_file_paths=True)
|
||||
document.save()
|
||||
|
||||
# test that creating dirs for the source_path creates the correct directory
|
||||
create_source_path_directory(document.source_path)
|
||||
@@ -190,7 +190,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
|
||||
# Set a correspondent and save the document
|
||||
document.correspondent = Correspondent.objects.get_or_create(name="test")[0]
|
||||
document.save(write_file_paths=True)
|
||||
document.save()
|
||||
|
||||
# Check proper handling of files
|
||||
self.assertIsFile(
|
||||
@@ -232,7 +232,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
disable_auditlog(),
|
||||
):
|
||||
m.side_effect = DatabaseError()
|
||||
document.save(write_file_paths=True)
|
||||
document.save()
|
||||
|
||||
# Check proper handling of files
|
||||
self.assertIsFile(document.source_path)
|
||||
@@ -336,7 +336,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
|
||||
# Ensure that filename is properly generated
|
||||
document.filename = generate_filename(document)
|
||||
document.save(write_file_paths=True)
|
||||
document.save()
|
||||
self.assertEqual(document.filename, "none/none.pdf")
|
||||
|
||||
create_source_path_directory(document.source_path)
|
||||
@@ -362,7 +362,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
|
||||
# Ensure that filename is properly generated
|
||||
document.filename = generate_filename(document)
|
||||
document.save(write_file_paths=True)
|
||||
document.save()
|
||||
self.assertEqual(document.filename, "none/none.pdf")
|
||||
|
||||
create_source_path_directory(document.source_path)
|
||||
@@ -385,7 +385,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
|
||||
document.save()
|
||||
document.filename = generate_filename(document)
|
||||
document.save(write_file_paths=True)
|
||||
document.save()
|
||||
create_source_path_directory(document.source_path)
|
||||
Path(document.source_path).touch()
|
||||
document.delete()
|
||||
@@ -421,7 +421,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
|
||||
# Set a correspondent and save the document
|
||||
document.correspondent = Correspondent.objects.get_or_create(name="test")[0]
|
||||
document.save(write_file_paths=True)
|
||||
document.save()
|
||||
|
||||
# Check proper handling of files
|
||||
self.assertIsDir(settings.ORIGINALS_DIR / "test")
|
||||
@@ -476,7 +476,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
def test_filename_relative(self) -> None:
|
||||
doc = Document.objects.create(title="doc1", mime_type="application/pdf")
|
||||
doc.filename = generate_filename(doc)
|
||||
doc.save(write_file_paths=True)
|
||||
doc.save()
|
||||
|
||||
self.assertEqual(
|
||||
doc.source_path,
|
||||
@@ -532,7 +532,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
|
||||
# Ensure that filename is properly generated
|
||||
document.filename = generate_filename(document)
|
||||
document.save(write_file_paths=True)
|
||||
document.save()
|
||||
self.assertEqual(document.filename, "none/none/none.pdf")
|
||||
create_source_path_directory(document.source_path)
|
||||
Path(document.source_path).touch()
|
||||
@@ -620,13 +620,13 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
Path(document.source_path).touch()
|
||||
Path(document2.source_path).touch()
|
||||
document.filename = "0000001.pdf"
|
||||
document.save(write_file_paths=True)
|
||||
document.save()
|
||||
|
||||
self.assertIsFile(document.source_path)
|
||||
self.assertEqual(document.filename, "qwe.pdf")
|
||||
|
||||
document2.filename = "0000002.pdf"
|
||||
document2.save(write_file_paths=True)
|
||||
document2.save()
|
||||
|
||||
self.assertIsFile(document.source_path)
|
||||
self.assertEqual(document2.filename, "qwe_01.pdf")
|
||||
@@ -656,17 +656,19 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
self.assertEqual(document2.filename, "qwe.pdf")
|
||||
|
||||
@override_settings(FILENAME_FORMAT="{title}")
|
||||
@mock.patch("documents.file_moves.Document.global_objects.filter")
|
||||
@mock.patch("documents.file_moves.shutil.move")
|
||||
@mock.patch("documents.signals.handlers.Document.objects.filter")
|
||||
@mock.patch("documents.signals.handlers.shutil.move")
|
||||
def test_no_move_only_save(self, mock_move, mock_filter) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document with a filename
|
||||
- The document is saved
|
||||
- The filename is not changed
|
||||
WHEN:
|
||||
- The document is saved without a change that affects its path
|
||||
- The document is saved
|
||||
THEN:
|
||||
- The document modified date is updated by the save itself
|
||||
- The file is not moved and the mover writes nothing
|
||||
- The document modified date is updated
|
||||
- The document is not moved
|
||||
"""
|
||||
with disable_auditlog():
|
||||
doc = Document.objects.create(
|
||||
@@ -684,7 +686,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
doc.save()
|
||||
doc.refresh_from_db()
|
||||
|
||||
mock_filter.assert_not_called()
|
||||
mock_filter.assert_called()
|
||||
self.assertNotEqual(original_modified, doc.modified)
|
||||
mock_move.assert_not_called()
|
||||
|
||||
@@ -692,7 +694,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
FILENAME_FORMAT="{{title}}_{{custom_fields|get_cf_value('test')}}",
|
||||
CELERY_TASK_ALWAYS_EAGER=True,
|
||||
)
|
||||
@mock.patch("documents.signals.handlers.move_files_for_document")
|
||||
@mock.patch("documents.signals.handlers.update_filename_and_move_files")
|
||||
def test_select_cf_updated(self, m) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
@@ -2043,7 +2045,7 @@ class TestCustomFieldFilenameUpdates(
|
||||
Path(self.doc.source_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(self.doc.source_path).touch()
|
||||
|
||||
with mock.patch("documents.file_moves.generate_unique_filename") as m:
|
||||
with mock.patch("documents.signals.handlers.generate_unique_filename") as m:
|
||||
m.side_effect = generate_unique_filename
|
||||
self.cfi.value_text = "updated"
|
||||
self.cfi.save()
|
||||
@@ -2065,7 +2067,7 @@ class TestCustomFieldFilenameUpdates(
|
||||
Path(self.doc.source_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(self.doc.source_path).touch()
|
||||
|
||||
with mock.patch("documents.file_moves.generate_unique_filename") as m:
|
||||
with mock.patch("documents.signals.handlers.generate_unique_filename") as m:
|
||||
m.side_effect = generate_unique_filename
|
||||
self.cfi.value_text = "updated"
|
||||
self.cfi.save()
|
||||
@@ -2143,7 +2145,7 @@ def test_refresh_failure_surfaces_database_error(
|
||||
GIVEN:
|
||||
- A document with a stored filename
|
||||
WHEN:
|
||||
- Saving it triggers a filename update and loading it from the database fails
|
||||
- Saving it triggers a filename update and refreshing it from the database fails
|
||||
THEN:
|
||||
- The database error is raised, not an unbound variable error from the rollback
|
||||
"""
|
||||
@@ -2151,8 +2153,8 @@ def test_refresh_failure_surfaces_database_error(
|
||||
|
||||
with (
|
||||
mock.patch.object(
|
||||
Document.global_objects,
|
||||
"get",
|
||||
Document,
|
||||
"refresh_from_db",
|
||||
side_effect=DatabaseError("database is locked"),
|
||||
),
|
||||
pytest.raises(DatabaseError, match="database is locked"),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,183 @@
|
||||
import pytest
|
||||
from rest_framework import status
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from paperless_testing.factories import DocumentFactory
|
||||
from paperless_testing.factories import TagFactory
|
||||
|
||||
HUGE = 2**63 # one above the largest signed 64 bit integer
|
||||
|
||||
|
||||
class TestFilterInputBounds:
|
||||
@pytest.mark.parametrize(
|
||||
("path", "query"),
|
||||
[
|
||||
pytest.param("/api/tags/", f"id__in={HUGE}", id="tags-id-in"),
|
||||
pytest.param("/api/tags/", f"id={HUGE}", id="tags-id-exact"),
|
||||
pytest.param("/api/tags/", f"id__in=1,{HUGE}", id="tags-id-in-mixed"),
|
||||
pytest.param("/api/documents/", f"id__in={HUGE}", id="documents-id-in"),
|
||||
pytest.param("/api/documents/", "created__year=0", id="year-zero"),
|
||||
pytest.param("/api/documents/", "created__year=10000", id="year-too-big"),
|
||||
pytest.param("/api/documents/", "created__month=13", id="month-13"),
|
||||
pytest.param("/api/documents/", "created__day=0", id="day-zero"),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
"created__year=-10000000000000000",
|
||||
id="year-hugely-negative",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
"added__gt=2024-01-01T00:00:00%2B16:29",
|
||||
id="offset-too-large",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
"added__gt=0001-01-01T00:00:00%2B05:00",
|
||||
id="utc-conversion-overflows",
|
||||
),
|
||||
pytest.param("/api/share_links/", "created__year=0", id="share-links-year"),
|
||||
pytest.param(
|
||||
"/api/share_links/",
|
||||
f"expiration__day={HUGE}",
|
||||
id="share-links-day",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/share_link_bundles/",
|
||||
"expiration__year=100000000000000000",
|
||||
id="bundles-year",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/tasks/",
|
||||
"date_created_after=2024-01-01T00:00:00%2B16:29",
|
||||
id="tasks-offset",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
"ordering=custom_field_abc",
|
||||
id="ordering-not-a-number",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
f"ordering=custom_field_{HUGE}",
|
||||
id="ordering-out-of-range",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_out_of_range_value_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
path: str,
|
||||
query: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- A filter or ordering value outside what the database can hold is sent
|
||||
THEN:
|
||||
- The response is a 400, not a server error
|
||||
"""
|
||||
response = admin_client.get(f"{path}?{query}")
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "query"),
|
||||
[
|
||||
pytest.param("/api/documents/", f"tags__id__all={HUGE}", id="tags-all"),
|
||||
pytest.param("/api/documents/", f"tags__id__in={HUGE}", id="tags-in"),
|
||||
pytest.param(
|
||||
"/api/share_link_bundles/",
|
||||
f"documents={HUGE}",
|
||||
id="bundle-documents",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_id_list_with_an_impossible_id_matches_nothing(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
path: str,
|
||||
query: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document that has a tag
|
||||
WHEN:
|
||||
- An id list filter includes an id that no row can have
|
||||
THEN:
|
||||
- The request succeeds and nothing matches
|
||||
"""
|
||||
document = DocumentFactory.create()
|
||||
document.tags.add(TagFactory.create())
|
||||
|
||||
response = admin_client.get(f"{path}?{query}")
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data["count"] == 0
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("path", "query"),
|
||||
[
|
||||
pytest.param("/api/tags/", "id__in=1,2", id="id-in"),
|
||||
pytest.param("/api/documents/", "created__year=2024", id="year"),
|
||||
pytest.param("/api/documents/", "created__year=9999", id="year-max"),
|
||||
pytest.param("/api/documents/", "created__month=12", id="month"),
|
||||
pytest.param("/api/documents/", "created__day=31", id="day"),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
"added__gt=2024-01-01T00:00:00%2B14:00",
|
||||
id="offset-at-the-limit",
|
||||
),
|
||||
pytest.param(
|
||||
"/api/documents/",
|
||||
"added__gt=2024-01-01T00:00:00-12:00",
|
||||
id="negative-offset",
|
||||
),
|
||||
pytest.param("/api/tasks/", "date_created_after=2024-01-01", id="tasks"),
|
||||
],
|
||||
)
|
||||
def test_in_range_values_still_work(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
path: str,
|
||||
query: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- Filters with ordinary values are sent
|
||||
THEN:
|
||||
- The request succeeds
|
||||
"""
|
||||
response = admin_client.get(f"{path}?{query}")
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
|
||||
class TestSetPermissionsIdBounds:
|
||||
@pytest.mark.parametrize("grantee", ["users", "groups"])
|
||||
@pytest.mark.parametrize("bad_id", [HUGE, -HUGE, "abc", None])
|
||||
def test_impossible_grantee_id_is_a_400(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
grantee: str,
|
||||
bad_id: object,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A tag
|
||||
WHEN:
|
||||
- Permissions are set with a user or group id that cannot exist
|
||||
THEN:
|
||||
- The response is a 400, not a server error
|
||||
"""
|
||||
tag = TagFactory.create()
|
||||
|
||||
response = admin_client.put(
|
||||
f"/api/tags/{tag.pk}/",
|
||||
{"name": tag.name, "set_permissions": {"view": {grantee: [bad_id]}}},
|
||||
format="json",
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
@@ -18,13 +18,11 @@ if TYPE_CHECKING:
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from documents.file_handling import generate_filename
|
||||
from documents.file_moves import move_files_for_document
|
||||
from documents.models import Document
|
||||
from documents.tasks import update_document_content_maybe_archive_file
|
||||
from paperless_testing.assertions import FileSystemAssertsMixin
|
||||
from paperless_testing.dirs import DirectoriesMixin
|
||||
from paperless_testing.factories import DocumentFactory
|
||||
from paperless_testing.locks import record_media_lock_acquisitions
|
||||
from paperless_testing.samples import SIMPLE_DIGITAL_PDF
|
||||
|
||||
sample_file: Path = SIMPLE_DIGITAL_PDF
|
||||
@@ -65,28 +63,6 @@ class TestArchiver(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
self.assertTrue(filecmp.cmp(sample_file, doc.source_path))
|
||||
self.assertEqual(doc.archive_filename, "none/A.pdf")
|
||||
|
||||
def test_handle_document_takes_media_lock_outside_transaction(self) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document whose archive version is being generated
|
||||
WHEN:
|
||||
- update_document_content_maybe_archive_file runs
|
||||
THEN:
|
||||
- media.lock is acquired
|
||||
- media.lock is never first acquired while a transaction holds the
|
||||
document row
|
||||
"""
|
||||
doc = self.make_models()
|
||||
shutil.copy(sample_file, Path(self.dirs.originals_dir) / f"{doc.id:07}.pdf")
|
||||
|
||||
with record_media_lock_acquisitions() as acquisitions:
|
||||
update_document_content_maybe_archive_file(doc.pk)
|
||||
|
||||
self.assertTrue(acquisitions)
|
||||
self.assertFalse(any(a.in_user_transaction for a in acquisitions))
|
||||
doc.refresh_from_db()
|
||||
self.assertIsFile(doc.archive_path)
|
||||
|
||||
def test_unknown_mime_type(self) -> None:
|
||||
doc = self.make_models()
|
||||
doc.mime_type = "sdgfh"
|
||||
@@ -260,7 +236,7 @@ class TestRenamer(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
doc = Document.objects.create(title="test", mime_type="image/jpeg")
|
||||
doc.filename = generate_filename(doc)
|
||||
doc.archive_filename = generate_filename(doc, archive_filename=True)
|
||||
doc.save(write_file_paths=True)
|
||||
doc.save()
|
||||
|
||||
Path(doc.source_path).touch()
|
||||
Path(doc.archive_path).touch()
|
||||
@@ -277,42 +253,6 @@ class TestRenamer(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
||||
self.assertIsFile(doc2.source_path)
|
||||
self.assertIsFile(doc2.archive_path)
|
||||
|
||||
@override_settings(FILENAME_FORMAT="")
|
||||
def test_rename_moves_each_document_by_direct_call(self) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Two documents whose filename format changed
|
||||
WHEN:
|
||||
- document_renamer runs
|
||||
THEN:
|
||||
- move_files_for_document is called once per document
|
||||
- Both files are at their new paths
|
||||
"""
|
||||
docs = []
|
||||
for title in ("first", "second"):
|
||||
doc = Document.objects.create(title=title, mime_type="image/jpeg")
|
||||
doc.filename = generate_filename(doc)
|
||||
doc.save(write_file_paths=True)
|
||||
Path(doc.source_path).touch()
|
||||
docs.append(doc)
|
||||
|
||||
with (
|
||||
override_settings(FILENAME_FORMAT="{title}"),
|
||||
mock.patch(
|
||||
"documents.management.commands.document_renamer.move_files_for_document",
|
||||
wraps=move_files_for_document,
|
||||
) as mover,
|
||||
):
|
||||
call_command("document_renamer", skip_checks=True)
|
||||
|
||||
self.assertCountEqual(
|
||||
[c.args[0] for c in mover.call_args_list],
|
||||
[d.pk for d in docs],
|
||||
)
|
||||
for doc in docs:
|
||||
doc.refresh_from_db()
|
||||
self.assertIsFile(doc.source_path)
|
||||
|
||||
|
||||
@pytest.mark.management
|
||||
class TestCreateClassifier:
|
||||
|
||||
@@ -4,13 +4,10 @@ Tests for the document_retagger management command.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
from django.core.management import call_command
|
||||
from django.core.management.base import CommandError
|
||||
|
||||
from documents.file_moves import _active_collector
|
||||
from documents.models import Correspondent
|
||||
from documents.models import Document
|
||||
from documents.models import DocumentType
|
||||
@@ -24,12 +21,6 @@ from paperless_testing.factories import DocumentTypeFactory
|
||||
from paperless_testing.factories import StoragePathFactory
|
||||
from paperless_testing.factories import TagFactory
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from pytest_django.fixtures import Settings
|
||||
from pytest_mock import MockerFixture
|
||||
|
||||
from paperless_testing.dirs import PaperlessDirs
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Module-level type aliases
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -493,69 +484,3 @@ class TestRetaggerEdgeCases(DirectoriesMixin):
|
||||
|
||||
assert d_first.tags.count() == 0
|
||||
assert d_unrelated.tags.count() == 2
|
||||
|
||||
|
||||
@pytest.mark.management
|
||||
@pytest.mark.django_db
|
||||
class TestRetaggerFileMoves:
|
||||
def test_each_document_is_processed_in_its_own_scope(
|
||||
self,
|
||||
paperless_dirs: PaperlessDirs,
|
||||
settings: Settings,
|
||||
mocker: MockerFixture,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Two documents and a filename format using the correspondent
|
||||
- A classifier suggestion assigning a correspondent to each
|
||||
WHEN:
|
||||
- document_retagger runs with --correspondent
|
||||
THEN:
|
||||
- Each document is processed inside an open file move scope
|
||||
- When the second document is processed, the first one's file has
|
||||
already moved
|
||||
- Both files end at their final paths
|
||||
"""
|
||||
settings.FILENAME_FORMAT = "{correspondent}/{title}"
|
||||
(paperless_dirs.originals_dir / "none").mkdir(exist_ok=True)
|
||||
for title in ("first", "second"):
|
||||
(paperless_dirs.originals_dir / "none" / f"{title}.pdf").write_bytes(b"x")
|
||||
DocumentFactory(
|
||||
title=title,
|
||||
filename=f"none/{title}.pdf",
|
||||
mime_type="application/pdf",
|
||||
)
|
||||
correspondent = CorrespondentFactory(name="acme")
|
||||
processed: list[Document] = []
|
||||
scope_open: list[bool] = []
|
||||
seen_first_moved: list[bool] = []
|
||||
|
||||
def fake_set_correspondent(sender, document, **kwargs):
|
||||
scope_open.append(_active_collector.get() is not None)
|
||||
# Order-agnostic: on the second call, check the first one's file.
|
||||
if processed:
|
||||
first = processed[0]
|
||||
seen_first_moved.append(
|
||||
(
|
||||
paperless_dirs.originals_dir / "acme" / f"{first.title}.pdf"
|
||||
).is_file(),
|
||||
)
|
||||
processed.append(document)
|
||||
document.correspondent = correspondent
|
||||
document.save(update_fields=("correspondent",))
|
||||
return correspondent
|
||||
|
||||
mocker.patch(
|
||||
"documents.management.commands.document_retagger.load_classifier",
|
||||
)
|
||||
mocker.patch(
|
||||
"documents.management.commands.document_retagger.set_correspondent",
|
||||
side_effect=fake_set_correspondent,
|
||||
)
|
||||
|
||||
call_command("document_retagger", "--correspondent", skip_checks=True)
|
||||
|
||||
assert scope_open == [True, True]
|
||||
assert seen_first_moved == [True]
|
||||
for title in ("first", "second"):
|
||||
assert (paperless_dirs.originals_dir / "acme" / f"{title}.pdf").is_file()
|
||||
@@ -1,121 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
from django.db import transaction
|
||||
from filelock import Timeout
|
||||
|
||||
from documents.file_moves import in_user_transaction
|
||||
from documents.media_lock import media_lock
|
||||
from paperless_testing.locks import record_media_lock_acquisitions
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from paperless_testing.dirs import PaperlessDirs
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("paperless_dirs")
|
||||
class TestMediaLock:
|
||||
def test_same_thread_reenters_without_blocking(self) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- media.lock held by the current thread
|
||||
WHEN:
|
||||
- The same thread acquires it again with a zero timeout
|
||||
THEN:
|
||||
- The nested acquisition succeeds immediately
|
||||
"""
|
||||
with media_lock(), media_lock(timeout=0):
|
||||
pass
|
||||
|
||||
def test_other_thread_is_excluded(self) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- media.lock held by the current thread
|
||||
WHEN:
|
||||
- Another thread tries to acquire it with a short timeout
|
||||
THEN:
|
||||
- The other thread times out
|
||||
- After release, the other thread can acquire it
|
||||
"""
|
||||
outcomes: list[str] = []
|
||||
|
||||
def try_acquire() -> None:
|
||||
try:
|
||||
with media_lock(timeout=0.2):
|
||||
outcomes.append("acquired")
|
||||
except Timeout:
|
||||
outcomes.append("timeout")
|
||||
|
||||
with media_lock():
|
||||
worker = threading.Thread(target=try_acquire)
|
||||
worker.start()
|
||||
worker.join()
|
||||
|
||||
worker = threading.Thread(target=try_acquire)
|
||||
worker.start()
|
||||
worker.join()
|
||||
|
||||
assert outcomes == ["timeout", "acquired"]
|
||||
|
||||
def test_lock_file_is_the_configured_path(
|
||||
self,
|
||||
paperless_dirs: PaperlessDirs,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The test's media directory layout
|
||||
WHEN:
|
||||
- media.lock is acquired
|
||||
THEN:
|
||||
- The lock file is created at settings.MEDIA_LOCK
|
||||
"""
|
||||
with media_lock():
|
||||
assert paperless_dirs.media_lock.exists()
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
class TestInUserTransaction:
|
||||
def test_false_inside_test_case_wrapper(self) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- The transaction pytest-django wraps around the test
|
||||
WHEN:
|
||||
- in_user_transaction is called
|
||||
THEN:
|
||||
- It returns False
|
||||
"""
|
||||
assert in_user_transaction() is False
|
||||
|
||||
def test_true_inside_atomic(self) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An atomic block opened by code under test
|
||||
WHEN:
|
||||
- in_user_transaction is called inside it
|
||||
THEN:
|
||||
- It returns True
|
||||
"""
|
||||
with transaction.atomic():
|
||||
assert in_user_transaction() is True
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.usefixtures("paperless_dirs")
|
||||
class TestRecordMediaLockAcquisitions:
|
||||
def test_records_only_first_acquisitions(self) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- Nested media.lock acquisitions, the outer one inside a transaction
|
||||
WHEN:
|
||||
- They are recorded
|
||||
THEN:
|
||||
- Only the outer, first acquisition is recorded, flagged as inside
|
||||
a transaction
|
||||
"""
|
||||
with record_media_lock_acquisitions() as acquisitions:
|
||||
with transaction.atomic(), media_lock(), media_lock():
|
||||
pass
|
||||
|
||||
assert [a.in_user_transaction for a in acquisitions] == [True]
|
||||
@@ -1,7 +1,4 @@
|
||||
import pytest
|
||||
from django.db import DatabaseError
|
||||
from django.db import models
|
||||
from django.db import transaction
|
||||
|
||||
from documents.models import Correspondent
|
||||
from documents.models import Document
|
||||
@@ -25,101 +22,3 @@ class TestDocument:
|
||||
assert Correspondent.objects.count() == 0
|
||||
assert Document.objects.count() == 1
|
||||
assert Document.objects.first().correspondent is None
|
||||
|
||||
|
||||
@pytest.mark.django_db
|
||||
@pytest.mark.usefixtures("paperless_dirs")
|
||||
class TestDocumentFilePathWrites:
|
||||
def test_full_save_does_not_write_file_paths(self) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A document whose filename columns were changed in the DB after
|
||||
an instance was loaded
|
||||
WHEN:
|
||||
- The stale instance is saved without update_fields
|
||||
THEN:
|
||||
- The DB filename columns keep the newer values
|
||||
- Other fields from the stale instance are written
|
||||
"""
|
||||
doc = DocumentFactory(filename="old.pdf", archive_filename="old.pdf")
|
||||
stale = Document.objects.get(pk=doc.pk)
|
||||
Document.objects.filter(pk=doc.pk).update(
|
||||
filename="new.pdf",
|
||||
archive_filename="new-archive.pdf",
|
||||
)
|
||||
|
||||
stale.title = "changed"
|
||||
stale.save()
|
||||
|
||||
doc.refresh_from_db()
|
||||
assert doc.filename == "new.pdf"
|
||||
assert doc.archive_filename == "new-archive.pdf"
|
||||
assert doc.title == "changed"
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"save_kwargs",
|
||||
[
|
||||
pytest.param({"write_file_paths": True}, id="write-file-paths"),
|
||||
pytest.param(
|
||||
{"update_fields": ["filename", "archive_filename"]},
|
||||
id="explicit-update-fields",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_opt_in_writes_file_paths(self, save_kwargs: dict[str, object]) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An existing document
|
||||
WHEN:
|
||||
- Its filename columns are changed in memory and saved with an
|
||||
explicit opt in
|
||||
THEN:
|
||||
- The DB filename columns are updated
|
||||
"""
|
||||
doc = DocumentFactory(filename="old.pdf", archive_filename="old.pdf")
|
||||
|
||||
doc.filename = "new.pdf"
|
||||
doc.archive_filename = "new.pdf"
|
||||
doc.save(**save_kwargs)
|
||||
|
||||
doc.refresh_from_db()
|
||||
assert doc.filename == "new.pdf"
|
||||
assert doc.archive_filename == "new.pdf"
|
||||
|
||||
def test_creation_writes_file_paths(self) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A new, unsaved document with filename columns set
|
||||
WHEN:
|
||||
- It is saved
|
||||
THEN:
|
||||
- The filename columns are written
|
||||
"""
|
||||
doc = DocumentFactory.build(filename="a.pdf", archive_filename="b.pdf")
|
||||
|
||||
doc.save()
|
||||
|
||||
doc.refresh_from_db()
|
||||
assert doc.filename == "a.pdf"
|
||||
assert doc.archive_filename == "b.pdf"
|
||||
|
||||
def test_full_save_of_deleted_row_raises(self) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An instance whose row was hard-deleted elsewhere
|
||||
WHEN:
|
||||
- The instance is saved without update_fields
|
||||
THEN:
|
||||
- A DatabaseError is raised instead of re-inserting the row
|
||||
"""
|
||||
doc = DocumentFactory()
|
||||
stale = Document.objects.get(pk=doc.pk)
|
||||
# A plain QuerySet bypasses the soft-delete manager, so the row is
|
||||
# really gone (as after emptying the trash).
|
||||
models.QuerySet(model=Document).filter(pk=doc.pk).delete()
|
||||
|
||||
# The savepoint keeps the failed UPDATE from poisoning the test transaction.
|
||||
with pytest.raises(DatabaseError), transaction.atomic():
|
||||
stale.save()
|
||||
|
||||
assert not Document.global_objects.filter(pk=doc.pk).exists()
|
||||
@@ -129,7 +129,7 @@ class TestCheckSanityOriginal:
|
||||
class TestCheckSanityArchive:
|
||||
def test_checksum_without_filename(self, sample_doc: Document) -> None:
|
||||
sample_doc.archive_filename = None
|
||||
sample_doc.save(write_file_paths=True)
|
||||
sample_doc.save()
|
||||
messages = check_sanity()
|
||||
assert messages.has_error
|
||||
assert any(
|
||||
@@ -182,7 +182,7 @@ class TestCheckSanityArchive:
|
||||
Path(sample_doc.archive_path).unlink()
|
||||
sample_doc.archive_checksum = None
|
||||
sample_doc.archive_filename = None
|
||||
sample_doc.save(write_file_paths=True)
|
||||
sample_doc.save()
|
||||
messages = check_sanity()
|
||||
assert not messages.has_error
|
||||
|
||||
|
||||
@@ -366,7 +366,7 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
|
||||
def _write_document_file(self, *, archive: bool, content: bytes) -> Path:
|
||||
if archive:
|
||||
self.document.archive_filename = f"{self.document.pk:07}.pdf"
|
||||
self.document.save(write_file_paths=True)
|
||||
self.document.save()
|
||||
path = self.document.archive_path
|
||||
assert path is not None
|
||||
else:
|
||||
|
||||
@@ -887,8 +887,8 @@ class TestSavedZoneExtraction:
|
||||
WHEN:
|
||||
- Zone extraction runs
|
||||
THEN:
|
||||
- The only on-commit callback is the deferred file move; reindexing
|
||||
and other finishing is left to the caller
|
||||
- No on-commit callbacks are registered; finishing is left to the
|
||||
caller
|
||||
"""
|
||||
make_zone(template, "Title")
|
||||
mock_zone_ocr_run.return_value = subprocess.CompletedProcess(
|
||||
@@ -900,10 +900,7 @@ class TestSavedZoneExtraction:
|
||||
with django_capture_on_commit_callbacks() as callbacks:
|
||||
run_zone_extraction(document, templates=[template])
|
||||
|
||||
assert all(
|
||||
callback.__qualname__.startswith("request_file_move")
|
||||
for callback in callbacks
|
||||
)
|
||||
assert callbacks == []
|
||||
|
||||
def test_document_run_renders_each_page_once_across_templates(
|
||||
self,
|
||||
|
||||
+225
-73
@@ -3,6 +3,7 @@ import logging
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
from collections import Counter
|
||||
@@ -134,7 +135,6 @@ from documents.data_models import ConsumableDocument
|
||||
from documents.data_models import DocumentMetadataOverrides
|
||||
from documents.data_models import DocumentSource
|
||||
from documents.file_handling import format_filename
|
||||
from documents.file_moves import flush_pending_file_moves
|
||||
from documents.filters import CorrespondentFilterSet
|
||||
from documents.filters import CustomFieldFilterSet
|
||||
from documents.filters import DocumentFilterSet
|
||||
@@ -150,6 +150,7 @@ from documents.filters import StoragePathFilterSet
|
||||
from documents.filters import TagFilterSet
|
||||
from documents.filters import TitleContentFilter
|
||||
from documents.filters import WorkflowFilterSet
|
||||
from documents.filters import in_range_ids
|
||||
from documents.mail import EmailAttachment
|
||||
from documents.mail import send_email
|
||||
from documents.matching import match_correspondents
|
||||
@@ -197,6 +198,7 @@ from documents.permissions import set_permissions_for_objects
|
||||
from documents.permissions import user_is_unrestricted
|
||||
from documents.plugins.date_parsing import get_date_parser
|
||||
from documents.regex import safe_regex_fullmatch
|
||||
from documents.schema import Int64Field
|
||||
from documents.schema import generate_object_with_permissions_schema
|
||||
from documents.search import SearchHit
|
||||
from documents.serialisers import AcknowledgeTasksViewSerializer
|
||||
@@ -265,6 +267,7 @@ from documents.versioning import resolve_effective_document
|
||||
from documents.versioning import resolve_requested_version_for_root
|
||||
from documents.versioning import versions_newest_first
|
||||
from paperless import version
|
||||
from paperless.api_parsers import ObjectJSONParser
|
||||
from paperless.celery import app as celery_app
|
||||
from paperless.config import AIConfig
|
||||
from paperless.config import GeneralConfig
|
||||
@@ -764,7 +767,8 @@ class EmailDocumentDetailSchema(EmailSerializer):
|
||||
location=OpenApiParameter.QUERY,
|
||||
),
|
||||
],
|
||||
responses={200: OpenApiTypes.BINARY},
|
||||
# The file is served with its own mime type
|
||||
responses={(200, "*/*"): OpenApiTypes.BINARY},
|
||||
),
|
||||
history=extend_schema(
|
||||
description="View the document history",
|
||||
@@ -783,6 +787,7 @@ class EmailDocumentDetailSchema(EmailSerializer):
|
||||
"id": serializers.IntegerField(),
|
||||
"username": serializers.CharField(),
|
||||
},
|
||||
allow_null=True,
|
||||
),
|
||||
},
|
||||
),
|
||||
@@ -931,11 +936,11 @@ class EmailDocumentDetailSchema(EmailSerializer):
|
||||
),
|
||||
thumb=extend_schema(
|
||||
description="View the document thumbnail",
|
||||
responses={200: OpenApiTypes.BINARY},
|
||||
responses={(200, "image/webp"): OpenApiTypes.BINARY},
|
||||
),
|
||||
preview=extend_schema(
|
||||
description="View the document preview",
|
||||
responses={200: OpenApiTypes.BINARY},
|
||||
responses={(200, "*/*"): OpenApiTypes.BINARY},
|
||||
),
|
||||
share_links=extend_schema(
|
||||
operation_id="document_share_links",
|
||||
@@ -943,23 +948,12 @@ class EmailDocumentDetailSchema(EmailSerializer):
|
||||
parameters=[
|
||||
OpenApiParameter(
|
||||
name="id",
|
||||
type=OpenApiTypes.STR,
|
||||
type=OpenApiTypes.INT,
|
||||
location=OpenApiParameter.PATH,
|
||||
),
|
||||
],
|
||||
responses={
|
||||
200: {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {"type": "integer"},
|
||||
"created": {"type": "string", "format": "date-time"},
|
||||
"expiration": {"type": "string", "format": "date-time"},
|
||||
"slug": {"type": "string"},
|
||||
},
|
||||
},
|
||||
},
|
||||
200: ShareLinkSerializer(many=True),
|
||||
400: None,
|
||||
403: None,
|
||||
404: None,
|
||||
@@ -1037,6 +1031,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],
|
||||
@@ -1310,8 +1312,6 @@ class DocumentViewSet(
|
||||
)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
self.perform_update(serializer)
|
||||
# The response must reflect the post-move filename and modified time
|
||||
flush_pending_file_moves()
|
||||
|
||||
if content_updated and content_doc.id != root_doc.id:
|
||||
content_doc.content = (
|
||||
@@ -2002,7 +2002,12 @@ class DocumentViewSet(
|
||||
},
|
||||
)
|
||||
|
||||
@action(methods=["get"], detail=True, filter_backends=[])
|
||||
@action(
|
||||
methods=["get"],
|
||||
detail=True,
|
||||
filter_backends=[],
|
||||
pagination_class=None,
|
||||
)
|
||||
def share_links(self, request, pk=None):
|
||||
currentUser = request.user
|
||||
try:
|
||||
@@ -2038,7 +2043,13 @@ class DocumentViewSet(
|
||||
serializer = ShareLinkSerializer(links, many=True)
|
||||
return Response(serializer.data)
|
||||
|
||||
@action(methods=["get"], detail=True, name="Audit Trail", filter_backends=[])
|
||||
@action(
|
||||
methods=["get"],
|
||||
detail=True,
|
||||
name="Audit Trail",
|
||||
filter_backends=[],
|
||||
pagination_class=None,
|
||||
)
|
||||
def history(self, request, pk=None):
|
||||
if not settings.AUDIT_LOG_ENABLED:
|
||||
return HttpResponseBadRequest("Audit log is disabled")
|
||||
@@ -2112,8 +2123,9 @@ class DocumentViewSet(
|
||||
)
|
||||
# TODO: deprecated, remove with drop of support for API v9
|
||||
def email_document(self, request, pk=None):
|
||||
request_data = request.data.copy()
|
||||
request_data.setlist("documents", [pk])
|
||||
# A JSON body is a plain dict and a form body a QueryDict, copy into a dict
|
||||
request_data = dict(request.data.items())
|
||||
request_data["documents"] = [pk]
|
||||
return self.email_documents(request, data=request_data)
|
||||
|
||||
@action(
|
||||
@@ -2889,6 +2901,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",
|
||||
@@ -2906,10 +2925,11 @@ class UnifiedSearchViewSet(DocumentViewSet):
|
||||
name="id",
|
||||
type=OpenApiTypes.STR,
|
||||
location=OpenApiParameter.PATH,
|
||||
enum=list(LOG_FILES),
|
||||
),
|
||||
OpenApiParameter(
|
||||
name="limit",
|
||||
type=OpenApiTypes.INT,
|
||||
type={"type": "integer", "minimum": 1},
|
||||
location=OpenApiParameter.QUERY,
|
||||
description="Return only the last N entries from the log file",
|
||||
required=False,
|
||||
@@ -2926,11 +2946,7 @@ class UnifiedSearchViewSet(DocumentViewSet):
|
||||
class LogViewSet(ViewSet):
|
||||
permission_classes = (IsAuthenticated, PaperlessAdminPermissions)
|
||||
|
||||
ALLOWED_LOG_FILES = {
|
||||
"paperless": "paperless.log",
|
||||
"mail": "mail.log",
|
||||
"celery": "celery.log",
|
||||
}
|
||||
ALLOWED_LOG_FILES = LOG_FILES
|
||||
|
||||
def get_log_file(self, log_key: str) -> Path:
|
||||
return Path(settings.LOGGING_DIR) / self.ALLOWED_LOG_FILES[log_key]
|
||||
@@ -2953,6 +2969,8 @@ class LogViewSet(ViewSet):
|
||||
raise ValidationError({"limit": "Must be a positive integer"})
|
||||
if limit < 1:
|
||||
raise ValidationError({"limit": "Must be a positive integer"})
|
||||
# A limit past what a deque can hold is the same as no limit at all
|
||||
limit = min(limit, sys.maxsize)
|
||||
else:
|
||||
limit = None
|
||||
|
||||
@@ -3123,7 +3141,7 @@ def queue_bulk_operation(
|
||||
|
||||
class DocumentOperationPermissionMixin(PassUserMixin, DocumentSelectionMixin):
|
||||
permission_classes = (IsAuthenticated,)
|
||||
parser_classes = (parsers.JSONParser,)
|
||||
parser_classes = (ObjectJSONParser,)
|
||||
|
||||
def _queue_bulk_operation(self, method, documents, parameters, from_webui):
|
||||
return queue_bulk_operation(
|
||||
@@ -3625,7 +3643,7 @@ class PostDocumentView(GenericAPIView[Any]):
|
||||
class SelectionDataView(DocumentSelectionMixin, GenericAPIView[Any]):
|
||||
permission_classes = (IsAuthenticated, ViewDocumentsPermissions)
|
||||
serializer_class = DocumentSelectionSerializer
|
||||
parser_classes = (parsers.MultiPartParser, parsers.JSONParser)
|
||||
parser_classes = (parsers.MultiPartParser, ObjectJSONParser)
|
||||
|
||||
def post(self, request, format=None):
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
@@ -3710,7 +3728,7 @@ class SelectionDataView(DocumentSelectionMixin, GenericAPIView[Any]):
|
||||
parameters=[
|
||||
OpenApiParameter(
|
||||
name="term",
|
||||
required=False,
|
||||
required=True,
|
||||
type=str,
|
||||
description="Term to search for",
|
||||
),
|
||||
@@ -3761,7 +3779,8 @@ class SearchAutoCompleteView(GenericAPIView[Any]):
|
||||
OpenApiParameter(
|
||||
name="query",
|
||||
required=True,
|
||||
type=str,
|
||||
# Shorter queries are answered with a 400
|
||||
type={"type": "string", "minLength": 3},
|
||||
description="Query to search for",
|
||||
),
|
||||
OpenApiParameter(
|
||||
@@ -3810,6 +3829,9 @@ class GlobalSearchView(PassUserMixin):
|
||||
return HttpResponseBadRequest(
|
||||
f"Query must be at most {_MAX_QUERY_LENGTH} characters",
|
||||
)
|
||||
if "\x00" in query:
|
||||
# Postgres cannot store or compare text containing a null byte
|
||||
return HttpResponseBadRequest("Query must not contain null characters")
|
||||
|
||||
db_only = request.query_params.get("db_only", False)
|
||||
|
||||
@@ -4019,7 +4041,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(),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
@@ -4134,7 +4185,7 @@ class StatisticsView(GenericAPIView[Any]):
|
||||
class BulkDownloadView(DocumentSelectionMixin, GenericAPIView[Any]):
|
||||
permission_classes = (IsAuthenticated, ViewDocumentsPermissions)
|
||||
serializer_class = BulkDownloadSerializer
|
||||
parser_classes = (parsers.JSONParser,)
|
||||
parser_classes = (ObjectJSONParser,)
|
||||
|
||||
def post(self, request, format=None):
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
@@ -4272,6 +4323,46 @@ class StoragePathViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Storag
|
||||
return Response(result)
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
get=extend_schema(
|
||||
description="The UI settings of the current user, merged with the settings of the server and the current user and permissions",
|
||||
request=None,
|
||||
responses={
|
||||
(200, "application/json"): inline_serializer(
|
||||
name="UiSettingsResponse",
|
||||
fields={
|
||||
"user": inline_serializer(
|
||||
name="UiSettingsUser",
|
||||
fields={
|
||||
"id": serializers.IntegerField(),
|
||||
"username": serializers.CharField(),
|
||||
"is_staff": serializers.BooleanField(),
|
||||
"is_superuser": serializers.BooleanField(),
|
||||
"groups": serializers.ListField(
|
||||
child=serializers.IntegerField(),
|
||||
),
|
||||
"first_name": serializers.CharField(required=False),
|
||||
"last_name": serializers.CharField(required=False),
|
||||
},
|
||||
),
|
||||
"settings": serializers.DictField(),
|
||||
"permissions": serializers.ListField(
|
||||
child=serializers.CharField(),
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
post=extend_schema(
|
||||
description="Save the UI settings of the current user",
|
||||
responses={
|
||||
(200, "application/json"): inline_serializer(
|
||||
name="UiSettingsSaveResult",
|
||||
fields={"success": serializers.BooleanField()},
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
class UiSettingsView(GenericAPIView[Any]):
|
||||
queryset = UiSettings.objects.all()
|
||||
permission_classes = (IsAuthenticated, PaperlessObjectPermissions)
|
||||
@@ -4284,8 +4375,10 @@ class UiSettingsView(GenericAPIView[Any]):
|
||||
user = User.objects.select_related("ui_settings").get(pk=request.user.id)
|
||||
ui_settings = {}
|
||||
if hasattr(user, "ui_settings"):
|
||||
ui_settings = user.ui_settings.settings
|
||||
if "update_checking" in ui_settings:
|
||||
# Saved as null or, before it was validated, as something else
|
||||
stored = user.ui_settings.settings
|
||||
ui_settings = stored if isinstance(stored, dict) else {}
|
||||
if isinstance(ui_settings.get("update_checking"), dict):
|
||||
ui_settings["update_checking"]["backend_setting"] = (
|
||||
settings.ENABLE_UPDATE_CHECK
|
||||
)
|
||||
@@ -4504,7 +4597,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(),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
@@ -4547,6 +4646,11 @@ class RemoteVersionView(GenericAPIView[Any]):
|
||||
)
|
||||
|
||||
|
||||
VERSION_PATTERN = (
|
||||
r"^v?[0-9]+(\.[0-9]+){0,3}((a|b|rc)[0-9]+)?(\.post[0-9]+)?(\.dev[0-9]+)?$"
|
||||
)
|
||||
|
||||
|
||||
@extend_schema_view(
|
||||
get=extend_schema(
|
||||
description=(
|
||||
@@ -4557,19 +4661,31 @@ class RemoteVersionView(GenericAPIView[Any]):
|
||||
parameters=[
|
||||
OpenApiParameter(
|
||||
name="since",
|
||||
type=OpenApiTypes.STR,
|
||||
# A version number, anything else is answered with a 400
|
||||
type={"type": "string", "pattern": VERSION_PATTERN},
|
||||
location=OpenApiParameter.QUERY,
|
||||
required=False,
|
||||
),
|
||||
OpenApiParameter(
|
||||
name="until",
|
||||
type=OpenApiTypes.STR,
|
||||
# A version number, anything else is answered with a 400
|
||||
type={"type": "string", "pattern": VERSION_PATTERN},
|
||||
location=OpenApiParameter.QUERY,
|
||||
required=False,
|
||||
),
|
||||
],
|
||||
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),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
)
|
||||
@@ -4999,9 +5115,9 @@ class ShareLinkBundleViewSet(PassUserMixin, ModelViewSet[ShareLinkBundle]):
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
document_ids = serializer.validated_data["document_ids"]
|
||||
documents_qs = Document.objects.filter(pk__in=document_ids).select_related(
|
||||
"owner",
|
||||
)
|
||||
documents_qs = Document.objects.filter(
|
||||
pk__in=in_range_ids(document_ids),
|
||||
).select_related("owner")
|
||||
found_ids = set(documents_qs.values_list("pk", flat=True))
|
||||
missing = sorted(set(document_ids) - found_ids)
|
||||
if missing:
|
||||
@@ -5253,7 +5369,7 @@ def serve_file(
|
||||
class BulkEditObjectsView(PassUserMixin):
|
||||
permission_classes = (IsAuthenticated,)
|
||||
serializer_class = BulkEditObjectsSerializer
|
||||
parser_classes = (parsers.JSONParser,)
|
||||
parser_classes = (ObjectJSONParser,)
|
||||
|
||||
def post(self, request, *args, **kwargs):
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
@@ -5484,8 +5600,8 @@ class CustomFieldViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Custom
|
||||
"storage": inline_serializer(
|
||||
name="Storage",
|
||||
fields={
|
||||
"total": serializers.IntegerField(),
|
||||
"available": serializers.IntegerField(),
|
||||
"total": Int64Field(),
|
||||
"available": Int64Field(),
|
||||
},
|
||||
),
|
||||
"database": inline_serializer(
|
||||
@@ -5494,7 +5610,7 @@ class CustomFieldViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Custom
|
||||
"type": serializers.CharField(),
|
||||
"url": serializers.CharField(),
|
||||
"status": serializers.CharField(),
|
||||
"error": serializers.CharField(),
|
||||
"error": serializers.CharField(allow_null=True),
|
||||
"migration_status": inline_serializer(
|
||||
name="MigrationStatus",
|
||||
fields={
|
||||
@@ -5513,8 +5629,32 @@ class CustomFieldViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Custom
|
||||
fields={
|
||||
"redis_url": serializers.CharField(),
|
||||
"redis_status": serializers.CharField(),
|
||||
"redis_error": serializers.CharField(),
|
||||
"redis_error": serializers.CharField(allow_null=True),
|
||||
"celery_status": serializers.CharField(),
|
||||
"celery_url": serializers.CharField(allow_null=True),
|
||||
"celery_error": serializers.CharField(allow_null=True),
|
||||
"index_status": serializers.CharField(),
|
||||
"index_last_modified": serializers.DateTimeField(
|
||||
allow_null=True,
|
||||
),
|
||||
"index_error": serializers.CharField(allow_null=True),
|
||||
"classifier_status": serializers.CharField(),
|
||||
"classifier_last_trained": serializers.DateTimeField(
|
||||
allow_null=True,
|
||||
),
|
||||
"classifier_error": serializers.CharField(allow_null=True),
|
||||
"sanity_check_status": serializers.CharField(),
|
||||
"sanity_check_last_run": serializers.DateTimeField(
|
||||
allow_null=True,
|
||||
),
|
||||
"sanity_check_error": serializers.CharField(
|
||||
allow_null=True,
|
||||
),
|
||||
"llmindex_status": serializers.CharField(),
|
||||
"llmindex_last_modified": serializers.DateTimeField(
|
||||
allow_null=True,
|
||||
),
|
||||
"llmindex_error": serializers.CharField(allow_null=True),
|
||||
"summary": inline_serializer(
|
||||
name="TasksSummaryOverview",
|
||||
fields={
|
||||
@@ -5527,30 +5667,6 @@ class CustomFieldViewSet(PermissionsAwareDocumentCountMixin, ModelViewSet[Custom
|
||||
),
|
||||
},
|
||||
),
|
||||
"index": inline_serializer(
|
||||
name="Index",
|
||||
fields={
|
||||
"status": serializers.CharField(),
|
||||
"error": serializers.CharField(),
|
||||
"last_modified": serializers.DateTimeField(),
|
||||
},
|
||||
),
|
||||
"classifier": inline_serializer(
|
||||
name="Classifier",
|
||||
fields={
|
||||
"status": serializers.CharField(),
|
||||
"error": serializers.CharField(),
|
||||
"last_trained": serializers.DateTimeField(),
|
||||
},
|
||||
),
|
||||
"sanity_check": inline_serializer(
|
||||
name="SanityCheck",
|
||||
fields={
|
||||
"status": serializers.CharField(),
|
||||
"error": serializers.CharField(),
|
||||
"last_run": serializers.DateTimeField(),
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
},
|
||||
@@ -5833,6 +5949,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
|
||||
@@ -5981,6 +6117,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"],
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
from rest_framework.exceptions import ParseError
|
||||
from rest_framework.parsers import JSONParser
|
||||
|
||||
|
||||
class ObjectJSONParser(JSONParser):
|
||||
"""
|
||||
DRF accepts any JSON document as a request body. The views and serializers here
|
||||
read the body as a mapping, so a top level list or scalar (or null) would end in
|
||||
a server error. Reject it as the malformed request it is.
|
||||
"""
|
||||
|
||||
def parse(self, stream, media_type=None, parser_context=None):
|
||||
data = super().parse(stream, media_type, parser_context)
|
||||
if not isinstance(data, dict):
|
||||
raise ParseError("The request body must be a JSON object.")
|
||||
return data
|
||||
+1
-23
@@ -1,7 +1,6 @@
|
||||
import os
|
||||
|
||||
from celery import Celery
|
||||
from celery.contrib.django.task import DjangoTask
|
||||
from celery.signals import worker_process_init
|
||||
from kombu.serialization import register
|
||||
|
||||
@@ -27,28 +26,7 @@ register(
|
||||
content_encoding="binary",
|
||||
)
|
||||
|
||||
|
||||
class FileMoveScopedTask(DjangoTask):
|
||||
"""
|
||||
Run every task inside a document file move scope, so each document a task
|
||||
changes is moved once when the task ends, after its writes have committed.
|
||||
The scope also flushes when the task raises, for writes that committed
|
||||
before the failure.
|
||||
|
||||
Subclasses DjangoTask because a custom task_cls replaces the Django fixup's
|
||||
default, and delay_on_commit lives there.
|
||||
"""
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
# Function-local: this module is imported by paperless/__init__.py
|
||||
# before Django apps are loaded.
|
||||
from documents.file_moves import defer_file_moves
|
||||
|
||||
with defer_file_moves():
|
||||
return super().__call__(*args, **kwargs)
|
||||
|
||||
|
||||
app = Celery("paperless", task_cls=FileMoveScopedTask)
|
||||
app = Celery("paperless")
|
||||
|
||||
# Using a string here means the worker doesn't have to serialize
|
||||
# the configuration object to child processes.
|
||||
|
||||
@@ -20,4 +20,6 @@ class ObfuscatedPasswordField(serializers.CharField):
|
||||
return OBFUSCATED_PASSWORD_MASK
|
||||
|
||||
def to_internal_value(self, data):
|
||||
if not isinstance(data, str):
|
||||
self.fail("invalid")
|
||||
return data
|
||||
@@ -1,5 +1,3 @@
|
||||
from asgiref.sync import iscoroutinefunction
|
||||
from asgiref.sync import markcoroutinefunction
|
||||
from compression_middleware.middleware import CompressionMiddleware
|
||||
from django.conf import settings
|
||||
|
||||
@@ -32,35 +30,3 @@ class ApiVersionMiddleware:
|
||||
response["X-Version"] = version.__full_version_str__
|
||||
|
||||
return response
|
||||
|
||||
|
||||
class FileMoveMiddleware:
|
||||
"""
|
||||
Open a document file move scope around each request, so every document the
|
||||
request changes is moved once, after its writes have committed, before the
|
||||
response is returned.
|
||||
"""
|
||||
|
||||
sync_capable = True
|
||||
async_capable = True
|
||||
|
||||
def __init__(self, get_response) -> None:
|
||||
self.get_response = get_response
|
||||
self.async_mode = iscoroutinefunction(get_response)
|
||||
if self.async_mode:
|
||||
markcoroutinefunction(self)
|
||||
|
||||
def __call__(self, request):
|
||||
if self.async_mode:
|
||||
return self.__acall__(request)
|
||||
|
||||
from documents.file_moves import defer_file_moves
|
||||
|
||||
with defer_file_moves():
|
||||
return self.get_response(request)
|
||||
|
||||
async def __acall__(self, request):
|
||||
from documents.file_moves import adefer_file_moves
|
||||
|
||||
async with adefer_file_moves():
|
||||
return await self.get_response(request)
|
||||
@@ -15,6 +15,7 @@ from django.contrib.auth.models import User
|
||||
from django.contrib.auth.password_validation import validate_password
|
||||
from django.core.files.uploadedfile import InMemoryUploadedFile
|
||||
from django.core.files.uploadedfile import UploadedFile
|
||||
from django.http import QueryDict
|
||||
from PIL import Image
|
||||
from rest_framework import serializers
|
||||
from rest_framework.authtoken.serializers import AuthTokenSerializer
|
||||
@@ -77,9 +78,21 @@ class PaperlessAuthTokenSerializer(AuthTokenSerializer):
|
||||
return attrs
|
||||
|
||||
|
||||
class CodenameRelatedField(serializers.SlugRelatedField):
|
||||
"""
|
||||
Looks a permission up by its codename. A codename with a null byte cannot exist, and
|
||||
Postgres raises an error, instead of finding nothing, if asked for one.
|
||||
"""
|
||||
|
||||
def to_internal_value(self, data):
|
||||
if isinstance(data, str) and "\x00" in data:
|
||||
self.fail("does_not_exist", slug_name=self.slug_field, value=repr(data))
|
||||
return super().to_internal_value(data)
|
||||
|
||||
|
||||
class UserSerializer(PasswordValidationMixin, serializers.ModelSerializer[User]):
|
||||
password = ObfuscatedPasswordField(required=False)
|
||||
user_permissions = serializers.SlugRelatedField(
|
||||
user_permissions = CodenameRelatedField(
|
||||
many=True,
|
||||
queryset=Permission.objects.exclude(content_type__app_label="admin"),
|
||||
slug_field="codename",
|
||||
@@ -146,7 +159,7 @@ class UserSerializer(PasswordValidationMixin, serializers.ModelSerializer[User])
|
||||
|
||||
|
||||
class GroupSerializer(serializers.ModelSerializer[Group]):
|
||||
permissions = serializers.SlugRelatedField(
|
||||
permissions = CodenameRelatedField(
|
||||
many=True,
|
||||
queryset=Permission.objects.exclude(content_type__app_label="admin"),
|
||||
slug_field="codename",
|
||||
@@ -272,6 +285,9 @@ class ApplicationConfigurationSerializer(
|
||||
return value
|
||||
|
||||
def run_validation(self, data):
|
||||
# A form encoded body arrives as an immutable QueryDict
|
||||
if isinstance(data, QueryDict) and not data._mutable:
|
||||
data = data.copy()
|
||||
# Empty strings treated as None to avoid unexpected behavior
|
||||
if "user_args" in data and data["user_args"] == "":
|
||||
data["user_args"] = None
|
||||
@@ -282,7 +298,8 @@ class ApplicationConfigurationSerializer(
|
||||
if "llm_output_language" in data and data["llm_output_language"] == "":
|
||||
data["llm_output_language"] = None
|
||||
for field in self.OBFUSCATED_FIELDS:
|
||||
if field in data and data[field] is not None:
|
||||
# Anything that is not a string is left for the field to reject
|
||||
if field in data and isinstance(data[field], str):
|
||||
if data[field] == "":
|
||||
data[field] = None
|
||||
# Not a real value, don't overwrite the stored one
|
||||
@@ -365,3 +382,8 @@ class ApplicationConfigurationSerializer(
|
||||
class Meta:
|
||||
model = ApplicationConfiguration
|
||||
fields = "__all__"
|
||||
|
||||
|
||||
class TOTPActivationSerializer(serializers.Serializer[dict[str, str]]):
|
||||
secret = serializers.CharField()
|
||||
code = serializers.CharField()
|
||||
@@ -169,6 +169,11 @@ REST_FRAMEWORK = {
|
||||
"rest_framework.authentication.TokenAuthentication",
|
||||
"rest_framework.authentication.SessionAuthentication",
|
||||
],
|
||||
"DEFAULT_PARSER_CLASSES": [
|
||||
"paperless.api_parsers.ObjectJSONParser",
|
||||
"rest_framework.parsers.FormParser",
|
||||
"rest_framework.parsers.MultiPartParser",
|
||||
],
|
||||
"DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.AcceptHeaderVersioning",
|
||||
"DEFAULT_VERSION": "10", # match src-ui/src/environments/environment.prod.ts
|
||||
# Make sure these are ordered and that the most recent version appears
|
||||
@@ -188,7 +193,6 @@ if DEBUG:
|
||||
|
||||
MIDDLEWARE = [
|
||||
"django.middleware.security.SecurityMiddleware",
|
||||
"paperless.middleware.FileMoveMiddleware",
|
||||
"whitenoise.middleware.WhiteNoiseMiddleware",
|
||||
"django.contrib.sessions.middleware.SessionMiddleware",
|
||||
"corsheaders.middleware.CorsMiddleware",
|
||||
@@ -233,6 +237,11 @@ SPECTACULAR_SETTINGS = {
|
||||
"NoteFormatEnum": "documents.models.Note.Format",
|
||||
},
|
||||
"SCHEMA_PATH_PREFIX_INSERT": FORCE_SCRIPT_NAME or "",
|
||||
"POSTPROCESSING_HOOKS": [
|
||||
"drf_spectacular.hooks.postprocess_schema_enums",
|
||||
"documents.schema.add_common_error_responses",
|
||||
"documents.schema.make_conditional_fields_optional",
|
||||
],
|
||||
}
|
||||
|
||||
WSGI_APPLICATION = "paperless.wsgi.application"
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from pytest_django.fixtures import DjangoAssertNumQueries
|
||||
from pytest_django.fixtures import Settings
|
||||
from rest_framework import status
|
||||
from rest_framework.exceptions import ValidationError
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
from paperless.serialisers import GroupSerializer
|
||||
from paperless.serialisers import UserSerializer
|
||||
|
||||
|
||||
class TestNullByteInput:
|
||||
@pytest.mark.parametrize("db_only", ["true", "false"])
|
||||
def test_global_search_rejects_null_byte(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
db_only: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- An authenticated client
|
||||
WHEN:
|
||||
- The global search query contains a null byte
|
||||
THEN:
|
||||
- The response is a 400, the query never reaches the database
|
||||
"""
|
||||
response = admin_client.get(
|
||||
"/api/search/",
|
||||
{"query": "invoice\x00number", "db_only": db_only},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("serializer", "field"),
|
||||
[
|
||||
pytest.param(GroupSerializer, "permissions", id="group"),
|
||||
pytest.param(UserSerializer, "user_permissions", id="user"),
|
||||
],
|
||||
)
|
||||
def test_codename_with_null_byte_is_rejected_without_a_query(
|
||||
self,
|
||||
db: None,
|
||||
django_assert_num_queries: DjangoAssertNumQueries,
|
||||
serializer: type,
|
||||
field: str,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A permission codename field
|
||||
WHEN:
|
||||
- A value containing a null byte is validated
|
||||
THEN:
|
||||
- It is rejected without querying, Postgres raises an error for it
|
||||
where SQLite does not
|
||||
"""
|
||||
codename_field = serializer().fields[field].child_relation
|
||||
|
||||
with django_assert_num_queries(0), pytest.raises(ValidationError):
|
||||
codename_field.to_internal_value("view_document\x00")
|
||||
|
||||
|
||||
class TestLogLimit:
|
||||
def test_limit_larger_than_any_file_returns_everything(
|
||||
self,
|
||||
admin_client: APIClient,
|
||||
settings: Settings,
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
"""
|
||||
GIVEN:
|
||||
- A log file
|
||||
WHEN:
|
||||
- The limit is larger than a platform integer can hold
|
||||
THEN:
|
||||
- The whole file is returned, as for any limit above its length
|
||||
"""
|
||||
settings.LOGGING_DIR = tmp_path
|
||||
(tmp_path / "paperless.log").write_text("one\ntwo\nthree\n")
|
||||
|
||||
response = admin_client.get("/api/logs/paperless/", {"limit": 2**70})
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
assert response.data == ["one", "two", "three"]
|
||||
|
||||
|
||||
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,
|
||||
) -> 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
|
||||
@@ -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")
|
||||
@@ -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"),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
+65
-9
@@ -24,17 +24,22 @@ 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
|
||||
from rest_framework.generics import GenericAPIView
|
||||
from rest_framework.generics import get_object_or_404
|
||||
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 +54,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
|
||||
|
||||
|
||||
@@ -206,17 +212,23 @@ class UserViewSet(ModelViewSet[User]):
|
||||
request=None,
|
||||
responses={
|
||||
200: OpenApiTypes.BOOL,
|
||||
404: OpenApiTypes.STR,
|
||||
(404, "text/html"): OpenApiTypes.STR,
|
||||
},
|
||||
)
|
||||
@action(detail=True, methods=["post"])
|
||||
def deactivate_totp(self, request, pk=None):
|
||||
request_user = request.user
|
||||
user = User.objects.get(pk=pk)
|
||||
if not request_user.is_superuser and request_user != user:
|
||||
# Decide on permission before looking the user up, so the response does not
|
||||
# reveal whether another user's id exists
|
||||
try:
|
||||
is_self = int(pk) == request_user.pk
|
||||
except (TypeError, ValueError):
|
||||
is_self = False
|
||||
if not request_user.is_superuser and not is_self:
|
||||
return HttpResponseForbidden(
|
||||
"You do not have permission to deactivate TOTP for this user",
|
||||
)
|
||||
user = get_object_or_404(User, pk=pk)
|
||||
authenticator = Authenticator.objects.filter(
|
||||
user=user,
|
||||
type=Authenticator.Type.TOTP,
|
||||
@@ -274,8 +286,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 +310,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 +336,7 @@ class TOTPView(GenericAPIView[Any]):
|
||||
"""
|
||||
|
||||
permission_classes = [IsAuthenticated]
|
||||
serializer_class = TOTPActivationSerializer
|
||||
|
||||
def get(self, request, *args, **kwargs):
|
||||
"""
|
||||
@@ -328,15 +359,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 +557,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 +598,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
|
||||
@@ -2,6 +2,8 @@ from django.utils.translation import gettext as _
|
||||
from rest_framework import serializers
|
||||
from rest_framework.exceptions import PermissionDenied
|
||||
|
||||
from documents.filters import INT16_MAX
|
||||
from documents.filters import INT16_MIN
|
||||
from documents.permissions import has_perms_owner_aware
|
||||
from documents.permissions import restrict_queryset_to_visible
|
||||
from documents.serialisers import CorrespondentField
|
||||
@@ -17,7 +19,12 @@ from paperless_mail.models import ProcessedMail
|
||||
|
||||
class MailAccountSerializer(OwnedObjectSerializer):
|
||||
password = ObfuscatedPasswordField()
|
||||
imap_port = serializers.IntegerField(required=True, allow_null=False)
|
||||
imap_port = serializers.IntegerField(
|
||||
required=True,
|
||||
allow_null=False,
|
||||
min_value=1,
|
||||
max_value=65535,
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = MailAccount
|
||||
@@ -39,6 +46,21 @@ class MailAccountSerializer(OwnedObjectSerializer):
|
||||
"expiration",
|
||||
]
|
||||
|
||||
def validate(self, attrs):
|
||||
attrs = super().validate(attrs)
|
||||
# On an update the other half of the pair is the stored one
|
||||
security = attrs.get(
|
||||
"imap_security",
|
||||
getattr(self.instance, "imap_security", None),
|
||||
)
|
||||
port = attrs.get("imap_port", getattr(self.instance, "imap_port", None))
|
||||
if security == MailAccount.ImapSecurity.STARTTLS and port == 993:
|
||||
# Connecting would fail every time, port 993 speaks SSL from the start
|
||||
raise serializers.ValidationError(
|
||||
{"imap_port": "Port 993 requires SSL, it cannot be used with STARTTLS"},
|
||||
)
|
||||
return attrs
|
||||
|
||||
def update(self, instance, validated_data):
|
||||
if "password" in validated_data and is_obfuscated_password(
|
||||
validated_data["password"],
|
||||
@@ -70,11 +92,16 @@ class MailRuleSerializer(OwnedObjectSerializer):
|
||||
allow_null=True,
|
||||
required=False,
|
||||
default="",
|
||||
max_length=256,
|
||||
)
|
||||
assign_correspondent = CorrespondentField(allow_null=True, required=False)
|
||||
assign_tags = TagsField(many=True, allow_null=True, required=False)
|
||||
assign_document_type = DocumentTypeField(allow_null=True, required=False)
|
||||
order = serializers.IntegerField(required=False)
|
||||
order = serializers.IntegerField(
|
||||
required=False,
|
||||
min_value=INT16_MIN,
|
||||
max_value=INT16_MAX,
|
||||
)
|
||||
|
||||
class Meta:
|
||||
model = MailRule
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import datetime
|
||||
import imaplib
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
@@ -10,6 +11,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
|
||||
@@ -65,7 +67,7 @@ class DeleteProcessedMailPermissions(BasePermission):
|
||||
name="MailAccountTestResponse",
|
||||
fields={"success": serializers.BooleanField()},
|
||||
),
|
||||
400: OpenApiTypes.STR,
|
||||
(400, "text/html"): OpenApiTypes.STR,
|
||||
},
|
||||
),
|
||||
process=extend_schema(
|
||||
@@ -98,8 +100,11 @@ class MailAccountViewSet(PassUserMixin, ModelViewSet[MailAccount]):
|
||||
@action(methods=["post"], detail=False)
|
||||
def test(self, request):
|
||||
logger = logging.getLogger("paperless_mail")
|
||||
request.data["name"] = datetime.datetime.now().isoformat()
|
||||
serializer = self.get_serializer(data=request.data)
|
||||
# request.data is read only for a form encoded body, and QueryDict.copy would
|
||||
# deep copy any uploaded file, so build a plain dict
|
||||
data = dict(request.data.items())
|
||||
data["name"] = datetime.datetime.now().isoformat()
|
||||
serializer = self.get_serializer(data=data)
|
||||
serializer.is_valid(raise_exception=True)
|
||||
existing_account = None
|
||||
account_id = request.data.get("id")
|
||||
@@ -135,7 +140,15 @@ class MailAccountViewSet(PassUserMixin, ModelViewSet[MailAccount]):
|
||||
serializer.validated_data["refresh_token"] = existing_account.refresh_token
|
||||
serializer.validated_data["expiration"] = existing_account.expiration
|
||||
|
||||
account = MailAccount(**serializer.validated_data)
|
||||
# The serializer also carries write only fields that are not model fields
|
||||
model_fields = {field.name for field in MailAccount._meta.concrete_fields}
|
||||
account = MailAccount(
|
||||
**{
|
||||
key: value
|
||||
for key, value in serializer.validated_data.items()
|
||||
if key in model_fields
|
||||
},
|
||||
)
|
||||
try:
|
||||
with get_mailbox(
|
||||
account.imap_server,
|
||||
@@ -161,9 +174,11 @@ class MailAccountViewSet(PassUserMixin, ModelViewSet[MailAccount]):
|
||||
|
||||
mailbox_login(M, account)
|
||||
return Response({"success": True})
|
||||
except MailError:
|
||||
except (MailError, OSError, imaplib.IMAP4.error, UnicodeError) as exc:
|
||||
# A refused connection, an unknown host, a timeout, a TLS failure or a bad
|
||||
# host name is exactly what this endpoint exists to report
|
||||
logger.error(
|
||||
"Mail account connectivity test failed",
|
||||
f"Mail account connectivity test failed: {type(exc).__name__}: {exc}",
|
||||
)
|
||||
return HttpResponseBadRequest("Unable to connect to server")
|
||||
|
||||
@@ -254,8 +269,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]):
|
||||
|
||||
@@ -9,7 +9,6 @@ from django.contrib.auth.models import User
|
||||
|
||||
from documents.models import Correspondent
|
||||
from documents.models import CustomField
|
||||
from documents.models import CustomFieldInstance
|
||||
from documents.models import Document
|
||||
from documents.models import DocumentBarcode
|
||||
from documents.models import DocumentType
|
||||
@@ -82,14 +81,6 @@ class DocumentFactory(TypedModelFactory[Document]):
|
||||
storage_path = None
|
||||
|
||||
|
||||
class CustomFieldInstanceFactory(TypedModelFactory[CustomFieldInstance]):
|
||||
class Meta:
|
||||
model = CustomFieldInstance
|
||||
|
||||
field = factory.SubFactory(CustomFieldFactory)
|
||||
document = factory.SubFactory(DocumentFactory)
|
||||
|
||||
|
||||
class DocumentBarcodeFactory(TypedModelFactory[DocumentBarcode]):
|
||||
class Meta:
|
||||
model = DocumentBarcode
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from django.http import HttpResponse
|
||||
from django.http import StreamingHttpResponse
|
||||
from rest_framework.test import APIClient
|
||||
|
||||
|
||||
def read_streaming_response(response: StreamingHttpResponse) -> bytes:
|
||||
@@ -11,3 +14,13 @@ def read_streaming_response(response: StreamingHttpResponse) -> bytes:
|
||||
content = b"".join(response.streaming_content)
|
||||
response.close()
|
||||
return content
|
||||
|
||||
|
||||
def send_json(client: APIClient, method: str, path: str, body: object) -> HttpResponse:
|
||||
"""Send a request with a JSON body, any method, whatever the body is."""
|
||||
return client.generic(
|
||||
method,
|
||||
path,
|
||||
data=json.dumps(body),
|
||||
content_type="application/json",
|
||||
)
|
||||
@@ -1,47 +0,0 @@
|
||||
"""Record first acquisitions of the global media lock during a test."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest import mock
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import Iterator
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class MediaLockAcquisition:
|
||||
"""One first (non-reentrant) acquisition of settings.MEDIA_LOCK."""
|
||||
|
||||
in_user_transaction: bool
|
||||
|
||||
|
||||
@contextmanager
|
||||
def record_media_lock_acquisitions() -> Iterator[list[MediaLockAcquisition]]:
|
||||
"""
|
||||
Record every first acquisition of settings.MEDIA_LOCK made in the block.
|
||||
|
||||
Reentrant acquisitions by a thread that already holds the lock never wait,
|
||||
so they are not recorded. Each record notes whether a real (non test case)
|
||||
transaction was open at that moment, which is the lock ordering hazard.
|
||||
"""
|
||||
from django.conf import settings
|
||||
from filelock import BaseFileLock
|
||||
|
||||
from documents.file_moves import in_user_transaction
|
||||
|
||||
records: list[MediaLockAcquisition] = []
|
||||
original_acquire = BaseFileLock.acquire
|
||||
|
||||
def recording_acquire(self: BaseFileLock, *args: object, **kwargs: object):
|
||||
if Path(self.lock_file) == Path(settings.MEDIA_LOCK) and not self.is_locked:
|
||||
records.append(
|
||||
MediaLockAcquisition(in_user_transaction=in_user_transaction()),
|
||||
)
|
||||
return original_acquire(self, *args, **kwargs)
|
||||
|
||||
with mock.patch.object(BaseFileLock, "acquire", recording_acquire):
|
||||
yield records
|
||||
Reference in new issue
Block a user