Compare commits

..
Author SHA1 Message Date
Trenton H afbdd07145 Fix: queue one consumption chord per mail so it produces a single ProcessedMail row
With the "everything" consumption scope the eml and the attachments were each queued
as their own chord, so each ran its own mail action and wrote its own ProcessedMail row.
A mail without attachments also got an early PROCESSED_WO_CONSUMPTION row alongside the
eml's SUCCESS row.

Build the eml and attachment tasks separately, then queue them together once per message.
2026-11-28 15:04:48 -08:00
Trenton H 9a2a50d23f Chore: share HMAC-signed pickle handling between classifier and celery (#14896) 2026-11-28 18:32:49 +00:00
Trenton H d4617d8177 Fix: correct OCR to dateparser language map entries (#14894)
* Fix: correct OCR to dateparser language map entries

* Fix: resolve language map TODO and map Norwegian
2026-11-28 16:29:38 +00:00
Trenton H 155a118f0d Fix: use a temporary directory for share link bundle zips so scratch files are not leaked (#14892) 2026-11-28 15:37:01 +00:00
Trenton H bc9d45cecc Fix: close the PDF after reading its XMP metadata (#14891) 2026-11-28 02:38:23 +00:00
Trenton H 1655a844e3 Chore: declare directly imported dependencies that were only transitive (#14897) 2026-11-28 02:21:27 +00:00
GitHub Actions 26599c3c25 Auto translate strings 2026-11-27 04:57:14 +00:00
shamoon b6247d0602 Enhancement: updated private tags UX (#14870) 2026-11-27 04:55:27 +00:00
Trenton H e116b3e7ac Chore: compare export JSON files in chunks instead of reading them into memory (#14884) 2026-11-26 19:15:59 -08:00
GitHub Actions a21c5086ab Auto translate strings 2026-11-27 02:54:58 +00:00
Trenton H 89f0037362 Feature: add PAPERLESS_COOKIE_SECURE to mark session, CSRF and language cookies Secure (#14886) 2026-11-26 18:53:45 -08:00
Trenton H 2b8697e850 Fix: close the output PDF even if building it fails (#14887) 2026-11-26 18:42:43 -08:00
Trenton H 33fb750529 Fix: close the uploaded logo image with a context manager when sanitizing (#14888) 2026-11-26 18:31:35 -08:00
Trenton H 0a8de70c26 Fix: detect Redis socket URLs by scheme instead of substring (#14885) 2026-11-26 17:32:33 -08:00
GitHub Actions 2f21aa80a6 Auto translate strings 2026-11-27 00:52:49 +00:00
Trenton H 8008646ae6 Fix: make URI validator error messages translatable (#14883) 2026-11-26 16:51:32 -08:00
Trenton H 748470d47c Chore: align ruff version between uv and pre-commit (#14881) 2026-11-27 00:08:35 +00:00
Trenton H b471679469 Chore: copy PDFs on disk instead of reading them into memory (#14882) 2026-11-26 23:24:20 +00:00
77 changed files with 1415 additions and 3453 deletions

No files matched your search

-1
View File
@@ -87,7 +87,6 @@ src/documents/classifier.py:0: error: Incompatible types in assignment (expressi
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment] src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment] src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "None", variable has type "DocumentClassifier") [assignment]
src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "str", variable has type "None") [assignment] src/documents/classifier.py:0: error: Incompatible types in assignment (expression has type "str", variable has type "None") [assignment]
src/documents/classifier.py:0: error: Item "None" of "str | None" has no attribute "encode" [union-attr]
src/documents/classifier.py:0: error: List comprehension has incompatible type List[int]; expected List[list[int]] [misc] src/documents/classifier.py:0: error: List comprehension has incompatible type List[int]; expected List[list[int]] [misc]
src/documents/classifier.py:0: error: Module "sklearn.exceptions" has no attribute "InconsistentVersionWarning" [attr-defined] src/documents/classifier.py:0: error: Module "sklearn.exceptions" has no attribute "InconsistentVersionWarning" [attr-defined]
src/documents/classifier.py:0: error: Unsupported operand types for >= ("datetime" and "None") [operator] src/documents/classifier.py:0: error: Unsupported operand types for >= ("datetime" and "None") [operator]
+1 -1
View File
@@ -50,7 +50,7 @@ repos:
- 'prettier-plugin-organize-imports@4.3.0' - 'prettier-plugin-organize-imports@4.3.0'
# Python hooks # Python hooks
- repo: https://github.com/astral-sh/ruff-pre-commit - repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.17.2 rev: v0.17.6
hooks: hooks:
- id: ruff-check - id: ruff-check
- id: ruff-format - id: ruff-format
+14
View File
@@ -641,6 +641,20 @@ you're running two instances of paperless on the same host.
Defaults to `""`, which does not alter the cookie names. Defaults to `""`, which does not alter the cookie names.
#### [`PAPERLESS_COOKIE_SECURE=<bool>`](#PAPERLESS_COOKIE_SECURE) {#PAPERLESS_COOKIE_SECURE}
: Marks the session, CSRF and language cookies with the `Secure` attribute, so browsers only send them over HTTPS. This sets the Django settings [`SESSION_COOKIE_SECURE`](https://docs.djangoproject.com/en/stable/ref/settings/#session-cookie-secure), [`CSRF_COOKIE_SECURE`](https://docs.djangoproject.com/en/stable/ref/settings/#csrf-cookie-secure) and [`LANGUAGE_COOKIE_SECURE`](https://docs.djangoproject.com/en/stable/ref/settings/#language-cookie-secure) together.
Enable this if you access paperless exclusively over HTTPS, for example behind a reverse proxy which terminates TLS.
!!! warning
Browsers will not send `Secure` cookies over plain HTTP, so logging in over HTTP, for example directly via a LAN address which bypasses the reverse proxy, will fail. Some browsers make an exception for `localhost`.
After changing this, you may have to login again.
Defaults to `false`.
#### [`PAPERLESS_ENABLE_HTTP_REMOTE_USER=<bool>`](#PAPERLESS_ENABLE_HTTP_REMOTE_USER) {#PAPERLESS_ENABLE_HTTP_REMOTE_USER} #### [`PAPERLESS_ENABLE_HTTP_REMOTE_USER=<bool>`](#PAPERLESS_ENABLE_HTTP_REMOTE_USER) {#PAPERLESS_ENABLE_HTTP_REMOTE_USER}
: Allows authentication via HTTP_REMOTE_USER which is used by some SSO : Allows authentication via HTTP_REMOTE_USER which is used by some SSO
+6 -1
View File
@@ -23,6 +23,7 @@ dependencies = [
"channels~=4.2", "channels~=4.2",
"channels-redis~=4.2", "channels-redis~=4.2",
"concurrent-log-handler~=0.9.25", "concurrent-log-handler~=0.9.25",
"cryptography>=50",
"dateparser~=1.4", "dateparser~=1.4",
# WARNING: django does not use semver. # WARNING: django does not use semver.
# Only patch versions are guaranteed to not introduce breaking changes. # Only patch versions are guaranteed to not introduce breaking changes.
@@ -46,6 +47,7 @@ dependencies = [
"flower>=2.0.1,<2.3", "flower>=2.0.1,<2.3",
"gotenberg-client[httpx]~=1.0", "gotenberg-client[httpx]~=1.0",
"httpx-oauth~=0.17", "httpx-oauth~=0.17",
"humanize>=4.15",
"ijson>=3.5.1", "ijson>=3.5.1",
"imap-tools>=1.14,<1.16", "imap-tools>=1.14,<1.16",
"jinja2~=3.1.6", "jinja2~=3.1.6",
@@ -56,10 +58,13 @@ dependencies = [
"llama-index-embeddings-openai-like>=0.2.2", "llama-index-embeddings-openai-like>=0.2.2",
"llama-index-llms-ollama>=0.9.1", "llama-index-llms-ollama>=0.9.1",
"llama-index-llms-openai-like>=0.7.1", "llama-index-llms-openai-like>=0.7.1",
"lxml>=6.1",
"ocrmypdf[heic]>=17.12,<17.13", "ocrmypdf[heic]>=17.12,<17.13",
"ollama>=0.6.1",
"openai>=2.48", "openai>=2.48",
"pathvalidate~=3.3.1", "pathvalidate~=3.3.1",
"pdf2image~=1.17.0", "pdf2image~=1.17.0",
"pikepdf>=10.13",
"python-dateutil~=2.9.0", "python-dateutil~=2.9.0",
"python-dotenv~=1.2.1", "python-dotenv~=1.2.1",
"python-gnupg~=0.5.4", "python-gnupg~=0.5.4",
@@ -106,7 +111,7 @@ docs = [
] ]
lint = [ lint = [
"prek>=0.4.11,<0.6", "prek>=0.4.11,<0.6",
"ruff~=0.16.1", "ruff~=0.17.2",
] ]
testing = [ testing = [
"daphne", "daphne",
+102 -56
View File
@@ -332,7 +332,7 @@
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context>
<context context-type="linenumber">216</context> <context context-type="linenumber">218</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/manage/document-attributes/custom-fields/custom-fields.component.html</context> <context context-type="sourcefile">src/app/components/manage/document-attributes/custom-fields/custom-fields.component.html</context>
@@ -1841,7 +1841,7 @@
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/input/tags/tags.component.ts</context> <context context-type="sourcefile">src/app/components/common/input/tags/tags.component.ts</context>
<context context-type="linenumber">93</context> <context context-type="linenumber">94</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/suggestions-dropdown/suggestions-dropdown.component.html</context> <context context-type="sourcefile">src/app/components/common/suggestions-dropdown/suggestions-dropdown.component.html</context>
@@ -2630,11 +2630,11 @@
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">76,77</context> <context context-type="linenumber">80,81</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">148</context> <context context-type="linenumber">153</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="3278307631146748151" datatype="html"> <trans-unit id="3278307631146748151" datatype="html">
@@ -3997,7 +3997,7 @@
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context> <context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context>
<context context-type="linenumber">125</context> <context context-type="linenumber">129</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-detail/document-detail.component.html</context> <context context-type="sourcefile">src/app/components/document-detail/document-detail.component.html</context>
@@ -4017,11 +4017,11 @@
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">82,83</context> <context context-type="linenumber">86,87</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">154</context> <context context-type="linenumber">159</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/data/saved-view-icons.ts</context> <context context-type="sourcefile">src/app/data/saved-view-icons.ts</context>
@@ -4308,11 +4308,11 @@
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context> <context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context>
<context context-type="linenumber">105</context> <context context-type="linenumber">109</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.html</context>
<context context-type="linenumber">391</context> <context context-type="linenumber">395</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="7515883357904500238" datatype="html"> <trans-unit id="7515883357904500238" datatype="html">
@@ -4617,7 +4617,7 @@
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">79,80</context> <context context-type="linenumber">83,84</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="3188389494264426470" datatype="html"> <trans-unit id="3188389494264426470" datatype="html">
@@ -6084,7 +6084,7 @@
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/input/tags/tags.component.html</context> <context context-type="sourcefile">src/app/components/common/input/tags/tags.component.html</context>
<context context-type="linenumber">56</context> <context context-type="linenumber">65</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="5872175735754226507" datatype="html"> <trans-unit id="5872175735754226507" datatype="html">
@@ -7176,6 +7176,20 @@
<context context-type="linenumber">874</context> <context context-type="linenumber">874</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="7016632905329233281" datatype="html">
<source>Tags you don&apos;t have access to</source>
<context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/hidden-tags-badge/hidden-tags-badge.component.html</context>
<context context-type="linenumber">1</context>
</context-group>
</trans-unit>
<trans-unit id="8380614898235701745" datatype="html">
<source><x id="INTERPOLATION" equiv-text="{{count()}}"/> hidden</source>
<context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/hidden-tags-badge/hidden-tags-badge.component.html</context>
<context context-type="linenumber">3,4</context>
</context-group>
</trans-unit>
<trans-unit id="7005745151564974365" datatype="html"> <trans-unit id="7005745151564974365" datatype="html">
<source>Keyboard shortcuts</source> <source>Keyboard shortcuts</source>
<context-group purpose="location"> <context-group purpose="location">
@@ -7221,6 +7235,10 @@
<context context-type="sourcefile">src/app/components/common/input/switch/switch.component.html</context> <context context-type="sourcefile">src/app/components/common/input/switch/switch.component.html</context>
<context context-type="linenumber">13</context> <context context-type="linenumber">13</context>
</context-group> </context-group>
<context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/input/tags/tags.component.ts</context>
<context context-type="linenumber">248</context>
</context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/input/text/text.component.html</context> <context context-type="sourcefile">src/app/components/common/input/text/text.component.html</context>
<context context-type="linenumber">9</context> <context context-type="linenumber">9</context>
@@ -7278,7 +7296,7 @@
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/input/tags/tags.component.html</context> <context context-type="sourcefile">src/app/components/common/input/tags/tags.component.html</context>
<context context-type="linenumber">71</context> <context context-type="linenumber">80</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="6344437738844463465" datatype="html"> <trans-unit id="6344437738844463465" datatype="html">
@@ -7440,11 +7458,18 @@
<context context-type="linenumber">5</context> <context context-type="linenumber">5</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="6626732174656850237" datatype="html">
<source>Remove tags you don&apos;t have access to</source>
<context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/input/tags/tags.component.html</context>
<context context-type="linenumber">29</context>
</context-group>
</trans-unit>
<trans-unit id="3392754525167799121" datatype="html"> <trans-unit id="3392754525167799121" datatype="html">
<source>Remove tag</source> <source>Remove tag</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/input/tags/tags.component.html</context> <context context-type="sourcefile">src/app/components/common/input/tags/tags.component.html</context>
<context context-type="linenumber">28</context> <context context-type="linenumber">37</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/utils/document-operation.ts</context> <context context-type="sourcefile">src/app/utils/document-operation.ts</context>
@@ -7455,7 +7480,28 @@
<source>Filter documents with these Tags</source> <source>Filter documents with these Tags</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/input/tags/tags.component.html</context> <context context-type="sourcefile">src/app/components/common/input/tags/tags.component.html</context>
<context context-type="linenumber">61,62</context> <context context-type="linenumber">70,71</context>
</context-group>
</trans-unit>
<trans-unit id="662220925494348602" datatype="html">
<source>Remove hidden tags</source>
<context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/input/tags/tags.component.ts</context>
<context context-type="linenumber">244</context>
</context-group>
</trans-unit>
<trans-unit id="4678840195328848571" datatype="html">
<source>Remove <x id="PH" equiv-text="hidden.size"/> tag(s) you don&apos;t have access to?</source>
<context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/input/tags/tags.component.ts</context>
<context context-type="linenumber">245</context>
</context-group>
</trans-unit>
<trans-unit id="636150860182684346" datatype="html">
<source>You will not be able to add them back.</source>
<context-group purpose="location">
<context context-type="sourcefile">src/app/components/common/input/tags/tags.component.ts</context>
<context context-type="linenumber">246</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="1400555558847223243" datatype="html"> <trans-unit id="1400555558847223243" datatype="html">
@@ -8855,55 +8901,55 @@
<source>Filter by document type</source> <source>Filter by document type</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context> <context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context>
<context context-type="linenumber">85</context> <context context-type="linenumber">89</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">100</context> <context context-type="linenumber">104</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.html</context>
<context context-type="linenumber">363</context> <context context-type="linenumber">367</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="157572966557284263" datatype="html"> <trans-unit id="157572966557284263" datatype="html">
<source>Filter by storage path</source> <source>Filter by storage path</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context> <context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context>
<context context-type="linenumber">90</context> <context context-type="linenumber">94</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">106</context> <context context-type="linenumber">110</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.html</context>
<context context-type="linenumber">370</context> <context context-type="linenumber">374</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="883965278435032344" datatype="html"> <trans-unit id="883965278435032344" datatype="html">
<source>Filter by owner</source> <source>Filter by owner</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context> <context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context>
<context context-type="linenumber">95</context> <context context-type="linenumber">99</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="3542042671420335679" datatype="html"> <trans-unit id="3542042671420335679" datatype="html">
<source>No</source> <source>No</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context> <context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context>
<context context-type="linenumber">105</context> <context context-type="linenumber">109</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.html</context>
<context context-type="linenumber">391</context> <context context-type="linenumber">395</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="872092479747931526" datatype="html"> <trans-unit id="872092479747931526" datatype="html">
<source>No documents</source> <source>No documents</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context> <context context-type="sourcefile">src/app/components/dashboard/widgets/saved-view-widget/saved-view-widget.component.html</context>
<context context-type="linenumber">191,194</context> <context context-type="linenumber">195,198</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="1069523139277190436" datatype="html"> <trans-unit id="1069523139277190436" datatype="html">
@@ -9145,7 +9191,7 @@
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">73,74</context> <context context-type="linenumber">77,78</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="1735242650910677773" datatype="html"> <trans-unit id="1735242650910677773" datatype="html">
@@ -10636,85 +10682,85 @@
<source>Filter by tag</source> <source>Filter by tag</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">40</context> <context context-type="linenumber">41</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.html</context>
<context context-type="linenumber">339</context> <context context-type="linenumber">340</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="106713086593101376" datatype="html"> <trans-unit id="106713086593101376" datatype="html">
<source>View notes</source> <source>View notes</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">95</context> <context context-type="linenumber">99</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="3727324658595204357" datatype="html"> <trans-unit id="3727324658595204357" datatype="html">
<source>Created: <x id="INTERPOLATION" equiv-text="{{ document().created | customDate }}"/></source> <source>Created: <x id="INTERPOLATION" equiv-text="{{ document().created | customDate }}"/></source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">119,120</context> <context context-type="linenumber">123,124</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">81,82</context> <context context-type="linenumber">86,87</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">96,97</context> <context context-type="linenumber">101,102</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="2030261243264601523" datatype="html"> <trans-unit id="2030261243264601523" datatype="html">
<source>Added: <x id="INTERPOLATION" equiv-text="{{ document().added | customDate }}"/></source> <source>Added: <x id="INTERPOLATION" equiv-text="{{ document().added | customDate }}"/></source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">120,121</context> <context context-type="linenumber">124,125</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">82,83</context> <context context-type="linenumber">87,88</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">97,98</context> <context context-type="linenumber">102,103</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="4235671847487610290" datatype="html"> <trans-unit id="4235671847487610290" datatype="html">
<source>Modified: <x id="INTERPOLATION" equiv-text="{{ document().modified | customDate }}"/></source> <source>Modified: <x id="INTERPOLATION" equiv-text="{{ document().modified | customDate }}"/></source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">121,122</context> <context context-type="linenumber">125,126</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">83,84</context> <context context-type="linenumber">88,89</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">98,99</context> <context context-type="linenumber">103,104</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="197162226430950645" datatype="html"> <trans-unit id="197162226430950645" datatype="html">
<source>{VAR_PLURAL, plural, =1 {1 page} other {<x id="INTERPOLATION"/> pages}}</source> <source>{VAR_PLURAL, plural, =1 {1 page} other {<x id="INTERPOLATION"/> pages}}</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">138</context> <context context-type="linenumber">142</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">111</context> <context context-type="linenumber">116</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="5739581984228459958" datatype="html"> <trans-unit id="5739581984228459958" datatype="html">
<source>Shared</source> <source>Shared</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">148,149</context> <context context-type="linenumber">152,153</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">130,131</context> <context context-type="linenumber">135,136</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/data/document.ts</context> <context context-type="sourcefile">src/app/data/document.ts</context>
@@ -10729,35 +10775,35 @@
<source>Score:</source> <source>Score:</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-large/document-card-large.component.html</context>
<context context-type="linenumber">153,154</context> <context context-type="linenumber">157,158</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="3661756380991326939" datatype="html"> <trans-unit id="3661756380991326939" datatype="html">
<source>Toggle tag filter</source> <source>Toggle tag filter</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">25</context> <context context-type="linenumber">27</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="4648526799630820486" datatype="html"> <trans-unit id="4648526799630820486" datatype="html">
<source>Toggle correspondent filter</source> <source>Toggle correspondent filter</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">48</context> <context context-type="linenumber">53</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="5319701482646590642" datatype="html"> <trans-unit id="5319701482646590642" datatype="html">
<source>Toggle document type filter</source> <source>Toggle document type filter</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">64</context> <context context-type="linenumber">69</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="8950368321707344185" datatype="html"> <trans-unit id="8950368321707344185" datatype="html">
<source>Toggle storage path filter</source> <source>Toggle storage path filter</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context> <context context-type="sourcefile">src/app/components/document-list/document-card-small/document-card-small.component.html</context>
<context context-type="linenumber">71</context> <context context-type="linenumber">76</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="3797570084942068182" datatype="html"> <trans-unit id="3797570084942068182" datatype="html">
@@ -10802,7 +10848,7 @@
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context>
<context context-type="linenumber">353</context> <context context-type="linenumber">355</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/manage/document-attributes/document-attributes.component.html</context> <context context-type="sourcefile">src/app/components/manage/document-attributes/document-attributes.component.html</context>
@@ -10817,7 +10863,7 @@
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context>
<context context-type="linenumber">346</context> <context context-type="linenumber">348</context>
</context-group> </context-group>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/manage/document-attributes/document-attributes.component.html</context> <context context-type="sourcefile">src/app/components/manage/document-attributes/document-attributes.component.html</context>
@@ -11081,56 +11127,56 @@
<source>Reset filters / selection</source> <source>Reset filters / selection</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context>
<context context-type="linenumber">334</context> <context context-type="linenumber">336</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="4135055128446167640" datatype="html"> <trans-unit id="4135055128446167640" datatype="html">
<source>Open first [selected] document</source> <source>Open first [selected] document</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context>
<context context-type="linenumber">362</context> <context context-type="linenumber">364</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="3629960544875360046" datatype="html"> <trans-unit id="3629960544875360046" datatype="html">
<source>Previous page</source> <source>Previous page</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context>
<context context-type="linenumber">378</context> <context context-type="linenumber">380</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="3337301694210287595" datatype="html"> <trans-unit id="3337301694210287595" datatype="html">
<source>Next page</source> <source>Next page</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context>
<context context-type="linenumber">390</context> <context context-type="linenumber">392</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="2155249406916744630" datatype="html"> <trans-unit id="2155249406916744630" datatype="html">
<source>View &quot;<x id="PH" equiv-text="view.name ?? title"/>&quot; saved successfully.</source> <source>View &quot;<x id="PH" equiv-text="view.name ?? title"/>&quot; saved successfully.</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context>
<context context-type="linenumber">425</context> <context context-type="linenumber">427</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="4646273665293421938" datatype="html"> <trans-unit id="4646273665293421938" datatype="html">
<source>Failed to save view &quot;<x id="PH" equiv-text="title"/>&quot;.</source> <source>Failed to save view &quot;<x id="PH" equiv-text="title"/>&quot;.</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context>
<context context-type="linenumber">431</context> <context context-type="linenumber">433</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="6837554170707123455" datatype="html"> <trans-unit id="6837554170707123455" datatype="html">
<source>View &quot;<x id="PH" equiv-text="savedView.name"/>&quot; created successfully.</source> <source>View &quot;<x id="PH" equiv-text="savedView.name"/>&quot; created successfully.</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context>
<context context-type="linenumber">500</context> <context context-type="linenumber">502</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="6028096992841030074" datatype="html"> <trans-unit id="6028096992841030074" datatype="html">
<source>View &quot;<x id="PH" equiv-text="savedView.name"/>&quot; created successfully, but could not update visibility settings.</source> <source>View &quot;<x id="PH" equiv-text="savedView.name"/>&quot; created successfully, but could not update visibility settings.</source>
<context-group purpose="location"> <context-group purpose="location">
<context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context> <context context-type="sourcefile">src/app/components/document-list/document-list.component.ts</context>
<context context-type="linenumber">506</context> <context context-type="linenumber">508</context>
</context-group> </context-group>
</trans-unit> </trans-unit>
<trans-unit id="739880801667335279" datatype="html"> <trans-unit id="739880801667335279" datatype="html">
@@ -68,6 +68,7 @@ import exclamationCircleFill from 'bootstrap-icons/icons/exclamation-circle-fill
import exclamationTriangleFill from 'bootstrap-icons/icons/exclamation-triangle-fill.svg' import exclamationTriangleFill from 'bootstrap-icons/icons/exclamation-triangle-fill.svg'
import exclamationTriangle from 'bootstrap-icons/icons/exclamation-triangle.svg' import exclamationTriangle from 'bootstrap-icons/icons/exclamation-triangle.svg'
import eye from 'bootstrap-icons/icons/eye.svg' import eye from 'bootstrap-icons/icons/eye.svg'
import eyeSlash from 'bootstrap-icons/icons/eye-slash.svg'
import fileEarmarkArrowUp from 'bootstrap-icons/icons/file-earmark-arrow-up.svg' import fileEarmarkArrowUp from 'bootstrap-icons/icons/file-earmark-arrow-up.svg'
import fileEarmarkCheck from 'bootstrap-icons/icons/file-earmark-check.svg' import fileEarmarkCheck from 'bootstrap-icons/icons/file-earmark-check.svg'
import fileEarmarkDiff from 'bootstrap-icons/icons/file-earmark-diff.svg' import fileEarmarkDiff from 'bootstrap-icons/icons/file-earmark-diff.svg'
@@ -234,6 +235,7 @@ export const icons: Record<string, string> = {
exclamationTriangle, exclamationTriangle,
exclamationTriangleFill, exclamationTriangleFill,
eye, eye,
eyeSlash,
fileEarmark, fileEarmark,
fileEarmarkArrowUp, fileEarmarkArrowUp,
fileEarmarkCheck, fileEarmarkCheck,
@@ -0,0 +1,4 @@
<span class="badge text-bg-secondary d-inline-flex align-items-center gap-1" title="Tags you don't have access to" i18n-title>
<pngx-bs-icon name="eye-slash" width=".8em" height=".8em"></pngx-bs-icon>
<ng-container i18n>{{count()}} hidden</ng-container>
</span>
@@ -0,0 +1,19 @@
import { ComponentFixture, TestBed } from '@angular/core/testing'
import { HiddenTagsBadgeComponent } from './hidden-tags-badge.component'
describe('HiddenTagsBadgeComponent', () => {
let fixture: ComponentFixture<HiddenTagsBadgeComponent>
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HiddenTagsBadgeComponent],
})
fixture = TestBed.createComponent(HiddenTagsBadgeComponent)
fixture.componentRef.setInput('count', 3)
fixture.detectChanges()
})
it('should show the hidden tag count', () => {
expect(fixture.nativeElement.textContent).toContain('3 hidden')
})
})
@@ -0,0 +1,15 @@
import { ChangeDetectionStrategy, Component, input } from '@angular/core'
import { BootstrapIconComponent } from '../bootstrap-icon/bootstrap-icon.component'
/**
* A badge indicating the number of hidden tags.
*/
@Component({
selector: 'pngx-hidden-tags-badge',
templateUrl: './hidden-tags-badge.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [BootstrapIconComponent],
})
export class HiddenTagsBadgeComponent {
readonly count = input.required<number>()
}
@@ -7,7 +7,7 @@
} }
<div class="position-relative" [class.col-md-9]="horizontal"> <div class="position-relative" [class.col-md-9]="horizontal">
<div class="input-group flex-nowrap"> <div class="input-group flex-nowrap">
<ng-select #tagSelect name="tags" [items]="tags" bindLabel="name" bindValue="id" [(ngModel)]="value" [ngModelOptions]="{standalone: true}" <ng-select #tagSelect name="tags" [items]="tags" bindLabel="name" bindValue="id" [ngModel]="value" (ngModelChange)="onModelChange($event)" [ngModelOptions]="{standalone: true}"
[disabled]="disabled" [disabled]="disabled"
[multiple]="multiple" [multiple]="multiple"
[closeOnSelect]="false" [closeOnSelect]="false"
@@ -24,11 +24,20 @@
<ng-template ng-label-tmp let-item="item"> <ng-template ng-label-tmp let-item="item">
@if (isImplied(item.id)) { @if (isImplied(item.id)) {
<span class="implied-tag"></span> <span class="implied-tag"></span>
} @else if (isHidden(item.id)) {
@if (item.id === hiddenTagIds[0]) {
<button class="tag-wrap hidden-tags btn p-0 d-flex align-items-center mw-100" (click)="removeHiddenTags()" (mousedown)="$event.stopImmediatePropagation()" type="button" title="Remove tags you don't have access to" i18n-title>
<pngx-bs-icon name="x" style="margin-inline-end: 1px;"></pngx-bs-icon>
<pngx-hidden-tags-badge class="d-flex" [count]="hiddenTagIds.length"></pngx-hidden-tags-badge>
</button>
} @else {
<span class="implied-tag"></span>
}
} @else { } @else {
<button class="tag-wrap btn p-0 d-flex align-items-center mw-100" (click)="removeBadge(item.id)" (mousedown)="$event.stopImmediatePropagation()" type="button" title="Remove tag" i18n-title> <button class="tag-wrap btn p-0 d-flex align-items-center mw-100" (click)="removeBadge(item.id)" (mousedown)="$event.stopImmediatePropagation()" type="button" title="Remove tag" i18n-title>
<pngx-bs-icon name="x" style="margin-inline-end: 1px;"></pngx-bs-icon> <pngx-bs-icon name="x" style="margin-inline-end: 1px;"></pngx-bs-icon>
@if (item.id && tags) { @if (item.id && tags) {
<pngx-tag class="mw-100 overflow-hidden" [tag]="getTag(item.id)" [split]="preserveHierarchy" (click)="removeTag(item.id); $event.stopPropagation()" (parentClick)="removeTag($event)"></pngx-tag> <pngx-tag class="mw-100 overflow-hidden d-flex" [tag]="getTag(item.id)" [split]="preserveHierarchy" (click)="removeTag(item.id); $event.stopPropagation()" (parentClick)="removeTag($event)"></pngx-tag>
} }
</button> </button>
} }
@@ -12,6 +12,15 @@
display: none !important; display: none !important;
} }
// hidden tags bundle always sits after the visible tags
::ng-deep .paperless-input-tags .ng-value:has(> .hidden-tags) {
order: 1;
}
::ng-deep .paperless-input-tags .ng-value-container .ng-input {
order: 2;
}
// let a long (nowrap) split badge shrink to the field instead of widening it // let a long (nowrap) split badge shrink to the field instead of widening it
ng-select, ng-select,
::ng-deep .paperless-input-tags .ng-value-container { ::ng-deep .paperless-input-tags .ng-value-container {
@@ -333,4 +333,87 @@ describe('TagsComponent', () => {
).toBe(true) ).toBe(true)
}) })
}) })
describe('hidden tags', () => {
// 98, 99 are not in the tags list i.e. the user cannot view them
beforeEach(() => {
component.tags = tags
component.value = [1, 98, 2, 99]
fixture.detectChanges()
})
it('should collapse hidden tags into a single badge', async () => {
await fixture.whenStable()
fixture.detectChanges()
expect(component.hiddenTagIds).toEqual([98, 99])
expect(component.isHidden(1)).toBe(false)
const badges = fixture.nativeElement.querySelectorAll('.ng-value')
const visible = Array.from(badges).filter(
(b: HTMLElement) => !b.querySelector('.implied-tag')
) as HTMLElement[]
expect(visible).toHaveLength(3)
expect(visible[1].textContent).toContain('2 hidden')
})
it('should only recompute hidden tags when the value or tags change', () => {
const first = component.hiddenTagIds
expect(component.hiddenTagIds).toBe(first)
component.value = [1, 99]
expect(component.hiddenTagIds).toEqual([99])
component.tags = [...tags, { id: 99, name: 'now visible' }]
expect(component.hiddenTagIds).toEqual([])
})
it('should not treat tags as hidden before tags load', () => {
;(component as any).tagsLoaded = false
expect(component.hiddenTagIds).toEqual([])
})
it('should not treat a hidden ancestor of a visible tag as hidden', () => {
component.tags = [{ id: 3, name: 'child', parent: 98 }]
component.value = [3, 98]
expect(component.hiddenTagIds).toEqual([])
})
it('should keep hidden tags when ng-select changes the selection', () => {
component.onModelChange([])
expect(component.value).toEqual([98, 99])
component.onModelChange([1, 10])
expect(component.value).toEqual([1, 10, 98, 99])
})
it('should skip hidden tags on backspace', () => {
const backspace = new KeyboardEvent('keydown', { key: 'Backspace' })
expect(component.onKeyDown(backspace)).toBe(false)
expect(component.value).toEqual([1, 98, 99])
expect(component.onKeyDown(backspace)).toBe(false)
expect(component.onKeyDown(backspace)).toBe(false)
expect(component.value).toEqual([98, 99])
})
it('should remove all hidden tags after confirmation', () => {
let propagated: number[]
component.registerOnChange((value: number[]) => (propagated = value))
let activeInstances: NgbModalRef[]
modalService.activeInstances.subscribe((v) => (activeInstances = v))
component.removeHiddenTags()
expect(modalService.hasOpenModals()).toBeTruthy()
expect(component.value).toEqual([1, 98, 2, 99])
activeInstances[0].componentInstance.confirmClicked.emit()
expect(component.value).toEqual([1, 2])
expect(propagated).toEqual([1, 2])
})
it('should not remove hidden tags when disabled or none exist', () => {
component.disabled = true
component.removeHiddenTags()
expect(modalService.hasOpenModals()).toBeFalsy()
component.disabled = false
component.value = [1]
component.removeHiddenTags()
expect(modalService.hasOpenModals()).toBeFalsy()
})
})
}) })
@@ -24,11 +24,10 @@ import { Tag } from 'src/app/data/tag'
import { SETTINGS_KEYS } from 'src/app/data/ui-settings' import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
import { TagService } from 'src/app/services/rest/tag.service' import { TagService } from 'src/app/services/rest/tag.service'
import { SettingsService } from 'src/app/services/settings.service' import { SettingsService } from 'src/app/services/settings.service'
import { import { getTagAncestors, partitionTags } from 'src/app/utils/tag-display'
collapseImpliedAncestors,
getTagAncestors,
} from 'src/app/utils/collapse-tags'
import { matchesSearchText } from 'src/app/utils/text-search' import { matchesSearchText } from 'src/app/utils/text-search'
import { ConfirmDialogComponent } from '../../confirm-dialog/confirm-dialog.component'
import { HiddenTagsBadgeComponent } from '../../hidden-tags-badge/hidden-tags-badge.component'
import { EditDialogMode } from '../../edit-dialog/edit-dialog.component' import { EditDialogMode } from '../../edit-dialog/edit-dialog.component'
import { TagEditDialogComponent } from '../../edit-dialog/tag-edit-dialog/tag-edit-dialog.component' import { TagEditDialogComponent } from '../../edit-dialog/tag-edit-dialog/tag-edit-dialog.component'
import { TagComponent } from '../../tag/tag.component' import { TagComponent } from '../../tag/tag.component'
@@ -51,6 +50,7 @@ import { TagComponent } from '../../tag/tag.component'
ReactiveFormsModule, ReactiveFormsModule,
RouterModule, RouterModule,
BootstrapIconComponent, BootstrapIconComponent,
HiddenTagsBadgeComponent,
], ],
}) })
export class TagsComponent implements OnInit, ControlValueAccessor { export class TagsComponent implements OnInit, ControlValueAccessor {
@@ -85,6 +85,7 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
ngOnInit(): void { ngOnInit(): void {
this.tagService.listAll().subscribe((result) => { this.tagService.listAll().subscribe((result) => {
this.tags = result.results this.tags = result.results
this.tagsLoaded = true
this.changeDetector.markForCheck() this.changeDetector.markForCheck()
}) })
} }
@@ -128,6 +129,8 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
tags: Tag[] = [] tags: Tag[] = []
private tagsLoaded = false
public createTagRef: (name) => void public createTagRef: (name) => void
public searchFn = (term: string, tag: Tag): boolean => public searchFn = (term: string, tag: Tag): boolean =>
@@ -143,8 +146,7 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
* as segments of their descendant's badge. * as segments of their descendant's badge.
*/ */
isImplied(id: number): boolean { isImplied(id: number): boolean {
if (!this.showsHierarchy || !this.tags || !this.value) return false return !!this.value?.includes(id) && !this.display.shown.has(id)
return !collapseImpliedAncestors(this.value, this.tagsById).includes(id)
} }
private get showsHierarchy(): boolean { private get showsHierarchy(): boolean {
@@ -154,17 +156,103 @@ export class TagsComponent implements OnInit, ControlValueAccessor {
) )
} }
isHidden(id: number): boolean {
return this.display.hiddenSet.has(id)
}
/** /**
* Remove the last visible tag (in case its actually a hidden ancestor) * Tags that are hidden from the current user.
*/
get hiddenTagIds(): number[] {
return this.display.hidden
}
private displayCache: {
value: number[]
tagsById: Map<number, Tag>
showsHierarchy: boolean
tagsLoaded: boolean
shown: Set<number>
hidden: number[]
hiddenSet: Set<number>
}
/**
* Partition of the current value, recomputed only when the value, tags or
* hierarchy setting change.
*/
private get display() {
const tagsById = this.tagsById
const showsHierarchy = this.showsHierarchy
const cached = this.displayCache
if (
cached?.value === this.value &&
cached.tagsById === tagsById &&
cached.showsHierarchy === showsHierarchy &&
cached.tagsLoaded === this.tagsLoaded
) {
return cached
}
const { visible, hidden } = partitionTags(
this.value,
tagsById,
showsHierarchy
)
const hiddenIds = this.tagsLoaded ? hidden : []
this.displayCache = {
value: this.value,
tagsById,
showsHierarchy,
tagsLoaded: this.tagsLoaded,
shown: new Set([...visible, ...hidden]),
hidden: hiddenIds,
hiddenSet: new Set(hiddenIds),
}
return this.displayCache
}
/**
* Remove the last visible tag (in case its actually a hidden ancestor or a
* tag the user cannot view)
*/ */
readonly onKeyDown = (event: KeyboardEvent): boolean => { readonly onKeyDown = (event: KeyboardEvent): boolean => {
if (event.key !== 'Backspace' || this.select?.searchTerm) return true if (event.key !== 'Backspace' || this.select?.searchTerm) return true
const visible = this.value?.filter((id) => !this.isImplied(id)) ?? [] const visible =
this.value?.filter((id) => !this.isImplied(id) && !this.isHidden(id)) ??
[]
if (visible.length === (this.value?.length ?? 0)) return true if (visible.length === (this.value?.length ?? 0)) return true
this.removeTag(visible.at(-1)) if (visible.length) this.removeTag(visible.at(-1))
return false return false
} }
/**
* Changes from ng-select itself (e.g. clear all) never drop hidden tags,
* those are only removed via their own badge.
*/
onModelChange(newValue: number[]) {
const kept = this.hiddenTagIds.filter((id) => !newValue?.includes(id))
this.value = [...(newValue ?? []), ...kept]
}
removeHiddenTags() {
if (this.disabled) return
const hidden = new Set(this.hiddenTagIds)
if (!hidden.size) return
const modal = this.modalService.open(ConfirmDialogComponent, {
backdrop: 'static',
})
modal.componentInstance.title = $localize`Remove hidden tags`
modal.componentInstance.messageBold = $localize`Remove ${hidden.size} tag(s) you don't have access to?`
modal.componentInstance.message = $localize`You will not be able to add them back.`
modal.componentInstance.btnClass = 'btn-danger'
modal.componentInstance.btnCaption = $localize`Remove`
modal.componentInstance.confirmClicked.pipe(first()).subscribe(() => {
modal.close()
this.value = this.value.filter((id) => !hidden.has(id))
this.onChange(this.value)
})
}
getTag(id: number) { getTag(id: number) {
if (this.tags) { if (this.tags) {
return this.tags.find((tag) => tag.id == id) return this.tags.find((tag) => tag.id == id)
@@ -17,7 +17,7 @@ import {
} from 'src/app/services/permissions.service' } from 'src/app/services/permissions.service'
import { TagService } from 'src/app/services/rest/tag.service' import { TagService } from 'src/app/services/rest/tag.service'
import { SettingsService } from 'src/app/services/settings.service' import { SettingsService } from 'src/app/services/settings.service'
import { getTagAncestors } from 'src/app/utils/collapse-tags' import { getTagAncestors } from 'src/app/utils/tag-display'
const FOCUS_ANIMATION_MS = 200 const FOCUS_ANIMATION_MS = 200
// matches the .split-parent min-width in tag.component.scss // matches the .split-parent min-width in tag.component.scss
@@ -76,9 +76,13 @@
} }
} }
@case (DisplayField.TAGS) { @case (DisplayField.TAGS) {
@for (tagID of doc.tags | collapseTags | async; track tagID) { @let tags = doc.tags | displayTags | async;
@for (tagID of tags?.visible; track tagID) {
<pngx-tag [tagID]="tagID" [split]="true" class="ms-1 fs-6" (click)="clickTag(tagID, $event)" (parentClick)="clickTag($event)" [clickable]="true" linkTitle="Filter by tag" i18n-title></pngx-tag> <pngx-tag [tagID]="tagID" [split]="true" class="ms-1 fs-6" (click)="clickTag(tagID, $event)" (parentClick)="clickTag($event)" [clickable]="true" linkTitle="Filter by tag" i18n-title></pngx-tag>
} }
@if (tags?.hidden.length) {
<pngx-hidden-tags-badge [count]="tags.hidden.length" class="ms-1 fs-6"></pngx-hidden-tags-badge>
}
} }
@case (DisplayField.DOCUMENT_TYPE) { @case (DisplayField.DOCUMENT_TYPE) {
@if (doc.document_type) { @if (doc.document_type) {
@@ -1,3 +1,4 @@
import { HiddenTagsBadgeComponent } from 'src/app/components/common/hidden-tags-badge/hidden-tags-badge.component'
import { AsyncPipe, NgClass, NgStyle } from '@angular/common' import { AsyncPipe, NgClass, NgStyle } from '@angular/common'
import { import {
Component, Component,
@@ -38,7 +39,7 @@ import {
} from 'src/app/data/filter-rule-type' } from 'src/app/data/filter-rule-type'
import { SavedView } from 'src/app/data/saved-view' import { SavedView } from 'src/app/data/saved-view'
import { IfPermissionsDirective } from 'src/app/directives/if-permissions.directive' import { IfPermissionsDirective } from 'src/app/directives/if-permissions.directive'
import { CollapseTagsPipe } from 'src/app/pipes/collapse-tags.pipe' import { DisplayTagsPipe } from 'src/app/pipes/display-tags.pipe'
import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe' import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe'
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe' import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe' import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe'
@@ -76,7 +77,8 @@ import { WidgetFrameComponent } from '../widget-frame/widget-frame.component'
DocumentTypeNamePipe, DocumentTypeNamePipe,
StoragePathNamePipe, StoragePathNamePipe,
AsyncPipe, AsyncPipe,
CollapseTagsPipe, DisplayTagsPipe,
HiddenTagsBadgeComponent,
DocumentTitlePipe, DocumentTitlePipe,
CustomDatePipe, CustomDatePipe,
NgClass, NgClass,
@@ -36,9 +36,13 @@
{{document().title | documentTitle}} {{document().title | documentTitle}}
} }
@if (displayFields().includes(DisplayField.TAGS)) { @if (displayFields().includes(DisplayField.TAGS)) {
@for (tagID of document().tags | collapseTags | async; track tagID) { @let tags = document().tags | displayTags | async;
@for (tagID of tags?.visible; track tagID) {
<pngx-tag [tagID]="tagID" [split]="true" linkTitle="Filter by tag" i18n-linkTitle class="ms-1" (click)="clickTag.emit(tagID);$event.stopPropagation()" (parentClick)="clickTag.emit($event)" [clickable]="clickTag.observers.length"></pngx-tag> <pngx-tag [tagID]="tagID" [split]="true" linkTitle="Filter by tag" i18n-linkTitle class="ms-1" (click)="clickTag.emit(tagID);$event.stopPropagation()" (parentClick)="clickTag.emit($event)" [clickable]="clickTag.observers.length"></pngx-tag>
} }
@if (tags?.hidden.length) {
<pngx-hidden-tags-badge [count]="tags.hidden.length" class="ms-1"></pngx-hidden-tags-badge>
}
} }
} @else { } @else {
<div class="placeholder bg-secondary w-75 mb-3">&nbsp;</div> <div class="placeholder bg-secondary w-75 mb-3">&nbsp;</div>
@@ -1,3 +1,4 @@
import { HiddenTagsBadgeComponent } from 'src/app/components/common/hidden-tags-badge/hidden-tags-badge.component'
import { AsyncPipe, NgOptimizedImage } from '@angular/common' import { AsyncPipe, NgOptimizedImage } from '@angular/common'
import { import {
AfterViewInit, AfterViewInit,
@@ -20,7 +21,7 @@ import {
Document, Document,
} from 'src/app/data/document' } from 'src/app/data/document'
import { SETTINGS_KEYS } from 'src/app/data/ui-settings' import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
import { CollapseTagsPipe } from 'src/app/pipes/collapse-tags.pipe' import { DisplayTagsPipe } from 'src/app/pipes/display-tags.pipe'
import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe' import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe'
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe' import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe' import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe'
@@ -46,7 +47,8 @@ import { LoadingComponentWithPermissions } from '../../loading-component/loading
TagComponent, TagComponent,
CustomFieldDisplayComponent, CustomFieldDisplayComponent,
AsyncPipe, AsyncPipe,
CollapseTagsPipe, DisplayTagsPipe,
HiddenTagsBadgeComponent,
NgOptimizedImage, NgOptimizedImage,
UsernamePipe, UsernamePipe,
CorrespondentNamePipe, CorrespondentNamePipe,
@@ -19,8 +19,10 @@
} }
@if (document() && displayFields().includes(DisplayField.TAGS)) { @if (document() && displayFields().includes(DisplayField.TAGS)) {
@let visibleTagIDs = document().tags | collapseTags | async; @let tags = document().tags | displayTags | async;
<div class="tags d-flex flex-column text-end position-absolute me-1 fs-6" [class.tags-no-wrap]="visibleTagIDs?.length > 3"> @let visibleTagIDs = tags?.visible;
@let showHidden = showHiddenTags(tags);
<div class="tags d-flex flex-column text-end position-absolute me-1 fs-6" [class.tags-no-wrap]="(visibleTagIDs?.length ?? 0) + (showHidden ? 1 : 0) > 3">
@for (tagID of getTagIDs(visibleTagIDs); track tagID) { @for (tagID of getTagIDs(visibleTagIDs); track tagID) {
<pngx-tag [tagID]="tagID" [split]="true" (click)="clickTag.emit(tagID);$event.stopPropagation()" (parentClick)="clickTag.emit($event)" [clickable]="true" linkTitle="Toggle tag filter" i18n-linkTitle></pngx-tag> <pngx-tag [tagID]="tagID" [split]="true" (click)="clickTag.emit(tagID);$event.stopPropagation()" (parentClick)="clickTag.emit($event)" [clickable]="true" linkTitle="Toggle tag filter" i18n-linkTitle></pngx-tag>
} }
@@ -29,6 +31,9 @@
<span class="badge text-dark">+ {{moreTags}}</span> <span class="badge text-dark">+ {{moreTags}}</span>
</div> </div>
} }
@if (showHidden) {
<pngx-hidden-tags-badge [count]="tags.hidden.length"></pngx-hidden-tags-badge>
}
</div> </div>
} }
</div> </div>
@@ -42,6 +42,19 @@ describe('DocumentCardSmallComponent', () => {
], ],
}).compileComponents() }).compileComponents()
jest
.spyOn(TestBed.inject(PermissionsService), 'currentUserCan')
.mockReturnValue(true)
jest.spyOn(TestBed.inject(TagService), 'listAll').mockReturnValue(
of({
count: 8,
all: [1, 2, 3, 4, 5, 6, 7, 8],
results: [1, 2, 3, 4, 5, 6, 7, 8].map((id) => ({
id,
name: `Tag ${id}`,
})),
})
)
fixture = TestBed.createComponent(DocumentCardSmallComponent) fixture = TestBed.createComponent(DocumentCardSmallComponent)
component = fixture.componentInstance component = fixture.componentInstance
fixture.componentRef.setInput('document', Object.assign({}, doc)) fixture.componentRef.setInput('document', Object.assign({}, doc))
@@ -148,4 +161,33 @@ describe('DocumentCardSmallComponent', () => {
component.mouseLeaveCard() component.mouseLeaveCard()
expect(component.popupPreview.close).toHaveBeenCalled() expect(component.popupPreview.close).toHaveBeenCalled()
}) })
it('should show hidden tags last, only when visible tags leave a slot free', () => {
fixture.componentRef.setInput('document', {
...component.document(),
tags: [1, 2, 3, 98, 99],
})
fixture.detectChanges()
const tagsEl = () => fixture.nativeElement.querySelector('.tags')
expect(tagsEl().lastElementChild.textContent).toContain('2 hidden')
// 6 visible tags fill the limit (document has notes)
fixture.componentRef.setInput('document', {
...component.document(),
tags: [1, 2, 3, 4, 5, 6, 98, 99],
})
fixture.detectChanges()
expect(tagsEl().textContent).not.toContain('hidden')
expect(
fixture.debugElement.queryAll(By.directive(TagComponent))
).toHaveLength(6)
fixture.componentRef.setInput('document', {
...component.document(),
tags: [1, 2, 3, 4, 5, 6, 7, 98],
})
fixture.detectChanges()
expect(tagsEl().textContent).toContain('+ 2')
expect(tagsEl().textContent).not.toContain('hidden')
})
}) })
@@ -1,3 +1,5 @@
import { TagPartition } from 'src/app/utils/tag-display'
import { HiddenTagsBadgeComponent } from 'src/app/components/common/hidden-tags-badge/hidden-tags-badge.component'
import { AsyncPipe, NgOptimizedImage } from '@angular/common' import { AsyncPipe, NgOptimizedImage } from '@angular/common'
import { import {
AfterViewInit, AfterViewInit,
@@ -20,7 +22,7 @@ import {
Document, Document,
} from 'src/app/data/document' } from 'src/app/data/document'
import { SETTINGS_KEYS } from 'src/app/data/ui-settings' import { SETTINGS_KEYS } from 'src/app/data/ui-settings'
import { CollapseTagsPipe } from 'src/app/pipes/collapse-tags.pipe' import { DisplayTagsPipe } from 'src/app/pipes/display-tags.pipe'
import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe' import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe'
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe' import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe' import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe'
@@ -46,7 +48,8 @@ import { LoadingComponentWithPermissions } from '../../loading-component/loading
TagComponent, TagComponent,
CustomFieldDisplayComponent, CustomFieldDisplayComponent,
AsyncPipe, AsyncPipe,
CollapseTagsPipe, DisplayTagsPipe,
HiddenTagsBadgeComponent,
NgOptimizedImage, NgOptimizedImage,
UsernamePipe, UsernamePipe,
CorrespondentNamePipe, CorrespondentNamePipe,
@@ -96,6 +99,13 @@ export class DocumentCardSmallComponent
return this.document()?.notes.length > 0 ? 6 : 7 return this.document()?.notes.length > 0 ? 6 : 7
} }
/**
* The hidden tags badge only fills a slot the visible tags leave free.
*/
showHiddenTags(tags: TagPartition): boolean {
return tags?.hidden.length > 0 && tags.visible.length < this.tagLimit
}
getMoreTags(tagIDs: number[]): number { getMoreTags(tagIDs: number[]): number {
const limit = this.tagLimit const limit = this.tagLimit
return tagIDs?.length > limit ? tagIDs.length - (limit - 1) : null return tagIDs?.length > limit ? tagIDs.length - (limit - 1) : null
@@ -335,9 +335,13 @@
<a routerLink="/documents/{{d.id}}" title="Edit document" i18n-title style="overflow-wrap: anywhere;">{{d.title | documentTitle}}</a> <a routerLink="/documents/{{d.id}}" title="Edit document" i18n-title style="overflow-wrap: anywhere;">{{d.title | documentTitle}}</a>
} }
@if (activeDisplayFields.includes(DisplayField.TAGS)) { @if (activeDisplayFields.includes(DisplayField.TAGS)) {
@for (tagID of d.tags | collapseTags | async; track tagID) { @let tags = d.tags | displayTags | async;
@for (tagID of tags?.visible; track tagID) {
<pngx-tag [tagID]="tagID" [split]="true" class="ms-1 fs-6" clickable="true" linkTitle="Filter by tag" i18n-linkTitle (click)="clickTag(tagID);$event.stopPropagation()" (parentClick)="clickTag($event)"></pngx-tag> <pngx-tag [tagID]="tagID" [split]="true" class="ms-1 fs-6" clickable="true" linkTitle="Filter by tag" i18n-linkTitle (click)="clickTag(tagID);$event.stopPropagation()" (parentClick)="clickTag($event)"></pngx-tag>
} }
@if (tags?.hidden.length) {
<pngx-hidden-tags-badge [count]="tags.hidden.length" class="ms-1 fs-6"></pngx-hidden-tags-badge>
}
} }
</td> </td>
} }
@@ -1,3 +1,4 @@
import { HiddenTagsBadgeComponent } from 'src/app/components/common/hidden-tags-badge/hidden-tags-badge.component'
import { AsyncPipe, NgClass, NgTemplateOutlet } from '@angular/common' import { AsyncPipe, NgClass, NgTemplateOutlet } from '@angular/common'
import { import {
Component, Component,
@@ -39,7 +40,7 @@ import {
SortableDirective, SortableDirective,
SortEvent, SortEvent,
} from 'src/app/directives/sortable.directive' } from 'src/app/directives/sortable.directive'
import { CollapseTagsPipe } from 'src/app/pipes/collapse-tags.pipe' import { DisplayTagsPipe } from 'src/app/pipes/display-tags.pipe'
import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe' import { CorrespondentNamePipe } from 'src/app/pipes/correspondent-name.pipe'
import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe' import { CustomDatePipe } from 'src/app/pipes/custom-date.pipe'
import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe' import { DocumentTitlePipe } from 'src/app/pipes/document-title.pipe'
@@ -97,7 +98,8 @@ import { SaveViewConfigDialogComponent } from './save-view-config-dialog/save-vi
StoragePathNamePipe, StoragePathNamePipe,
BootstrapIconComponent, BootstrapIconComponent,
AsyncPipe, AsyncPipe,
CollapseTagsPipe, DisplayTagsPipe,
HiddenTagsBadgeComponent,
FormsModule, FormsModule,
ReactiveFormsModule, ReactiveFormsModule,
NgTemplateOutlet, NgTemplateOutlet,
@@ -6,7 +6,7 @@ import { Tag } from '../data/tag'
import { PermissionsService } from '../services/permissions.service' import { PermissionsService } from '../services/permissions.service'
import { TagService } from '../services/rest/tag.service' import { TagService } from '../services/rest/tag.service'
import { SettingsService } from '../services/settings.service' import { SettingsService } from '../services/settings.service'
import { CollapseTagsPipe } from './collapse-tags.pipe' import { DisplayTagsPipe } from './display-tags.pipe'
const tags: Tag[] = [ const tags: Tag[] = [
{ id: 1, name: 'Parent' }, { id: 1, name: 'Parent' },
@@ -14,8 +14,8 @@ const tags: Tag[] = [
{ id: 3, name: 'Other' }, { id: 3, name: 'Other' },
] ]
describe('CollapseTagsPipe', () => { describe('DisplayTagsPipe', () => {
let pipe: CollapseTagsPipe let pipe: DisplayTagsPipe
let tagService: TagService let tagService: TagService
let settingsService: SettingsService let settingsService: SettingsService
let permissionsService: PermissionsService let permissionsService: PermissionsService
@@ -23,12 +23,12 @@ describe('CollapseTagsPipe', () => {
beforeEach(() => { beforeEach(() => {
TestBed.configureTestingModule({ TestBed.configureTestingModule({
providers: [ providers: [
CollapseTagsPipe, DisplayTagsPipe,
provideHttpClient(withInterceptorsFromDi()), provideHttpClient(withInterceptorsFromDi()),
provideHttpClientTesting(), provideHttpClientTesting(),
], ],
}) })
pipe = TestBed.inject(CollapseTagsPipe) pipe = TestBed.inject(DisplayTagsPipe)
tagService = TestBed.inject(TagService) tagService = TestBed.inject(TagService)
settingsService = TestBed.inject(SettingsService) settingsService = TestBed.inject(SettingsService)
permissionsService = TestBed.inject(PermissionsService) permissionsService = TestBed.inject(PermissionsService)
@@ -39,29 +39,43 @@ describe('CollapseTagsPipe', () => {
.mockReturnValue(of({ count: 3, all: [1, 2, 3], results: tags })) .mockReturnValue(of({ count: 3, all: [1, 2, 3], results: tags }))
}) })
it('should drop parents implied by a selected child', async () => { it('should split visible and hidden tags, collapsing implied parents', async () => {
expect(await firstValueFrom(pipe.transform([1, 2, 3]))).toEqual([2, 3]) expect(await firstValueFrom(pipe.transform([1, 2, 98, 3]))).toEqual({
visible: [2, 3],
hidden: [98],
})
}) })
it('should pass ids through when hierarchy display is off or not permitted', async () => { it('should not collapse parents when hierarchy display is off', async () => {
jest.spyOn(settingsService, 'get').mockReturnValue(false) jest.spyOn(settingsService, 'get').mockReturnValue(false)
expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual([1, 2]) expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual({
visible: [1, 2],
hidden: [],
})
})
jest.spyOn(settingsService, 'get').mockReturnValue(true) it('should hide all tags without tag view permission', async () => {
jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(false) jest.spyOn(permissionsService, 'currentUserCan').mockReturnValue(false)
expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual([1, 2]) expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual({
visible: [],
hidden: [1, 2],
})
expect(tagService.listAll).not.toHaveBeenCalled() expect(tagService.listAll).not.toHaveBeenCalled()
}) })
it('should handle empty input', async () => { it('should handle empty input', async () => {
expect(await firstValueFrom(pipe.transform(null))).toEqual([]) const empty = { visible: [], hidden: [] }
expect(await firstValueFrom(pipe.transform([]))).toEqual([]) expect(await firstValueFrom(pipe.transform(null))).toEqual(empty)
expect(await firstValueFrom(pipe.transform([]))).toEqual(empty)
}) })
it('should fall back to the original ids if tags fail to load', async () => { it('should show the original ids if tags fail to load', async () => {
jest jest
.spyOn(tagService, 'listAll') .spyOn(tagService, 'listAll')
.mockReturnValue(throwError(() => new Error('failed'))) .mockReturnValue(throwError(() => new Error('failed')))
expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual([1, 2]) expect(await firstValueFrom(pipe.transform([1, 2]))).toEqual({
visible: [1, 2],
hidden: [],
})
}) })
}) })
@@ -9,39 +9,39 @@ import {
} from '../services/permissions.service' } from '../services/permissions.service'
import { TagService } from '../services/rest/tag.service' import { TagService } from '../services/rest/tag.service'
import { SettingsService } from '../services/settings.service' import { SettingsService } from '../services/settings.service'
import { collapseImpliedAncestors } from '../utils/collapse-tags' import { partitionTags, TagPartition } from '../utils/tag-display'
/** /**
* Drops tag IDs whose descendant is also in the list for when the child's * Splits a document's tag IDs into regular ones vs those the
* Tag badge already shows its parent. * current user cannot view, see partitionTags.
*/ */
@Pipe({ @Pipe({
name: 'collapseTags', name: 'displayTags',
}) })
export class CollapseTagsPipe implements PipeTransform { export class DisplayTagsPipe implements PipeTransform {
private readonly permissionsService = inject(PermissionsService) private readonly permissionsService = inject(PermissionsService)
private readonly tagService = inject(TagService) private readonly tagService = inject(TagService)
private readonly settingsService = inject(SettingsService) private readonly settingsService = inject(SettingsService)
transform(ids: number[]): Observable<number[]> { transform(ids: number[]): Observable<TagPartition> {
if (!ids?.length) return of({ visible: [], hidden: [] })
if ( if (
!ids?.length ||
!this.settingsService.get(SETTINGS_KEYS.TAGS_SHOW_HIERARCHY) ||
!this.permissionsService.currentUserCan( !this.permissionsService.currentUserCan(
PermissionAction.View, PermissionAction.View,
PermissionType.Tag PermissionType.Tag
) )
) { ) {
return of(ids ?? []) return of({ visible: [], hidden: ids })
} }
return this.tagService.listAll().pipe( return this.tagService.listAll().pipe(
map((tags) => map((tags) =>
collapseImpliedAncestors( partitionTags(
ids, ids,
new Map<number, Tag>(tags.results.map((t) => [t.id, t])) new Map<number, Tag>(tags.results.map((t) => [t.id, t])),
!!this.settingsService.get(SETTINGS_KEYS.TAGS_SHOW_HIERARCHY)
) )
), ),
catchError(() => of(ids)) catchError(() => of({ visible: ids, hidden: [] }))
) )
} }
} }
@@ -1,5 +1,9 @@
import { Tag } from '../data/tag' import { Tag } from '../data/tag'
import { collapseImpliedAncestors, getTagAncestors } from './collapse-tags' import {
collapseImpliedAncestors,
getTagAncestors,
partitionTags,
} from './tag-display'
const tags: Tag[] = [ const tags: Tag[] = [
{ id: 1, name: 'Finance' }, { id: 1, name: 'Finance' },
@@ -45,3 +49,33 @@ describe('getTagAncestors', () => {
expect(getTagAncestors(7, cyclic).map((t) => t.id)).toEqual([7, 8]) expect(getTagAncestors(7, cyclic).map((t) => t.id)).toEqual([7, 8])
}) })
}) })
describe('partitionTags', () => {
it('splits ids into visible and hidden, keeping order', () => {
expect(partitionTags([5, 98, 4, 99], tagsById, true)).toEqual({
visible: [5, 4],
hidden: [98, 99],
})
expect(partitionTags(null, tagsById, true)).toEqual({
visible: [],
hidden: [],
})
})
it('drops implied ancestors only when showing hierarchy', () => {
expect(partitionTags([1, 2, 3], tagsById, true).visible).toEqual([3])
expect(partitionTags([1, 2, 3], tagsById, false).visible).toEqual([1, 2, 3])
})
it('drops a hidden ancestor of a visible tag only when showing hierarchy', () => {
const withHiddenParent = new Map(tagsById)
withHiddenParent.set(6, { id: 6, name: 'Child', parent: 98 })
expect(partitionTags([6, 98, 99], withHiddenParent, true)).toEqual({
visible: [6],
hidden: [99],
})
expect(partitionTags([6, 98, 99], withHiddenParent, false).hidden).toEqual([
98, 99,
])
})
})
@@ -41,3 +41,27 @@ export function getTagAncestors(id: number, tagsById: Map<number, Tag>): Tag[] {
} }
return chain return chain
} }
export interface TagPartition {
visible: number[]
hidden: number[]
}
/**
* Splits a document's tag IDs for display. Tags missing from tagsById are hidden
* from the current user and when showing hierarchy, ancestors of a child are dropped
* since the descendant badge will show them.
*/
export function partitionTags(
ids: number[],
tagsById: Map<number, Tag>,
showHierarchy: boolean
): TagPartition {
const shown = showHierarchy
? collapseImpliedAncestors(ids, tagsById)
: (ids ?? [])
return {
visible: shown.filter((id) => tagsById.has(id)),
hidden: shown.filter((id) => !tagsById.has(id)),
}
}
+8 -1
View File
@@ -415,10 +415,17 @@ th[pngxSortable] {
.ng-select.ng-select-multiple .ng-select-container .ng-value-container .ng-value { .ng-select.ng-select-multiple .ng-select-container .ng-value-container .ng-value {
background-color: transparent; background-color: transparent;
border-color: transparent; border-color: transparent;
// split ng-select's 5px bottom margin so values stay vertically centered
margin-block: 2.5px;
} }
.ng-select.ng-select-multiple .ng-select-container .ng-value-container { .ng-select.ng-select-multiple .ng-select-container .ng-value-container {
padding-top: 1px; padding-top: 0;
}
// undo bootstrap's .btn .badge nudge
.tag-wrap .badge {
top: 0;
} }
} }
+11 -73
View File
@@ -1,7 +1,6 @@
from __future__ import annotations from __future__ import annotations
import functools import functools
import hmac
import logging import logging
import pickle import pickle
import re import re
@@ -15,9 +14,6 @@ if TYPE_CHECKING:
from collections.abc import Callable from collections.abc import Callable
from collections.abc import Iterator from collections.abc import Iterator
from datetime import datetime from datetime import datetime
from types import TracebackType
from typing import BinaryIO
from typing import Self
import tantivy import tantivy
from numpy import ndarray from numpy import ndarray
@@ -37,9 +33,11 @@ from documents.caching import CLASSIFIER_VERSION_KEY
from documents.models import Document from documents.models import Document
from documents.models import MatchingModel from documents.models import MatchingModel
from documents.models import Tag from documents.models import Tag
from paperless.signed_pickle import SignedFileWriter
from paperless.signed_pickle import SignedPickleError from paperless.signed_pickle import SignedPickleError
from paperless.signed_pickle import signed_pickle_dumps from paperless.signed_pickle import signed_pickle_dumps
from paperless.signed_pickle import signed_pickle_loads from paperless.signed_pickle import signed_pickle_loads
from paperless.signed_pickle import verify_signed
logger = logging.getLogger("paperless.classifier") logger = logging.getLogger("paperless.classifier")
@@ -77,49 +75,6 @@ RE_WORD = re.compile(r"\b[\w]+\b") # words that may contain digits
_CONTENT_CHUNK_SIZE = 1000 _CONTENT_CHUNK_SIZE = 1000
class _SignedFileWriter:
"""
Atomically writes a file made of an HMAC signature followed by the data,
signing the data as it streams to disk rather than holding it in memory.
The signature is only known once everything is written, so its space is
reserved at the start of the file and filled in on exit. The target is only
replaced once the file is complete; on error the partial file is removed.
"""
def __init__(self, target: Path, mac: hmac.HMAC) -> None:
self._target = target
self._temp = target.with_name(f"{target.name}.part")
self._mac = mac
self._file: BinaryIO
def __enter__(self) -> Self:
self._file = self._temp.open("wb")
self._file.write(bytes(self._mac.digest_size))
return self
def write(self, data: bytes | memoryview) -> int:
self._mac.update(data)
return self._file.write(data)
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None:
try:
with self._file:
if exc_type is None:
self._file.seek(0)
self._file.write(self._mac.digest())
if exc_type is None:
self._temp.rename(self._target)
finally:
# A no-op after a successful rename, otherwise removes the partial file
self._temp.unlink(missing_ok=True)
@functools.cache @functools.cache
def _text_analyzer(language: str) -> tantivy.TextAnalyzer: def _text_analyzer(language: str) -> tantivy.TextAnalyzer:
""" """
@@ -209,8 +164,6 @@ class DocumentClassifier:
# Tantivy text preprocessing # Tantivy text preprocessing
FORMAT_VERSION = 11 FORMAT_VERSION = 11
HMAC_SIZE = 32 # SHA-256 digest length
def __init__(self) -> None: def __init__(self) -> None:
# last time a document changed and therefore training might be required # last time a document changed and therefore training might be required
self.last_doc_change_time: datetime | None = None self.last_doc_change_time: datetime | None = None
@@ -230,10 +183,6 @@ class DocumentClassifier:
pickle.dumps(self.data_vectorizer), pickle.dumps(self.data_vectorizer),
).hexdigest() ).hexdigest()
@staticmethod
def _new_hmac() -> hmac.HMAC:
return hmac.new(settings.SECRET_KEY.encode(), digestmod=sha256)
@staticmethod @staticmethod
def _strip_training_state(classifier: MLPClassifier) -> None: def _strip_training_state(classifier: MLPClassifier) -> None:
""" """
@@ -248,30 +197,19 @@ class DocumentClassifier:
del classifier._best_coefs del classifier._best_coefs
del classifier._best_intercepts del classifier._best_intercepts
@staticmethod
def _compute_hmac(data: bytes | memoryview) -> bytes:
mac = DocumentClassifier._new_hmac()
mac.update(data)
return mac.digest()
def load(self) -> None: def load(self) -> None:
from sklearn.exceptions import InconsistentVersionWarning from sklearn.exceptions import InconsistentVersionWarning
raw = Path(settings.MODEL_FILE).read_bytes() raw = Path(settings.MODEL_FILE).read_bytes()
if len(raw) <= self.HMAC_SIZE: # The whole file is verified from memory before unpickling, rather than
raise ClassifierModelCorruptError # streamed from disk, so it cannot change between check and load.
# verify_signed returns a view of the data without copying the
# Slice through a memoryview so the (potentially multi-GB) payload is # (potentially multi-GB) payload.
# not copied; hmac and pickle both accept buffers directly. try:
# The whole file is still verified from memory before unpickling, rather data = verify_signed(raw)
# than streamed from disk, so it cannot change between check and load. except SignedPickleError as err:
view = memoryview(raw) raise ClassifierModelCorruptError from err
signature = view[: self.HMAC_SIZE]
data = view[self.HMAC_SIZE :]
if not hmac.compare_digest(signature, self._compute_hmac(data)):
raise ClassifierModelCorruptError
# Catch warnings for processing # Catch warnings for processing
with warnings.catch_warnings(record=True) as w: with warnings.catch_warnings(record=True) as w:
@@ -315,7 +253,7 @@ class DocumentClassifier:
def save(self) -> None: def save(self) -> None:
# Stream to disk instead of building the payload in memory. Protocol 5+ # Stream to disk instead of building the payload in memory. Protocol 5+
# pickles numpy arrays without copying them (the default is 4 before 3.14). # pickles numpy arrays without copying them (the default is 4 before 3.14).
with _SignedFileWriter(settings.MODEL_FILE, self._new_hmac()) as f: with SignedFileWriter(settings.MODEL_FILE) as f:
pickle.dump( pickle.dump(
( (
self.FORMAT_VERSION, self.FORMAT_VERSION,
+10 -19
View File
@@ -15,6 +15,7 @@ from django.db import transaction
from django.db.models import Max from django.db.models import Max
from django.db.models import Q from django.db.models import Q
from django.utils import timezone from django.utils import timezone
from filelock import FileLock
from rest_framework.reverse import reverse from rest_framework.reverse import reverse
from documents.barcodes import read_barcode_values from documents.barcodes import read_barcode_values
@@ -26,10 +27,7 @@ from documents.file_handling import create_source_path_directory
from documents.file_handling import generate_filename from documents.file_handling import generate_filename
from documents.file_handling import generate_unique_filename from documents.file_handling import generate_unique_filename
from documents.file_handling import validate_path_in_root 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.loggers import LoggingMixin
from documents.media_lock import media_lock
from documents.models import Correspondent from documents.models import Correspondent
from documents.models import CustomField from documents.models import CustomField
from documents.models import CustomFieldInstance from documents.models import CustomFieldInstance
@@ -625,13 +623,7 @@ class ConsumerPlugin(
# now that everything is done, we can start to store the document # now that everything is done, we can start to store the document
# in the system. This will be a transaction and reasonably fast. # in the system. This will be a transaction and reasonably fast.
try: try:
# File moves requested in here run after commit and after with transaction.atomic():
# 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():
# store the document. # store the document.
if self.input_doc.root_document_id: if self.input_doc.root_document_id:
# If this is a new version of an existing document, we need # If this is a new version of an existing document, we need
@@ -722,7 +714,7 @@ class ConsumerPlugin(
# After everything is in the database, copy the files into # After everything is in the database, copy the files into
# place. If this fails, we'll also rollback the transaction. # place. If this fails, we'll also rollback the transaction.
with media_lock(): with FileLock(settings.MEDIA_LOCK):
generated_filename = generate_unique_filename(document) generated_filename = generate_unique_filename(document)
if ( if (
len(str(generated_filename)) len(str(generated_filename))
@@ -786,9 +778,10 @@ class ConsumerPlugin(
document.archive_path, document.archive_path,
) )
# Any filename follow-up from this save is deferred by # Don't save with the lock active. Saving will cause the file
# the scope above until after commit. # renaming logic to acquire the lock as well.
document.save(write_file_paths=True) # This triggers things like file renaming
document.save()
if document.root_document_id: if document.root_document_id:
document_updated.send( document_updated.send(
@@ -829,11 +822,6 @@ class ConsumerPlugin(
exception=e, 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.run_post_consume_script(document)
self.log.info(f"Document {document} consumption finished") self.log.info(f"Document {document} consumption finished")
@@ -846,6 +834,9 @@ class ConsumerPlugin(
document.id, document.id,
) )
# Return the most up to date fields
document.refresh_from_db()
return ConsumeFileSuccessResult(document_id=document.pk) return ConsumeFileSuccessResult(document_id=document.pk)
def _parse_title_placeholders(self, title: str) -> str: def _parse_title_placeholders(self, title: str) -> str:
+16 -9
View File
@@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
import abc import abc
import filecmp
import hashlib import hashlib
import json import json
import os import os
@@ -166,11 +167,18 @@ class DirectoryExportSink(ExportSink):
@staticmethod @staticmethod
def _content_unchanged(target: Path, new_bytes: bytes) -> bool: def _content_unchanged(target: Path, new_bytes: bytes) -> bool:
"""True if ``target`` already holds byte-identical content (BLAKE2b).""" """
return ( True if ``target`` already holds byte-identical content (BLAKE2b).
hashlib.blake2b(target.read_bytes()).hexdigest()
== hashlib.blake2b(new_bytes).hexdigest() The existing file is hashed in chunks rather than read into memory.
) """
if target.stat().st_size != len(new_bytes):
return False
with target.open("rb") as handle:
return (
hashlib.file_digest(handle, "blake2b").hexdigest()
== hashlib.blake2b(new_bytes).hexdigest()
)
def add_json(self, content: list | dict, arcname: str) -> None: def add_json(self, content: list | dict, arcname: str) -> None:
target = (self._target / arcname).resolve() target = (self._target / arcname).resolve()
@@ -214,10 +222,9 @@ class DirectoryExportSink(ExportSink):
def _commit_streamed_file(self, target: Path, tmp: Path) -> None: def _commit_streamed_file(self, target: Path, tmp: Path) -> None:
if target in self._snapshot: if target in self._snapshot:
self._snapshot.discard(target) self._snapshot.discard(target)
if self._compare_json and self._content_unchanged( # A streamed manifest can be very large, so compare the two files
target, # in chunks instead of reading them into memory
tmp.read_bytes(), if self._compare_json and filecmp.cmp(target, tmp, shallow=False):
):
tmp.unlink() tmp.unlink()
return return
tmp.rename(target) tmp.rename(target)
-480
View File
@@ -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)
+3 -3
View File
@@ -4,9 +4,9 @@ from dataclasses import dataclass
from email import message_from_bytes from email import message_from_bytes
from pathlib import Path from pathlib import Path
from django.conf import settings
from django.core.mail import EmailMessage from django.core.mail import EmailMessage
from filelock import FileLock
from documents.media_lock import media_lock
@dataclass(frozen=True) @dataclass(frozen=True)
@@ -48,7 +48,7 @@ def send_email(
used_filenames: set[str] = set() used_filenames: set[str] = set()
# Something could be renaming the file concurrently so it can't be attached # 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: for attachment in attachments:
filename = _get_unique_filename( filename = _get_unique_filename(
attachment.friendly_name, attachment.friendly_name,
@@ -18,11 +18,10 @@ from django.core import serializers
from django.core.management.base import CommandError from django.core.management.base import CommandError
from django.db import transaction from django.db import transaction
from django.utils import timezone from django.utils import timezone
from filelock import FileLock
from guardian.models import GroupObjectPermission from guardian.models import GroupObjectPermission
from guardian.models import UserObjectPermission from guardian.models import UserObjectPermission
from documents.media_lock import media_lock
if TYPE_CHECKING: if TYPE_CHECKING:
from collections.abc import Generator from collections.abc import Generator
@@ -331,7 +330,7 @@ class Command(CryptMixin, PaperlessCommand):
) )
# Prevent any ongoing changes in the documents while exporting # Prevent any ongoing changes in the documents while exporting
with media_lock(), sink: with FileLock(settings.MEDIA_LOCK), sink:
self.dump(sink) self.dump(sink)
def dump(self, sink: ExportSink) -> None: 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 import Model
from django.db.models.signals import m2m_changed from django.db.models.signals import m2m_changed
from django.db.models.signals import post_save from django.db.models.signals import post_save
from filelock import FileLock
from guardian.shortcuts import clear_ct_cache from guardian.shortcuts import clear_ct_cache
from documents.export.compression import compress_type_readable 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.file_handling import create_source_path_directory
from documents.management.commands.base import PaperlessCommand from documents.management.commands.base import PaperlessCommand
from documents.management.commands.mixins import CryptMixin from documents.management.commands.mixins import CryptMixin
from documents.media_lock import media_lock
from documents.models import Correspondent from documents.models import Correspondent
from documents.models import CustomField from documents.models import CustomField
from documents.models import CustomFieldInstance from documents.models import CustomFieldInstance
@@ -662,7 +662,7 @@ class Command(CryptMixin, PaperlessCommand):
else: else:
archive_path = None archive_path = None
with media_lock(): with FileLock(settings.MEDIA_LOCK):
if Path(document.source_path).is_file(): if Path(document.source_path).is_file():
raise FileExistsError(document.source_path) 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.", 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) bundle_target_path.parent.mkdir(parents=True, exist_ok=True)
copy_file_with_basic_stats( copy_file_with_basic_stats(
bundle_source_path, 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.management.commands.base import PaperlessCommand
from documents.models import Document from documents.models import Document
@@ -10,9 +11,5 @@ class Command(PaperlessCommand):
supports_multiprocessing = False supports_multiprocessing = False
def handle(self, *args, **options): def handle(self, *args, **options):
for document in self.track( for document in self.track(Document.objects.all(), description="Renaming..."):
# move_files_for_document handles a root's versions itself post_save.send(Document, instance=document, created=False)
Document.objects.filter(root_document__isnull=True).only("pk"),
description="Renaming...",
):
move_files_for_document(document.pk)
@@ -9,7 +9,6 @@ from rich.table import Table
from rich.text import Text from rich.text import Text
from documents.classifier import load_classifier from documents.classifier import load_classifier
from documents.file_moves import defer_file_moves
from documents.management.commands.base import PaperlessCommand from documents.management.commands.base import PaperlessCommand
from documents.models import Document from documents.models import Document
from documents.signals.handlers import set_correspondent from documents.signals.handlers import set_correspondent
@@ -274,63 +273,61 @@ class Command(PaperlessCommand):
description="Retagging...", description="Retagging...",
stats_renderer=render_stats, stats_renderer=render_stats,
): ):
# One file move per document, after all of its assignments. suggestion = DocumentSuggestion(document=document)
with defer_file_moves():
suggestion = DocumentSuggestion(document=document)
if do_correspondent: if do_correspondent:
correspondent = set_correspondent( correspondent = set_correspondent(
None, None,
document, document,
classifier=classifier, classifier=classifier,
replace=overwrite, replace=overwrite,
use_first=use_first, use_first=use_first,
dry_run=suggest, dry_run=suggest,
) )
if correspondent is not None: if correspondent is not None:
stats.correspondents += 1 stats.correspondents += 1
suggestion.correspondent = correspondent suggestion.correspondent = correspondent
if do_document_type: if do_document_type:
document_type = set_document_type( document_type = set_document_type(
None, None,
document, document,
classifier=classifier, classifier=classifier,
replace=overwrite, replace=overwrite,
use_first=use_first, use_first=use_first,
dry_run=suggest, dry_run=suggest,
) )
if document_type is not None: if document_type is not None:
stats.document_types += 1 stats.document_types += 1
suggestion.document_type = document_type suggestion.document_type = document_type
if do_tags: if do_tags:
tags_to_add, tags_to_remove = set_tags( tags_to_add, tags_to_remove = set_tags(
None, None,
document, document,
classifier=classifier, classifier=classifier,
replace=overwrite, replace=overwrite,
dry_run=suggest, dry_run=suggest,
) )
stats.tags_added += len(tags_to_add) stats.tags_added += len(tags_to_add)
stats.tags_removed += len(tags_to_remove) stats.tags_removed += len(tags_to_remove)
suggestion.tags_to_add = frozenset(tags_to_add) suggestion.tags_to_add = frozenset(tags_to_add)
suggestion.tags_to_remove = frozenset(tags_to_remove) suggestion.tags_to_remove = frozenset(tags_to_remove)
if do_storage_path: if do_storage_path:
storage_path = set_storage_path( storage_path = set_storage_path(
None, None,
document, document,
classifier=classifier, classifier=classifier,
replace=overwrite, replace=overwrite,
use_first=use_first, use_first=use_first,
dry_run=suggest, dry_run=suggest,
) )
if storage_path is not None: if storage_path is not None:
stats.storage_paths += 1 stats.storage_paths += 1
suggestion.storage_path = storage_path suggestion.storage_path = storage_path
stats.documents_processed += 1 stats.documents_processed += 1
if suggest: if suggest:
suggestions.append(suggestion) suggestions.append(suggestion)
-36
View File
@@ -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
-32
View File
@@ -2,7 +2,6 @@ import datetime
import uuid import uuid
from pathlib import Path from pathlib import Path
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from typing import Any
from typing import Final from typing import Final
import pathvalidate import pathvalidate
@@ -212,12 +211,6 @@ class StoragePath(MatchingModel):
class Document(SoftDeleteModel, ModelWithOwner): # type: ignore[django-manager-missing] class Document(SoftDeleteModel, ModelWithOwner): # type: ignore[django-manager-missing]
MAX_STORED_FILENAME_LENGTH: Final[int] = 1024 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) # Per-component limit of common filesystems (ext4, XFS, btrfs, ZFS, APFS)
MAX_PUBLIC_FILENAME_BYTES: Final[int] = 255 MAX_PUBLIC_FILENAME_BYTES: Final[int] = 255
@@ -429,31 +422,6 @@ class Document(SoftDeleteModel, ModelWithOwner): # type: ignore[django-manager-
res += f" {self.title}" res += f" {self.title}"
return res return res
def save(self, *, write_file_paths: bool = False, **kwargs: Any) -> 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.
"""
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)
def get_effective_barcodes(self) -> list["DocumentBarcode"]: def get_effective_barcodes(self) -> list["DocumentBarcode"]:
""" """
Returns the stored barcodes for the document, like Returns the stored barcodes for the document, like
+8 -9
View File
@@ -99,15 +99,14 @@ def build_pdfs(
f"{page_count} pages", f"{page_count} pages",
) )
for specs, make_dst in outputs: for specs, make_dst in outputs:
dst = pikepdf.new() with pikepdf.new() as dst:
for spec in specs: for spec in specs:
dst.pages.append(source.pages[spec.page - 1]) dst.pages.append(source.pages[spec.page - 1])
if spec.rotate: if spec.rotate:
dst.pages[-1].rotate(spec.rotate, relative=True) dst.pages[-1].rotate(spec.rotate, relative=True)
dst.remove_unreferenced_resources() dst.remove_unreferenced_resources()
path = make_dst() path = make_dst()
dst.save(path) dst.save(path)
dst.close()
written.append(path) written.append(path)
return written return written
+244 -32
View File
@@ -21,22 +21,25 @@ from channels.layers import get_channel_layer
from django.conf import settings from django.conf import settings
from django.contrib.auth.models import Group from django.contrib.auth.models import Group
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.db import DatabaseError
from django.db import close_old_connections from django.db import close_old_connections
from django.db import connections from django.db import connections
from django.db import models from django.db import models
from django.db.models import Q from django.db.models import Q
from django.dispatch import receiver from django.dispatch import receiver
from django.utils import timezone from django.utils import timezone
from filelock import FileLock
from rest_framework import serializers from rest_framework import serializers
from documents import matching from documents import matching
from documents.caching import clear_document_caches
from documents.caching import invalidate_llm_suggestions_cache from documents.caching import invalidate_llm_suggestions_cache
from documents.caching import invalidate_suggestions_cache from documents.caching import invalidate_suggestions_cache
from documents.data_models import ConsumableDocument 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_handling import delete_empty_directories
from documents.file_moves import move_files_for_document from documents.file_handling import generate_filename
from documents.file_moves import request_file_move from documents.file_handling import generate_unique_filename
from documents.media_lock import media_lock
from documents.models import Correspondent from documents.models import Correspondent
from documents.models import CustomField from documents.models import CustomField
from documents.models import CustomFieldInstance from documents.models import CustomFieldInstance
@@ -56,6 +59,7 @@ from documents.models import WorkflowTrigger
from documents.permissions import restrict_queryset_to_visible from documents.permissions import restrict_queryset_to_visible
from documents.plugins.helpers import DocumentsStatusManager from documents.plugins.helpers import DocumentsStatusManager
from documents.templating.utils import convert_format_str_to_template_format 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.utils import copy_file_with_basic_stats
from documents.workflows.actions import build_workflow_action_context from documents.workflows.actions import build_workflow_action_context
from documents.workflows.actions import execute_email_action 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 # see empty_trash in documents/tasks.py for signal handling
def cleanup_document_deletion(sender, instance, **kwargs) -> None: def cleanup_document_deletion(sender, instance, **kwargs) -> None:
with media_lock(): with FileLock(settings.MEDIA_LOCK):
if settings.EMPTY_TRASH_DIR: if settings.EMPTY_TRASH_DIR:
# Find a non-conflicting filename in case a document with the same # Find a non-conflicting filename in case a document with the same
# name was moved to trash earlier # 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: def _filename_template_uses_custom_fields(doc: Document) -> bool:
template = None template = None
if doc.storage_path is not None: if doc.storage_path is not None:
@@ -427,37 +442,235 @@ def update_filename_and_move_files(
instance: Document | CustomFieldInstance, instance: Document | CustomFieldInstance,
**kwargs, **kwargs,
) -> None: ) -> 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 isinstance(instance, CustomFieldInstance):
if not _filename_template_uses_custom_fields(instance.document): if not _filename_template_uses_custom_fields(instance.document):
return return
instance = instance.document 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 @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(): for cf_instance in custom_field.fields.select_related("document").iterator():
# Update the filename and move files if necessary # Update the filename and move files if necessary
if _filename_template_uses_custom_fields(cf_instance.document): update_filename_and_move_files(CustomFieldInstance, cf_instance)
move_files_for_document(cf_instance.document_id)
# should be disabled in /src/documents/management/commands/document_importer.py handle # should be disabled in /src/documents/management/commands/document_importer.py handle
+19 -70
View File
@@ -6,7 +6,6 @@ import zipfile
from collections.abc import Callable from collections.abc import Callable
from pathlib import Path from pathlib import Path
from tempfile import TemporaryDirectory from tempfile import TemporaryDirectory
from tempfile import mkstemp
from celery import Task from celery import Task
from celery import shared_task from celery import shared_task
@@ -17,6 +16,7 @@ from django.db import models
from django.db import transaction from django.db import transaction
from django.db.models.signals import post_save from django.db.models.signals import post_save
from django.utils import timezone from django.utils import timezone
from filelock import FileLock
from documents import sanity_checker from documents import sanity_checker
from documents.barcodes import BarcodePlugin from documents.barcodes import BarcodePlugin
@@ -42,7 +42,6 @@ from documents.double_sided import CollatePlugin
from documents.file_handling import create_source_path_directory from documents.file_handling import create_source_path_directory
from documents.file_handling import generate_unique_filename from documents.file_handling import generate_unique_filename
from documents.matching import prefilter_documents_by_workflowtrigger from documents.matching import prefilter_documents_by_workflowtrigger
from documents.media_lock import media_lock
from documents.models import Correspondent from documents.models import Correspondent
from documents.models import CustomFieldInstance from documents.models import CustomFieldInstance
from documents.models import Document from documents.models import Document
@@ -312,14 +311,9 @@ def sanity_check(*, raise_on_error: bool = True) -> str:
@shared_task @shared_task
def bulk_update_documents(document_ids) -> None: def bulk_update_documents(document_ids) -> None:
from documents.file_moves import flush_pending_file_moves
from documents.search import get_backend from documents.search import get_backend
document_ids = list(document_ids) 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 # 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 # versions of each document. Indexing re-queries and re-annotates its own
# copy via add_or_update_ids() below, after these signals (and any # copy via add_or_update_ids() below, after these signals (and any
@@ -330,32 +324,13 @@ def bulk_update_documents(document_ids) -> None:
for doc in documents: for doc in documents:
clear_document_caches(doc.pk) 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( document_updated.send(
sender=None, sender=None,
document=doc, document=doc,
logging_group=uuid.uuid4(), logging_group=uuid.uuid4(),
skip_ai_index=True, # bulk path calls update_llm_index once below skip_ai_index=True, # bulk path calls update_llm_index once below
) )
# Moves requested by workflows that document_updated ran. Moving per post_save.send(Document, instance=doc, created=False)
# document, rather than at the end of the task, keeps a long bulk
# edit making steady progress.
flush_pending_file_moves()
with get_backend().batch_update() as batch: with get_backend().batch_update() as batch:
batch.add_or_update_ids(document_ids) batch.add_or_update_ids(document_ids)
@@ -443,13 +418,7 @@ def update_document_content_maybe_archive_file(
thumbnail = parser.get_thumbnail(document.source_path, mime_type) thumbnail = parser.get_thumbnail(document.source_path, mime_type)
# media.lock first, then the transaction: never wait on media.lock with transaction.atomic():
# 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()
oldDocument = Document.objects.get(pk=document.pk) oldDocument = Document.objects.get(pk=document.pk)
if parser.get_archive_path(): if parser.get_archive_path():
checksum = compute_checksum(parser.get_archive_path()) checksum = compute_checksum(parser.get_archive_path())
@@ -514,10 +483,11 @@ def update_document_content_maybe_archive_file(
modified=timezone.now(), modified=timezone.now(),
) )
if parser.get_archive_path(): with FileLock(settings.MEDIA_LOCK):
create_source_path_directory(document.archive_path) if parser.get_archive_path():
shutil.move(parser.get_archive_path(), document.archive_path) create_source_path_directory(document.archive_path)
shutil.move(thumbnail, document.thumbnail_path) shutil.move(parser.get_archive_path(), document.archive_path)
shutil.move(thumbnail, document.thumbnail_path)
document.refresh_from_db() document.refresh_from_db()
logger.info( logger.info(
@@ -562,11 +532,7 @@ def empty_trash(doc_ids=None) -> None:
deleted_document_ids = list(documents.values_list("id", flat=True)) deleted_document_ids = list(documents.values_list("id", flat=True))
# Temporarily connect the cleanup handler # Temporarily connect the cleanup handler
models.signals.post_delete.connect(cleanup_document_deletion, sender=Document) models.signals.post_delete.connect(cleanup_document_deletion, sender=Document)
# media.lock before Django's delete transaction: post_delete runs documents.delete() # this is effectively a hard delete
# 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
logger.info(f"Deleted {len(deleted_document_ids)} documents from trash") logger.info(f"Deleted {len(deleted_document_ids)} documents from trash")
if settings.AUDIT_LOG_ENABLED: if settings.AUDIT_LOG_ENABLED:
@@ -596,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. 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( scheduled_workflows = get_workflows_for_trigger(
WorkflowTrigger.WorkflowTriggerType.SCHEDULED, WorkflowTrigger.WorkflowTriggerType.SCHEDULED,
) )
@@ -720,11 +684,6 @@ def check_scheduled_workflows() -> None:
workflow_to_run=workflow, workflow_to_run=workflow,
document=document, 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 # Scheduled workflows dont send document_updated signal, so send a websocket update here to ensure clients are updated
send_websocket_document_updated( send_websocket_document_updated(
sender=None, sender=None,
@@ -937,26 +896,25 @@ def build_share_link_bundle(bundle_id: int) -> None:
documents = list(bundle.documents.all().order_by("pk")) documents = list(bundle.documents.all().order_by("pk"))
_, temp_zip_path_str = mkstemp(suffix=".zip", dir=settings.SCRATCH_DIR)
temp_zip_path = Path(temp_zip_path_str)
try: try:
strategy_class = ( strategy_class = (
ArchiveOnlyStrategy ArchiveOnlyStrategy
if bundle.file_version == ShareLink.FileVersion.ARCHIVE if bundle.file_version == ShareLink.FileVersion.ARCHIVE
else OriginalsOnlyStrategy else OriginalsOnlyStrategy
) )
with zipfile.ZipFile(temp_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
strategy = strategy_class(zipf)
for document in documents:
strategy.add_document(document)
output_dir = settings.SHARE_LINK_BUNDLE_DIR output_dir = settings.SHARE_LINK_BUNDLE_DIR
output_dir.mkdir(parents=True, exist_ok=True) output_dir.mkdir(parents=True, exist_ok=True)
final_path = (output_dir / f"{bundle.slug}.zip").resolve() final_path = (output_dir / f"{bundle.slug}.zip").resolve()
if final_path.exists():
final_path.unlink() with TemporaryDirectory(dir=settings.SCRATCH_DIR) as tmp_dir:
shutil.move(temp_zip_path, final_path) temp_zip_path = Path(tmp_dir) / "bundle.zip"
with zipfile.ZipFile(temp_zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
strategy = strategy_class(zipf)
for document in documents:
strategy.add_document(document)
final_path.unlink(missing_ok=True)
shutil.move(temp_zip_path, final_path)
bundle.file_path = f"{bundle.slug}.zip" bundle.file_path = f"{bundle.slug}.zip"
bundle.size_bytes = final_path.stat().st_size bundle.size_bytes = final_path.stat().st_size
@@ -987,16 +945,7 @@ def build_share_link_bundle(bundle_id: int) -> None:
"timestamp": timezone.now().isoformat(), "timestamp": timezone.now().isoformat(),
} }
bundle.save(update_fields=["status", "last_error"]) bundle.save(update_fields=["status", "last_error"])
try:
temp_zip_path.unlink()
except OSError:
pass
raise raise
finally:
try:
temp_zip_path.unlink(missing_ok=True)
except OSError:
pass
@shared_task @shared_task
+78
View File
@@ -91,6 +91,84 @@ class TestDirectoryExportSink:
writer.close() writer.close()
assert json.loads((target / "manifest.json").read_text()) == [{"pk": 1}] assert json.loads((target / "manifest.json").read_text()) == [{"pk": 1}]
@pytest.mark.parametrize(
("existing", "unchanged"),
[
pytest.param(_dumps({"version": "x"}), True, id="identical"),
pytest.param(_dumps({"version": "y"}), False, id="same-size-different"),
],
)
def test_add_json_compare_json(
self,
tmp_path: Path,
*,
existing: str,
unchanged: bool,
) -> None:
target: Path = tmp_path / "out"
target.mkdir()
(target / "metadata.json").write_text(existing)
os.utime(target / "metadata.json", (1, 1))
with DirectoryExportSink(
target,
compare_checksums=False,
compare_json=True,
delete=False,
) as sink:
sink.add_json({"version": "x"}, "metadata.json")
assert json.loads((target / "metadata.json").read_text()) == (
json.loads(existing) if unchanged else {"version": "x"}
)
# An unchanged file is not rewritten, so its mtime is left alone
assert ((target / "metadata.json").stat().st_mtime == 1) is unchanged
@pytest.mark.parametrize(
("existing", "unchanged"),
[
pytest.param([{"pk": 1}], True, id="identical"),
pytest.param([{"pk": 2}], False, id="changed"),
],
)
def test_stream_compare_json(
self,
tmp_path: Path,
*,
existing: list[dict],
unchanged: bool,
) -> None:
target: Path = tmp_path / "out"
target.mkdir()
# Write the existing manifest the same way the sink does
with DirectoryExportSink(
target,
compare_checksums=False,
compare_json=False,
delete=False,
) as sink:
with sink.stream("manifest.json") as handle:
writer: StreamingManifestWriter = StreamingManifestWriter(handle)
for record in existing:
writer.write_record(record)
writer.close()
os.utime(target / "manifest.json", (1, 1))
with DirectoryExportSink(
target,
compare_checksums=False,
compare_json=True,
delete=False,
) as sink:
with sink.stream("manifest.json") as handle:
writer = StreamingManifestWriter(handle)
writer.write_record({"pk": 1})
writer.close()
assert json.loads((target / "manifest.json").read_text()) == (
existing if unchanged else [{"pk": 1}]
)
assert ((target / "manifest.json").stat().st_mtime == 1) is unchanged
assert not (target / "manifest.json.tmp").exists()
def test_add_file_skips_when_size_and_mtime_match( def test_add_file_skips_when_size_and_mtime_match(
self, self,
tmp_path: Path, tmp_path: Path,
+3 -3
View File
@@ -743,7 +743,7 @@ class TestPDFActions(DirectoriesMixin, TestCase):
mime_type="application/pdf", mime_type="application/pdf",
) )
self.doc1.archive_filename = sample1_archive self.doc1.archive_filename = sample1_archive
self.doc1.save(write_file_paths=True) self.doc1.save()
self.doc2 = Document.objects.create( self.doc2 = Document.objects.create(
checksum="B", checksum="B",
title="B", title="B",
@@ -753,7 +753,7 @@ class TestPDFActions(DirectoriesMixin, TestCase):
created=date(2023, 1, 2), created=date(2023, 1, 2),
) )
self.doc2.archive_filename = sample2_archive self.doc2.archive_filename = sample2_archive
self.doc2.save(write_file_paths=True) self.doc2.save()
self.doc3 = Document.objects.create( self.doc3 = Document.objects.create(
checksum="C", checksum="C",
title="C", title="C",
@@ -778,7 +778,7 @@ class TestPDFActions(DirectoriesMixin, TestCase):
created=date(2023, 1, 3), created=date(2023, 1, 3),
) )
self.img_doc.archive_filename = img_doc_archive self.img_doc.archive_filename = img_doc_archive
self.img_doc.save(write_file_paths=True) self.img_doc.save()
@staticmethod @staticmethod
def fake_decrypt( def fake_decrypt(
+15 -4
View File
@@ -1,3 +1,5 @@
import hashlib
import hmac
import pickle import pickle
import warnings import warnings
from datetime import UTC from datetime import UTC
@@ -31,6 +33,7 @@ from documents.models import Tag
from documents.tests.helpers import dummy_preprocess from documents.tests.helpers import dummy_preprocess
from paperless.settings import CLASSIFIER_LANGUAGES from paperless.settings import CLASSIFIER_LANGUAGES
from paperless.signed_pickle import HMAC_SIZE from paperless.signed_pickle import HMAC_SIZE
from paperless.signed_pickle import compute_signature
from paperless.signed_pickle import signed_pickle_dumps from paperless.signed_pickle import signed_pickle_dumps
from paperless_testing.dirs import DirectoriesMixin from paperless_testing.dirs import DirectoriesMixin
from paperless_testing.factories import DocumentFactory from paperless_testing.factories import DocumentFactory
@@ -423,7 +426,7 @@ class TestClassifier(DirectoriesMixin, TestCase):
- The ClassifierModelCorruptError is raised - The ClassifierModelCorruptError is raised
""" """
garbage_data = b"this is not valid pickle data" garbage_data = b"this is not valid pickle data"
signature = DocumentClassifier._compute_hmac(garbage_data) signature = compute_signature(garbage_data)
Path(settings.MODEL_FILE).write_bytes(signature + garbage_data) Path(settings.MODEL_FILE).write_bytes(signature + garbage_data)
with self.assertRaises(ClassifierModelCorruptError): with self.assertRaises(ClassifierModelCorruptError):
@@ -944,9 +947,17 @@ class TestClassifierSave:
classifier.save() classifier.save()
raw = model_file.read_bytes() raw = model_file.read_bytes()
signature = raw[: DocumentClassifier.HMAC_SIZE] signature = raw[:HMAC_SIZE]
data = raw[DocumentClassifier.HMAC_SIZE :] data = raw[HMAC_SIZE:]
assert signature == DocumentClassifier._compute_hmac(data) # Computed independently so the on-disk format stays what is documented
assert (
signature
== hmac.new(
settings.SECRET_KEY.encode(),
data,
hashlib.sha256,
).digest()
)
# A pickle opens with the PROTO opcode followed by the protocol number # A pickle opens with the PROTO opcode followed by the protocol number
assert data[:2] == bytes([pickle.PROTO[0], pickle.HIGHEST_PROTOCOL]) assert data[:2] == bytes([pickle.PROTO[0], pickle.HIGHEST_PROTOCOL])
assert pickle.loads(data)[:3] == ( assert pickle.loads(data)[:3] == (
+1 -160
View File
@@ -27,10 +27,6 @@ from documents.models import Document
from documents.models import DocumentType from documents.models import DocumentType
from documents.models import StoragePath from documents.models import StoragePath
from documents.models import Tag 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.parsers import ParseError
from documents.plugins.helpers import ProgressStatusOptions from documents.plugins.helpers import ProgressStatusOptions
from documents.tasks import sanity_check 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 TagFactory
from paperless_testing.factories import UserFactory from paperless_testing.factories import UserFactory
from paperless_testing.fakes.progress import FakeProgressManager 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.permissions import grant_object
from paperless_testing.samples import MULTI_PAGE_DIGITAL_PDF from paperless_testing.samples import MULTI_PAGE_DIGITAL_PDF
from paperless_testing.samples import MULTI_PAGE_IMAGES_PDF from paperless_testing.samples import MULTI_PAGE_IMAGES_PDF
@@ -226,160 +221,6 @@ class TestConsumer(
shutil.copy(src, dst) shutil.copy(src, dst)
return 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( @override_settings(
FILENAME_FORMAT=None, FILENAME_FORMAT=None,
TIME_ZONE="America/Chicago", TIME_ZONE="America/Chicago",
@@ -909,7 +750,7 @@ class TestConsumer(
FILENAME_FORMAT="{correspondent}/{title}", FILENAME_FORMAT="{correspondent}/{title}",
ARCHIVE_FILE_GENERATION="always", 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: def testFilenameHandlingUnstableFormat(self, m) -> None:
filenames = ["this", "that", "now this", "i cannot decide"] filenames = ["this", "that", "now this", "i cannot decide"]
+25 -23
View File
@@ -92,7 +92,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
# Ensure that filename is properly generated # Ensure that filename is properly generated
self.assertEqual(document.filename, Path("none/none.pdf")) 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 # test that creating dirs for the source_path creates the correct directory
create_source_path_directory(document.source_path) create_source_path_directory(document.source_path)
@@ -190,7 +190,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
# Set a correspondent and save the document # Set a correspondent and save the document
document.correspondent = Correspondent.objects.get_or_create(name="test")[0] document.correspondent = Correspondent.objects.get_or_create(name="test")[0]
document.save(write_file_paths=True) document.save()
# Check proper handling of files # Check proper handling of files
self.assertIsFile( self.assertIsFile(
@@ -232,7 +232,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
disable_auditlog(), disable_auditlog(),
): ):
m.side_effect = DatabaseError() m.side_effect = DatabaseError()
document.save(write_file_paths=True) document.save()
# Check proper handling of files # Check proper handling of files
self.assertIsFile(document.source_path) self.assertIsFile(document.source_path)
@@ -336,7 +336,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
# Ensure that filename is properly generated # Ensure that filename is properly generated
document.filename = generate_filename(document) document.filename = generate_filename(document)
document.save(write_file_paths=True) document.save()
self.assertEqual(document.filename, "none/none.pdf") self.assertEqual(document.filename, "none/none.pdf")
create_source_path_directory(document.source_path) create_source_path_directory(document.source_path)
@@ -362,7 +362,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
# Ensure that filename is properly generated # Ensure that filename is properly generated
document.filename = generate_filename(document) document.filename = generate_filename(document)
document.save(write_file_paths=True) document.save()
self.assertEqual(document.filename, "none/none.pdf") self.assertEqual(document.filename, "none/none.pdf")
create_source_path_directory(document.source_path) create_source_path_directory(document.source_path)
@@ -385,7 +385,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
document.save() document.save()
document.filename = generate_filename(document) document.filename = generate_filename(document)
document.save(write_file_paths=True) document.save()
create_source_path_directory(document.source_path) create_source_path_directory(document.source_path)
Path(document.source_path).touch() Path(document.source_path).touch()
document.delete() document.delete()
@@ -421,7 +421,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
# Set a correspondent and save the document # Set a correspondent and save the document
document.correspondent = Correspondent.objects.get_or_create(name="test")[0] document.correspondent = Correspondent.objects.get_or_create(name="test")[0]
document.save(write_file_paths=True) document.save()
# Check proper handling of files # Check proper handling of files
self.assertIsDir(settings.ORIGINALS_DIR / "test") self.assertIsDir(settings.ORIGINALS_DIR / "test")
@@ -476,7 +476,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
def test_filename_relative(self) -> None: def test_filename_relative(self) -> None:
doc = Document.objects.create(title="doc1", mime_type="application/pdf") doc = Document.objects.create(title="doc1", mime_type="application/pdf")
doc.filename = generate_filename(doc) doc.filename = generate_filename(doc)
doc.save(write_file_paths=True) doc.save()
self.assertEqual( self.assertEqual(
doc.source_path, doc.source_path,
@@ -532,7 +532,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
# Ensure that filename is properly generated # Ensure that filename is properly generated
document.filename = generate_filename(document) document.filename = generate_filename(document)
document.save(write_file_paths=True) document.save()
self.assertEqual(document.filename, "none/none/none.pdf") self.assertEqual(document.filename, "none/none/none.pdf")
create_source_path_directory(document.source_path) create_source_path_directory(document.source_path)
Path(document.source_path).touch() Path(document.source_path).touch()
@@ -620,13 +620,13 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
Path(document.source_path).touch() Path(document.source_path).touch()
Path(document2.source_path).touch() Path(document2.source_path).touch()
document.filename = "0000001.pdf" document.filename = "0000001.pdf"
document.save(write_file_paths=True) document.save()
self.assertIsFile(document.source_path) self.assertIsFile(document.source_path)
self.assertEqual(document.filename, "qwe.pdf") self.assertEqual(document.filename, "qwe.pdf")
document2.filename = "0000002.pdf" document2.filename = "0000002.pdf"
document2.save(write_file_paths=True) document2.save()
self.assertIsFile(document.source_path) self.assertIsFile(document.source_path)
self.assertEqual(document2.filename, "qwe_01.pdf") self.assertEqual(document2.filename, "qwe_01.pdf")
@@ -656,17 +656,19 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
self.assertEqual(document2.filename, "qwe.pdf") self.assertEqual(document2.filename, "qwe.pdf")
@override_settings(FILENAME_FORMAT="{title}") @override_settings(FILENAME_FORMAT="{title}")
@mock.patch("documents.file_moves.Document.global_objects.filter") @mock.patch("documents.signals.handlers.Document.objects.filter")
@mock.patch("documents.file_moves.shutil.move") @mock.patch("documents.signals.handlers.shutil.move")
def test_no_move_only_save(self, mock_move, mock_filter) -> None: def test_no_move_only_save(self, mock_move, mock_filter) -> None:
""" """
GIVEN: GIVEN:
- A document with a filename - A document with a filename
- The document is saved
- The filename is not changed
WHEN: WHEN:
- The document is saved without a change that affects its path - The document is saved
THEN: THEN:
- The document modified date is updated by the save itself - The document modified date is updated
- The file is not moved and the mover writes nothing - The document is not moved
""" """
with disable_auditlog(): with disable_auditlog():
doc = Document.objects.create( doc = Document.objects.create(
@@ -684,7 +686,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
doc.save() doc.save()
doc.refresh_from_db() doc.refresh_from_db()
mock_filter.assert_not_called() mock_filter.assert_called()
self.assertNotEqual(original_modified, doc.modified) self.assertNotEqual(original_modified, doc.modified)
mock_move.assert_not_called() mock_move.assert_not_called()
@@ -692,7 +694,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
FILENAME_FORMAT="{{title}}_{{custom_fields|get_cf_value('test')}}", FILENAME_FORMAT="{{title}}_{{custom_fields|get_cf_value('test')}}",
CELERY_TASK_ALWAYS_EAGER=True, 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: def test_select_cf_updated(self, m) -> None:
""" """
GIVEN: GIVEN:
@@ -2043,7 +2045,7 @@ class TestCustomFieldFilenameUpdates(
Path(self.doc.source_path).parent.mkdir(parents=True, exist_ok=True) Path(self.doc.source_path).parent.mkdir(parents=True, exist_ok=True)
Path(self.doc.source_path).touch() 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 m.side_effect = generate_unique_filename
self.cfi.value_text = "updated" self.cfi.value_text = "updated"
self.cfi.save() 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).parent.mkdir(parents=True, exist_ok=True)
Path(self.doc.source_path).touch() 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 m.side_effect = generate_unique_filename
self.cfi.value_text = "updated" self.cfi.value_text = "updated"
self.cfi.save() self.cfi.save()
@@ -2143,7 +2145,7 @@ def test_refresh_failure_surfaces_database_error(
GIVEN: GIVEN:
- A document with a stored filename - A document with a stored filename
WHEN: 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: THEN:
- The database error is raised, not an unbound variable error from the rollback - 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 ( with (
mock.patch.object( mock.patch.object(
Document.global_objects, Document,
"get", "refresh_from_db",
side_effect=DatabaseError("database is locked"), side_effect=DatabaseError("database is locked"),
), ),
pytest.raises(DatabaseError, match="database is locked"), pytest.raises(DatabaseError, match="database is locked"),
File diff suppressed because it is too large. Load diff
+1 -61
View File
@@ -18,13 +18,11 @@ if TYPE_CHECKING:
from pytest_mock import MockerFixture from pytest_mock import MockerFixture
from documents.file_handling import generate_filename from documents.file_handling import generate_filename
from documents.file_moves import move_files_for_document
from documents.models import Document from documents.models import Document
from documents.tasks import update_document_content_maybe_archive_file from documents.tasks import update_document_content_maybe_archive_file
from paperless_testing.assertions import FileSystemAssertsMixin from paperless_testing.assertions import FileSystemAssertsMixin
from paperless_testing.dirs import DirectoriesMixin from paperless_testing.dirs import DirectoriesMixin
from paperless_testing.factories import DocumentFactory from paperless_testing.factories import DocumentFactory
from paperless_testing.locks import record_media_lock_acquisitions
from paperless_testing.samples import SIMPLE_DIGITAL_PDF from paperless_testing.samples import SIMPLE_DIGITAL_PDF
sample_file: Path = 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.assertTrue(filecmp.cmp(sample_file, doc.source_path))
self.assertEqual(doc.archive_filename, "none/A.pdf") 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: def test_unknown_mime_type(self) -> None:
doc = self.make_models() doc = self.make_models()
doc.mime_type = "sdgfh" doc.mime_type = "sdgfh"
@@ -260,7 +236,7 @@ class TestRenamer(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
doc = Document.objects.create(title="test", mime_type="image/jpeg") doc = Document.objects.create(title="test", mime_type="image/jpeg")
doc.filename = generate_filename(doc) doc.filename = generate_filename(doc)
doc.archive_filename = generate_filename(doc, archive_filename=True) doc.archive_filename = generate_filename(doc, archive_filename=True)
doc.save(write_file_paths=True) doc.save()
Path(doc.source_path).touch() Path(doc.source_path).touch()
Path(doc.archive_path).touch() Path(doc.archive_path).touch()
@@ -277,42 +253,6 @@ class TestRenamer(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
self.assertIsFile(doc2.source_path) self.assertIsFile(doc2.source_path)
self.assertIsFile(doc2.archive_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 @pytest.mark.management
class TestCreateClassifier: class TestCreateClassifier:
@@ -4,13 +4,10 @@ Tests for the document_retagger management command.
from __future__ import annotations from __future__ import annotations
from typing import TYPE_CHECKING
import pytest import pytest
from django.core.management import call_command from django.core.management import call_command
from django.core.management.base import CommandError from django.core.management.base import CommandError
from documents.file_moves import _active_collector
from documents.models import Correspondent from documents.models import Correspondent
from documents.models import Document from documents.models import Document
from documents.models import DocumentType 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 StoragePathFactory
from paperless_testing.factories import TagFactory 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 # Module-level type aliases
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -493,69 +484,3 @@ class TestRetaggerEdgeCases(DirectoriesMixin):
assert d_first.tags.count() == 0 assert d_first.tags.count() == 0
assert d_unrelated.tags.count() == 2 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()
-121
View 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]
-101
View File
@@ -1,7 +1,4 @@
import pytest 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 Correspondent
from documents.models import Document from documents.models import Document
@@ -25,101 +22,3 @@ class TestDocument:
assert Correspondent.objects.count() == 0 assert Correspondent.objects.count() == 0
assert Document.objects.count() == 1 assert Document.objects.count() == 1
assert Document.objects.first().correspondent is None 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()
+2 -2
View File
@@ -129,7 +129,7 @@ class TestCheckSanityOriginal:
class TestCheckSanityArchive: class TestCheckSanityArchive:
def test_checksum_without_filename(self, sample_doc: Document) -> None: def test_checksum_without_filename(self, sample_doc: Document) -> None:
sample_doc.archive_filename = None sample_doc.archive_filename = None
sample_doc.save(write_file_paths=True) sample_doc.save()
messages = check_sanity() messages = check_sanity()
assert messages.has_error assert messages.has_error
assert any( assert any(
@@ -182,7 +182,7 @@ class TestCheckSanityArchive:
Path(sample_doc.archive_path).unlink() Path(sample_doc.archive_path).unlink()
sample_doc.archive_checksum = None sample_doc.archive_checksum = None
sample_doc.archive_filename = None sample_doc.archive_filename = None
sample_doc.save(write_file_paths=True) sample_doc.save()
messages = check_sanity() messages = check_sanity()
assert not messages.has_error assert not messages.has_error
+3 -11
View File
@@ -366,7 +366,7 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
def _write_document_file(self, *, archive: bool, content: bytes) -> Path: def _write_document_file(self, *, archive: bool, content: bytes) -> Path:
if archive: if archive:
self.document.archive_filename = f"{self.document.pk:07}.pdf" 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 path = self.document.archive_path
assert path is not None assert path is not None
else: else:
@@ -434,13 +434,9 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
"documents.tasks.OriginalsOnlyStrategy.add_document", "documents.tasks.OriginalsOnlyStrategy.add_document",
side_effect=RuntimeError("zip failure"), side_effect=RuntimeError("zip failure"),
), ),
mock.patch("pathlib.Path.unlink") as unlink_mock, self.assertRaises(RuntimeError),
): ):
unlink_mock.side_effect = [OSError("unlink"), OSError("unlink-finally")] + [ build_share_link_bundle(bundle.pk)
None,
] * 5
with self.assertRaises(RuntimeError):
build_share_link_bundle(bundle.pk)
bundle.refresh_from_db() bundle.refresh_from_db()
self.assertEqual(bundle.status, ShareLinkBundle.Status.FAILED) self.assertEqual(bundle.status, ShareLinkBundle.Status.FAILED)
@@ -448,10 +444,6 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
assert isinstance(bundle.last_error, dict) assert isinstance(bundle.last_error, dict)
self.assertEqual(bundle.last_error.get("message"), "zip failure") self.assertEqual(bundle.last_error.get("message"), "zip failure")
self.assertEqual(bundle.last_error.get("exception_type"), "RuntimeError") self.assertEqual(bundle.last_error.get("exception_type"), "RuntimeError")
scratch_zips = list(Path(settings.SCRATCH_DIR).glob("*.zip"))
self.assertTrue(scratch_zips)
for path in scratch_zips:
path.unlink(missing_ok=True)
def test_build_share_link_bundle_missing_bundle_noop(self) -> None: def test_build_share_link_bundle_missing_bundle_noop(self) -> None:
# Should not raise when bundle does not exist # Should not raise when bundle does not exist
+3 -6
View File
@@ -887,8 +887,8 @@ class TestSavedZoneExtraction:
WHEN: WHEN:
- Zone extraction runs - Zone extraction runs
THEN: THEN:
- The only on-commit callback is the deferred file move; reindexing - No on-commit callbacks are registered; finishing is left to the
and other finishing is left to the caller caller
""" """
make_zone(template, "Title") make_zone(template, "Title")
mock_zone_ocr_run.return_value = subprocess.CompletedProcess( mock_zone_ocr_run.return_value = subprocess.CompletedProcess(
@@ -900,10 +900,7 @@ class TestSavedZoneExtraction:
with django_capture_on_commit_callbacks() as callbacks: with django_capture_on_commit_callbacks() as callbacks:
run_zone_extraction(document, templates=[template]) run_zone_extraction(document, templates=[template])
assert all( assert callbacks == []
callback.__qualname__.startswith("request_file_move")
for callback in callbacks
)
def test_document_run_renders_each_page_once_across_templates( def test_document_run_renders_each_page_once_across_templates(
self, self,
+9 -5
View File
@@ -24,28 +24,32 @@ def uri_validator(value: str, allowed_schemes: set[str] | None = None) -> None:
parts = urlparse(value) parts = urlparse(value)
if not parts.scheme: if not parts.scheme:
raise ValidationError( raise ValidationError(
_(f"Unable to parse URI {value}, missing scheme"), _("Unable to parse URI %(value)s, missing scheme"),
params={"value": value}, params={"value": value},
) )
elif not parts.netloc and not parts.path: elif not parts.netloc and not parts.path:
raise ValidationError( raise ValidationError(
_(f"Unable to parse URI {value}, missing net location or path"), _("Unable to parse URI %(value)s, missing net location or path"),
params={"value": value}, params={"value": value},
) )
if allowed_schemes and parts.scheme not in allowed_schemes: if allowed_schemes and parts.scheme not in allowed_schemes:
raise ValidationError( raise ValidationError(
_( _(
f"URI scheme '{parts.scheme}' is not allowed. Allowed schemes: {', '.join(allowed_schemes)}", "URI scheme '%(scheme)s' is not allowed. Allowed schemes: %(allowed)s",
), ),
params={"value": value, "scheme": parts.scheme}, params={
"value": value,
"scheme": parts.scheme,
"allowed": ", ".join(sorted(allowed_schemes)),
},
) )
except ValidationError: except ValidationError:
raise raise
except Exception as e: except Exception as e:
raise ValidationError( raise ValidationError(
_(f"Unable to parse URI {value}"), _("Unable to parse URI %(value)s"),
params={"value": value}, params={"value": value},
) from e ) from e
-3
View File
@@ -134,7 +134,6 @@ from documents.data_models import ConsumableDocument
from documents.data_models import DocumentMetadataOverrides from documents.data_models import DocumentMetadataOverrides
from documents.data_models import DocumentSource from documents.data_models import DocumentSource
from documents.file_handling import format_filename 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 CorrespondentFilterSet
from documents.filters import CustomFieldFilterSet from documents.filters import CustomFieldFilterSet
from documents.filters import DocumentFilterSet from documents.filters import DocumentFilterSet
@@ -1310,8 +1309,6 @@ class DocumentViewSet(
) )
serializer.is_valid(raise_exception=True) serializer.is_valid(raise_exception=True)
self.perform_update(serializer) 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: if content_updated and content_doc.id != root_doc.id:
content_doc.content = ( content_doc.content = (
+55 -39
View File
@@ -2,7 +2,7 @@ msgid ""
msgstr "" msgstr ""
"Project-Id-Version: paperless-ngx\n" "Project-Id-Version: paperless-ngx\n"
"Report-Msgid-Bugs-To: \n" "Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-11-26 22:28+0000\n" "POT-Creation-Date: 2026-11-27 02:54+0000\n"
"PO-Revision-Date: 2022-02-17 04:17\n" "PO-Revision-Date: 2022-02-17 04:17\n"
"Last-Translator: \n" "Last-Translator: \n"
"Language-Team: English\n" "Language-Team: English\n"
@@ -2168,8 +2168,24 @@ msgstr ""
msgid "As a final step, please complete the following form:" msgid "As a final step, please complete the following form:"
msgstr "" msgstr ""
#: documents/validators.py:27
#, python-format
msgid "Unable to parse URI %(value)s, missing scheme"
msgstr ""
#: documents/validators.py:32
#, python-format
msgid "Unable to parse URI %(value)s, missing net location or path"
msgstr ""
#: documents/validators.py:39 #: documents/validators.py:39
msgid ", " #, python-format
msgid "URI scheme '%(scheme)s' is not allowed. Allowed schemes: %(allowed)s"
msgstr ""
#: documents/validators.py:52
#, python-format
msgid "Unable to parse URI %(value)s"
msgstr "" msgstr ""
#: documents/views.py:327 #: documents/views.py:327
@@ -2497,151 +2513,151 @@ msgstr ""
msgid "paperless application settings" msgid "paperless application settings"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:588 #: paperless/settings/__init__.py:595
msgid "English (US)" msgid "English (US)"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:589 #: paperless/settings/__init__.py:596
msgid "Arabic" msgid "Arabic"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:590 #: paperless/settings/__init__.py:597
msgid "Afrikaans" msgid "Afrikaans"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:591 #: paperless/settings/__init__.py:598
msgid "Belarusian" msgid "Belarusian"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:592 #: paperless/settings/__init__.py:599
msgid "Bulgarian" msgid "Bulgarian"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:593 #: paperless/settings/__init__.py:600
msgid "Catalan" msgid "Catalan"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:594 #: paperless/settings/__init__.py:601
msgid "Czech" msgid "Czech"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:595 #: paperless/settings/__init__.py:602
msgid "Danish" msgid "Danish"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:596 #: paperless/settings/__init__.py:603
msgid "German" msgid "German"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:597 #: paperless/settings/__init__.py:604
msgid "Greek" msgid "Greek"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:598 #: paperless/settings/__init__.py:605
msgid "English (GB)" msgid "English (GB)"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:599 #: paperless/settings/__init__.py:606
msgid "Spanish" msgid "Spanish"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:600 #: paperless/settings/__init__.py:607
msgid "Persian" msgid "Persian"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:601 #: paperless/settings/__init__.py:608
msgid "Finnish" msgid "Finnish"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:602 #: paperless/settings/__init__.py:609
msgid "French" msgid "French"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:603 #: paperless/settings/__init__.py:610
msgid "Hungarian" msgid "Hungarian"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:604 #: paperless/settings/__init__.py:611
msgid "Indonesian" msgid "Indonesian"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:605 #: paperless/settings/__init__.py:612
msgid "Italian" msgid "Italian"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:606 #: paperless/settings/__init__.py:613
msgid "Japanese" msgid "Japanese"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:607 #: paperless/settings/__init__.py:614
msgid "Korean" msgid "Korean"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:608 #: paperless/settings/__init__.py:615
msgid "Luxembourgish" msgid "Luxembourgish"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:609 #: paperless/settings/__init__.py:616
msgid "Norwegian" msgid "Norwegian"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:610 #: paperless/settings/__init__.py:617
msgid "Dutch" msgid "Dutch"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:611 #: paperless/settings/__init__.py:618
msgid "Polish" msgid "Polish"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:612 #: paperless/settings/__init__.py:619
msgid "Portuguese (Brazil)" msgid "Portuguese (Brazil)"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:613 #: paperless/settings/__init__.py:620
msgid "Portuguese" msgid "Portuguese"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:614 #: paperless/settings/__init__.py:621
msgid "Romanian" msgid "Romanian"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:615 #: paperless/settings/__init__.py:622
msgid "Russian" msgid "Russian"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:616 #: paperless/settings/__init__.py:623
msgid "Slovak" msgid "Slovak"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:617 #: paperless/settings/__init__.py:624
msgid "Slovenian" msgid "Slovenian"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:618 #: paperless/settings/__init__.py:625
msgid "Serbian" msgid "Serbian"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:619 #: paperless/settings/__init__.py:626
msgid "Swedish" msgid "Swedish"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:620 #: paperless/settings/__init__.py:627
msgid "Turkish" msgid "Turkish"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:621 #: paperless/settings/__init__.py:628
msgid "Ukrainian" msgid "Ukrainian"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:622 #: paperless/settings/__init__.py:629
msgid "Vietnamese" msgid "Vietnamese"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:623 #: paperless/settings/__init__.py:630
msgid "Chinese Simplified" msgid "Chinese Simplified"
msgstr "" msgstr ""
#: paperless/settings/__init__.py:624 #: paperless/settings/__init__.py:631
msgid "Chinese Traditional" msgid "Chinese Traditional"
msgstr "" msgstr ""
+1 -23
View File
@@ -1,7 +1,6 @@
import os import os
from celery import Celery from celery import Celery
from celery.contrib.django.task import DjangoTask
from celery.signals import worker_process_init from celery.signals import worker_process_init
from kombu.serialization import register from kombu.serialization import register
@@ -27,28 +26,7 @@ register(
content_encoding="binary", content_encoding="binary",
) )
app = Celery("paperless")
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)
# Using a string here means the worker doesn't have to serialize # Using a string here means the worker doesn't have to serialize
# the configuration object to child processes. # the configuration object to child processes.
-34
View File
@@ -1,5 +1,3 @@
from asgiref.sync import iscoroutinefunction
from asgiref.sync import markcoroutinefunction
from compression_middleware.middleware import CompressionMiddleware from compression_middleware.middleware import CompressionMiddleware
from django.conf import settings from django.conf import settings
@@ -32,35 +30,3 @@ class ApiVersionMiddleware:
response["X-Version"] = version.__full_version_str__ response["X-Version"] = version.__full_version_str__
return response 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)
+1 -1
View File
@@ -566,7 +566,7 @@ class MailDocumentParser:
# If no HTML content, create the PDF from the message. # If no HTML content, create the PDF from the message.
# Otherwise, create 2 PDFs and merge them with Gotenberg. # Otherwise, create 2 PDFs and merge them with Gotenberg.
if not mail_message.html: if not mail_message.html:
archive_path.write_bytes(mail_pdf_file.read_bytes()) shutil.copyfile(mail_pdf_file, archive_path)
else: else:
pdf_of_html_content = self.generate_pdf_from_html( pdf_of_html_content = self.generate_pdf_from_html(
mail_message.html, mail_message.html,
+1 -1
View File
@@ -443,7 +443,7 @@ class RasterisedDocumentParser:
self.log.warning( self.log.warning(
f"PDF/A metadata stamping failed ({e!s}); falling back to plain PDF.", f"PDF/A metadata stamping failed ({e!s}); falling back to plain PDF.",
) )
pdfa_path.write_bytes(plain_pdf_path.read_bytes()) shutil.copyfile(plain_pdf_path, pdfa_path)
return pdfa_path return pdfa_path
+4 -3
View File
@@ -364,13 +364,14 @@ def extract_pdf_metadata(
namespace_pattern = re.compile(r"\{(.*)\}(.*)") namespace_pattern = re.compile(r"\{(.*)\}(.*)")
try: try:
pdf = pikepdf.open(document_path) with pikepdf.open(document_path) as pdf:
meta = pdf.open_metadata() meta = pdf.open_metadata()
items = list(meta.items())
except Exception as e: except Exception as e:
_log.warning("Could not open PDF metadata for %s: %s", document_path, e) _log.warning("Could not open PDF metadata for %s: %s", document_path, e)
return [] return []
for key, value in meta.items(): for key, value in items:
if isinstance(value, list): if isinstance(value, list):
value = " ".join(str(e) for e in value) value = " ".join(str(e) for e in value)
value = str(value) value = str(value)
+1 -4
View File
@@ -296,9 +296,8 @@ class ApplicationConfigurationSerializer(
return super().update(instance, validated_data) return super().update(instance, validated_data)
def _sanitize_raster_image(self, file: UploadedFile) -> UploadedFile: def _sanitize_raster_image(self, file: UploadedFile) -> UploadedFile:
try: with Image.open(file) as image:
data = BytesIO() data = BytesIO()
image = Image.open(file)
image.save(data, format=image.format) image.save(data, format=image.format)
data.seek(0) data.seek(0)
@@ -310,8 +309,6 @@ class ApplicationConfigurationSerializer(
size=data.getbuffer().nbytes, size=data.getbuffer().nbytes,
charset=getattr(file, "charset", None), charset=getattr(file, "charset", None),
) )
finally:
image.close()
def validate_app_logo(self, file: UploadedFile): def validate_app_logo(self, file: UploadedFile):
""" """
+7 -1
View File
@@ -188,7 +188,6 @@ if DEBUG:
MIDDLEWARE = [ MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware", "django.middleware.security.SecurityMiddleware",
"paperless.middleware.FileMoveMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware", "django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware", "corsheaders.middleware.CorsMiddleware",
@@ -557,6 +556,13 @@ CSRF_COOKIE_NAME = f"{COOKIE_PREFIX}csrftoken"
SESSION_COOKIE_NAME = f"{COOKIE_PREFIX}sessionid" SESSION_COOKIE_NAME = f"{COOKIE_PREFIX}sessionid"
LANGUAGE_COOKIE_NAME = f"{COOKIE_PREFIX}django_language" LANGUAGE_COOKIE_NAME = f"{COOKIE_PREFIX}django_language"
# Mark the session, CSRF and language cookies as Secure, so browsers only send
# them over HTTPS. Off by default, as it breaks any access over plain HTTP.
COOKIE_SECURE = get_bool_from_env("PAPERLESS_COOKIE_SECURE", "false")
SESSION_COOKIE_SECURE = COOKIE_SECURE
CSRF_COOKIE_SECURE = COOKIE_SECURE
LANGUAGE_COOKIE_SECURE = COOKIE_SECURE
EMAIL_CERTIFICATE_FILE = get_path_from_env("PAPERLESS_EMAIL_CERTIFICATE_LOCATION") EMAIL_CERTIFICATE_FILE = get_path_from_env("PAPERLESS_EMAIL_CERTIFICATE_LOCATION")
EMAIL_ALLOW_INTERNAL_HOSTS = get_bool_from_env( EMAIL_ALLOW_INTERNAL_HOSTS = get_bool_from_env(
"PAPERLESS_EMAIL_ALLOW_INTERNAL_HOSTS", "PAPERLESS_EMAIL_ALLOW_INTERNAL_HOSTS",
+39 -24
View File
@@ -4,6 +4,9 @@ import os
from hashlib import sha256 from hashlib import sha256
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
from urllib.parse import parse_qsl
from urllib.parse import urlencode
from urllib.parse import urlsplit
from celery.schedules import crontab from celery.schedules import crontab
@@ -26,6 +29,23 @@ def parse_hosting_settings() -> tuple[str | None, str, str, str, str]:
return script_name, base_url, login_url, login_redirect_url, logout_redirect_url return script_name, base_url, login_url, login_redirect_url, logout_redirect_url
def _rewrite_socket_url(url: str, scheme: str, old_param: str, new_param: str) -> str:
"""
Swaps the scheme of a socket URL and renames the database query parameter.
The URL is rewritten by hand, as urlunsplit drops the empty netloc
("scheme:///path" would become "scheme:/path") for non-standard schemes.
"""
parts = urlsplit(url)
base = f"{scheme}{url[len(parts.scheme) :]}".split("?", maxsplit=1)[0]
query = urlencode(
[
(new_param if key == old_param else key, value)
for key, value in parse_qsl(parts.query, keep_blank_values=True)
],
)
return f"{base}?{query}" if query else base
def parse_redis_url(env_redis: str | None) -> tuple[str, str]: def parse_redis_url(env_redis: str | None) -> tuple[str, str]:
""" """
Gets the Redis information from the environment or a default and handles Gets the Redis information from the environment or a default and handles
@@ -38,30 +58,25 @@ def parse_redis_url(env_redis: str | None) -> tuple[str, str]:
if env_redis is None: if env_redis is None:
return ("redis://localhost:6379", "redis://localhost:6379") return ("redis://localhost:6379", "redis://localhost:6379")
if "unix" in env_redis.lower(): match urlsplit(env_redis).scheme.lower():
# channels_redis socket format, looks like: case "unix":
# "unix:///path/to/redis.sock" # channels_redis socket format, looks like:
_, path = env_redis.split(":", maxsplit=1) # "unix:///path/to/redis.sock" with an optional "?db=N"
# Optionally setting a db number return (
if "?db=" in env_redis: _rewrite_socket_url(env_redis, "redis+socket", "db", "virtual_host"),
path, number = path.split("?db=") env_redis,
return (f"redis+socket:{path}?virtual_host={number}", env_redis) )
else: case "redis+socket":
return (f"redis+socket:{path}", env_redis) # celery socket style, looks like:
# "redis+socket:///path/to/redis.sock" with an optional "?virtual_host=N"
elif "+socket" in env_redis.lower(): # (virtual host is the db number)
# celery socket style, looks like: return (
# "redis+socket:///path/to/redis.sock" env_redis,
_, path = env_redis.split(":", maxsplit=1) _rewrite_socket_url(env_redis, "unix", "virtual_host", "db"),
if "?virtual_host=" in env_redis: )
# Virtual host (aka db number) case _:
path, number = path.split("?virtual_host=") # Not a socket
return (env_redis, f"unix:{path}?db={number}") return (env_redis, env_redis)
else:
return (env_redis, f"unix:{path}")
# Not a socket
return (env_redis, env_redis)
def parse_beat_schedule() -> dict: def parse_beat_schedule() -> dict:
+84 -12
View File
@@ -3,10 +3,17 @@ from __future__ import annotations
import hmac import hmac
import pickle import pickle
from hashlib import sha256 from hashlib import sha256
from typing import TYPE_CHECKING
from typing import Any from typing import Any
from django.conf import settings from django.conf import settings
if TYPE_CHECKING:
from pathlib import Path
from types import TracebackType
from typing import BinaryIO
from typing import Self
HMAC_SIZE = sha256().digest_size HMAC_SIZE = sha256().digest_size
@@ -14,26 +21,91 @@ class SignedPickleError(ValueError):
"""Raised when a signed pickle payload cannot be authenticated.""" """Raised when a signed pickle payload cannot be authenticated."""
def _get_signing_key() -> bytes: def new_mac() -> hmac.HMAC:
return settings.SECRET_KEY.encode() """
A new HMAC-SHA256 keyed with the SECRET_KEY, for signing incrementally.
"""
return hmac.new(settings.SECRET_KEY.encode(), digestmod=sha256)
def signed_pickle_dumps(obj: object) -> bytes: def compute_signature(data: bytes | memoryview) -> bytes:
data = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL) mac = new_mac()
signature = hmac.new(_get_signing_key(), data, sha256).digest() mac.update(data)
return signature + data return mac.digest()
def signed_pickle_loads(payload: bytes) -> Any: def verify_signed(payload: bytes | memoryview) -> memoryview:
"""
Verifies a payload made of an HMAC signature followed by the data, returning
a view of the data.
The data is sliced through a memoryview, so a (potentially multi-GB) payload
is not copied. The view is only returned once the whole payload has been
verified, and callers should unpickle from it rather than from the source,
so what is loaded is exactly what was checked.
"""
if len(payload) <= HMAC_SIZE: if len(payload) <= HMAC_SIZE:
msg = "Signed-pickle payload too short" msg = "Signed-pickle payload too short"
raise SignedPickleError(msg) raise SignedPickleError(msg)
signature = payload[:HMAC_SIZE] view = memoryview(payload)
data = payload[HMAC_SIZE:] signature = view[:HMAC_SIZE]
expected = hmac.new(_get_signing_key(), data, sha256).digest() data = view[HMAC_SIZE:]
if not hmac.compare_digest(signature, expected): if not hmac.compare_digest(signature, compute_signature(data)):
msg = "Signed-pickle HMAC verification failed; payload may have been tampered with" msg = "Signed-pickle HMAC verification failed; payload may have been tampered with"
raise SignedPickleError(msg) raise SignedPickleError(msg)
return pickle.loads(data) return data
def signed_pickle_dumps(obj: object) -> bytes:
data = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL)
return compute_signature(data) + data
def signed_pickle_loads(payload: bytes) -> Any:
return pickle.loads(verify_signed(payload))
class SignedFileWriter:
"""
Atomically writes a file made of an HMAC signature followed by the data,
signing the data as it streams to disk rather than holding it in memory.
The result can be read back with verify_signed.
The signature is only known once everything is written, so its space is
reserved at the start of the file and filled in on exit. The target is only
replaced once the file is complete; on error the partial file is removed.
"""
def __init__(self, target: Path) -> None:
self._target = target
self._temp = target.with_name(f"{target.name}.part")
self._mac = new_mac()
self._file: BinaryIO
def __enter__(self) -> Self:
self._file = self._temp.open("wb")
self._file.write(bytes(HMAC_SIZE))
return self
def write(self, data: bytes | memoryview) -> int:
self._mac.update(data)
return self._file.write(data)
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None:
try:
with self._file:
if exc_type is None:
self._file.seek(0)
self._file.write(self._mac.digest())
if exc_type is None:
self._temp.rename(self._target)
finally:
# A no-op after a successful rename, otherwise removes the partial file
self._temp.unlink(missing_ok=True)
@@ -61,6 +61,20 @@ class TestRedisSocketConversion:
("redis://myredishost:6379", "redis://myredishost:6379"), ("redis://myredishost:6379", "redis://myredishost:6379"),
id="host_with_port_unchanged", id="host_with_port_unchanged",
), ),
# "unix" or "+socket" appearing outside the scheme must not trigger conversion
pytest.param(
"redis://unix-redis:6379",
("redis://unix-redis:6379", "redis://unix-redis:6379"),
id="tcp_host_containing_unix",
),
pytest.param(
"redis://:unixsecret@myredishost:6379",
(
"redis://:unixsecret@myredishost:6379",
"redis://:unixsecret@myredishost:6379",
),
id="tcp_password_containing_unix",
),
# Credentials in unix:// URL contain multiple colons (user:password@) # Credentials in unix:// URL contain multiple colons (user:password@)
# Regression test for https://github.com/paperless-ngx/paperless-ngx/pull/12239 # Regression test for https://github.com/paperless-ngx/paperless-ngx/pull/12239
pytest.param( pytest.param(
+10
View File
@@ -12,6 +12,8 @@ from django.test import override_settings
from paperless.celery import signed_pickle_dumps from paperless.celery import signed_pickle_dumps
from paperless.celery import signed_pickle_loads from paperless.celery import signed_pickle_loads
from paperless.signed_pickle import HMAC_SIZE from paperless.signed_pickle import HMAC_SIZE
from paperless.signed_pickle import compute_signature
from paperless.signed_pickle import verify_signed
def test_tasks_registered_without_system_checks() -> None: def test_tasks_registered_without_system_checks() -> None:
@@ -80,6 +82,14 @@ class TestSignedPickleSerializer:
with pytest.raises(ValueError, match="HMAC verification failed"): with pytest.raises(ValueError, match="HMAC verification failed"):
signed_pickle_loads(bytes(tampered)) signed_pickle_loads(bytes(tampered))
def test_verified_data_is_a_view_not_a_copy(self) -> None:
"""Verified data is a view of the payload, so large payloads aren't copied."""
data = b"x" * 1024
payload = compute_signature(data) + data
verified = verify_signed(payload)
assert verified.obj is payload
assert bytes(verified) == data
def test_truncated_payload_rejected(self) -> None: def test_truncated_payload_rejected(self) -> None:
"""A payload shorter than HMAC_SIZE is rejected.""" """A payload shorter than HMAC_SIZE is rejected."""
with pytest.raises(ValueError, match="too short"): with pytest.raises(ValueError, match="too short"):
+18
View File
@@ -12,6 +12,11 @@ from paperless.utils import ocr_to_dateparser_languages
pytest.param("eng", ["en"], id="single-language"), pytest.param("eng", ["en"], id="single-language"),
pytest.param("fra+ita+lao", ["fr", "it", "lo"], id="multiple-languages"), pytest.param("fra+ita+lao", ["fr", "it", "lo"], id="multiple-languages"),
pytest.param("fil", ["fil"], id="no-two-letter-equivalent"), pytest.param("fil", ["fil"], id="no-two-letter-equivalent"),
pytest.param(
"afr+vie+kan+chr+mkd", # codespell:ignore
["af", "vi", "kn", "chr", "mk"],
id="previously-unmapped-languages",
),
pytest.param( pytest.param(
"aze_cyrl+srp_latn", "aze_cyrl+srp_latn",
["az-Cyrl", "sr-Latn"], ["az-Cyrl", "sr-Latn"],
@@ -49,6 +54,19 @@ def test_ocr_to_dateparser_languages(ocr_language: str, expected: list[str]) ->
assert sorted(ocr_to_dateparser_languages(ocr_language)) == sorted(expected) assert sorted(ocr_to_dateparser_languages(ocr_language)) == sorted(expected)
def test_ocr_to_dateparser_map_values_supported_by_dateparser() -> None:
from dateparser.languages.loader import LocaleDataLoader
loader = LocaleDataLoader()
unsupported = []
for ocr_code, dateparser_code in utils.OCR_TO_DATEPARSER_LANGUAGES.items():
try:
loader.get_locale_map(locales=[dateparser_code])
except Exception:
unsupported.append((ocr_code, dateparser_code))
assert unsupported == []
def test_ocr_to_dateparser_languages_exception( def test_ocr_to_dateparser_languages_exception(
monkeypatch: pytest.MonkeyPatch, monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
+16 -16
View File
@@ -2,19 +2,18 @@ import logging
logger = logging.getLogger("paperless.utils") logger = logging.getLogger("paperless.utils")
# Translation map from languages supported by Tesseract OCR
# to languages supported by dateparser.
# To add a language, make sure it is supported by both libraries.
# The ISO 639-2 will help you link a 3-char to 2-char language code.
# Links:
# - Tesseract languages: https://tesseract-ocr.github.io/tessdoc/Data-Files-in-different-versions.html
# - Python dateparser languages: https://dateparser.readthedocs.io/en/latest/supported_locales.html
# - ISO 639-2: https://www.loc.gov/standards/iso639-2/php/code_list.php
OCR_TO_DATEPARSER_LANGUAGES = { OCR_TO_DATEPARSER_LANGUAGES = {
""" # These dateparser languages have no equivalent in any Tesseract release
Translation map from languages supported by Tesseract OCR # (checked against tessdata, tessdata_best and tessdata_fast), so they cannot
to languages supported by dateparser. # be reached from the OCR language. Set PAPERLESS_DATE_PARSER_LANGUAGES to use them:
To add a language, make sure it is supported by both libraries.
The ISO 639-2 will help you link a 3-char to 2-char language code.
Links:
- Tesseract languages: https://tesseract-ocr.github.io/tessdoc/Data-Files-in-different-versions.html
- Python dateparser languages: https://dateparser.readthedocs.io/en/latest/supported_locales.html
- ISO 639-2: https://www.loc.gov/standards/iso639-2/php/code_list.php
"""
# TODO check these Dateparser languages as they are not referenced on the ISO639-2 standard,
# so we didn't find the equivalent in Tesseract:
# agq, asa, bez, brx, cgg, ckb, dav, dje, dyo, ebu, guz, jgo, jmc, kde, kea, khq, kln, # agq, asa, bez, brx, cgg, ckb, dav, dje, dyo, ebu, guz, jgo, jmc, kde, kea, khq, kln,
# ksb, ksf, ksh, lag, lkt, lrc, luy, mer, mfe, mgh, mgo, mua, mzn, naq, nmg, nnh, nus, # ksb, ksf, ksh, lag, lkt, lrc, luy, mer, mfe, mgh, mgo, mua, mzn, naq, nmg, nnh, nus,
# rof, rwk, saq, sbp, she, ses, shi, teo, twq, tzm, vun, wae, xog, yav, yue # rof, rwk, saq, sbp, she, ses, shi, teo, twq, tzm, vun, wae, xog, yav, yue
@@ -22,7 +21,6 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"amh": "am", "amh": "am",
"ara": "ar", "ara": "ar",
"asm": "as", "asm": "as",
"ast": "ast",
"aze": "az", "aze": "az",
"bel": "be", "bel": "be",
"bul": "bg", "bul": "bg",
@@ -31,7 +29,7 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"bre": "br", "bre": "br",
"bos": "bs", "bos": "bs",
"cat": "ca", "cat": "ca",
"cher": "chr", "chr": "chr",
"ces": "cs", "ces": "cs",
"cym": "cy", "cym": "cy",
"dan": "da", "dan": "da",
@@ -65,19 +63,21 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"kat": "ka", "kat": "ka",
"kaz": "kk", "kaz": "kk",
"khm": "km", "khm": "km",
"knda": "kn", "kan": "kn",
"kor": "ko", "kor": "ko",
"kir": "ky", "kir": "ky",
"ltz": "lb", "ltz": "lb",
"lao": "lo", "lao": "lo",
"lit": "lt", "lit": "lt",
"lav": "lv", "lav": "lv",
"mkd": "mk",
"mal": "ml", "mal": "ml",
"mon": "mn", "mon": "mn",
"mar": "mr", "mar": "mr",
"msa": "ms", "msa": "ms",
"mlt": "mt", "mlt": "mt",
"mya": "my", "mya": "my",
"nor": "nb",
"nep": "ne", "nep": "ne",
"nld": "nl", "nld": "nl",
"ori": "or", "ori": "or",
@@ -106,7 +106,7 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"ukr": "uk", "ukr": "uk",
"urd": "ur", "urd": "ur",
"uzb": "uz", "uzb": "uz",
"via": "vi", "vie": "vi", # codespell:ignore
"yid": "yi", "yid": "yi",
"yor": "yo", "yor": "yo",
"chi": "zh", "chi": "zh",
+37 -46
View File
@@ -893,8 +893,6 @@ class MailAccountHandler(LoggingMixin):
def _handle_message(self, message, rule: MailRule) -> int: def _handle_message(self, message, rule: MailRule) -> int:
message = self._preprocess_message(message) message = self._preprocess_message(message)
processed_elements = 0
# Skip Message handling when only attachments are to be processed but # Skip Message handling when only attachments are to be processed but
# message doesn't have any. # message doesn't have any.
if ( if (
@@ -902,7 +900,7 @@ class MailAccountHandler(LoggingMixin):
and rule.consumption_scope == MailRule.ConsumptionScope.ATTACHMENTS_ONLY and rule.consumption_scope == MailRule.ConsumptionScope.ATTACHMENTS_ONLY
): ):
self._record_processed_without_consumption(message, rule) self._record_processed_without_consumption(message, rule)
return processed_elements return 0
self.log.debug( self.log.debug(
f"Rule {rule}: " f"Rule {rule}: "
@@ -913,29 +911,47 @@ class MailAccountHandler(LoggingMixin):
tag_ids: list[int] = [tag.id for tag in rule.assign_tags.all()] tag_ids: list[int] = [tag.id for tag in rule.assign_tags.all()]
doc_type = rule.assign_document_type doc_type = rule.assign_document_type
consume_tasks: list[Signature] = []
if ( if (
rule.consumption_scope == MailRule.ConsumptionScope.EML_ONLY rule.consumption_scope == MailRule.ConsumptionScope.EML_ONLY
or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING
): ):
processed_elements += self._process_eml( consume_tasks.append(
message, self._build_eml_task(
rule, message,
tag_ids, rule,
doc_type, tag_ids,
doc_type,
),
) )
if ( if (
rule.consumption_scope == MailRule.ConsumptionScope.ATTACHMENTS_ONLY rule.consumption_scope == MailRule.ConsumptionScope.ATTACHMENTS_ONLY
or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING or rule.consumption_scope == MailRule.ConsumptionScope.EVERYTHING
): ):
processed_elements += self._process_attachments( consume_tasks.extend(
message, self._build_attachment_tasks(
rule, message,
tag_ids, rule,
doc_type, tag_ids,
doc_type,
),
) )
return processed_elements # One chord per message, so the mail action and the ProcessedMail row
# are written once, after every part of the message has been consumed
if consume_tasks:
queue_consumption_tasks(
consume_tasks=consume_tasks,
rule=rule,
message=message,
uid_validity=self._current_uid_validity,
)
else:
self._record_processed_without_consumption(message, rule)
return len(consume_tasks)
def _record_processed_without_consumption( def _record_processed_without_consumption(
self, self,
@@ -994,16 +1010,14 @@ class MailAccountHandler(LoggingMixin):
return True return True
return False return False
def _process_attachments( def _build_attachment_tasks(
self, self,
message: MailMessage, message: MailMessage,
rule: MailRule, rule: MailRule,
tag_ids, tag_ids,
doc_type, doc_type,
): ) -> list[Signature]:
processed_attachments = 0 consume_tasks: list[Signature] = []
consume_tasks = []
for att in message.attachments: for att in message.attachments:
if ( if (
@@ -1104,8 +1118,6 @@ class MailAccountHandler(LoggingMixin):
) )
consume_tasks.append(consume_task) consume_tasks.append(consume_task)
processed_attachments += 1
else: else:
self.log.debug( self.log.debug(
f"Rule {rule}: " f"Rule {rule}: "
@@ -1114,26 +1126,15 @@ class MailAccountHandler(LoggingMixin):
f"by paperless", f"by paperless",
) )
if len(consume_tasks) > 0: return consume_tasks
queue_consumption_tasks(
consume_tasks=consume_tasks,
rule=rule,
message=message,
uid_validity=self._current_uid_validity,
)
else:
# No files to consume, just mark as processed if it wasn't by .eml processing
self._record_processed_without_consumption(message, rule)
return processed_attachments def _build_eml_task(
def _process_eml(
self, self,
message: MailMessage, message: MailMessage,
rule: MailRule, rule: MailRule,
tag_ids, tag_ids,
doc_type, doc_type,
): ) -> Signature:
settings.SCRATCH_DIR.mkdir(parents=True, exist_ok=True) settings.SCRATCH_DIR.mkdir(parents=True, exist_ok=True)
_, temp_filename = tempfile.mkstemp( _, temp_filename = tempfile.mkstemp(
prefix="paperless-mail-", prefix="paperless-mail-",
@@ -1191,17 +1192,7 @@ class MailAccountHandler(LoggingMixin):
owner_id=rule.owner.id if rule.owner else None, owner_id=rule.owner.id if rule.owner else None,
) )
consume_task = consume_file.s( return consume_file.s(
input_doc=input_doc, input_doc=input_doc,
overrides=doc_overrides, overrides=doc_overrides,
).set(headers={"trigger_source": PaperlessTask.TriggerSource.EMAIL_CONSUME}) ).set(headers={"trigger_source": PaperlessTask.TriggerSource.EMAIL_CONSUME})
queue_consumption_tasks(
consume_tasks=[consume_task],
rule=rule,
message=message,
uid_validity=self._current_uid_validity,
)
processed_elements = 1
return processed_elements
+38
View File
@@ -416,6 +416,44 @@ class TestMail(
1, 1,
) )
def test_handle_message_everything_scope_single_row(self) -> None:
"""
GIVEN:
- A rule consuming the eml and attachments, and a mail with or
without attachments
WHEN:
- The mail is handled and its queued mail action is applied
THEN:
- The eml and attachments are queued together in one call
- Exactly one ProcessedMail row exists and it is not
PROCESSED_WO_CONSUMPTION
"""
rule = MailRule.objects.create(
account=MailAccount.objects.create(
name="test",
imap_server="",
username="admin",
password="secret",
),
consumption_scope=MailRule.ConsumptionScope.EVERYTHING,
)
for attachments in (0, 2):
with self.subTest(attachments=attachments):
self.mailMocker._queue_consumption_tasks_mock.reset_mock()
message = self.mailMocker.messageBuilder.create_message(
subject=f"{attachments} attachments",
attachments=attachments,
)
result = self.mail_account_handler._handle_message(message, rule)
self.mailMocker.apply_mail_actions()
self.assertEqual(result, 1 + attachments)
self.mailMocker._queue_consumption_tasks_mock.assert_called_once()
processed = ProcessedMail.objects.get(rule=rule, uid=message.uid)
self.assertEqual(processed.status, "SUCCESS")
def test_handle_empty_message_long_subject(self) -> None: def test_handle_empty_message_long_subject(self) -> None:
""" """
GIVEN: GIVEN:
@@ -272,8 +272,6 @@ class TestMailMessageGpgDecryptor(TestMail):
"override_title": message.subject, "override_title": message.subject,
"override_filename": f"{message.subject}.eml", "override_filename": f"{message.subject}.eml",
}, },
],
[
{"override_title": "file_0", "override_filename": "file_0.pdf"}, {"override_title": "file_0", "override_filename": "file_0.pdf"},
{"override_title": "file_1", "override_filename": "file_1.pdf"}, {"override_title": "file_1", "override_filename": "file_1.pdf"},
], ],
-9
View File
@@ -9,7 +9,6 @@ from django.contrib.auth.models import User
from documents.models import Correspondent from documents.models import Correspondent
from documents.models import CustomField from documents.models import CustomField
from documents.models import CustomFieldInstance
from documents.models import Document from documents.models import Document
from documents.models import DocumentBarcode from documents.models import DocumentBarcode
from documents.models import DocumentType from documents.models import DocumentType
@@ -82,14 +81,6 @@ class DocumentFactory(TypedModelFactory[Document]):
storage_path = None storage_path = None
class CustomFieldInstanceFactory(TypedModelFactory[CustomFieldInstance]):
class Meta:
model = CustomFieldInstance
field = factory.SubFactory(CustomFieldFactory)
document = factory.SubFactory(DocumentFactory)
class DocumentBarcodeFactory(TypedModelFactory[DocumentBarcode]): class DocumentBarcodeFactory(TypedModelFactory[DocumentBarcode]):
class Meta: class Meta:
model = DocumentBarcode model = DocumentBarcode
-47
View File
@@ -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
Generated
+19 -9
View File
@@ -2516,6 +2516,7 @@ dependencies = [
{ name = "channels" }, { name = "channels" },
{ name = "channels-redis" }, { name = "channels-redis" },
{ name = "concurrent-log-handler" }, { name = "concurrent-log-handler" },
{ name = "cryptography" },
{ name = "dateparser" }, { name = "dateparser" },
{ name = "django" }, { name = "django" },
{ name = "django-allauth", extra = ["mfa", "socialaccount"] }, { name = "django-allauth", extra = ["mfa", "socialaccount"] },
@@ -2537,6 +2538,7 @@ dependencies = [
{ name = "flower" }, { name = "flower" },
{ name = "gotenberg-client", extra = ["httpx"] }, { name = "gotenberg-client", extra = ["httpx"] },
{ name = "httpx-oauth" }, { name = "httpx-oauth" },
{ name = "humanize" },
{ name = "ijson" }, { name = "ijson" },
{ name = "imap-tools" }, { name = "imap-tools" },
{ name = "jinja2" }, { name = "jinja2" },
@@ -2547,10 +2549,13 @@ dependencies = [
{ name = "llama-index-embeddings-openai-like" }, { name = "llama-index-embeddings-openai-like" },
{ name = "llama-index-llms-ollama" }, { name = "llama-index-llms-ollama" },
{ name = "llama-index-llms-openai-like" }, { name = "llama-index-llms-openai-like" },
{ name = "lxml" },
{ name = "ocrmypdf", extra = ["heic"] }, { name = "ocrmypdf", extra = ["heic"] },
{ name = "ollama" },
{ name = "openai" }, { name = "openai" },
{ name = "pathvalidate" }, { name = "pathvalidate" },
{ name = "pdf2image" }, { name = "pdf2image" },
{ name = "pikepdf" },
{ name = "python-dateutil" }, { name = "python-dateutil" },
{ name = "python-dotenv" }, { name = "python-dotenv" },
{ name = "python-gnupg" }, { name = "python-gnupg" },
@@ -2668,6 +2673,7 @@ requires-dist = [
{ name = "channels", specifier = "~=4.2" }, { name = "channels", specifier = "~=4.2" },
{ name = "channels-redis", specifier = "~=4.2" }, { name = "channels-redis", specifier = "~=4.2" },
{ name = "concurrent-log-handler", specifier = "~=0.9.25" }, { name = "concurrent-log-handler", specifier = "~=0.9.25" },
{ name = "cryptography", specifier = ">=50.0.0" },
{ name = "dateparser", specifier = "~=1.4" }, { name = "dateparser", specifier = "~=1.4" },
{ name = "django", specifier = "~=5.2.18" }, { name = "django", specifier = "~=5.2.18" },
{ name = "django-allauth", extras = ["mfa", "socialaccount"], specifier = "~=65.21.1" }, { name = "django-allauth", extras = ["mfa", "socialaccount"], specifier = "~=65.21.1" },
@@ -2690,6 +2696,7 @@ requires-dist = [
{ name = "gotenberg-client", extras = ["httpx"], specifier = "~=1.0" }, { name = "gotenberg-client", extras = ["httpx"], specifier = "~=1.0" },
{ name = "granian", extras = ["uvloop"], marker = "extra == 'webserver'", specifier = ">=2.7,<2.9" }, { name = "granian", extras = ["uvloop"], marker = "extra == 'webserver'", specifier = ">=2.7,<2.9" },
{ name = "httpx-oauth", specifier = "~=0.17" }, { name = "httpx-oauth", specifier = "~=0.17" },
{ name = "humanize", specifier = ">=4.15.0" },
{ name = "ijson", specifier = ">=3.5.1" }, { name = "ijson", specifier = ">=3.5.1" },
{ name = "imap-tools", specifier = ">=1.14,<1.16" }, { name = "imap-tools", specifier = ">=1.14,<1.16" },
{ name = "jinja2", specifier = "~=3.1.6" }, { name = "jinja2", specifier = "~=3.1.6" },
@@ -2700,11 +2707,14 @@ requires-dist = [
{ name = "llama-index-embeddings-openai-like", specifier = ">=0.2.2" }, { name = "llama-index-embeddings-openai-like", specifier = ">=0.2.2" },
{ name = "llama-index-llms-ollama", specifier = ">=0.9.1" }, { name = "llama-index-llms-ollama", specifier = ">=0.9.1" },
{ name = "llama-index-llms-openai-like", specifier = ">=0.7.1" }, { name = "llama-index-llms-openai-like", specifier = ">=0.7.1" },
{ name = "lxml", specifier = ">=6.1.0" },
{ name = "mysqlclient", marker = "extra == 'mariadb'", specifier = ">=2.2.7,<2.4" }, { name = "mysqlclient", marker = "extra == 'mariadb'", specifier = ">=2.2.7,<2.4" },
{ name = "ocrmypdf", extras = ["heic"], specifier = ">=17.12,<17.13" }, { name = "ocrmypdf", extras = ["heic"], specifier = ">=17.12,<17.13" },
{ name = "ollama", specifier = ">=0.6.1" },
{ name = "openai", specifier = ">=2.48" }, { name = "openai", specifier = ">=2.48" },
{ name = "pathvalidate", specifier = "~=3.3.1" }, { name = "pathvalidate", specifier = "~=3.3.1" },
{ name = "pdf2image", specifier = "~=1.17.0" }, { name = "pdf2image", specifier = "~=1.17.0" },
{ name = "pikepdf", specifier = ">=10.13" },
{ name = "psycopg", extras = ["c", "pool"], marker = "extra == 'postgres'", specifier = "==3.3.8" }, { name = "psycopg", extras = ["c", "pool"], marker = "extra == 'postgres'", specifier = "==3.3.8" },
{ name = "psycopg-c", marker = "python_full_version == '3.12.*' and platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'postgres'", url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp312-cp312-manylinux_2_38_aarch64.whl" }, { name = "psycopg-c", marker = "python_full_version == '3.12.*' and platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'postgres'", url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp312-cp312-manylinux_2_38_aarch64.whl" },
{ name = "psycopg-c", marker = "python_full_version == '3.14.*' and platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'postgres'", url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp314-cp314-manylinux_2_38_aarch64.whl" }, { name = "psycopg-c", marker = "python_full_version == '3.14.*' and platform_machine == 'aarch64' and sys_platform == 'linux' and extra == 'postgres'", url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp314-cp314-manylinux_2_38_aarch64.whl" },
@@ -2755,14 +2765,14 @@ dev = [
{ name = "pytest-rerunfailures", specifier = "~=16.4" }, { name = "pytest-rerunfailures", specifier = "~=16.4" },
{ name = "pytest-sugar" }, { name = "pytest-sugar" },
{ name = "pytest-xdist", specifier = "~=3.8.0" }, { name = "pytest-xdist", specifier = "~=3.8.0" },
{ name = "ruff", specifier = "~=0.16.1" }, { name = "ruff", specifier = "~=0.17.2" },
{ name = "time-machine", specifier = ">=2.13" }, { name = "time-machine", specifier = ">=2.13" },
{ name = "zensical", specifier = ">=0.0.51" }, { name = "zensical", specifier = ">=0.0.51" },
] ]
docs = [{ name = "zensical", specifier = ">=0.0.51" }] docs = [{ name = "zensical", specifier = ">=0.0.51" }]
lint = [ lint = [
{ name = "prek", specifier = ">=0.4.11,<0.6" }, { name = "prek", specifier = ">=0.4.11,<0.6" },
{ name = "ruff", specifier = "~=0.16.1" }, { name = "ruff", specifier = "~=0.17.2" },
] ]
testing = [ testing = [
{ name = "daphne" }, { name = "daphne" },
@@ -3840,15 +3850,15 @@ wheels = [
[[package]] [[package]]
name = "ruff" name = "ruff"
version = "0.16.10" version = "0.17.6"
source = { registry = "https://pypi.org/simple" } source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/c4/49/23802c45f093eb14bde54b141d2b2f058edfa63a06db7beed047308cc08f/ruff-0.16.10.tar.gz", hash = "sha256:eff4728c4eaae93f0955cd264d24b2ab348e74bf59986ccf282ba6dc16b3b017", size = 4958724, upload-time = "2026-10-01T18:03:21.697Z" } sdist = { url = "https://files.pythonhosted.org/packages/df/8e/6929d337aa5380aafc7355f3149f3ccfe55cba5fdd34a045697ebaceb5a0/ruff-0.17.6.tar.gz", hash = "sha256:2b04276561331300325040bdca21460770029ec574d4c479099e39e8ad1ed43c", size = 5374388, upload-time = "2026-11-19T15:56:27.106Z" }
wheels = [ wheels = [
{ url = "https://files.pythonhosted.org/packages/9f/16/1a5a4a2657effe4806110f2b907313802f1367fcdbb29e8122766e407fab/ruff-0.16.10-py3-none-macosx_11_0_arm64.whl", hash = "sha256:3031a4a2e8e7b8a46f70be45f198c35a11ece509a94b80334d8d397a33c67550", size = 9774282, upload-time = "2026-10-01T18:02:41.79Z" }, { url = "https://files.pythonhosted.org/packages/ba/d4/c31391b36c729cd9fafa65b7a52a58850b99afb2b65da6be4263a53302f2/ruff-0.17.6-py3-none-macosx_11_0_arm64.whl", hash = "sha256:9fbddc08577592e283c265d865e0182de6e33db185494db7b06290d989d888e5", size = 9580986, upload-time = "2026-11-19T15:55:57.391Z" },
{ url = "https://files.pythonhosted.org/packages/6e/fb/470085af734da396e68cd80fb0a3e7c109a459716ae59588c0f6fab8a17d/ruff-0.16.10-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:494401c86df4c4c25f69b9419605d944467ee98c42fb6ad405ef4fa40b8fb67d", size = 9920895, upload-time = "2026-10-01T18:02:44.458Z" }, { url = "https://files.pythonhosted.org/packages/eb/11/f3032684dcb3a676d7924545153d76fb56f76753e038f2ea650b99c71bdf/ruff-0.17.6-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:435241c61af5909a022f76219d3d1bf24730dc1bf0acabb5ddf4b569ab3cbb30", size = 10271368, upload-time = "2026-11-19T15:55:59.654Z" },
{ url = "https://files.pythonhosted.org/packages/e4/03/17234145f302a645a123e8c3bb2411ecf4669fbc350de3b0d803230a1729/ruff-0.16.10-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f33f43a864a8483eebd160e713336c8bab02c934feaff0a33cf5ccb41546d09a", size = 10387968, upload-time = "2026-10-01T18:02:57.497Z" }, { url = "https://files.pythonhosted.org/packages/be/48/3df7d81249fd69ee6a49519b149fb5d11e13118fd7d0e8d65329a237087b/ruff-0.17.6-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:aa3b08254a732acba246891089a152c47c5733dc36b8ecb76ce8602f8326e5e4", size = 10645279, upload-time = "2026-11-19T15:56:09.785Z" },
{ url = "https://files.pythonhosted.org/packages/2e/9a/f56b28f3b143bb9e518c34fb89ab191b626bca8b70dbf8af0d2e2d473572/ruff-0.16.10-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:6553498afc35f580f036030795810b9e6bcea31604b0fd9e8d352795473042e3", size = 10012938, upload-time = "2026-10-01T18:03:03.006Z" }, { url = "https://files.pythonhosted.org/packages/98/0a/b477f075a4a94eb541bf1c759a3e72b2a3d6390af7a13a5be0887229f67c/ruff-0.17.6-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:fb589e032806bb942e4fb526f30b80a1a64112147ed9f1d38cc3de2e255b6f45", size = 10136036, upload-time = "2026-11-19T15:56:13.779Z" },
{ url = "https://files.pythonhosted.org/packages/21/aa/5c9f3b68737c0e4a33a1db5dfab44f7b786d96ca91a7233112ddab1e6dc2/ruff-0.16.10-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:7ae7375f803b5520dc9f546bed7e3a0acb70b91812e9bb4b19927de22f25b77d", size = 10741702, upload-time = "2026-10-01T18:03:10.775Z" }, { url = "https://files.pythonhosted.org/packages/81/c7/e09d220818ab146b736d62e0676dad215215d7de0884bbdad9fa075dc7d2/ruff-0.17.6-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:3db61f5015600543a581b07fa7f6f64afa0eeedefe16034cadd88c4074087582", size = 10760296, upload-time = "2026-11-19T15:56:19.463Z" },
] ]
[[package]] [[package]]