mirror of
https://github.com/paperless-ngx/paperless-ngx.git
synced 2026-12-03 17:58:41 +00:00
Compare commits
38
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc2c32d2b2 | ||
|
|
26f5468834 | ||
|
|
6e7154ef64 | ||
|
|
814b3f903b | ||
|
|
75c685d3e9 | ||
|
|
cd41640312 | ||
|
|
28f6e8e58a | ||
|
|
c6d78d525e | ||
|
|
40ea2ea8d1 | ||
|
|
3f5d14bf05 | ||
|
|
aa44ff75e1 | ||
|
|
b783d5e895 | ||
|
|
3c295be9b4 | ||
|
|
8464a91b4c | ||
|
|
2d28fc216c | ||
|
|
e399937109 | ||
|
|
9c8fd02bf8 | ||
|
|
ec82da6d9a | ||
|
|
00a73a24d2 | ||
|
|
9d8903b32d | ||
|
|
637d190332 | ||
|
|
8b34780d3e | ||
|
|
bb3604624b | ||
|
|
8591e71a4e | ||
|
|
5f6617ff29 | ||
|
|
56a77ed914 | ||
|
|
970aab73ea | ||
|
|
d1251aaef6 | ||
|
|
fca95bc821 | ||
|
|
f684baaea8 | ||
|
|
e7ead755d3 | ||
|
|
be4c4cdbfe | ||
|
|
3e6e1e6efd | ||
|
|
1dc797e9be | ||
|
|
0cb56c49bb | ||
|
|
5cea561838 | ||
|
|
ca32553478 | ||
|
|
cfbb383514 |
No files matched your search
@@ -1,8 +1,6 @@
|
|||||||
# Please see the documentation for all configuration options:
|
# Please see the documentation for all configuration options:
|
||||||
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
|
||||||
version: 2
|
version: 2
|
||||||
# Required for uv support for now
|
|
||||||
enable-beta-ecosystems: true
|
|
||||||
updates:
|
updates:
|
||||||
# Enable version updates for pnpm
|
# Enable version updates for pnpm
|
||||||
- package-ecosystem: "npm"
|
- package-ecosystem: "npm"
|
||||||
|
|||||||
@@ -104,7 +104,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
python-version: "${{ matrix.python-version }}"
|
python-version: "${{ matrix.python-version }}"
|
||||||
- name: Install uv
|
- name: Install uv
|
||||||
uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
|
uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
|
||||||
with:
|
with:
|
||||||
version: ${{ env.DEFAULT_UV_VERSION }}
|
version: ${{ env.DEFAULT_UV_VERSION }}
|
||||||
enable-cache: true
|
enable-cache: true
|
||||||
@@ -174,7 +174,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
python-version: "${{ env.DEFAULT_PYTHON }}"
|
python-version: "${{ env.DEFAULT_PYTHON }}"
|
||||||
- name: Install uv
|
- name: Install uv
|
||||||
uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
|
uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
|
||||||
with:
|
with:
|
||||||
version: ${{ env.DEFAULT_UV_VERSION }}
|
version: ${{ env.DEFAULT_UV_VERSION }}
|
||||||
enable-cache: true
|
enable-cache: true
|
||||||
|
|||||||
@@ -109,7 +109,7 @@ jobs:
|
|||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||||
- name: Login to GitHub Container Registry
|
- name: Login to GitHub Container Registry
|
||||||
uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
|
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||||
with:
|
with:
|
||||||
registry: ${{ env.REGISTRY }}
|
registry: ${{ env.REGISTRY }}
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
@@ -185,20 +185,20 @@ jobs:
|
|||||||
- name: Set up Docker Buildx
|
- name: Set up Docker Buildx
|
||||||
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||||
- name: Login to GitHub Container Registry
|
- name: Login to GitHub Container Registry
|
||||||
uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
|
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||||
with:
|
with:
|
||||||
registry: ${{ env.REGISTRY }}
|
registry: ${{ env.REGISTRY }}
|
||||||
username: ${{ github.actor }}
|
username: ${{ github.actor }}
|
||||||
password: ${{ secrets.GITHUB_TOKEN }}
|
password: ${{ secrets.GITHUB_TOKEN }}
|
||||||
- name: Login to Docker Hub
|
- name: Login to Docker Hub
|
||||||
if: needs.build-arch.outputs.push-external == 'true'
|
if: needs.build-arch.outputs.push-external == 'true'
|
||||||
uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
|
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||||
with:
|
with:
|
||||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||||
- name: Login to Quay.io
|
- name: Login to Quay.io
|
||||||
if: needs.build-arch.outputs.push-external == 'true'
|
if: needs.build-arch.outputs.push-external == 'true'
|
||||||
uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
|
uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||||
with:
|
with:
|
||||||
registry: quay.io
|
registry: quay.io
|
||||||
username: ${{ secrets.QUAY_USERNAME }}
|
username: ${{ secrets.QUAY_USERNAME }}
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
python-version: ${{ env.DEFAULT_PYTHON_VERSION }}
|
python-version: ${{ env.DEFAULT_PYTHON_VERSION }}
|
||||||
- name: Install uv
|
- name: Install uv
|
||||||
uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
|
uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
|
||||||
with:
|
with:
|
||||||
version: ${{ env.DEFAULT_UV_VERSION }}
|
version: ${{ env.DEFAULT_UV_VERSION }}
|
||||||
enable-cache: true
|
enable-cache: true
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Install pnpm
|
- name: Install pnpm
|
||||||
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
|
||||||
with:
|
with:
|
||||||
package_json_file: src-ui/package.json
|
package_json_file: src-ui/package.json
|
||||||
- name: Use Node.js 24
|
- name: Use Node.js 24
|
||||||
@@ -115,7 +115,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Install pnpm
|
- name: Install pnpm
|
||||||
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
|
||||||
with:
|
with:
|
||||||
package_json_file: src-ui/package.json
|
package_json_file: src-ui/package.json
|
||||||
- name: Use Node.js 24
|
- name: Use Node.js 24
|
||||||
@@ -154,7 +154,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Install pnpm
|
- name: Install pnpm
|
||||||
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
|
||||||
with:
|
with:
|
||||||
package_json_file: src-ui/package.json
|
package_json_file: src-ui/package.json
|
||||||
- name: Use Node.js 24
|
- name: Use Node.js 24
|
||||||
@@ -193,7 +193,7 @@ jobs:
|
|||||||
runs-on: ubuntu-26.04
|
runs-on: ubuntu-26.04
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
container: mcr.microsoft.com/playwright:v1.64.1-resolute
|
container: mcr.microsoft.com/playwright:v1.65.1-resolute
|
||||||
env:
|
env:
|
||||||
PLAYWRIGHT_BROWSERS_PATH: /ms-playwright
|
PLAYWRIGHT_BROWSERS_PATH: /ms-playwright
|
||||||
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
|
PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: 1
|
||||||
@@ -203,7 +203,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Install pnpm
|
- name: Install pnpm
|
||||||
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
|
||||||
with:
|
with:
|
||||||
package_json_file: src-ui/package.json
|
package_json_file: src-ui/package.json
|
||||||
- name: Use Node.js 24
|
- name: Use Node.js 24
|
||||||
@@ -218,7 +218,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
python-version: '3.12'
|
python-version: '3.12'
|
||||||
- name: Install uv
|
- name: Install uv
|
||||||
uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
|
uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
|
||||||
with:
|
with:
|
||||||
version: '0.13.x'
|
version: '0.13.x'
|
||||||
enable-cache: false
|
enable-cache: false
|
||||||
@@ -258,7 +258,7 @@ jobs:
|
|||||||
fetch-depth: 2
|
fetch-depth: 2
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Install pnpm
|
- name: Install pnpm
|
||||||
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
|
||||||
with:
|
with:
|
||||||
package_json_file: src-ui/package.json
|
package_json_file: src-ui/package.json
|
||||||
- name: Use Node.js 24
|
- name: Use Node.js 24
|
||||||
|
|||||||
@@ -26,4 +26,4 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
python-version: "3.14"
|
python-version: "3.14"
|
||||||
- name: Run prek
|
- name: Run prek
|
||||||
uses: j178/prek-action@44924fe9ef4a6f88253c4b6b1bf11c689d3ce53d # v3.1.0
|
uses: j178/prek-action@7b101f8338a08d2bd6fdb3625e4e7692428763a3 # v3.1.1
|
||||||
@@ -40,7 +40,7 @@ jobs:
|
|||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
# ---- Frontend Build ----
|
# ---- Frontend Build ----
|
||||||
- name: Install pnpm
|
- name: Install pnpm
|
||||||
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
|
||||||
with:
|
with:
|
||||||
package_json_file: src-ui/package.json
|
package_json_file: src-ui/package.json
|
||||||
- name: Use Node.js 24
|
- name: Use Node.js 24
|
||||||
@@ -59,7 +59,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
python-version: ${{ env.DEFAULT_PYTHON_VERSION }}
|
python-version: ${{ env.DEFAULT_PYTHON_VERSION }}
|
||||||
- name: Install uv
|
- name: Install uv
|
||||||
uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
|
uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
|
||||||
with:
|
with:
|
||||||
version: ${{ env.DEFAULT_UV_VERSION }}
|
version: ${{ env.DEFAULT_UV_VERSION }}
|
||||||
enable-cache: false
|
enable-cache: false
|
||||||
@@ -172,7 +172,7 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
- name: Create release and changelog
|
- name: Create release and changelog
|
||||||
id: create-release
|
id: create-release
|
||||||
uses: release-drafter/release-drafter@978bb0b30c5ee8cdd332ced253758157150d43f0 # v7.10.0
|
uses: release-drafter/release-drafter@d1a19e60e81a7e650d00a7de9277f87e439117ea # v7.11.0
|
||||||
with:
|
with:
|
||||||
name: Paperless-ngx ${{ steps.get-version.outputs.version }}
|
name: Paperless-ngx ${{ steps.get-version.outputs.version }}
|
||||||
tag: ${{ steps.get-version.outputs.version }}
|
tag: ${{ steps.get-version.outputs.version }}
|
||||||
@@ -213,7 +213,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
python-version: ${{ env.DEFAULT_PYTHON_VERSION }}
|
python-version: ${{ env.DEFAULT_PYTHON_VERSION }}
|
||||||
- name: Install uv
|
- name: Install uv
|
||||||
uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
|
uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
|
||||||
with:
|
with:
|
||||||
version: ${{ env.DEFAULT_UV_VERSION }}
|
version: ${{ env.DEFAULT_UV_VERSION }}
|
||||||
enable-cache: false
|
enable-cache: false
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: Run zizmor
|
- name: Run zizmor
|
||||||
uses: zizmorcore/zizmor-action@53290badfa369cb0bf7ad16342cb62c2fa47ac7b # v0.8.0
|
uses: zizmorcore/zizmor-action@1b4550e929643b8b26a62303c6bd64814271a4f1 # v0.9.2
|
||||||
semgrep:
|
semgrep:
|
||||||
name: Semgrep CE
|
name: Semgrep CE
|
||||||
runs-on: ubuntu-26.04
|
runs-on: ubuntu-26.04
|
||||||
@@ -45,7 +45,7 @@ jobs:
|
|||||||
- name: Run Semgrep
|
- name: Run Semgrep
|
||||||
run: semgrep scan --config auto --sarif-output results.sarif
|
run: semgrep scan --config auto --sarif-output results.sarif
|
||||||
- name: Upload results to GitHub code scanning
|
- name: Upload results to GitHub code scanning
|
||||||
uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
uses: github/codeql-action/upload-sarif@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
|
||||||
if: always()
|
if: always()
|
||||||
with:
|
with:
|
||||||
sarif_file: results.sarif
|
sarif_file: results.sarif
|
||||||
@@ -39,7 +39,7 @@ jobs:
|
|||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
# Initializes the CodeQL tools for scanning.
|
# Initializes the CodeQL tools for scanning.
|
||||||
- name: Initialize CodeQL
|
- name: Initialize CodeQL
|
||||||
uses: github/codeql-action/init@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
uses: github/codeql-action/init@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
|
||||||
with:
|
with:
|
||||||
languages: ${{ matrix.language }}
|
languages: ${{ matrix.language }}
|
||||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||||
@@ -47,4 +47,4 @@ jobs:
|
|||||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||||
# queries: ./path/to/local/query, your-org/your-repo/queries@main
|
# queries: ./path/to/local/query, your-org/your-repo/queries@main
|
||||||
- name: Perform CodeQL Analysis
|
- name: Perform CodeQL Analysis
|
||||||
uses: github/codeql-action/analyze@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1
|
uses: github/codeql-action/analyze@915412ff23e8b7659517e607487dbeae018f2934 # v4.39.5
|
||||||
@@ -22,7 +22,7 @@ jobs:
|
|||||||
token: ${{ secrets.PNGX_BOT_PAT }}
|
token: ${{ secrets.PNGX_BOT_PAT }}
|
||||||
persist-credentials: false
|
persist-credentials: false
|
||||||
- name: crowdin action
|
- name: crowdin action
|
||||||
uses: crowdin/github-action@959dc74ac104447731cba99a016f85d0ae719788 # v3.5.0
|
uses: crowdin/github-action@d651c77756acbe11a31d77a6fb79d8a239e1e05a # v3.6.0
|
||||||
with:
|
with:
|
||||||
upload_translations: false
|
upload_translations: false
|
||||||
download_translations: true
|
download_translations: true
|
||||||
|
|||||||
@@ -19,6 +19,6 @@ jobs:
|
|||||||
if: github.event_name == 'pull_request_target' && (github.event.action == 'opened' || github.event.action == 'reopened') && github.event.pull_request.user.login != 'dependabot'
|
if: github.event_name == 'pull_request_target' && (github.event.action == 'opened' || github.event.action == 'reopened') && github.event.pull_request.user.login != 'dependabot'
|
||||||
steps:
|
steps:
|
||||||
- name: Label PR with release-drafter
|
- name: Label PR with release-drafter
|
||||||
uses: release-drafter/release-drafter@978bb0b30c5ee8cdd332ced253758157150d43f0 # v7.10.0
|
uses: release-drafter/release-drafter@d1a19e60e81a7e650d00a7de9277f87e439117ea # v7.11.0
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -30,7 +30,7 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
packages: gettext
|
packages: gettext
|
||||||
- name: Install uv
|
- name: Install uv
|
||||||
uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3
|
uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0
|
||||||
with:
|
with:
|
||||||
version: ${{ env.DEFAULT_UV_VERSION }}
|
version: ${{ env.DEFAULT_UV_VERSION }}
|
||||||
enable-cache: true
|
enable-cache: true
|
||||||
@@ -44,7 +44,7 @@ jobs:
|
|||||||
PAPERLESS_SECRET_KEY: "ci-translate-not-a-real-secret"
|
PAPERLESS_SECRET_KEY: "ci-translate-not-a-real-secret"
|
||||||
run: cd src/ && uv run manage.py makemessages -l en_US -i "samples*"
|
run: cd src/ && uv run manage.py makemessages -l en_US -i "samples*"
|
||||||
- name: Install pnpm
|
- name: Install pnpm
|
||||||
uses: pnpm/action-setup@ea17c68df8912ef543352723c149a84f56e3d413 # v6.1.0
|
uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1
|
||||||
with:
|
with:
|
||||||
package_json_file: src-ui/package.json
|
package_json_file: src-ui/package.json
|
||||||
- name: Use Node.js 24
|
- name: Use Node.js 24
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ repos:
|
|||||||
- json
|
- json
|
||||||
# See https://github.com/prettier/prettier/issues/15742 for the fork reason
|
# See https://github.com/prettier/prettier/issues/15742 for the fork reason
|
||||||
- repo: https://github.com/rbubley/mirrors-prettier
|
- repo: https://github.com/rbubley/mirrors-prettier
|
||||||
rev: 'v3.9.10'
|
rev: 'v3.10.1'
|
||||||
hooks:
|
hooks:
|
||||||
- id: prettier
|
- id: prettier
|
||||||
types_or:
|
types_or:
|
||||||
@@ -46,7 +46,7 @@ repos:
|
|||||||
- ts
|
- ts
|
||||||
- markdown
|
- markdown
|
||||||
additional_dependencies:
|
additional_dependencies:
|
||||||
- prettier@3.9.10
|
- prettier@3.10.1
|
||||||
- '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
|
||||||
@@ -55,7 +55,7 @@ repos:
|
|||||||
- id: ruff-check
|
- id: ruff-check
|
||||||
- id: ruff-format
|
- id: ruff-format
|
||||||
- repo: https://github.com/tox-dev/pyproject-fmt
|
- repo: https://github.com/tox-dev/pyproject-fmt
|
||||||
rev: "v2.30.3"
|
rev: "v2.31.2"
|
||||||
hooks:
|
hooks:
|
||||||
- id: pyproject-fmt
|
- id: pyproject-fmt
|
||||||
additional_dependencies: [tomli]
|
additional_dependencies: [tomli]
|
||||||
|
|||||||
+5
-5
@@ -30,7 +30,7 @@ RUN set -eux \
|
|||||||
# Purpose: Installs s6-overlay and rootfs
|
# Purpose: Installs s6-overlay and rootfs
|
||||||
# Comments:
|
# Comments:
|
||||||
# - Don't leave anything extra in here either
|
# - Don't leave anything extra in here either
|
||||||
FROM ghcr.io/astral-sh/uv:0.13.7-python3.14-trixie-slim@sha256:e80c05a310400cfc90af00b5b7271ef9ad24816e3265e1162af8a678e1aad099 AS s6-overlay-base
|
FROM ghcr.io/astral-sh/uv:0.13.10-python3.14-trixie-slim@sha256:b093dbbd7963c765325ecdf866d42915f5327e135569f9dae9c77cac63559bf2 AS s6-overlay-base
|
||||||
|
|
||||||
WORKDIR /usr/src/s6
|
WORKDIR /usr/src/s6
|
||||||
|
|
||||||
@@ -129,10 +129,10 @@ ARG RUNTIME_PACKAGES="\
|
|||||||
ghostscript \
|
ghostscript \
|
||||||
gnupg \
|
gnupg \
|
||||||
icc-profiles-free \
|
icc-profiles-free \
|
||||||
# PostgreSQL client library, used by psycopg
|
# PostgreSQL
|
||||||
libpq5 \
|
postgresql-client \
|
||||||
# MariaDB client library, used by mysqlclient
|
# MySQL / MariaDB
|
||||||
libmariadb3 \
|
mariadb-client \
|
||||||
# OCRmyPDF dependencies
|
# OCRmyPDF dependencies
|
||||||
tesseract-ocr \
|
tesseract-ocr \
|
||||||
tesseract-ocr-eng \
|
tesseract-ocr-eng \
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ services:
|
|||||||
- "3143:3143" # IMAP
|
- "3143:3143" # IMAP
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
nginx:
|
nginx:
|
||||||
image: docker.io/nginx:1.31.7-alpine
|
image: docker.io/nginx:1.31.9-alpine
|
||||||
hostname: nginx
|
hostname: nginx
|
||||||
container_name: nginx
|
container_name: nginx
|
||||||
ports:
|
ports:
|
||||||
|
|||||||
@@ -32,11 +32,15 @@ services:
|
|||||||
broker:
|
broker:
|
||||||
image: docker.io/valkey/valkey:9-alpine
|
image: docker.io/valkey/valkey:9-alpine
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- backend
|
||||||
volumes:
|
volumes:
|
||||||
- redisdata:/data
|
- redisdata:/data
|
||||||
db:
|
db:
|
||||||
image: docker.io/library/mariadb:12
|
image: docker.io/library/mariadb:12
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- backend
|
||||||
volumes:
|
volumes:
|
||||||
- dbdata:/var/lib/mysql
|
- dbdata:/var/lib/mysql
|
||||||
environment:
|
environment:
|
||||||
@@ -47,6 +51,9 @@ services:
|
|||||||
webserver:
|
webserver:
|
||||||
image: ghcr.io/paperless-ngx/paperless-ngx:latest
|
image: ghcr.io/paperless-ngx/paperless-ngx:latest
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- backend
|
||||||
|
- document-processing
|
||||||
depends_on:
|
depends_on:
|
||||||
- db
|
- db
|
||||||
- broker
|
- broker
|
||||||
@@ -73,6 +80,8 @@ services:
|
|||||||
gotenberg:
|
gotenberg:
|
||||||
image: docker.io/gotenberg/gotenberg:8.38
|
image: docker.io/gotenberg/gotenberg:8.38
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- document-processing
|
||||||
# The gotenberg chromium route is used to convert .eml files. We do not
|
# The gotenberg chromium route is used to convert .eml files. We do not
|
||||||
# want to allow external content like tracking pixels or even javascript.
|
# want to allow external content like tracking pixels or even javascript.
|
||||||
command:
|
command:
|
||||||
@@ -82,6 +91,12 @@ services:
|
|||||||
tika:
|
tika:
|
||||||
image: docker.io/apache/tika:3.3.1.0
|
image: docker.io/apache/tika:3.3.1.0
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- document-processing
|
||||||
|
networks:
|
||||||
|
backend:
|
||||||
|
document-processing:
|
||||||
|
internal: true
|
||||||
volumes:
|
volumes:
|
||||||
data:
|
data:
|
||||||
media:
|
media:
|
||||||
|
|||||||
@@ -32,11 +32,15 @@ services:
|
|||||||
broker:
|
broker:
|
||||||
image: docker.io/valkey/valkey:9-alpine
|
image: docker.io/valkey/valkey:9-alpine
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- backend
|
||||||
volumes:
|
volumes:
|
||||||
- redisdata:/data
|
- redisdata:/data
|
||||||
db:
|
db:
|
||||||
image: docker.io/library/postgres:18
|
image: docker.io/library/postgres:18
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- backend
|
||||||
volumes:
|
volumes:
|
||||||
- pgdata:/var/lib/postgresql
|
- pgdata:/var/lib/postgresql
|
||||||
environment:
|
environment:
|
||||||
@@ -46,6 +50,9 @@ services:
|
|||||||
webserver:
|
webserver:
|
||||||
image: ghcr.io/paperless-ngx/paperless-ngx:latest
|
image: ghcr.io/paperless-ngx/paperless-ngx:latest
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- backend
|
||||||
|
- document-processing
|
||||||
depends_on:
|
depends_on:
|
||||||
- db
|
- db
|
||||||
- broker
|
- broker
|
||||||
@@ -69,6 +76,8 @@ services:
|
|||||||
gotenberg:
|
gotenberg:
|
||||||
image: docker.io/gotenberg/gotenberg:8.38
|
image: docker.io/gotenberg/gotenberg:8.38
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- document-processing
|
||||||
# The gotenberg chromium route is used to convert .eml files. We do not
|
# The gotenberg chromium route is used to convert .eml files. We do not
|
||||||
# want to allow external content like tracking pixels or even javascript.
|
# want to allow external content like tracking pixels or even javascript.
|
||||||
command:
|
command:
|
||||||
@@ -78,6 +87,12 @@ services:
|
|||||||
tika:
|
tika:
|
||||||
image: docker.io/apache/tika:3.3.1.0
|
image: docker.io/apache/tika:3.3.1.0
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- document-processing
|
||||||
|
networks:
|
||||||
|
backend:
|
||||||
|
document-processing:
|
||||||
|
internal: true
|
||||||
volumes:
|
volumes:
|
||||||
data:
|
data:
|
||||||
media:
|
media:
|
||||||
|
|||||||
@@ -32,11 +32,16 @@ services:
|
|||||||
broker:
|
broker:
|
||||||
image: docker.io/valkey/valkey:9-alpine
|
image: docker.io/valkey/valkey:9-alpine
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- backend
|
||||||
volumes:
|
volumes:
|
||||||
- redisdata:/data
|
- redisdata:/data
|
||||||
webserver:
|
webserver:
|
||||||
image: ghcr.io/paperless-ngx/paperless-ngx:latest
|
image: ghcr.io/paperless-ngx/paperless-ngx:latest
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- backend
|
||||||
|
- document-processing
|
||||||
depends_on:
|
depends_on:
|
||||||
- broker
|
- broker
|
||||||
- gotenberg
|
- gotenberg
|
||||||
@@ -58,6 +63,8 @@ services:
|
|||||||
gotenberg:
|
gotenberg:
|
||||||
image: docker.io/gotenberg/gotenberg:8.38
|
image: docker.io/gotenberg/gotenberg:8.38
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- document-processing
|
||||||
# The gotenberg chromium route is used to convert .eml files. We do not
|
# The gotenberg chromium route is used to convert .eml files. We do not
|
||||||
# want to allow external content like tracking pixels or even javascript.
|
# want to allow external content like tracking pixels or even javascript.
|
||||||
command:
|
command:
|
||||||
@@ -67,6 +74,12 @@ services:
|
|||||||
tika:
|
tika:
|
||||||
image: docker.io/apache/tika:3.3.1.0
|
image: docker.io/apache/tika:3.3.1.0
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
networks:
|
||||||
|
- document-processing
|
||||||
|
networks:
|
||||||
|
backend:
|
||||||
|
document-processing:
|
||||||
|
internal: true
|
||||||
volumes:
|
volumes:
|
||||||
data:
|
data:
|
||||||
media:
|
media:
|
||||||
|
|||||||
@@ -1,66 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
"""
|
|
||||||
Single-shot database readiness probe used by the init-wait-for-db s6 service.
|
|
||||||
|
|
||||||
Exits 0 if the database server is accepting connections, 1 otherwise. The
|
|
||||||
retry and backoff loop lives in the calling shell script.
|
|
||||||
|
|
||||||
This replaces pg_isready / mariadb-admin ping, so the image does not need the
|
|
||||||
PostgreSQL or MariaDB command line clients. Like those tools, this only checks
|
|
||||||
that the server answers. A server which responds with an error, such as bad
|
|
||||||
credentials or an unknown database, counts as ready, so the real error is
|
|
||||||
reported by the migrations step instead of this one timing out.
|
|
||||||
"""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
CONNECT_TIMEOUT = 5
|
|
||||||
|
|
||||||
|
|
||||||
def postgres_ready() -> bool:
|
|
||||||
from psycopg import pq
|
|
||||||
from psycopg.conninfo import make_conninfo
|
|
||||||
|
|
||||||
# This is libpq's PQping, which is what pg_isready uses. It reports OK when
|
|
||||||
# the server answers, even if it would refuse these credentials, and REJECT
|
|
||||||
# when the server is up but still starting or shutting down.
|
|
||||||
conninfo = make_conninfo(
|
|
||||||
host=os.environ.get("PAPERLESS_DBHOST", "localhost"),
|
|
||||||
port=int(os.environ.get("PAPERLESS_DBPORT", "5432")),
|
|
||||||
user=os.environ.get("PAPERLESS_DBUSER", "paperless"),
|
|
||||||
connect_timeout=CONNECT_TIMEOUT,
|
|
||||||
)
|
|
||||||
return pq.PGconn.ping(conninfo.encode()) == pq.Ping.OK
|
|
||||||
|
|
||||||
|
|
||||||
def mariadb_ready() -> bool:
|
|
||||||
import MySQLdb
|
|
||||||
|
|
||||||
try:
|
|
||||||
MySQLdb.connect(
|
|
||||||
host=os.environ.get("PAPERLESS_DBHOST", "localhost"),
|
|
||||||
port=int(os.environ.get("PAPERLESS_DBPORT", "3306")),
|
|
||||||
user=os.environ.get("PAPERLESS_DBUSER", "paperless"),
|
|
||||||
passwd=os.environ.get("PAPERLESS_DBPASS", "paperless"),
|
|
||||||
connect_timeout=CONNECT_TIMEOUT,
|
|
||||||
).close()
|
|
||||||
return True
|
|
||||||
except MySQLdb.OperationalError as e:
|
|
||||||
# Codes below 2000 are errors sent by the server (access denied, too
|
|
||||||
# many connections, ...). 2000+ are client side (can't connect, lost
|
|
||||||
# connection), meaning the server was not reached.
|
|
||||||
code = e.args[0] if e.args and isinstance(e.args[0], int) else 0
|
|
||||||
return 0 < code < 2000
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
if os.environ.get("PAPERLESS_DBENGINE") == "mariadb":
|
|
||||||
ready = mariadb_ready()
|
|
||||||
else:
|
|
||||||
ready = postgres_ready()
|
|
||||||
return 0 if ready else 1
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
@@ -7,7 +7,6 @@ set -euo pipefail
|
|||||||
declare -r LOG_PREFIX="[init-db-wait]"
|
declare -r LOG_PREFIX="[init-db-wait]"
|
||||||
|
|
||||||
declare -ri TIMEOUT=60
|
declare -ri TIMEOUT=60
|
||||||
declare -r PROBE="/etc/s6-overlay/s6-rc.d/init-wait-for-db/db_ready.py"
|
|
||||||
declare -i ATTEMPT=0
|
declare -i ATTEMPT=0
|
||||||
declare -i DELAY=0
|
declare -i DELAY=0
|
||||||
declare -i STARTED_AT=${EPOCHSECONDS:?EPOCHSECONDS var unset}
|
declare -i STARTED_AT=${EPOCHSECONDS:?EPOCHSECONDS var unset}
|
||||||
@@ -36,7 +35,11 @@ delay_next_attempt() {
|
|||||||
wait_for_postgres() {
|
wait_for_postgres() {
|
||||||
echo "${LOG_PREFIX} Waiting for PostgreSQL to start..."
|
echo "${LOG_PREFIX} Waiting for PostgreSQL to start..."
|
||||||
|
|
||||||
while ! python3 "${PROBE}"; do
|
local -r host="${PAPERLESS_DBHOST:-localhost}"
|
||||||
|
local -r port="${PAPERLESS_DBPORT:-5432}"
|
||||||
|
local -r user="${PAPERLESS_DBUSER:-paperless}"
|
||||||
|
|
||||||
|
while ! pg_isready -h "${host}" -p "${port}" --username "${user}"; do
|
||||||
delay_next_attempt
|
delay_next_attempt
|
||||||
done
|
done
|
||||||
echo "${LOG_PREFIX} Connected to PostgreSQL"
|
echo "${LOG_PREFIX} Connected to PostgreSQL"
|
||||||
@@ -45,7 +48,10 @@ wait_for_postgres() {
|
|||||||
wait_for_mariadb() {
|
wait_for_mariadb() {
|
||||||
echo "${LOG_PREFIX} Waiting for MariaDB to start..."
|
echo "${LOG_PREFIX} Waiting for MariaDB to start..."
|
||||||
|
|
||||||
while ! python3 "${PROBE}"; do
|
local -r host="${PAPERLESS_DBHOST:-localhost}"
|
||||||
|
local -r port="${PAPERLESS_DBPORT:-3306}"
|
||||||
|
|
||||||
|
while ! mariadb-admin --host="${host}" --port="${port}" --skip-ssl ping --silent >/dev/null 2>&1; do
|
||||||
delay_next_attempt
|
delay_next_attempt
|
||||||
done
|
done
|
||||||
echo "${LOG_PREFIX} Connected to MariaDB"
|
echo "${LOG_PREFIX} Connected to MariaDB"
|
||||||
|
|||||||
@@ -30,6 +30,7 @@
|
|||||||
"fa-IR": "src/locale/messages.fa_IR.xlf",
|
"fa-IR": "src/locale/messages.fa_IR.xlf",
|
||||||
"fi-FI": "src/locale/messages.fi_FI.xlf",
|
"fi-FI": "src/locale/messages.fi_FI.xlf",
|
||||||
"fr-FR": "src/locale/messages.fr_FR.xlf",
|
"fr-FR": "src/locale/messages.fr_FR.xlf",
|
||||||
|
"hr-HR": "src/locale/messages.hr_HR.xlf",
|
||||||
"hu-HU": "src/locale/messages.hu_HU.xlf",
|
"hu-HU": "src/locale/messages.hu_HU.xlf",
|
||||||
"id-ID": "src/locale/messages.id_ID.xlf",
|
"id-ID": "src/locale/messages.id_ID.xlf",
|
||||||
"it-IT": "src/locale/messages.it_IT.xlf",
|
"it-IT": "src/locale/messages.it_IT.xlf",
|
||||||
|
|||||||
+72
-65
@@ -5,14 +5,14 @@
|
|||||||
<trans-unit id="ngb.alert.close" datatype="html">
|
<trans-unit id="ngb.alert.close" datatype="html">
|
||||||
<source>Close</source>
|
<source>Close</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/alert/alert.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/alert/alert.ts</context>
|
||||||
<context context-type="linenumber">38,39</context>
|
<context context-type="linenumber">38,39</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.carousel.slide-number" datatype="html">
|
<trans-unit id="ngb.carousel.slide-number" datatype="html">
|
||||||
<source> Slide <x id="INTERPOLATION" equiv-text="source?: NgbSli"/> of <x id="INTERPOLATION_1" equiv-text="s._cycleToSelec"/> </source>
|
<source> Slide <x id="INTERPOLATION" equiv-text="source?: NgbSli"/> of <x id="INTERPOLATION_1" equiv-text="s._cycleToSelec"/> </source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/carousel/carousel.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/carousel/carousel.ts</context>
|
||||||
<context context-type="linenumber">386,393</context>
|
<context context-type="linenumber">386,393</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
<note priority="1" from="description">Currently selected slide number read by screen reader</note>
|
<note priority="1" from="description">Currently selected slide number read by screen reader</note>
|
||||||
@@ -20,219 +20,219 @@
|
|||||||
<trans-unit id="ngb.carousel.previous" datatype="html">
|
<trans-unit id="ngb.carousel.previous" datatype="html">
|
||||||
<source>Previous</source>
|
<source>Previous</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/carousel/carousel.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/carousel/carousel.ts</context>
|
||||||
<context context-type="linenumber">425,426</context>
|
<context context-type="linenumber">425,426</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.carousel.next" datatype="html">
|
<trans-unit id="ngb.carousel.next" datatype="html">
|
||||||
<source>Next</source>
|
<source>Next</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/carousel/carousel.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/carousel/carousel.ts</context>
|
||||||
<context context-type="linenumber">452,453</context>
|
<context context-type="linenumber">452,453</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.datepicker.select-month" datatype="html">
|
<trans-unit id="ngb.datepicker.select-month" datatype="html">
|
||||||
<source>Select month</source>
|
<source>Select month</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
|
||||||
<context context-type="linenumber">52</context>
|
<context context-type="linenumber">52</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
|
||||||
<context context-type="linenumber">52</context>
|
<context context-type="linenumber">52</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.datepicker.select-year" datatype="html">
|
<trans-unit id="ngb.datepicker.select-year" datatype="html">
|
||||||
<source>Select year</source>
|
<source>Select year</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
|
||||||
<context context-type="linenumber">52</context>
|
<context context-type="linenumber">52</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation-select.ts</context>
|
||||||
<context context-type="linenumber">52</context>
|
<context context-type="linenumber">52</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.datepicker.previous-month" datatype="html">
|
<trans-unit id="ngb.datepicker.previous-month" datatype="html">
|
||||||
<source>Previous month</source>
|
<source>Previous month</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation.ts</context>
|
||||||
<context context-type="linenumber">73,76</context>
|
<context context-type="linenumber">73,76</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation.ts</context>
|
||||||
<context context-type="linenumber">73,76</context>
|
<context context-type="linenumber">73,76</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.datepicker.next-month" datatype="html">
|
<trans-unit id="ngb.datepicker.next-month" datatype="html">
|
||||||
<source>Next month</source>
|
<source>Next month</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation.ts</context>
|
||||||
<context context-type="linenumber">73,74</context>
|
<context context-type="linenumber">73,74</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/datepicker/datepicker-navigation.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/datepicker/datepicker-navigation.ts</context>
|
||||||
<context context-type="linenumber">73,74</context>
|
<context context-type="linenumber">73,74</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.pagination.first" datatype="html">
|
<trans-unit id="ngb.pagination.first" datatype="html">
|
||||||
<source>««</source>
|
<source>««</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
|
||||||
<context context-type="linenumber">277,278</context>
|
<context context-type="linenumber">277,278</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.pagination.previous" datatype="html">
|
<trans-unit id="ngb.pagination.previous" datatype="html">
|
||||||
<source>«</source>
|
<source>«</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
|
||||||
<context context-type="linenumber">277,278</context>
|
<context context-type="linenumber">277,278</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.pagination.next" datatype="html">
|
<trans-unit id="ngb.pagination.next" datatype="html">
|
||||||
<source>»</source>
|
<source>»</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
|
||||||
<context context-type="linenumber">277</context>
|
<context context-type="linenumber">277</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.pagination.last" datatype="html">
|
<trans-unit id="ngb.pagination.last" datatype="html">
|
||||||
<source>»»</source>
|
<source>»»</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
|
||||||
<context context-type="linenumber">277</context>
|
<context context-type="linenumber">277</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.pagination.first-aria" datatype="html">
|
<trans-unit id="ngb.pagination.first-aria" datatype="html">
|
||||||
<source>First</source>
|
<source>First</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
|
||||||
<context context-type="linenumber">277,278</context>
|
<context context-type="linenumber">277,278</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.pagination.previous-aria" datatype="html">
|
<trans-unit id="ngb.pagination.previous-aria" datatype="html">
|
||||||
<source>Previous</source>
|
<source>Previous</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
|
||||||
<context context-type="linenumber">277,278</context>
|
<context context-type="linenumber">277,278</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.pagination.next-aria" datatype="html">
|
<trans-unit id="ngb.pagination.next-aria" datatype="html">
|
||||||
<source>Next</source>
|
<source>Next</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
|
||||||
<context context-type="linenumber">277,278</context>
|
<context context-type="linenumber">277,278</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.pagination.last-aria" datatype="html">
|
<trans-unit id="ngb.pagination.last-aria" datatype="html">
|
||||||
<source>Last</source>
|
<source>Last</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/pagination/pagination.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/pagination/pagination.ts</context>
|
||||||
<context context-type="linenumber">277,278</context>
|
<context context-type="linenumber">277,278</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.progressbar.value" datatype="html">
|
<trans-unit id="ngb.progressbar.value" datatype="html">
|
||||||
<source><x id="INTERPOLATION"/></source>
|
<source><x id="INTERPOLATION"/></source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/progressbar/progressbar.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/progressbar/progressbar.ts</context>
|
||||||
<context context-type="linenumber">39,40</context>
|
<context context-type="linenumber">39,40</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.timepicker.HH" datatype="html">
|
<trans-unit id="ngb.timepicker.HH" datatype="html">
|
||||||
<source>HH</source>
|
<source>HH</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
|
||||||
<context context-type="linenumber">442</context>
|
<context context-type="linenumber">442</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.timepicker.hours" datatype="html">
|
<trans-unit id="ngb.timepicker.hours" datatype="html">
|
||||||
<source>Hours</source>
|
<source>Hours</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
|
||||||
<context context-type="linenumber">442</context>
|
<context context-type="linenumber">442</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.timepicker.MM" datatype="html">
|
<trans-unit id="ngb.timepicker.MM" datatype="html">
|
||||||
<source>MM</source>
|
<source>MM</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
|
||||||
<context context-type="linenumber">442</context>
|
<context context-type="linenumber">442</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.timepicker.minutes" datatype="html">
|
<trans-unit id="ngb.timepicker.minutes" datatype="html">
|
||||||
<source>Minutes</source>
|
<source>Minutes</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
|
||||||
<context context-type="linenumber">442</context>
|
<context context-type="linenumber">442</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.timepicker.increment-hours" datatype="html">
|
<trans-unit id="ngb.timepicker.increment-hours" datatype="html">
|
||||||
<source>Increment hours</source>
|
<source>Increment hours</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
|
||||||
<context context-type="linenumber">442</context>
|
<context context-type="linenumber">442</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.timepicker.decrement-hours" datatype="html">
|
<trans-unit id="ngb.timepicker.decrement-hours" datatype="html">
|
||||||
<source>Decrement hours</source>
|
<source>Decrement hours</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
|
||||||
<context context-type="linenumber">442</context>
|
<context context-type="linenumber">442</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.timepicker.increment-minutes" datatype="html">
|
<trans-unit id="ngb.timepicker.increment-minutes" datatype="html">
|
||||||
<source>Increment minutes</source>
|
<source>Increment minutes</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
|
||||||
<context context-type="linenumber">442</context>
|
<context context-type="linenumber">442</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.timepicker.decrement-minutes" datatype="html">
|
<trans-unit id="ngb.timepicker.decrement-minutes" datatype="html">
|
||||||
<source>Decrement minutes</source>
|
<source>Decrement minutes</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
|
||||||
<context context-type="linenumber">442</context>
|
<context context-type="linenumber">442</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.timepicker.SS" datatype="html">
|
<trans-unit id="ngb.timepicker.SS" datatype="html">
|
||||||
<source>SS</source>
|
<source>SS</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
|
||||||
<context context-type="linenumber">442</context>
|
<context context-type="linenumber">442</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.timepicker.seconds" datatype="html">
|
<trans-unit id="ngb.timepicker.seconds" datatype="html">
|
||||||
<source>Seconds</source>
|
<source>Seconds</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
|
||||||
<context context-type="linenumber">442</context>
|
<context context-type="linenumber">442</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.timepicker.increment-seconds" datatype="html">
|
<trans-unit id="ngb.timepicker.increment-seconds" datatype="html">
|
||||||
<source>Increment seconds</source>
|
<source>Increment seconds</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
|
||||||
<context context-type="linenumber">442</context>
|
<context context-type="linenumber">442</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.timepicker.decrement-seconds" datatype="html">
|
<trans-unit id="ngb.timepicker.decrement-seconds" datatype="html">
|
||||||
<source>Decrement seconds</source>
|
<source>Decrement seconds</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
|
||||||
<context context-type="linenumber">442</context>
|
<context context-type="linenumber">442</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.timepicker.PM" datatype="html">
|
<trans-unit id="ngb.timepicker.PM" datatype="html">
|
||||||
<source><x id="INTERPOLATION"/></source>
|
<source><x id="INTERPOLATION"/></source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/timepicker/timepicker.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/timepicker/timepicker.ts</context>
|
||||||
<context context-type="linenumber">442</context>
|
<context context-type="linenumber">442</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="ngb.toast.close-aria" datatype="html">
|
<trans-unit id="ngb.toast.close-aria" datatype="html">
|
||||||
<source>Close</source>
|
<source>Close</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.2.3_@angular+core@22.2.3_@angular+_2a970977f09c8afdd1f9933e219c8db5/node_modules/src/toast/toast.ts</context>
|
<context context-type="sourcefile">node_modules/.pnpm/@ng-bootstrap+ng-bootstrap@21.0.0_@angular+common@22.3.0_@angular+core@22.3.0_@angular+_a7f2e22ebef7f277c3d304e2c62cd610/node_modules/src/toast/toast.ts</context>
|
||||||
<context context-type="linenumber">80</context>
|
<context context-type="linenumber">80</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
@@ -9250,7 +9250,7 @@
|
|||||||
</context-group>
|
</context-group>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/main.ts</context>
|
<context context-type="sourcefile">src/main.ts</context>
|
||||||
<context context-type="linenumber">168</context>
|
<context context-type="linenumber">170</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="5028777105388019087" datatype="html">
|
<trans-unit id="5028777105388019087" datatype="html">
|
||||||
@@ -12635,7 +12635,7 @@
|
|||||||
</context-group>
|
</context-group>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">153</context>
|
<context context-type="linenumber">159</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="5190825892106392539" datatype="html">
|
<trans-unit id="5190825892106392539" datatype="html">
|
||||||
@@ -12657,7 +12657,7 @@
|
|||||||
</context-group>
|
</context-group>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">207</context>
|
<context context-type="linenumber">213</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="3071065188816255493" datatype="html">
|
<trans-unit id="3071065188816255493" datatype="html">
|
||||||
@@ -12668,7 +12668,7 @@
|
|||||||
</context-group>
|
</context-group>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">177</context>
|
<context context-type="linenumber">183</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="1622944968441880123" datatype="html">
|
<trans-unit id="1622944968441880123" datatype="html">
|
||||||
@@ -14393,172 +14393,179 @@
|
|||||||
<context context-type="linenumber">129</context>
|
<context context-type="linenumber">129</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
|
<trans-unit id="4825433858141848865" datatype="html">
|
||||||
|
<source>Croatian</source>
|
||||||
|
<context-group purpose="location">
|
||||||
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
|
<context context-type="linenumber">141</context>
|
||||||
|
</context-group>
|
||||||
|
</trans-unit>
|
||||||
<trans-unit id="7891809788881004730" datatype="html">
|
<trans-unit id="7891809788881004730" datatype="html">
|
||||||
<source>Hungarian</source>
|
<source>Hungarian</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">141</context>
|
<context context-type="linenumber">147</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="8312065814232621608" datatype="html">
|
<trans-unit id="8312065814232621608" datatype="html">
|
||||||
<source>Indonesian</source>
|
<source>Indonesian</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">147</context>
|
<context context-type="linenumber">153</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="6924606686202701860" datatype="html">
|
<trans-unit id="6924606686202701860" datatype="html">
|
||||||
<source>Japanese</source>
|
<source>Japanese</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">159</context>
|
<context context-type="linenumber">165</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="6145439649200570157" datatype="html">
|
<trans-unit id="6145439649200570157" datatype="html">
|
||||||
<source>Korean</source>
|
<source>Korean</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">165</context>
|
<context context-type="linenumber">171</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="1334425850005897370" datatype="html">
|
<trans-unit id="1334425850005897370" datatype="html">
|
||||||
<source>Luxembourgish</source>
|
<source>Luxembourgish</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">171</context>
|
<context context-type="linenumber">177</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="8069284467804715623" datatype="html">
|
<trans-unit id="8069284467804715623" datatype="html">
|
||||||
<source>Norwegian</source>
|
<source>Norwegian</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">183</context>
|
<context context-type="linenumber">189</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="4977087909184008115" datatype="html">
|
<trans-unit id="4977087909184008115" datatype="html">
|
||||||
<source>Persian</source>
|
<source>Persian</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">189</context>
|
<context context-type="linenumber">195</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="792060551707690640" datatype="html">
|
<trans-unit id="792060551707690640" datatype="html">
|
||||||
<source>Polish</source>
|
<source>Polish</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">195</context>
|
<context context-type="linenumber">201</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="9184513005098760425" datatype="html">
|
<trans-unit id="9184513005098760425" datatype="html">
|
||||||
<source>Portuguese (Brazil)</source>
|
<source>Portuguese (Brazil)</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">201</context>
|
<context context-type="linenumber">207</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="8118856427047826368" datatype="html">
|
<trans-unit id="8118856427047826368" datatype="html">
|
||||||
<source>Romanian</source>
|
<source>Romanian</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">213</context>
|
<context context-type="linenumber">219</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="7137419789978325708" datatype="html">
|
<trans-unit id="7137419789978325708" datatype="html">
|
||||||
<source>Russian</source>
|
<source>Russian</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">219</context>
|
<context context-type="linenumber">225</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="9102963095355753902" datatype="html">
|
<trans-unit id="9102963095355753902" datatype="html">
|
||||||
<source>Slovak</source>
|
<source>Slovak</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">225</context>
|
<context context-type="linenumber">231</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="4287008301409320881" datatype="html">
|
<trans-unit id="4287008301409320881" datatype="html">
|
||||||
<source>Slovenian</source>
|
<source>Slovenian</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">231</context>
|
<context context-type="linenumber">237</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="8608389829607915090" datatype="html">
|
<trans-unit id="8608389829607915090" datatype="html">
|
||||||
<source>Serbian</source>
|
<source>Serbian</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">237</context>
|
<context context-type="linenumber">243</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="499386805970351976" datatype="html">
|
<trans-unit id="499386805970351976" datatype="html">
|
||||||
<source>Swedish</source>
|
<source>Swedish</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">243</context>
|
<context context-type="linenumber">249</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="5682359291233237791" datatype="html">
|
<trans-unit id="5682359291233237791" datatype="html">
|
||||||
<source>Turkish</source>
|
<source>Turkish</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">249</context>
|
<context context-type="linenumber">255</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="3578644052206125685" datatype="html">
|
<trans-unit id="3578644052206125685" datatype="html">
|
||||||
<source>Ukrainian</source>
|
<source>Ukrainian</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">255</context>
|
<context context-type="linenumber">261</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="3611216939636790848" datatype="html">
|
<trans-unit id="3611216939636790848" datatype="html">
|
||||||
<source>Vietnamese</source>
|
<source>Vietnamese</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">261</context>
|
<context context-type="linenumber">267</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="4689443708886954687" datatype="html">
|
<trans-unit id="4689443708886954687" datatype="html">
|
||||||
<source>Chinese Simplified</source>
|
<source>Chinese Simplified</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">267</context>
|
<context context-type="linenumber">273</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="8082606363137705994" datatype="html">
|
<trans-unit id="8082606363137705994" datatype="html">
|
||||||
<source>Chinese Traditional</source>
|
<source>Chinese Traditional</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">273</context>
|
<context context-type="linenumber">279</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="4912706592792948707" datatype="html">
|
<trans-unit id="4912706592792948707" datatype="html">
|
||||||
<source>ISO 8601</source>
|
<source>ISO 8601</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">281</context>
|
<context context-type="linenumber">287</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="313643372755303297" datatype="html">
|
<trans-unit id="313643372755303297" datatype="html">
|
||||||
<source>Successfully completed one-time migratration of settings to the database!</source>
|
<source>Successfully completed one-time migratration of settings to the database!</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">675</context>
|
<context context-type="linenumber">681</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="5558341108007064934" datatype="html">
|
<trans-unit id="5558341108007064934" datatype="html">
|
||||||
<source>Unable to migrate settings to the database, please try saving manually.</source>
|
<source>Unable to migrate settings to the database, please try saving manually.</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">676</context>
|
<context context-type="linenumber">682</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="1168781785897678748" datatype="html">
|
<trans-unit id="1168781785897678748" datatype="html">
|
||||||
<source>You can restart the tour from the settings page.</source>
|
<source>You can restart the tour from the settings page.</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
<context context-type="sourcefile">src/app/services/settings.service.ts</context>
|
||||||
<context context-type="linenumber">787</context>
|
<context context-type="linenumber">793</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="1283895920974679461" datatype="html">
|
<trans-unit id="1283895920974679461" datatype="html">
|
||||||
@@ -14884,14 +14891,14 @@
|
|||||||
<source>Prev</source>
|
<source>Prev</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/main.ts</context>
|
<context context-type="sourcefile">src/main.ts</context>
|
||||||
<context context-type="linenumber">167</context>
|
<context context-type="linenumber">169</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
<trans-unit id="1241348629231510663" datatype="html">
|
<trans-unit id="1241348629231510663" datatype="html">
|
||||||
<source>End</source>
|
<source>End</source>
|
||||||
<context-group purpose="location">
|
<context-group purpose="location">
|
||||||
<context context-type="sourcefile">src/main.ts</context>
|
<context context-type="sourcefile">src/main.ts</context>
|
||||||
<context context-type="linenumber">169</context>
|
<context context-type="linenumber">171</context>
|
||||||
</context-group>
|
</context-group>
|
||||||
</trans-unit>
|
</trans-unit>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
+30
-30
@@ -15,60 +15,60 @@
|
|||||||
},
|
},
|
||||||
"private": true,
|
"private": true,
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@angular/cdk": "^22.2.4",
|
"@angular/cdk": "^22.3.0",
|
||||||
"@angular/common": "~22.2.3",
|
"@angular/common": "~22.3.0",
|
||||||
"@angular/compiler": "~22.2.3",
|
"@angular/compiler": "~22.3.0",
|
||||||
"@angular/core": "~22.2.3",
|
"@angular/core": "~22.3.0",
|
||||||
"@angular/forms": "~22.2.3",
|
"@angular/forms": "~22.3.0",
|
||||||
"@angular/localize": "~22.2.3",
|
"@angular/localize": "~22.3.0",
|
||||||
"@angular/platform-browser": "~22.2.3",
|
"@angular/platform-browser": "~22.3.0",
|
||||||
"@angular/router": "~22.2.3",
|
"@angular/router": "~22.3.0",
|
||||||
"@ng-bootstrap/ng-bootstrap": "^21.0.0",
|
"@ng-bootstrap/ng-bootstrap": "^21.0.0",
|
||||||
"@ng-select/ng-select": "~24.2.1",
|
"@ng-select/ng-select": "~24.2.1",
|
||||||
"@ngneat/dirty-check-forms": "^3.0.3",
|
"@ngneat/dirty-check-forms": "^3.0.3",
|
||||||
"@popperjs/core": "^2.11.8",
|
"@popperjs/core": "^2.11.8",
|
||||||
"bootstrap": "^5.3.8",
|
"bootstrap": "^5.3.9",
|
||||||
"bootstrap-icons": "^1.13.2",
|
"bootstrap-icons": "^1.13.2",
|
||||||
"file-saver": "^2.0.5",
|
"file-saver": "^2.0.5",
|
||||||
"lodash-es": "^4.18.1",
|
"lodash-es": "^4.18.1",
|
||||||
"marked": "~18.1.1",
|
"marked": "~18.3.0",
|
||||||
"mime-names": "^1.0.0",
|
"mime-names": "^1.0.0",
|
||||||
"ngx-color": "^10.1.0",
|
"ngx-color": "^10.1.0",
|
||||||
"ngx-cookie-service": "^22.0.0",
|
"ngx-cookie-service": "^22.2.0",
|
||||||
"ngx-device-detector": "^12.0.0",
|
"ngx-device-detector": "^12.0.0",
|
||||||
"ngx-ui-tour-ng-bootstrap": "^19.0.0",
|
"ngx-ui-tour-ng-bootstrap": "^19.0.0",
|
||||||
"normalize-diacritics": "^5.0.0",
|
"normalize-diacritics": "^5.0.0",
|
||||||
"pdfjs-dist": "^6.4.299",
|
"pdfjs-dist": "^6.5.438",
|
||||||
"rxjs": "^7.8.2",
|
"rxjs": "^7.8.2",
|
||||||
"tslib": "^2.8.1",
|
"tslib": "^2.9.1",
|
||||||
"utif": "^3.1.0",
|
"utif": "^3.1.0",
|
||||||
"uuid": "^14.0.3"
|
"uuid": "^14.0.3"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@angular-builders/jest": "^22.0.1",
|
"@angular-builders/jest": "^22.0.1",
|
||||||
"@angular-devkit/core": "^22.2.4",
|
"@angular-devkit/core": "^22.3.0",
|
||||||
"@angular-devkit/schematics": "^22.2.4",
|
"@angular-devkit/schematics": "^22.3.0",
|
||||||
"@angular-eslint/builder": "22.6.0",
|
"@angular-eslint/builder": "22.8.0",
|
||||||
"@angular-eslint/eslint-plugin": "22.6.0",
|
"@angular-eslint/eslint-plugin": "22.8.0",
|
||||||
"@angular-eslint/eslint-plugin-template": "22.6.0",
|
"@angular-eslint/eslint-plugin-template": "22.8.0",
|
||||||
"@angular-eslint/schematics": "22.6.0",
|
"@angular-eslint/schematics": "22.8.0",
|
||||||
"@angular-eslint/template-parser": "22.6.0",
|
"@angular-eslint/template-parser": "22.8.0",
|
||||||
"@angular/build": "22.2.4",
|
"@angular/build": "22.3.0",
|
||||||
"@angular/cli": "22.2.4",
|
"@angular/cli": "22.3.0",
|
||||||
"@angular/compiler-cli": "~22.2.3",
|
"@angular/compiler-cli": "~22.3.0",
|
||||||
"@playwright/test": "^1.64.1",
|
"@playwright/test": "^1.65.1",
|
||||||
"@types/jest": "^30.0.0",
|
"@types/jest": "^30.0.0",
|
||||||
"@types/node": "^26.6.5",
|
"@types/node": "^26.6.7",
|
||||||
"@typescript-eslint/eslint-plugin": "^8.72.0",
|
"@typescript-eslint/eslint-plugin": "^8.74.0",
|
||||||
"@typescript-eslint/parser": "^8.72.0",
|
"@typescript-eslint/parser": "^8.74.0",
|
||||||
"@typescript-eslint/utils": "^8.72.0",
|
"@typescript-eslint/utils": "^8.74.0",
|
||||||
"eslint": "^10.13.0",
|
"eslint": "^10.15.0",
|
||||||
"jest": "30.5.2",
|
"jest": "30.5.2",
|
||||||
"jest-environment-jsdom": "^30.5.2",
|
"jest-environment-jsdom": "^30.5.2",
|
||||||
"jest-junit": "^17.0.0",
|
"jest-junit": "^17.0.0",
|
||||||
"jest-preset-angular": "^17.0.3",
|
"jest-preset-angular": "^17.0.3",
|
||||||
"jest-websocket-mock": "^2.5.0",
|
"jest-websocket-mock": "^2.5.0",
|
||||||
"prettier": "^3.9.10",
|
"prettier": "^3.10.1",
|
||||||
"prettier-plugin-organize-imports": "^4.3.0",
|
"prettier-plugin-organize-imports": "^4.3.0",
|
||||||
"ts-node": "~10.9.2",
|
"ts-node": "~10.9.2",
|
||||||
"typescript": "^6.0.3"
|
"typescript": "^6.0.3"
|
||||||
|
|||||||
Generated
+1670
-1235
File diff suppressed because it is too large.
Load diff
@@ -27,6 +27,7 @@ import localeEs from '@angular/common/locales/es'
|
|||||||
import localeFa from '@angular/common/locales/fa'
|
import localeFa from '@angular/common/locales/fa'
|
||||||
import localeFi from '@angular/common/locales/fi'
|
import localeFi from '@angular/common/locales/fi'
|
||||||
import localeFr from '@angular/common/locales/fr'
|
import localeFr from '@angular/common/locales/fr'
|
||||||
|
import localeHr from '@angular/common/locales/hr'
|
||||||
import localeHu from '@angular/common/locales/hu'
|
import localeHu from '@angular/common/locales/hu'
|
||||||
import localeId from '@angular/common/locales/id'
|
import localeId from '@angular/common/locales/id'
|
||||||
import localeIt from '@angular/common/locales/it'
|
import localeIt from '@angular/common/locales/it'
|
||||||
@@ -63,6 +64,7 @@ registerLocaleData(localeEs)
|
|||||||
registerLocaleData(localeFa)
|
registerLocaleData(localeFa)
|
||||||
registerLocaleData(localeFi)
|
registerLocaleData(localeFi)
|
||||||
registerLocaleData(localeFr)
|
registerLocaleData(localeFr)
|
||||||
|
registerLocaleData(localeHr)
|
||||||
registerLocaleData(localeHu)
|
registerLocaleData(localeHu)
|
||||||
registerLocaleData(localeId)
|
registerLocaleData(localeId)
|
||||||
registerLocaleData(localeIt)
|
registerLocaleData(localeIt)
|
||||||
|
|||||||
@@ -136,6 +136,12 @@ const LANGUAGE_OPTIONS = [
|
|||||||
englishName: 'French',
|
englishName: 'French',
|
||||||
dateInputFormat: 'dd/mm/yyyy',
|
dateInputFormat: 'dd/mm/yyyy',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
code: 'hr-hr',
|
||||||
|
name: $localize`Croatian`,
|
||||||
|
englishName: 'Croatian',
|
||||||
|
dateInputFormat: 'dd.mm.yyyy',
|
||||||
|
},
|
||||||
{
|
{
|
||||||
code: 'hu-hu',
|
code: 'hu-hu',
|
||||||
name: $localize`Hungarian`,
|
name: $localize`Hungarian`,
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ import localeEs from '@angular/common/locales/es'
|
|||||||
import localeFa from '@angular/common/locales/fa'
|
import localeFa from '@angular/common/locales/fa'
|
||||||
import localeFi from '@angular/common/locales/fi'
|
import localeFi from '@angular/common/locales/fi'
|
||||||
import localeFr from '@angular/common/locales/fr'
|
import localeFr from '@angular/common/locales/fr'
|
||||||
|
import localeHr from '@angular/common/locales/hr'
|
||||||
import localeHu from '@angular/common/locales/hu'
|
import localeHu from '@angular/common/locales/hu'
|
||||||
import localeId from '@angular/common/locales/id'
|
import localeId from '@angular/common/locales/id'
|
||||||
import localeIt from '@angular/common/locales/it'
|
import localeIt from '@angular/common/locales/it'
|
||||||
@@ -94,6 +95,7 @@ registerLocaleData(localeEs)
|
|||||||
registerLocaleData(localeFa)
|
registerLocaleData(localeFa)
|
||||||
registerLocaleData(localeFi)
|
registerLocaleData(localeFi)
|
||||||
registerLocaleData(localeFr)
|
registerLocaleData(localeFr)
|
||||||
|
registerLocaleData(localeHr)
|
||||||
registerLocaleData(localeHu)
|
registerLocaleData(localeHu)
|
||||||
registerLocaleData(localeId)
|
registerLocaleData(localeId)
|
||||||
registerLocaleData(localeIt)
|
registerLocaleData(localeIt)
|
||||||
|
|||||||
@@ -73,9 +73,10 @@ def get_suggestion_cache(document_id: int) -> SuggestionCacheData | None:
|
|||||||
|
|
||||||
doc_key = get_suggestion_cache_key(document_id)
|
doc_key = get_suggestion_cache_key(document_id)
|
||||||
cache_hits = cache.get_many([CLASSIFIER_VERSION_KEY, CLASSIFIER_HASH_KEY, doc_key])
|
cache_hits = cache.get_many([CLASSIFIER_VERSION_KEY, CLASSIFIER_HASH_KEY, doc_key])
|
||||||
# The document suggestions are in the cache
|
# The document suggestions are in the cache. get_many keeps an entry the cache
|
||||||
if doc_key in cache_hits:
|
# serializer rejected as None, rather than leaving the key out.
|
||||||
doc_suggestions: SuggestionCacheData = cache_hits[doc_key]
|
doc_suggestions: SuggestionCacheData | None = cache_hits.get(doc_key)
|
||||||
|
if doc_suggestions is not None:
|
||||||
# The classifier format is the same
|
# The classifier format is the same
|
||||||
# The classifier hash is the same
|
# The classifier hash is the same
|
||||||
# Then the suggestions can be used
|
# Then the suggestions can be used
|
||||||
|
|||||||
+19
-10
@@ -15,7 +15,6 @@ 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
|
||||||
@@ -27,7 +26,10 @@ 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
|
||||||
@@ -623,7 +625,13 @@ 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:
|
||||||
with transaction.atomic():
|
# File moves requested in here run after commit and after
|
||||||
|
# media.lock is released. media.lock is taken before the
|
||||||
|
# transaction: the version path locks the root row with
|
||||||
|
# select_for_update, and workflow email actions and file
|
||||||
|
# placement below re-enter media.lock instead of waiting
|
||||||
|
# on it while rows are locked.
|
||||||
|
with defer_file_moves(), media_lock(), transaction.atomic():
|
||||||
# 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
|
||||||
@@ -714,7 +722,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 FileLock(settings.MEDIA_LOCK):
|
with media_lock():
|
||||||
generated_filename = generate_unique_filename(document)
|
generated_filename = generate_unique_filename(document)
|
||||||
if (
|
if (
|
||||||
len(str(generated_filename))
|
len(str(generated_filename))
|
||||||
@@ -778,10 +786,9 @@ class ConsumerPlugin(
|
|||||||
document.archive_path,
|
document.archive_path,
|
||||||
)
|
)
|
||||||
|
|
||||||
# Don't save with the lock active. Saving will cause the file
|
# Any filename follow-up from this save is deferred by
|
||||||
# renaming logic to acquire the lock as well.
|
# the scope above until after commit.
|
||||||
# This triggers things like file renaming
|
document.save(write_file_paths=True)
|
||||||
document.save()
|
|
||||||
|
|
||||||
if document.root_document_id:
|
if document.root_document_id:
|
||||||
document_updated.send(
|
document_updated.send(
|
||||||
@@ -822,6 +829,11 @@ 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")
|
||||||
@@ -834,9 +846,6 @@ 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:
|
||||||
|
|||||||
@@ -0,0 +1,480 @@
|
|||||||
|
"""
|
||||||
|
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)
|
||||||
@@ -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 FileLock(settings.MEDIA_LOCK):
|
with 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,10 +18,11 @@ 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
|
||||||
|
|
||||||
@@ -330,7 +331,7 @@ class Command(CryptMixin, PaperlessCommand):
|
|||||||
)
|
)
|
||||||
|
|
||||||
# Prevent any ongoing changes in the documents while exporting
|
# Prevent any ongoing changes in the documents while exporting
|
||||||
with FileLock(settings.MEDIA_LOCK), sink:
|
with media_lock(), sink:
|
||||||
self.dump(sink)
|
self.dump(sink)
|
||||||
|
|
||||||
def dump(self, sink: ExportSink) -> None:
|
def dump(self, sink: ExportSink) -> None:
|
||||||
|
|||||||
@@ -29,7 +29,6 @@ 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
|
||||||
@@ -37,6 +36,7 @@ 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 FileLock(settings.MEDIA_LOCK):
|
with 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 FileLock(settings.MEDIA_LOCK):
|
with 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,5 +1,4 @@
|
|||||||
from django.db.models.signals import post_save
|
from documents.file_moves import move_files_for_document
|
||||||
|
|
||||||
from documents.management.commands.base import PaperlessCommand
|
from documents.management.commands.base import PaperlessCommand
|
||||||
from documents.models import Document
|
from documents.models import Document
|
||||||
|
|
||||||
@@ -11,5 +10,9 @@ class Command(PaperlessCommand):
|
|||||||
supports_multiprocessing = False
|
supports_multiprocessing = False
|
||||||
|
|
||||||
def handle(self, *args, **options):
|
def handle(self, *args, **options):
|
||||||
for document in self.track(Document.objects.all(), description="Renaming..."):
|
for document in self.track(
|
||||||
post_save.send(Document, instance=document, created=False)
|
# move_files_for_document handles a root's versions itself
|
||||||
|
Document.objects.filter(root_document__isnull=True).only("pk"),
|
||||||
|
description="Renaming...",
|
||||||
|
):
|
||||||
|
move_files_for_document(document.pk)
|
||||||
@@ -9,6 +9,7 @@ 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
|
||||||
@@ -273,6 +274,8 @@ 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.
|
||||||
|
with defer_file_moves():
|
||||||
suggestion = DocumentSuggestion(document=document)
|
suggestion = DocumentSuggestion(document=document)
|
||||||
|
|
||||||
if do_correspondent:
|
if do_correspondent:
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
"""
|
||||||
|
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
|
||||||
@@ -2,6 +2,7 @@ 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
|
||||||
@@ -211,6 +212,12 @@ 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
|
||||||
|
|
||||||
@@ -422,6 +429,31 @@ 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
|
||||||
|
|||||||
@@ -74,6 +74,10 @@ _LOCK_BACKOFF_CAP: Final[float] = 10.0 # seconds
|
|||||||
|
|
||||||
T = TypeVar("T")
|
T = TypeVar("T")
|
||||||
|
|
||||||
|
# Upper bound on autocomplete suggestions. tantivy sizes its collector from the
|
||||||
|
# requested limit, so an unbounded value aborts the whole process on allocation.
|
||||||
|
MAX_AUTOCOMPLETE_LIMIT = 1000
|
||||||
|
|
||||||
|
|
||||||
class ViewerGrant(NamedTuple):
|
class ViewerGrant(NamedTuple):
|
||||||
"""Direct user and group view grants for a single document.
|
"""Direct user and group view grants for a single document.
|
||||||
@@ -998,7 +1002,8 @@ class TantivyBackend:
|
|||||||
|
|
||||||
Args:
|
Args:
|
||||||
term: Prefix to match against autocomplete words
|
term: Prefix to match against autocomplete words
|
||||||
limit: Maximum number of suggestions to return
|
limit: Maximum number of suggestions to return, capped at
|
||||||
|
MAX_AUTOCOMPLETE_LIMIT
|
||||||
user: User for permission filtering (None for no filtering)
|
user: User for permission filtering (None for no filtering)
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
@@ -1021,7 +1026,7 @@ class TantivyBackend:
|
|||||||
"autocomplete_word",
|
"autocomplete_word",
|
||||||
normalized_term,
|
normalized_term,
|
||||||
permission_query,
|
permission_query,
|
||||||
limit,
|
min(limit, MAX_AUTOCOMPLETE_LIMIT),
|
||||||
)
|
)
|
||||||
|
|
||||||
return [x[0] for x in matches]
|
return [x[0] for x in matches]
|
||||||
|
|||||||
@@ -112,6 +112,10 @@ if TYPE_CHECKING:
|
|||||||
|
|
||||||
logger = logging.getLogger("paperless.serializers")
|
logger = logging.getLogger("paperless.serializers")
|
||||||
|
|
||||||
|
# How much of an upload is read to detect its type. libmagic examines at most
|
||||||
|
# 7 MiB (its default bytes_max), so this is more than it will ever look at.
|
||||||
|
_MIME_SNIFF_BYTES = 8 * 1024 * 1024
|
||||||
|
|
||||||
|
|
||||||
# https://www.django-rest-framework.org/api-guide/serializers/#example
|
# https://www.django-rest-framework.org/api-guide/serializers/#example
|
||||||
class DynamicFieldsModelSerializer(serializers.ModelSerializer[Any]):
|
class DynamicFieldsModelSerializer(serializers.ModelSerializer[Any]):
|
||||||
@@ -2363,8 +2367,9 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
|
|||||||
)
|
)
|
||||||
|
|
||||||
def validate_document(self, document):
|
def validate_document(self, document):
|
||||||
document_data = document.file.read()
|
# libmagic only examines a bounded prefix, so an upload of any size is
|
||||||
mime_type = magic.from_buffer(document_data, mime=True)
|
# never read into memory just to detect its type
|
||||||
|
mime_type = magic.from_buffer(document.read(_MIME_SNIFF_BYTES), mime=True)
|
||||||
|
|
||||||
if not is_mime_type_supported(mime_type):
|
if not is_mime_type_supported(mime_type):
|
||||||
if (
|
if (
|
||||||
@@ -2380,7 +2385,7 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
|
|||||||
_("File type %(type)s not supported") % {"type": mime_type},
|
_("File type %(type)s not supported") % {"type": mime_type},
|
||||||
)
|
)
|
||||||
|
|
||||||
return document.name, document_data
|
return document.name, document
|
||||||
|
|
||||||
def validate_correspondent(self, correspondent):
|
def validate_correspondent(self, correspondent):
|
||||||
if correspondent:
|
if correspondent:
|
||||||
|
|||||||
@@ -21,25 +21,22 @@ 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_handling import generate_filename
|
from documents.file_moves import move_files_for_document
|
||||||
from documents.file_handling import generate_unique_filename
|
from documents.file_moves import request_file_move
|
||||||
|
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
|
||||||
@@ -59,7 +56,6 @@ 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
|
||||||
@@ -343,7 +339,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 FileLock(settings.MEDIA_LOCK):
|
with 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
|
||||||
@@ -409,17 +405,6 @@ 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:
|
||||||
@@ -442,235 +427,37 @@ 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
|
||||||
|
|
||||||
def validate_move(instance, old_path: Path, new_path: Path, root: Path) -> None:
|
request_file_move(instance)
|
||||||
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
|
||||||
@@ -695,7 +482,8 @@ 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
|
||||||
update_filename_and_move_files(CustomFieldInstance, cf_instance)
|
if _filename_template_uses_custom_fields(cf_instance.document):
|
||||||
|
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
|
||||||
@@ -786,15 +574,15 @@ def cleanup_user_deletion(sender, instance: User | Group, **kwargs) -> None:
|
|||||||
if instance.pk in permissions.get("default_view_users", []):
|
if instance.pk in permissions.get("default_view_users", []):
|
||||||
permissions["default_view_users"].remove(instance.pk)
|
permissions["default_view_users"].remove(instance.pk)
|
||||||
updated = True
|
updated = True
|
||||||
if instance.pk in permissions.get("default_change_users", []):
|
if instance.pk in permissions.get("default_edit_users", []):
|
||||||
permissions["default_change_users"].remove(instance.pk)
|
permissions["default_edit_users"].remove(instance.pk)
|
||||||
updated = True
|
updated = True
|
||||||
elif isinstance(instance, Group):
|
elif isinstance(instance, Group):
|
||||||
if instance.pk in permissions.get("default_view_groups", []):
|
if instance.pk in permissions.get("default_view_groups", []):
|
||||||
permissions["default_view_groups"].remove(instance.pk)
|
permissions["default_view_groups"].remove(instance.pk)
|
||||||
updated = True
|
updated = True
|
||||||
if instance.pk in permissions.get("default_change_groups", []):
|
if instance.pk in permissions.get("default_edit_groups", []):
|
||||||
permissions["default_change_groups"].remove(instance.pk)
|
permissions["default_edit_groups"].remove(instance.pk)
|
||||||
updated = True
|
updated = True
|
||||||
if updated:
|
if updated:
|
||||||
ui_settings.settings["permissions"] = permissions
|
ui_settings.settings["permissions"] = permissions
|
||||||
|
|||||||
+92
-11
@@ -1,9 +1,12 @@
|
|||||||
import datetime
|
import datetime
|
||||||
import logging
|
import logging
|
||||||
import shutil
|
import shutil
|
||||||
|
import threading
|
||||||
import uuid
|
import uuid
|
||||||
import zipfile
|
import zipfile
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from contextlib import contextmanager
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from tempfile import TemporaryDirectory
|
from tempfile import TemporaryDirectory
|
||||||
|
|
||||||
@@ -16,7 +19,6 @@ 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
|
||||||
@@ -40,8 +42,10 @@ from documents.data_models import DocumentMetadataOverrides
|
|||||||
from documents.data_models import StoredBarcode
|
from documents.data_models import StoredBarcode
|
||||||
from documents.double_sided import CollatePlugin
|
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 delete_empty_directories
|
||||||
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
|
||||||
@@ -311,9 +315,14 @@ 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
|
||||||
@@ -324,13 +333,32 @@ 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
|
||||||
)
|
)
|
||||||
post_save.send(Document, instance=doc, created=False)
|
# Moves requested by workflows that document_updated ran. Moving per
|
||||||
|
# document, rather than at the end of the task, keeps a long bulk
|
||||||
|
# edit making steady progress.
|
||||||
|
flush_pending_file_moves()
|
||||||
|
|
||||||
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)
|
||||||
@@ -418,7 +446,13 @@ 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)
|
||||||
|
|
||||||
with transaction.atomic():
|
# media.lock first, then the transaction: never wait on media.lock
|
||||||
|
# while this transaction holds the document row. Also keeps the
|
||||||
|
# unique archive filename generation under the lock.
|
||||||
|
with media_lock(), transaction.atomic():
|
||||||
|
# Loaded before the (long) parse; read current metadata now
|
||||||
|
# that the lock is held, for the archive filename.
|
||||||
|
document.refresh_from_db()
|
||||||
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())
|
||||||
@@ -483,10 +517,21 @@ def update_document_content_maybe_archive_file(
|
|||||||
modified=timezone.now(),
|
modified=timezone.now(),
|
||||||
)
|
)
|
||||||
|
|
||||||
with FileLock(settings.MEDIA_LOCK):
|
|
||||||
if parser.get_archive_path():
|
if parser.get_archive_path():
|
||||||
create_source_path_directory(document.archive_path)
|
create_source_path_directory(document.archive_path)
|
||||||
shutil.move(parser.get_archive_path(), document.archive_path)
|
shutil.move(parser.get_archive_path(), document.archive_path)
|
||||||
|
# A rename that has not been applied yet puts the new archive
|
||||||
|
# at a different path, so the one it replaces must go.
|
||||||
|
replaced_archive_path = oldDocument.archive_path
|
||||||
|
if (
|
||||||
|
replaced_archive_path is not None
|
||||||
|
and replaced_archive_path != document.archive_path
|
||||||
|
):
|
||||||
|
replaced_archive_path.unlink(missing_ok=True)
|
||||||
|
delete_empty_directories(
|
||||||
|
replaced_archive_path.parent,
|
||||||
|
root=settings.ARCHIVE_DIR,
|
||||||
|
)
|
||||||
shutil.move(thumbnail, document.thumbnail_path)
|
shutil.move(thumbnail, document.thumbnail_path)
|
||||||
|
|
||||||
document.refresh_from_db()
|
document.refresh_from_db()
|
||||||
@@ -513,6 +558,38 @@ def update_document_content_maybe_archive_file(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
_cleanup_handler_users = 0
|
||||||
|
_cleanup_handler_lock = threading.Lock()
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _cleanup_handler_connected() -> Iterator[None]:
|
||||||
|
"""
|
||||||
|
Keep the file cleanup handler connected to post_delete while any empty_trash
|
||||||
|
call in this process is running. The signal is process wide, so one call
|
||||||
|
finishing must not disconnect it from another that is still waiting for
|
||||||
|
media.lock.
|
||||||
|
"""
|
||||||
|
global _cleanup_handler_users
|
||||||
|
with _cleanup_handler_lock:
|
||||||
|
if _cleanup_handler_users == 0:
|
||||||
|
models.signals.post_delete.connect(
|
||||||
|
cleanup_document_deletion,
|
||||||
|
sender=Document,
|
||||||
|
)
|
||||||
|
_cleanup_handler_users += 1
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
with _cleanup_handler_lock:
|
||||||
|
_cleanup_handler_users -= 1
|
||||||
|
if _cleanup_handler_users == 0:
|
||||||
|
models.signals.post_delete.disconnect(
|
||||||
|
cleanup_document_deletion,
|
||||||
|
sender=Document,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@shared_task
|
@shared_task
|
||||||
def empty_trash(doc_ids=None) -> None:
|
def empty_trash(doc_ids=None) -> None:
|
||||||
if doc_ids is None:
|
if doc_ids is None:
|
||||||
@@ -530,8 +607,10 @@ def empty_trash(doc_ids=None) -> None:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
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
|
# media.lock before Django's delete transaction: post_delete runs
|
||||||
models.signals.post_delete.connect(cleanup_document_deletion, sender=Document)
|
# cleanup_document_deletion inside it while the rows are locked, and
|
||||||
|
# that handler re-enters the lock instead of waiting.
|
||||||
|
with _cleanup_handler_connected(), media_lock():
|
||||||
documents.delete() # this is effectively a hard delete
|
documents.delete() # this is effectively a hard delete
|
||||||
logger.info(f"Deleted {len(deleted_document_ids)} documents from trash")
|
logger.info(f"Deleted {len(deleted_document_ids)} documents from trash")
|
||||||
|
|
||||||
@@ -543,11 +622,6 @@ def empty_trash(doc_ids=None) -> None:
|
|||||||
).delete()
|
).delete()
|
||||||
except Exception as e: # pragma: no cover
|
except Exception as e: # pragma: no cover
|
||||||
logger.exception(f"Error while emptying trash: {e}")
|
logger.exception(f"Error while emptying trash: {e}")
|
||||||
finally:
|
|
||||||
models.signals.post_delete.disconnect(
|
|
||||||
cleanup_document_deletion,
|
|
||||||
sender=Document,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@shared_task
|
@shared_task
|
||||||
@@ -562,6 +636,8 @@ 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,
|
||||||
)
|
)
|
||||||
@@ -684,6 +760,11 @@ 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,
|
||||||
|
|||||||
@@ -1069,6 +1069,13 @@ class TestAutocomplete:
|
|||||||
results = backend.autocomplete("micro", limit=10)
|
results = backend.autocomplete("micro", limit=10)
|
||||||
assert "microsoft" in results
|
assert "microsoft" in results
|
||||||
|
|
||||||
|
def test_huge_limit_is_clamped(self, backend: TantivyBackend) -> None:
|
||||||
|
"""An oversized limit must be capped, not handed to tantivy as-is."""
|
||||||
|
doc = DocumentFactory.create(title="Microsoft invoice", content="payment")
|
||||||
|
backend.add_or_update(doc)
|
||||||
|
|
||||||
|
assert "microsoft" in backend.autocomplete("micro", limit=10**15)
|
||||||
|
|
||||||
def test_results_ordered_by_document_frequency(
|
def test_results_ordered_by_document_frequency(
|
||||||
self,
|
self,
|
||||||
backend: TantivyBackend,
|
backend: TantivyBackend,
|
||||||
|
|||||||
@@ -0,0 +1,44 @@
|
|||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from rest_framework import status
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
|
||||||
|
from documents.models import Document
|
||||||
|
from paperless_testing.factories import DocumentFactory
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestDocumentUpdateConcurrentDelete:
|
||||||
|
def test_patch_of_document_trashed_mid_request_returns_404(
|
||||||
|
self,
|
||||||
|
admin_client: APIClient,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- A document that another request moves to the trash after this
|
||||||
|
request has saved its changes, but before it re-reads the document
|
||||||
|
WHEN:
|
||||||
|
- The document is updated through the API
|
||||||
|
THEN:
|
||||||
|
- The response is a 404, not a server error
|
||||||
|
- The committed change is not lost
|
||||||
|
"""
|
||||||
|
doc = DocumentFactory(title="before")
|
||||||
|
|
||||||
|
def trash_concurrently() -> None:
|
||||||
|
Document.objects.get(pk=doc.pk).delete()
|
||||||
|
|
||||||
|
with mock.patch(
|
||||||
|
"documents.views.flush_pending_file_moves",
|
||||||
|
side_effect=trash_concurrently,
|
||||||
|
):
|
||||||
|
response = admin_client.patch(
|
||||||
|
f"/api/documents/{doc.pk}/",
|
||||||
|
{"title": "after"},
|
||||||
|
format="json",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||||
|
assert Document.deleted_objects.filter(pk=doc.pk).exists()
|
||||||
|
assert Document.global_objects.get(pk=doc.pk).title == "after"
|
||||||
@@ -2089,6 +2089,38 @@ class TestDocumentApi(DirectoriesMixin, ConsumeTaskMixin, APITestCase):
|
|||||||
self.assertIsNone(overrides.document_type_id)
|
self.assertIsNone(overrides.document_type_id)
|
||||||
self.assertIsNone(overrides.tag_ids)
|
self.assertIsNone(overrides.tag_ids)
|
||||||
|
|
||||||
|
def test_upload_type_is_detected_from_a_prefix(self) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- An upload larger than the prefix read to detect its type
|
||||||
|
WHEN:
|
||||||
|
- The document is posted
|
||||||
|
THEN:
|
||||||
|
- The type is detected from the prefix and the upload is accepted
|
||||||
|
- The file handed to the consumer holds the whole upload
|
||||||
|
"""
|
||||||
|
self.consume_file_mock.return_value = celery.result.AsyncResult(
|
||||||
|
id=str(uuid.uuid4()),
|
||||||
|
)
|
||||||
|
content = SIMPLE_DIGITAL_PDF.read_bytes()
|
||||||
|
|
||||||
|
with (
|
||||||
|
mock.patch("documents.serialisers._MIME_SNIFF_BYTES", 1024),
|
||||||
|
SimpleUploadedFile(
|
||||||
|
"simple.pdf",
|
||||||
|
content,
|
||||||
|
content_type="application/pdf",
|
||||||
|
) as f,
|
||||||
|
):
|
||||||
|
response = self.client.post(
|
||||||
|
"/api/documents/post_document/",
|
||||||
|
{"document": f},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(response.status_code, status.HTTP_200_OK)
|
||||||
|
input_doc, _ = self.assert_queue_consumption_task_call_args()
|
||||||
|
self.assertEqual(input_doc.original_file.read_bytes(), content)
|
||||||
|
|
||||||
def test_upload_with_path_traversal_filename_is_reduced_to_basename(self) -> None:
|
def test_upload_with_path_traversal_filename_is_reduced_to_basename(self) -> None:
|
||||||
self.consume_file_mock.return_value = celery.result.AsyncResult(
|
self.consume_file_mock.return_value = celery.result.AsyncResult(
|
||||||
id=str(uuid.uuid4()),
|
id=str(uuid.uuid4()),
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
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
|
||||||
@@ -337,3 +339,41 @@ class TestDocumentListObjectFilterSchema:
|
|||||||
param = next(p for p in params if p["name"] == param_name)
|
param = next(p for p in params if p["name"] == param_name)
|
||||||
assert param["schema"] == {"type": "array", "items": {"type": "integer"}}
|
assert param["schema"] == {"type": "array", "items": {"type": "integer"}}
|
||||||
assert param["explode"] is False
|
assert param["explode"] is False
|
||||||
|
|
||||||
|
|
||||||
|
class TestOauthCallbackSchema:
|
||||||
|
@pytest.mark.parametrize("name", ["code", "state"])
|
||||||
|
def test_empty_code_and_state_are_not_schema_valid(
|
||||||
|
self,
|
||||||
|
api_schema: dict[str, Any],
|
||||||
|
name: str,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- The generated schema
|
||||||
|
WHEN:
|
||||||
|
- The code and state parameters of the OAuth callback are read
|
||||||
|
THEN:
|
||||||
|
- They are required and not empty, the view answers 400 to an empty one
|
||||||
|
"""
|
||||||
|
params = api_schema["paths"]["/api/oauth/callback/"]["get"]["parameters"]
|
||||||
|
param = next(p for p in params if p["name"] == name)
|
||||||
|
|
||||||
|
assert param["required"] is True
|
||||||
|
assert param["schema"]["minLength"] == 1
|
||||||
|
|
||||||
|
|
||||||
|
class TestOcrPageImageSchema:
|
||||||
|
def test_page_image_is_declared_as_png(self, api_schema: dict[str, Any]) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- The generated schema
|
||||||
|
WHEN:
|
||||||
|
- The 200 response of the OCR template page image is read
|
||||||
|
THEN:
|
||||||
|
- It is a PNG, which is what the view serves
|
||||||
|
"""
|
||||||
|
path = "/api/ocr_templates/document-page-image/{doc_id}/{page}/"
|
||||||
|
content = api_schema["paths"][path]["get"]["responses"]["200"]["content"]
|
||||||
|
|
||||||
|
assert list(content) == ["image/png"]
|
||||||
@@ -671,8 +671,8 @@ class TestDocumentSearchApi(DirectoriesMixin, APITestCase):
|
|||||||
content="things i paid for in august",
|
content="things i paid for in august",
|
||||||
pk=2,
|
pk=2,
|
||||||
checksum="B",
|
checksum="B",
|
||||||
# 1 month, 1 day ago
|
# More than 1 month ago, in the search timezone
|
||||||
added=timezone.now() - relativedelta(months=1, days=1),
|
added=timezone.localtime() - relativedelta(months=1, days=7),
|
||||||
)
|
)
|
||||||
d3 = Document.objects.create(
|
d3 = Document.objects.create(
|
||||||
title="bank statement 3",
|
title="bank statement 3",
|
||||||
@@ -706,6 +706,10 @@ class TestDocumentSearchApi(DirectoriesMixin, APITestCase):
|
|||||||
@override_settings(
|
@override_settings(
|
||||||
TIME_ZONE="America/Denver",
|
TIME_ZONE="America/Denver",
|
||||||
)
|
)
|
||||||
|
@time_machine.travel(
|
||||||
|
datetime.datetime(2026, 12, 1, 0, 1, tzinfo=datetime.UTC),
|
||||||
|
tick=False,
|
||||||
|
)
|
||||||
def test_search_added_in_last_month_timezone_behind(self) -> None:
|
def test_search_added_in_last_month_timezone_behind(self) -> None:
|
||||||
"""
|
"""
|
||||||
GIVEN:
|
GIVEN:
|
||||||
@@ -729,8 +733,8 @@ class TestDocumentSearchApi(DirectoriesMixin, APITestCase):
|
|||||||
content="things i paid for in august",
|
content="things i paid for in august",
|
||||||
pk=2,
|
pk=2,
|
||||||
checksum="B",
|
checksum="B",
|
||||||
# 1 month, 1 day ago
|
# More than 1 month ago, in the search timezone
|
||||||
added=timezone.now() - relativedelta(months=1, days=1),
|
added=timezone.localtime() - relativedelta(months=1, days=7),
|
||||||
)
|
)
|
||||||
d3 = Document.objects.create(
|
d3 = Document.objects.create(
|
||||||
title="bank statement 3",
|
title="bank statement 3",
|
||||||
@@ -996,6 +1000,9 @@ class TestDocumentSearchApi(DirectoriesMixin, APITestCase):
|
|||||||
response = self.client.get("/api/search/autocomplete/?term=test&limit=-1")
|
response = self.client.get("/api/search/autocomplete/?term=test&limit=-1")
|
||||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||||
|
|
||||||
|
response = self.client.get("/api/search/autocomplete/?term=test&limit=null")
|
||||||
|
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||||
|
|
||||||
response = self.client.get("/api/search/autocomplete/")
|
response = self.client.get("/api/search/autocomplete/")
|
||||||
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
|
||||||
|
|
||||||
|
|||||||
@@ -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()
|
self.doc1.save(write_file_paths=True)
|
||||||
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()
|
self.doc2.save(write_file_paths=True)
|
||||||
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()
|
self.img_doc.save(write_file_paths=True)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def fake_decrypt(
|
def fake_decrypt(
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
from pytest_mock import MockerFixture
|
||||||
|
|
||||||
|
from documents.caching import CLASSIFIER_VERSION_KEY
|
||||||
|
from documents.caching import get_suggestion_cache
|
||||||
|
from documents.caching import get_suggestion_cache_key
|
||||||
|
from documents.classifier import DocumentClassifier
|
||||||
|
|
||||||
|
|
||||||
|
class TestGetSuggestionCache:
|
||||||
|
def test_rejected_entry_is_a_cache_miss(self, mocker: MockerFixture) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- A document suggestion entry the cache serializer rejected, which
|
||||||
|
get_many reports as None
|
||||||
|
- A classifier version entry matching the current format
|
||||||
|
WHEN:
|
||||||
|
- The suggestion cache is read
|
||||||
|
THEN:
|
||||||
|
- It is treated as a cache miss
|
||||||
|
"""
|
||||||
|
doc_key = get_suggestion_cache_key(1)
|
||||||
|
mocker.patch(
|
||||||
|
"documents.caching.cache.get_many",
|
||||||
|
return_value={
|
||||||
|
CLASSIFIER_VERSION_KEY: DocumentClassifier.FORMAT_VERSION,
|
||||||
|
doc_key: None,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert get_suggestion_cache(1) is None
|
||||||
@@ -27,6 +27,10 @@ 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
|
||||||
@@ -38,6 +42,7 @@ 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
|
||||||
@@ -221,6 +226,160 @@ 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",
|
||||||
@@ -750,7 +909,7 @@ class TestConsumer(
|
|||||||
FILENAME_FORMAT="{correspondent}/{title}",
|
FILENAME_FORMAT="{correspondent}/{title}",
|
||||||
ARCHIVE_FILE_GENERATION="always",
|
ARCHIVE_FILE_GENERATION="always",
|
||||||
)
|
)
|
||||||
@mock.patch("documents.signals.handlers.generate_unique_filename")
|
@mock.patch("documents.file_moves.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"]
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import shutil
|
||||||
|
from collections.abc import Iterator
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from pytest_django.fixtures import Settings
|
||||||
|
|
||||||
|
from documents import tasks
|
||||||
|
from documents.media_lock import media_lock
|
||||||
|
from documents.models import Document
|
||||||
|
from paperless_testing.dirs import PaperlessDirs
|
||||||
|
from paperless_testing.factories import DocumentFactory
|
||||||
|
from paperless_testing.samples import SIMPLE_DIGITAL_PDF
|
||||||
|
|
||||||
|
|
||||||
|
def _trashed_document(dirs: PaperlessDirs, title: str) -> tuple[Document, Path]:
|
||||||
|
# The title-only filename format keeps the generated filename equal to the
|
||||||
|
# stored one, so creating the document does not move the file.
|
||||||
|
doc = DocumentFactory(
|
||||||
|
title=title,
|
||||||
|
filename=f"{title}.pdf",
|
||||||
|
mime_type="application/pdf",
|
||||||
|
)
|
||||||
|
original = dirs.originals_dir / f"{title}.pdf"
|
||||||
|
shutil.copy(SIMPLE_DIGITAL_PDF, original)
|
||||||
|
doc.delete()
|
||||||
|
return doc, original
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestEmptyTrashOverlappingCalls:
|
||||||
|
def test_call_that_waits_for_the_lock_still_removes_its_files(
|
||||||
|
self,
|
||||||
|
paperless_dirs: PaperlessDirs,
|
||||||
|
settings: Settings,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- Two trashed documents with files on disk
|
||||||
|
- A second empty_trash call that runs to completion while the first
|
||||||
|
is waiting for media.lock, as happens with two overlapping
|
||||||
|
requests in one process
|
||||||
|
WHEN:
|
||||||
|
- The first call gets the lock and deletes its document
|
||||||
|
THEN:
|
||||||
|
- Both documents are gone from the database
|
||||||
|
- Both documents' files are gone from disk, not just the files of
|
||||||
|
the call that finished first
|
||||||
|
"""
|
||||||
|
settings.FILENAME_FORMAT = "{{ title }}"
|
||||||
|
first, first_original = _trashed_document(paperless_dirs, "first")
|
||||||
|
second, second_original = _trashed_document(paperless_dirs, "second")
|
||||||
|
assert first_original.is_file()
|
||||||
|
assert second_original.is_file()
|
||||||
|
interleaved = False
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def lock_after_other_call(*args, **kwargs) -> Iterator[None]:
|
||||||
|
nonlocal interleaved
|
||||||
|
if not interleaved:
|
||||||
|
interleaved = True
|
||||||
|
tasks.empty_trash(doc_ids=[second.pk])
|
||||||
|
with media_lock(*args, **kwargs):
|
||||||
|
yield
|
||||||
|
|
||||||
|
with mock.patch("documents.tasks.media_lock", lock_after_other_call):
|
||||||
|
tasks.empty_trash(doc_ids=[first.pk])
|
||||||
|
|
||||||
|
assert not Document.global_objects.filter(pk__in=[first.pk, second.pk]).exists()
|
||||||
|
assert not second_original.exists()
|
||||||
|
assert not first_original.exists()
|
||||||
@@ -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()
|
document.save(write_file_paths=True)
|
||||||
|
|
||||||
# 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()
|
document.save(write_file_paths=True)
|
||||||
|
|
||||||
# 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()
|
document.save(write_file_paths=True)
|
||||||
|
|
||||||
# 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()
|
document.save(write_file_paths=True)
|
||||||
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()
|
document.save(write_file_paths=True)
|
||||||
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()
|
document.save(write_file_paths=True)
|
||||||
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()
|
document.save(write_file_paths=True)
|
||||||
|
|
||||||
# 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()
|
doc.save(write_file_paths=True)
|
||||||
|
|
||||||
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()
|
document.save(write_file_paths=True)
|
||||||
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()
|
document.save(write_file_paths=True)
|
||||||
|
|
||||||
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()
|
document2.save(write_file_paths=True)
|
||||||
|
|
||||||
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,19 +656,17 @@ 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.signals.handlers.Document.objects.filter")
|
@mock.patch("documents.file_moves.Document.global_objects.filter")
|
||||||
@mock.patch("documents.signals.handlers.shutil.move")
|
@mock.patch("documents.file_moves.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
|
- The document is saved without a change that affects its path
|
||||||
THEN:
|
THEN:
|
||||||
- The document modified date is updated
|
- The document modified date is updated by the save itself
|
||||||
- The document is not moved
|
- The file is not moved and the mover writes nothing
|
||||||
"""
|
"""
|
||||||
with disable_auditlog():
|
with disable_auditlog():
|
||||||
doc = Document.objects.create(
|
doc = Document.objects.create(
|
||||||
@@ -686,7 +684,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
|
|||||||
doc.save()
|
doc.save()
|
||||||
doc.refresh_from_db()
|
doc.refresh_from_db()
|
||||||
|
|
||||||
mock_filter.assert_called()
|
mock_filter.assert_not_called()
|
||||||
self.assertNotEqual(original_modified, doc.modified)
|
self.assertNotEqual(original_modified, doc.modified)
|
||||||
mock_move.assert_not_called()
|
mock_move.assert_not_called()
|
||||||
|
|
||||||
@@ -694,7 +692,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.update_filename_and_move_files")
|
@mock.patch("documents.signals.handlers.move_files_for_document")
|
||||||
def test_select_cf_updated(self, m) -> None:
|
def test_select_cf_updated(self, m) -> None:
|
||||||
"""
|
"""
|
||||||
GIVEN:
|
GIVEN:
|
||||||
@@ -2045,7 +2043,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.signals.handlers.generate_unique_filename") as m:
|
with mock.patch("documents.file_moves.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()
|
||||||
@@ -2067,7 +2065,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.signals.handlers.generate_unique_filename") as m:
|
with mock.patch("documents.file_moves.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()
|
||||||
@@ -2145,7 +2143,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 refreshing it from the database fails
|
- Saving it triggers a filename update and loading 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
|
||||||
"""
|
"""
|
||||||
@@ -2153,8 +2151,8 @@ def test_refresh_failure_surfaces_database_error(
|
|||||||
|
|
||||||
with (
|
with (
|
||||||
mock.patch.object(
|
mock.patch.object(
|
||||||
Document,
|
Document.global_objects,
|
||||||
"refresh_from_db",
|
"get",
|
||||||
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
@@ -18,11 +18,13 @@ 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
|
||||||
@@ -63,6 +65,28 @@ 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"
|
||||||
@@ -236,7 +260,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()
|
doc.save(write_file_paths=True)
|
||||||
|
|
||||||
Path(doc.source_path).touch()
|
Path(doc.source_path).touch()
|
||||||
Path(doc.archive_path).touch()
|
Path(doc.archive_path).touch()
|
||||||
@@ -253,6 +277,42 @@ 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,10 +4,13 @@ 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
|
||||||
@@ -21,6 +24,12 @@ 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
|
||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
@@ -484,3 +493,69 @@ 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()
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import threading
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from django.db import transaction
|
||||||
|
from filelock import Timeout
|
||||||
|
|
||||||
|
from documents.file_moves import in_user_transaction
|
||||||
|
from documents.media_lock import media_lock
|
||||||
|
from paperless_testing.locks import record_media_lock_acquisitions
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from paperless_testing.dirs import PaperlessDirs
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.usefixtures("paperless_dirs")
|
||||||
|
class TestMediaLock:
|
||||||
|
def test_same_thread_reenters_without_blocking(self) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- media.lock held by the current thread
|
||||||
|
WHEN:
|
||||||
|
- The same thread acquires it again with a zero timeout
|
||||||
|
THEN:
|
||||||
|
- The nested acquisition succeeds immediately
|
||||||
|
"""
|
||||||
|
with media_lock(), media_lock(timeout=0):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_other_thread_is_excluded(self) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- media.lock held by the current thread
|
||||||
|
WHEN:
|
||||||
|
- Another thread tries to acquire it with a short timeout
|
||||||
|
THEN:
|
||||||
|
- The other thread times out
|
||||||
|
- After release, the other thread can acquire it
|
||||||
|
"""
|
||||||
|
outcomes: list[str] = []
|
||||||
|
|
||||||
|
def try_acquire() -> None:
|
||||||
|
try:
|
||||||
|
with media_lock(timeout=0.2):
|
||||||
|
outcomes.append("acquired")
|
||||||
|
except Timeout:
|
||||||
|
outcomes.append("timeout")
|
||||||
|
|
||||||
|
with media_lock():
|
||||||
|
worker = threading.Thread(target=try_acquire)
|
||||||
|
worker.start()
|
||||||
|
worker.join()
|
||||||
|
|
||||||
|
worker = threading.Thread(target=try_acquire)
|
||||||
|
worker.start()
|
||||||
|
worker.join()
|
||||||
|
|
||||||
|
assert outcomes == ["timeout", "acquired"]
|
||||||
|
|
||||||
|
def test_lock_file_is_the_configured_path(
|
||||||
|
self,
|
||||||
|
paperless_dirs: PaperlessDirs,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- The test's media directory layout
|
||||||
|
WHEN:
|
||||||
|
- media.lock is acquired
|
||||||
|
THEN:
|
||||||
|
- The lock file is created at settings.MEDIA_LOCK
|
||||||
|
"""
|
||||||
|
with media_lock():
|
||||||
|
assert paperless_dirs.media_lock.exists()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestInUserTransaction:
|
||||||
|
def test_false_inside_test_case_wrapper(self) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- The transaction pytest-django wraps around the test
|
||||||
|
WHEN:
|
||||||
|
- in_user_transaction is called
|
||||||
|
THEN:
|
||||||
|
- It returns False
|
||||||
|
"""
|
||||||
|
assert in_user_transaction() is False
|
||||||
|
|
||||||
|
def test_true_inside_atomic(self) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- An atomic block opened by code under test
|
||||||
|
WHEN:
|
||||||
|
- in_user_transaction is called inside it
|
||||||
|
THEN:
|
||||||
|
- It returns True
|
||||||
|
"""
|
||||||
|
with transaction.atomic():
|
||||||
|
assert in_user_transaction() is True
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
@pytest.mark.usefixtures("paperless_dirs")
|
||||||
|
class TestRecordMediaLockAcquisitions:
|
||||||
|
def test_records_only_first_acquisitions(self) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- Nested media.lock acquisitions, the outer one inside a transaction
|
||||||
|
WHEN:
|
||||||
|
- They are recorded
|
||||||
|
THEN:
|
||||||
|
- Only the outer, first acquisition is recorded, flagged as inside
|
||||||
|
a transaction
|
||||||
|
"""
|
||||||
|
with record_media_lock_acquisitions() as acquisitions:
|
||||||
|
with transaction.atomic(), media_lock(), media_lock():
|
||||||
|
pass
|
||||||
|
|
||||||
|
assert [a.in_user_transaction for a in acquisitions] == [True]
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
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
|
||||||
@@ -22,3 +25,101 @@ 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()
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
import shutil
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from pytest_django.fixtures import Settings
|
||||||
|
|
||||||
|
from documents import tasks
|
||||||
|
from documents.models import Correspondent
|
||||||
|
from documents.models import Document
|
||||||
|
from documents.utils import compute_checksum
|
||||||
|
from paperless_testing.dirs import PaperlessDirs
|
||||||
|
from paperless_testing.samples import SIMPLE_DIGITAL_PDF
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.django_db
|
||||||
|
class TestReprocessArchiveCleanup:
|
||||||
|
def test_reprocess_with_pending_rename_leaves_one_archive(
|
||||||
|
self,
|
||||||
|
paperless_dirs: PaperlessDirs,
|
||||||
|
settings: Settings,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- A document whose committed metadata already generates a different
|
||||||
|
filename than the one its files still have, because its file move
|
||||||
|
has not run yet
|
||||||
|
WHEN:
|
||||||
|
- The document is reprocessed and a new archive file is produced
|
||||||
|
THEN:
|
||||||
|
- Exactly one archive file remains, the one the document points at
|
||||||
|
- The superseded archive file is not left behind
|
||||||
|
"""
|
||||||
|
settings.FILENAME_FORMAT = "{{ correspondent }}/{{ title }}"
|
||||||
|
settings.ARCHIVE_FILE_GENERATION = "always"
|
||||||
|
old_correspondent = Correspondent.objects.create(name="old")
|
||||||
|
new_correspondent = Correspondent.objects.create(name="new")
|
||||||
|
|
||||||
|
original = paperless_dirs.originals_dir / "old" / "t.pdf"
|
||||||
|
archive = paperless_dirs.archive_dir / "old" / "t.pdf"
|
||||||
|
for path in (original, archive):
|
||||||
|
path.parent.mkdir(parents=True)
|
||||||
|
shutil.copy(SIMPLE_DIGITAL_PDF, path)
|
||||||
|
doc = Document.objects.create(
|
||||||
|
title="t",
|
||||||
|
content="my document",
|
||||||
|
checksum=compute_checksum(original),
|
||||||
|
archive_checksum="stale",
|
||||||
|
filename="old/t.pdf",
|
||||||
|
archive_filename="old/t.pdf",
|
||||||
|
mime_type="application/pdf",
|
||||||
|
correspondent=old_correspondent,
|
||||||
|
)
|
||||||
|
# A queryset update sends no signals, so no file move is requested, as
|
||||||
|
# with a committed edit whose deferred move has not run yet.
|
||||||
|
Document.objects.filter(pk=doc.pk).update(correspondent=new_correspondent)
|
||||||
|
|
||||||
|
tasks.update_document_content_maybe_archive_file(doc.pk)
|
||||||
|
|
||||||
|
refreshed = Document.objects.get(pk=doc.pk)
|
||||||
|
archives = sorted(
|
||||||
|
p.relative_to(paperless_dirs.archive_dir).as_posix()
|
||||||
|
for p in Path(paperless_dirs.archive_dir).rglob("*.pdf")
|
||||||
|
)
|
||||||
|
assert archives == [refreshed.archive_filename]
|
||||||
|
assert refreshed.archive_filename == "new/t.pdf"
|
||||||
|
assert (paperless_dirs.originals_dir / refreshed.filename).is_file()
|
||||||
|
|
||||||
|
def test_reprocess_without_pending_rename_keeps_archive_in_place(
|
||||||
|
self,
|
||||||
|
paperless_dirs: PaperlessDirs,
|
||||||
|
settings: Settings,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- A document whose files already match its generated filename
|
||||||
|
WHEN:
|
||||||
|
- The document is reprocessed and a new archive file is produced
|
||||||
|
THEN:
|
||||||
|
- The new archive replaces the old one at the same path and is not
|
||||||
|
deleted as a superseded file
|
||||||
|
"""
|
||||||
|
settings.FILENAME_FORMAT = "{{ correspondent }}/{{ title }}"
|
||||||
|
settings.ARCHIVE_FILE_GENERATION = "always"
|
||||||
|
correspondent = Correspondent.objects.create(name="same")
|
||||||
|
|
||||||
|
original = paperless_dirs.originals_dir / "same" / "t.pdf"
|
||||||
|
archive = paperless_dirs.archive_dir / "same" / "t.pdf"
|
||||||
|
for path in (original, archive):
|
||||||
|
path.parent.mkdir(parents=True)
|
||||||
|
shutil.copy(SIMPLE_DIGITAL_PDF, path)
|
||||||
|
doc = Document.objects.create(
|
||||||
|
title="t",
|
||||||
|
content="my document",
|
||||||
|
checksum=compute_checksum(original),
|
||||||
|
archive_checksum="stale",
|
||||||
|
filename="same/t.pdf",
|
||||||
|
archive_filename="same/t.pdf",
|
||||||
|
mime_type="application/pdf",
|
||||||
|
correspondent=correspondent,
|
||||||
|
)
|
||||||
|
|
||||||
|
tasks.update_document_content_maybe_archive_file(doc.pk)
|
||||||
|
|
||||||
|
refreshed = Document.objects.get(pk=doc.pk)
|
||||||
|
assert refreshed.archive_filename == "same/t.pdf"
|
||||||
|
assert archive.is_file()
|
||||||
|
assert compute_checksum(archive) == refreshed.archive_checksum
|
||||||
@@ -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()
|
sample_doc.save(write_file_paths=True)
|
||||||
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()
|
sample_doc.save(write_file_paths=True)
|
||||||
messages = check_sanity()
|
messages = check_sanity()
|
||||||
assert not messages.has_error
|
assert not messages.has_error
|
||||||
|
|
||||||
|
|||||||
@@ -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()
|
self.document.save(write_file_paths=True)
|
||||||
path = self.document.archive_path
|
path = self.document.archive_path
|
||||||
assert path is not None
|
assert path is not None
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -887,8 +887,8 @@ class TestSavedZoneExtraction:
|
|||||||
WHEN:
|
WHEN:
|
||||||
- Zone extraction runs
|
- Zone extraction runs
|
||||||
THEN:
|
THEN:
|
||||||
- No on-commit callbacks are registered; finishing is left to the
|
- The only on-commit callback is the deferred file move; reindexing
|
||||||
caller
|
and other finishing is left to the 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,7 +900,10 @@ 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 callbacks == []
|
assert all(
|
||||||
|
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,
|
||||||
|
|||||||
+122
-19
@@ -134,6 +134,7 @@ 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
|
||||||
@@ -942,7 +943,7 @@ class EmailDocumentDetailSchema(EmailSerializer):
|
|||||||
parameters=[
|
parameters=[
|
||||||
OpenApiParameter(
|
OpenApiParameter(
|
||||||
name="id",
|
name="id",
|
||||||
type=OpenApiTypes.STR,
|
type=OpenApiTypes.INT,
|
||||||
location=OpenApiParameter.PATH,
|
location=OpenApiParameter.PATH,
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
@@ -1036,6 +1037,14 @@ class DocumentViewSet(
|
|||||||
# Bound the IN clauses used for search results and through-table lookups.
|
# Bound the IN clauses used for search results and through-table lookups.
|
||||||
selection_data_batch_size = 10_000
|
selection_data_batch_size = 10_000
|
||||||
|
|
||||||
|
def initial(self, request, *args, **kwargs):
|
||||||
|
super().initial(request, *args, **kwargs)
|
||||||
|
# Only ASCII digits can be a document id, reject anything else here, before
|
||||||
|
# any action calls int() on it
|
||||||
|
pk = kwargs.get("pk")
|
||||||
|
if pk is not None and not (pk.isascii() and pk.isdigit()):
|
||||||
|
raise Http404
|
||||||
|
|
||||||
def _get_selection_data_for_queryset(
|
def _get_selection_data_for_queryset(
|
||||||
self,
|
self,
|
||||||
queryset: QuerySet[Document],
|
queryset: QuerySet[Document],
|
||||||
@@ -1309,6 +1318,8 @@ 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 = (
|
||||||
@@ -1316,7 +1327,11 @@ class DocumentViewSet(
|
|||||||
)
|
)
|
||||||
content_doc.save(update_fields=["content", "modified"])
|
content_doc.save(update_fields=["content", "modified"])
|
||||||
|
|
||||||
|
try:
|
||||||
refreshed_doc = self.get_queryset().get(pk=root_doc.pk)
|
refreshed_doc = self.get_queryset().get(pk=root_doc.pk)
|
||||||
|
except Document.DoesNotExist:
|
||||||
|
# Trashed by a concurrent request after our write committed
|
||||||
|
raise Http404
|
||||||
response_data = self.get_serializer(refreshed_doc).data
|
response_data = self.get_serializer(refreshed_doc).data
|
||||||
if "version" in request.query_params and "content" in response_data:
|
if "version" in request.query_params and "content" in response_data:
|
||||||
response_data["content"] = content_doc.content
|
response_data["content"] = content_doc.content
|
||||||
@@ -2205,7 +2220,7 @@ class DocumentViewSet(
|
|||||||
raise Http404
|
raise Http404
|
||||||
|
|
||||||
try:
|
try:
|
||||||
doc_name, doc_data = serializer.validated_data.get("document")
|
doc_name, doc_file = serializer.validated_data.get("document")
|
||||||
version_label = serializer.validated_data.get("version_label")
|
version_label = serializer.validated_data.get("version_label")
|
||||||
|
|
||||||
t = int(mktime(datetime.now().timetuple()))
|
t = int(mktime(datetime.now().timetuple()))
|
||||||
@@ -2216,7 +2231,9 @@ class DocumentViewSet(
|
|||||||
pathvalidate.sanitize_filename(doc_name),
|
pathvalidate.sanitize_filename(doc_name),
|
||||||
)
|
)
|
||||||
|
|
||||||
temp_file_path.write_bytes(doc_data)
|
with temp_file_path.open("wb") as scratch_file:
|
||||||
|
for chunk in doc_file.chunks():
|
||||||
|
scratch_file.write(chunk)
|
||||||
|
|
||||||
os.utime(temp_file_path, times=(t, t))
|
os.utime(temp_file_path, times=(t, t))
|
||||||
|
|
||||||
@@ -2884,6 +2901,13 @@ class UnifiedSearchViewSet(DocumentViewSet):
|
|||||||
return Response(max_asn + 1)
|
return Response(max_asn + 1)
|
||||||
|
|
||||||
|
|
||||||
|
LOG_FILES = {
|
||||||
|
"paperless": "paperless.log",
|
||||||
|
"mail": "mail.log",
|
||||||
|
"celery": "celery.log",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@extend_schema_view(
|
@extend_schema_view(
|
||||||
list=extend_schema(
|
list=extend_schema(
|
||||||
description="Logs view",
|
description="Logs view",
|
||||||
@@ -2901,6 +2925,7 @@ class UnifiedSearchViewSet(DocumentViewSet):
|
|||||||
name="id",
|
name="id",
|
||||||
type=OpenApiTypes.STR,
|
type=OpenApiTypes.STR,
|
||||||
location=OpenApiParameter.PATH,
|
location=OpenApiParameter.PATH,
|
||||||
|
enum=list(LOG_FILES),
|
||||||
),
|
),
|
||||||
OpenApiParameter(
|
OpenApiParameter(
|
||||||
name="limit",
|
name="limit",
|
||||||
@@ -2921,18 +2946,12 @@ class UnifiedSearchViewSet(DocumentViewSet):
|
|||||||
class LogViewSet(ViewSet):
|
class LogViewSet(ViewSet):
|
||||||
permission_classes = (IsAuthenticated, PaperlessAdminPermissions)
|
permission_classes = (IsAuthenticated, PaperlessAdminPermissions)
|
||||||
|
|
||||||
ALLOWED_LOG_FILES = {
|
|
||||||
"paperless": "paperless.log",
|
|
||||||
"mail": "mail.log",
|
|
||||||
"celery": "celery.log",
|
|
||||||
}
|
|
||||||
|
|
||||||
def get_log_file(self, log_key: str) -> Path:
|
def get_log_file(self, log_key: str) -> Path:
|
||||||
return Path(settings.LOGGING_DIR) / self.ALLOWED_LOG_FILES[log_key]
|
return Path(settings.LOGGING_DIR) / LOG_FILES[log_key]
|
||||||
|
|
||||||
def retrieve(self, request, *args, **kwargs):
|
def retrieve(self, request, *args, **kwargs):
|
||||||
log_key = kwargs.get("pk")
|
log_key = kwargs.get("pk")
|
||||||
if log_key not in self.ALLOWED_LOG_FILES:
|
if log_key not in LOG_FILES:
|
||||||
raise Http404
|
raise Http404
|
||||||
|
|
||||||
log_file = self.get_log_file(log_key)
|
log_file = self.get_log_file(log_key)
|
||||||
@@ -2961,9 +2980,7 @@ class LogViewSet(ViewSet):
|
|||||||
|
|
||||||
def list(self, request, *args, **kwargs):
|
def list(self, request, *args, **kwargs):
|
||||||
existing_logs = [
|
existing_logs = [
|
||||||
log_key
|
log_key for log_key in LOG_FILES if self.get_log_file(log_key).is_file()
|
||||||
for log_key in self.ALLOWED_LOG_FILES
|
|
||||||
if self.get_log_file(log_key).is_file()
|
|
||||||
]
|
]
|
||||||
return Response(existing_logs)
|
return Response(existing_logs)
|
||||||
|
|
||||||
@@ -3498,7 +3515,7 @@ class PostDocumentView(GenericAPIView[Any]):
|
|||||||
serializer = self.get_serializer(data=request.data)
|
serializer = self.get_serializer(data=request.data)
|
||||||
serializer.is_valid(raise_exception=True)
|
serializer.is_valid(raise_exception=True)
|
||||||
|
|
||||||
doc_name, doc_data = serializer.validated_data.get("document")
|
doc_name, doc_file = serializer.validated_data.get("document")
|
||||||
doc_name = normalize("NFC", doc_name)
|
doc_name = normalize("NFC", doc_name)
|
||||||
correspondent_id = serializer.validated_data.get("correspondent")
|
correspondent_id = serializer.validated_data.get("correspondent")
|
||||||
document_type_id = serializer.validated_data.get("document_type")
|
document_type_id = serializer.validated_data.get("document_type")
|
||||||
@@ -3518,7 +3535,9 @@ class PostDocumentView(GenericAPIView[Any]):
|
|||||||
pathvalidate.sanitize_filename(doc_name),
|
pathvalidate.sanitize_filename(doc_name),
|
||||||
)
|
)
|
||||||
|
|
||||||
temp_file_path.write_bytes(doc_data)
|
with temp_file_path.open("wb") as scratch_file:
|
||||||
|
for chunk in doc_file.chunks():
|
||||||
|
scratch_file.write(chunk)
|
||||||
|
|
||||||
os.utime(temp_file_path, times=(t, t))
|
os.utime(temp_file_path, times=(t, t))
|
||||||
|
|
||||||
@@ -3733,7 +3752,10 @@ class SearchAutoCompleteView(GenericAPIView[Any]):
|
|||||||
return HttpResponseBadRequest("Term required")
|
return HttpResponseBadRequest("Term required")
|
||||||
|
|
||||||
if "limit" in request.query_params:
|
if "limit" in request.query_params:
|
||||||
|
try:
|
||||||
limit = int(request.query_params["limit"])
|
limit = int(request.query_params["limit"])
|
||||||
|
except ValueError:
|
||||||
|
return HttpResponseBadRequest("Invalid limit")
|
||||||
if limit <= 0:
|
if limit <= 0:
|
||||||
return HttpResponseBadRequest("Invalid limit")
|
return HttpResponseBadRequest("Invalid limit")
|
||||||
else:
|
else:
|
||||||
@@ -4009,7 +4031,36 @@ class GlobalSearchView(PassUserMixin):
|
|||||||
get=extend_schema(
|
get=extend_schema(
|
||||||
description="Get statistics for the current user",
|
description="Get statistics for the current user",
|
||||||
responses={
|
responses={
|
||||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
(200, "application/json"): inline_serializer(
|
||||||
|
name="Statistics",
|
||||||
|
fields={
|
||||||
|
"documents_total": serializers.IntegerField(),
|
||||||
|
"documents_inbox": serializers.IntegerField(allow_null=True),
|
||||||
|
"inbox_tag": serializers.IntegerField(
|
||||||
|
allow_null=True,
|
||||||
|
help_text="The first inbox tag, kept for backwards compatibility",
|
||||||
|
),
|
||||||
|
"inbox_tags": serializers.ListField(
|
||||||
|
child=serializers.IntegerField(),
|
||||||
|
allow_null=True,
|
||||||
|
),
|
||||||
|
"document_file_type_counts": serializers.ListField(
|
||||||
|
child=inline_serializer(
|
||||||
|
name="MimeTypeCount",
|
||||||
|
fields={
|
||||||
|
"mime_type": serializers.CharField(),
|
||||||
|
"mime_type_count": serializers.IntegerField(),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
"character_count": serializers.IntegerField(),
|
||||||
|
"tag_count": serializers.IntegerField(),
|
||||||
|
"correspondent_count": serializers.IntegerField(),
|
||||||
|
"document_type_count": serializers.IntegerField(),
|
||||||
|
"storage_path_count": serializers.IntegerField(),
|
||||||
|
"current_asn": serializers.IntegerField(),
|
||||||
|
},
|
||||||
|
),
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -4494,7 +4545,13 @@ def get_github_stars() -> int | None:
|
|||||||
get=extend_schema(
|
get=extend_schema(
|
||||||
description="Get the current version of the Paperless-NGX server",
|
description="Get the current version of the Paperless-NGX server",
|
||||||
responses={
|
responses={
|
||||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
(200, "application/json"): inline_serializer(
|
||||||
|
name="RemoteVersion",
|
||||||
|
fields={
|
||||||
|
"version": serializers.CharField(),
|
||||||
|
"update_available": serializers.BooleanField(),
|
||||||
|
},
|
||||||
|
),
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -4559,7 +4616,17 @@ class RemoteVersionView(GenericAPIView[Any]):
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
responses={
|
responses={
|
||||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
(200, "application/json"): inline_serializer(
|
||||||
|
name="ReleaseNotes",
|
||||||
|
fields={
|
||||||
|
"version": serializers.CharField(),
|
||||||
|
"releases": serializers.ListField(
|
||||||
|
child=serializers.DictField(),
|
||||||
|
help_text="GitHub release objects",
|
||||||
|
),
|
||||||
|
"stars": serializers.IntegerField(allow_null=True),
|
||||||
|
},
|
||||||
|
),
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -5823,6 +5890,26 @@ class SystemStatusView(PassUserMixin):
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@extend_schema_view(
|
||||||
|
get=extend_schema(
|
||||||
|
description="List the documents in the trash",
|
||||||
|
responses={(200, "application/json"): DocumentSerializer(many=True)},
|
||||||
|
),
|
||||||
|
post=extend_schema(
|
||||||
|
description="Restore documents from the trash, or delete them permanently",
|
||||||
|
responses={
|
||||||
|
(200, "application/json"): inline_serializer(
|
||||||
|
name="TrashActionResult",
|
||||||
|
fields={
|
||||||
|
"result": serializers.CharField(),
|
||||||
|
"doc_ids": serializers.ListField(
|
||||||
|
child=serializers.IntegerField(),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
class TrashView(ListModelMixin, PassUserMixin):
|
class TrashView(ListModelMixin, PassUserMixin):
|
||||||
permission_classes = (IsAuthenticated, TrashPermissions)
|
permission_classes = (IsAuthenticated, TrashPermissions)
|
||||||
serializer_class = TrashSerializer
|
serializer_class = TrashSerializer
|
||||||
@@ -5971,6 +6058,22 @@ class OcrTemplateViewSet(BulkPermissionMixin, PassUserMixin, ModelViewSet[OcrTem
|
|||||||
]
|
]
|
||||||
return super().get_permissions()
|
return super().get_permissions()
|
||||||
|
|
||||||
|
@extend_schema(
|
||||||
|
parameters=[
|
||||||
|
OpenApiParameter(
|
||||||
|
name="doc_id",
|
||||||
|
type=OpenApiTypes.INT,
|
||||||
|
location=OpenApiParameter.PATH,
|
||||||
|
),
|
||||||
|
OpenApiParameter(
|
||||||
|
name="page",
|
||||||
|
type={"type": "integer", "minimum": 1},
|
||||||
|
location=OpenApiParameter.PATH,
|
||||||
|
description="1-based page number",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
responses={(200, "image/png"): OpenApiTypes.BINARY},
|
||||||
|
)
|
||||||
@action(
|
@action(
|
||||||
detail=False,
|
detail=False,
|
||||||
methods=["get"],
|
methods=["get"],
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,40 @@
|
|||||||
|
import logging
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from paperless.signed_pickle import SignedPickleError
|
||||||
|
from paperless.signed_pickle import signed_pickle_dumps
|
||||||
|
from paperless.signed_pickle import signed_pickle_loads
|
||||||
|
|
||||||
|
logger = logging.getLogger("paperless.cache")
|
||||||
|
|
||||||
|
|
||||||
|
class SignedRedisSerializer:
|
||||||
|
"""
|
||||||
|
Cache serializer for Django's RedisCache which HMAC-signs every pickled value.
|
||||||
|
|
||||||
|
Django's default serializer unpickles whatever it finds under a key, so anything
|
||||||
|
able to write to the Redis instance could get code run in the web server, for
|
||||||
|
example through a session entry. Values are signed with SECRET_KEY on write and
|
||||||
|
verified before unpickling on read, the same protection the Celery messages on
|
||||||
|
the same broker have.
|
||||||
|
|
||||||
|
An entry that fails verification is dropped and reported as a cache miss.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def dumps(self, obj: Any) -> bytes | int:
|
||||||
|
# Like Django's own serializer, keep plain integers unpickled so incr() and
|
||||||
|
# decr() stay atomic. Using type() rather than isinstance() excludes bool.
|
||||||
|
if type(obj) is int:
|
||||||
|
return obj
|
||||||
|
return signed_pickle_dumps(obj)
|
||||||
|
|
||||||
|
def loads(self, data: bytes) -> Any:
|
||||||
|
try:
|
||||||
|
return int(data)
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
return signed_pickle_loads(data)
|
||||||
|
except SignedPickleError:
|
||||||
|
logger.warning("Ignoring cache entry with an invalid signature")
|
||||||
|
return None
|
||||||
+23
-1
@@ -1,6 +1,7 @@
|
|||||||
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
|
||||||
|
|
||||||
@@ -26,7 +27,28 @@ 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.
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
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
|
||||||
|
|
||||||
@@ -30,3 +32,35 @@ 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)
|
||||||
@@ -374,15 +374,19 @@ class TikaDocumentParser:
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
parsed = self._tika_client.metadata.from_file(document_path, mime_type)
|
parsed = self._tika_client.metadata.from_file(document_path, mime_type)
|
||||||
return [
|
metadata: list[MetadataEntry] = []
|
||||||
|
for key, value in parsed.data.items():
|
||||||
|
if isinstance(value, list):
|
||||||
|
value = " ".join(str(item) for item in value)
|
||||||
|
metadata.append(
|
||||||
{
|
{
|
||||||
"namespace": "",
|
"namespace": "",
|
||||||
"prefix": "",
|
"prefix": "",
|
||||||
"key": key,
|
"key": key,
|
||||||
"value": parsed.data[key],
|
"value": str(value),
|
||||||
}
|
},
|
||||||
for key in parsed.data
|
)
|
||||||
]
|
return metadata
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(
|
logger.warning(
|
||||||
"Error while fetching document metadata for %s: %s",
|
"Error while fetching document metadata for %s: %s",
|
||||||
|
|||||||
@@ -365,3 +365,8 @@ class ApplicationConfigurationSerializer(
|
|||||||
class Meta:
|
class Meta:
|
||||||
model = ApplicationConfiguration
|
model = ApplicationConfiguration
|
||||||
fields = "__all__"
|
fields = "__all__"
|
||||||
|
|
||||||
|
|
||||||
|
class TOTPActivationSerializer(serializers.Serializer[dict[str, str]]):
|
||||||
|
secret = serializers.CharField()
|
||||||
|
code = serializers.CharField()
|
||||||
@@ -188,6 +188,7 @@ 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",
|
||||||
@@ -607,6 +608,7 @@ LANGUAGES = [
|
|||||||
("fa-ir", _("Persian")),
|
("fa-ir", _("Persian")),
|
||||||
("fi-fi", _("Finnish")),
|
("fi-fi", _("Finnish")),
|
||||||
("fr-fr", _("French")),
|
("fr-fr", _("French")),
|
||||||
|
("hr-hr", _("Croatian")),
|
||||||
("hu-hu", _("Hungarian")),
|
("hu-hu", _("Hungarian")),
|
||||||
("id-id", _("Indonesian")),
|
("id-id", _("Indonesian")),
|
||||||
("it-it", _("Italian")),
|
("it-it", _("Italian")),
|
||||||
@@ -807,17 +809,23 @@ _CACHE_BACKEND = os.environ.get(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# Entries are HMAC-signed so values planted in Redis are never unpickled
|
||||||
|
_CACHE_OPTIONS = {"serializer": "paperless.cache.SignedRedisSerializer"}
|
||||||
|
|
||||||
|
|
||||||
def _parse_caches():
|
def _parse_caches():
|
||||||
return {
|
return {
|
||||||
"default": {
|
"default": {
|
||||||
"BACKEND": _CACHE_BACKEND,
|
"BACKEND": _CACHE_BACKEND,
|
||||||
"LOCATION": _CHANNELS_REDIS_URL,
|
"LOCATION": _CHANNELS_REDIS_URL,
|
||||||
"KEY_PREFIX": _REDIS_KEY_PREFIX,
|
"KEY_PREFIX": _REDIS_KEY_PREFIX,
|
||||||
|
"OPTIONS": _CACHE_OPTIONS,
|
||||||
},
|
},
|
||||||
"read-cache": {
|
"read-cache": {
|
||||||
"BACKEND": _CACHE_BACKEND,
|
"BACKEND": _CACHE_BACKEND,
|
||||||
"LOCATION": cachalot_settings["CACHALOT_REDIS_URL"],
|
"LOCATION": cachalot_settings["CACHALOT_REDIS_URL"],
|
||||||
"KEY_PREFIX": _REDIS_KEY_PREFIX,
|
"KEY_PREFIX": _REDIS_KEY_PREFIX,
|
||||||
|
"OPTIONS": _CACHE_OPTIONS,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -131,8 +131,10 @@ class TestTikaParser:
|
|||||||
httpx_mock.add_response(
|
httpx_mock.add_response(
|
||||||
json={
|
json={
|
||||||
"Content-Type": "application/vnd.oasis.opendocument.text",
|
"Content-Type": "application/vnd.oasis.opendocument.text",
|
||||||
"X-TIKA:Parsed-By": [],
|
"X-TIKA:Parsed-By": ["ParserA", "ParserB"],
|
||||||
|
"X-TIKA:Parsed-By-Full-Set": [],
|
||||||
"Some-key": "value",
|
"Some-key": "value",
|
||||||
|
"meta:page-count": 2,
|
||||||
"dcterms:created": "2020-11-21T00:00:00",
|
"dcterms:created": "2020-11-21T00:00:00",
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -144,6 +146,11 @@ class TestTikaParser:
|
|||||||
|
|
||||||
assert "dcterms:created" in [m["key"] for m in metadata]
|
assert "dcterms:created" in [m["key"] for m in metadata]
|
||||||
assert "Some-key" in [m["key"] for m in metadata]
|
assert "Some-key" in [m["key"] for m in metadata]
|
||||||
|
values = {entry["key"]: entry["value"] for entry in metadata}
|
||||||
|
assert values["X-TIKA:Parsed-By"] == "ParserA ParserB"
|
||||||
|
assert values["X-TIKA:Parsed-By-Full-Set"] == ""
|
||||||
|
assert values["meta:page-count"] == "2"
|
||||||
|
assert all(isinstance(value, str) for value in values.values())
|
||||||
|
|
||||||
def test_convert_failure(
|
def test_convert_failure(
|
||||||
self,
|
self,
|
||||||
|
|||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import pytest
|
||||||
|
from django.test import Client
|
||||||
|
from rest_framework import status
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
|
||||||
|
|
||||||
|
class TestUnmatchedApiPaths:
|
||||||
|
@pytest.mark.parametrize("method", ["get", "post", "put", "patch", "delete"])
|
||||||
|
def test_unmatched_api_path_is_a_json_404(
|
||||||
|
self,
|
||||||
|
rest_api_client: APIClient,
|
||||||
|
method: str,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- An unauthenticated client
|
||||||
|
WHEN:
|
||||||
|
- Any method is sent to an /api/ URL that no route matches
|
||||||
|
THEN:
|
||||||
|
- The response is a JSON 404, not a redirect to the login page
|
||||||
|
"""
|
||||||
|
response = getattr(rest_api_client, method)("/api/this_does_not_exist/")
|
||||||
|
|
||||||
|
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||||
|
assert response["Content-Type"].startswith("application/json")
|
||||||
|
|
||||||
|
def test_unmatched_api_path_is_a_json_404_when_authenticated(
|
||||||
|
self,
|
||||||
|
admin_client: APIClient,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- An authenticated client
|
||||||
|
WHEN:
|
||||||
|
- An /api/ URL that no route matches is requested
|
||||||
|
THEN:
|
||||||
|
- The response is a JSON 404, not the frontend page
|
||||||
|
"""
|
||||||
|
response = admin_client.get("/api/this/is/nested/and/missing/")
|
||||||
|
|
||||||
|
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||||
|
assert response["Content-Type"].startswith("application/json")
|
||||||
|
|
||||||
|
def test_other_paths_still_reach_the_frontend_catch_all(
|
||||||
|
self,
|
||||||
|
client: Client,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- An anonymous browser request
|
||||||
|
WHEN:
|
||||||
|
- A non-API path is requested
|
||||||
|
THEN:
|
||||||
|
- The frontend catch-all still applies, which sends the user to log in
|
||||||
|
"""
|
||||||
|
response = client.get("/documents/")
|
||||||
|
|
||||||
|
assert response.status_code == status.HTTP_302_FOUND
|
||||||
|
assert "login" in response["Location"]
|
||||||
|
|
||||||
|
|
||||||
|
class TestDocumentRouteIds:
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"action",
|
||||||
|
[
|
||||||
|
"download",
|
||||||
|
"history",
|
||||||
|
"metadata",
|
||||||
|
"notes",
|
||||||
|
"preview",
|
||||||
|
"root",
|
||||||
|
"share_links",
|
||||||
|
"suggestions",
|
||||||
|
"thumb",
|
||||||
|
],
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize("pk", ["null", "true", "abc", "0.5", "%20"])
|
||||||
|
def test_non_numeric_document_id_is_a_json_404(
|
||||||
|
self,
|
||||||
|
admin_client: APIClient,
|
||||||
|
action: str,
|
||||||
|
pk: str,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- An authenticated client
|
||||||
|
WHEN:
|
||||||
|
- A document sub-route is requested with an id that is not a number
|
||||||
|
THEN:
|
||||||
|
- The response is a JSON 404, not a server error
|
||||||
|
"""
|
||||||
|
response = admin_client.get(f"/api/documents/{pk}/{action}/")
|
||||||
|
|
||||||
|
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||||
|
assert response["Content-Type"].startswith("application/json")
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import pytest
|
||||||
|
from rest_framework import status
|
||||||
|
from rest_framework.test import APIClient
|
||||||
|
|
||||||
|
|
||||||
|
class TestTotpView:
|
||||||
|
def test_options_does_not_fail(self, admin_client: APIClient) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- An authenticated client
|
||||||
|
WHEN:
|
||||||
|
- OPTIONS is sent to the TOTP endpoint
|
||||||
|
THEN:
|
||||||
|
- The request succeeds, DRF's metadata needs a serializer on the view
|
||||||
|
"""
|
||||||
|
response = admin_client.options("/api/profile/totp/")
|
||||||
|
|
||||||
|
assert response.status_code == status.HTTP_200_OK
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"body",
|
||||||
|
[{}, {"secret": "abc"}, {"code": "123456"}, {"secret": None, "code": None}],
|
||||||
|
)
|
||||||
|
def test_activation_with_missing_fields_is_a_400(
|
||||||
|
self,
|
||||||
|
admin_client: APIClient,
|
||||||
|
body: dict[str, str | None],
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- An authenticated client
|
||||||
|
WHEN:
|
||||||
|
- TOTP is activated without both the secret and the code
|
||||||
|
THEN:
|
||||||
|
- The response is a 400, not a server error
|
||||||
|
"""
|
||||||
|
response = admin_client.post("/api/profile/totp/", body, format="json")
|
||||||
|
|
||||||
|
assert response.status_code == status.HTTP_400_BAD_REQUEST
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import pickle
|
||||||
|
from collections.abc import Callable
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from django.conf import settings
|
||||||
|
|
||||||
|
from paperless.cache import SignedRedisSerializer
|
||||||
|
from paperless.signed_pickle import compute_signature
|
||||||
|
|
||||||
|
|
||||||
|
class _Evil:
|
||||||
|
def __init__(self, marker: Path) -> None:
|
||||||
|
self.marker = marker
|
||||||
|
|
||||||
|
def __reduce__(self) -> tuple[Any, tuple[str]]:
|
||||||
|
return (self.marker.write_text, ("pwned",))
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def serializer() -> SignedRedisSerializer:
|
||||||
|
return SignedRedisSerializer()
|
||||||
|
|
||||||
|
|
||||||
|
class TestSignedRedisSerializer:
|
||||||
|
def test_round_trip(self, serializer: SignedRedisSerializer) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- A nested value
|
||||||
|
WHEN:
|
||||||
|
- It is serialized and then deserialized
|
||||||
|
THEN:
|
||||||
|
- The original value is returned
|
||||||
|
"""
|
||||||
|
value = {"a": [1, 2, 3], "b": ("x", None)}
|
||||||
|
|
||||||
|
assert serializer.loads(serializer.dumps(value)) == value
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("value", "stored_type"),
|
||||||
|
[
|
||||||
|
pytest.param(7, int, id="int"),
|
||||||
|
pytest.param(True, bytes, id="bool"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_only_plain_integers_are_stored_raw(
|
||||||
|
self,
|
||||||
|
serializer: SignedRedisSerializer,
|
||||||
|
value: object,
|
||||||
|
stored_type: type,
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- A plain integer or a bool
|
||||||
|
WHEN:
|
||||||
|
- The value is serialized
|
||||||
|
THEN:
|
||||||
|
- Only the integer is stored unpickled, so incr/decr stay atomic
|
||||||
|
"""
|
||||||
|
assert type(serializer.dumps(value)) is stored_type
|
||||||
|
|
||||||
|
def test_raw_integer_is_loaded(self, serializer: SignedRedisSerializer) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- An integer as stored by Redis incr/decr
|
||||||
|
WHEN:
|
||||||
|
- It is deserialized
|
||||||
|
THEN:
|
||||||
|
- The integer is returned without signature verification
|
||||||
|
"""
|
||||||
|
assert serializer.loads(b"7") == 7
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"forge",
|
||||||
|
[
|
||||||
|
pytest.param(lambda data: data, id="unsigned"),
|
||||||
|
pytest.param(
|
||||||
|
lambda data: compute_signature(b"other data") + data,
|
||||||
|
id="signature-for-other-data",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_forged_pickle_is_not_loaded(
|
||||||
|
self,
|
||||||
|
serializer: SignedRedisSerializer,
|
||||||
|
tmp_path: Path,
|
||||||
|
caplog: pytest.LogCaptureFixture,
|
||||||
|
forge: Callable[[bytes], bytes],
|
||||||
|
) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- A malicious pickle without a valid signature
|
||||||
|
WHEN:
|
||||||
|
- It is deserialized
|
||||||
|
THEN:
|
||||||
|
- It is treated as a cache miss, never executed, and a warning is logged
|
||||||
|
"""
|
||||||
|
marker = tmp_path / "marker"
|
||||||
|
payload = forge(pickle.dumps(_Evil(marker)))
|
||||||
|
|
||||||
|
assert serializer.loads(payload) is None
|
||||||
|
assert not marker.exists()
|
||||||
|
assert "invalid signature" in caplog.text
|
||||||
|
|
||||||
|
|
||||||
|
class TestCacheSettings:
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"alias",
|
||||||
|
[
|
||||||
|
pytest.param("default", id="default"),
|
||||||
|
pytest.param("read-cache", id="read-cache"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_caches_use_signed_serializer(self, alias: str) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- The configured cache aliases
|
||||||
|
WHEN:
|
||||||
|
- Their options are inspected
|
||||||
|
THEN:
|
||||||
|
- Each uses the signed serializer
|
||||||
|
"""
|
||||||
|
options = settings.CACHES[alias]["OPTIONS"]
|
||||||
|
|
||||||
|
assert options["serializer"] == "paperless.cache.SignedRedisSerializer"
|
||||||
@@ -658,9 +658,9 @@ class TestUserGroupDeletionCleanup(TestCase):
|
|||||||
"permissions": {
|
"permissions": {
|
||||||
"default_owner": user2.id,
|
"default_owner": user2.id,
|
||||||
"default_view_users": [user2.id],
|
"default_view_users": [user2.id],
|
||||||
"default_change_users": [user2.id],
|
"default_edit_users": [user2.id],
|
||||||
"default_view_groups": [group.id],
|
"default_view_groups": [group.id],
|
||||||
"default_change_groups": [group.id],
|
"default_edit_groups": [group.id],
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -670,13 +670,13 @@ class TestUserGroupDeletionCleanup(TestCase):
|
|||||||
permissions = ui_settings.settings.get("permissions", {})
|
permissions = ui_settings.settings.get("permissions", {})
|
||||||
self.assertIsNone(permissions.get("default_owner"))
|
self.assertIsNone(permissions.get("default_owner"))
|
||||||
self.assertEqual(permissions.get("default_view_users"), [])
|
self.assertEqual(permissions.get("default_view_users"), [])
|
||||||
self.assertEqual(permissions.get("default_change_users"), [])
|
self.assertEqual(permissions.get("default_edit_users"), [])
|
||||||
|
|
||||||
group.delete()
|
group.delete()
|
||||||
ui_settings.refresh_from_db()
|
ui_settings.refresh_from_db()
|
||||||
permissions = ui_settings.settings.get("permissions", {})
|
permissions = ui_settings.settings.get("permissions", {})
|
||||||
self.assertEqual(permissions.get("default_view_groups"), [])
|
self.assertEqual(permissions.get("default_view_groups"), [])
|
||||||
self.assertEqual(permissions.get("default_change_groups"), [])
|
self.assertEqual(permissions.get("default_edit_groups"), [])
|
||||||
|
|
||||||
def test_user_group_deletion_error_handling(self) -> None:
|
def test_user_group_deletion_error_handling(self) -> None:
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -57,6 +57,7 @@ from documents.views import WorkflowTriggerViewSet
|
|||||||
from documents.views import WorkflowViewSet
|
from documents.views import WorkflowViewSet
|
||||||
from documents.views import serve_logo
|
from documents.views import serve_logo
|
||||||
from paperless.consumers import StatusConsumer
|
from paperless.consumers import StatusConsumer
|
||||||
|
from paperless.views import ApiNotFoundView
|
||||||
from paperless.views import ApplicationConfigurationViewSet
|
from paperless.views import ApplicationConfigurationViewSet
|
||||||
from paperless.views import DisconnectSocialAccountView
|
from paperless.views import DisconnectSocialAccountView
|
||||||
from paperless.views import FaviconView
|
from paperless.views import FaviconView
|
||||||
@@ -309,6 +310,8 @@ urlpatterns = [
|
|||||||
RedirectView.as_view(url="schema/view/"),
|
RedirectView.as_view(url="schema/view/"),
|
||||||
),
|
),
|
||||||
*api_router.urls,
|
*api_router.urls,
|
||||||
|
# Must stay last, anything unmatched under /api/ is a JSON 404
|
||||||
|
re_path(r"^.*$", ApiNotFoundView.as_view(), name="api_not_found"),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
+55
-6
@@ -24,9 +24,12 @@ from django_filters.rest_framework import DjangoFilterBackend
|
|||||||
from drf_spectacular.types import OpenApiTypes
|
from drf_spectacular.types import OpenApiTypes
|
||||||
from drf_spectacular.utils import extend_schema
|
from drf_spectacular.utils import extend_schema
|
||||||
from drf_spectacular.utils import extend_schema_view
|
from drf_spectacular.utils import extend_schema_view
|
||||||
|
from drf_spectacular.utils import inline_serializer
|
||||||
|
from rest_framework import serializers
|
||||||
from rest_framework.authtoken.models import Token
|
from rest_framework.authtoken.models import Token
|
||||||
from rest_framework.authtoken.views import ObtainAuthToken
|
from rest_framework.authtoken.views import ObtainAuthToken
|
||||||
from rest_framework.decorators import action
|
from rest_framework.decorators import action
|
||||||
|
from rest_framework.exceptions import NotFound
|
||||||
from rest_framework.exceptions import ValidationError
|
from rest_framework.exceptions import ValidationError
|
||||||
from rest_framework.fields import BooleanField
|
from rest_framework.fields import BooleanField
|
||||||
from rest_framework.filters import OrderingFilter
|
from rest_framework.filters import OrderingFilter
|
||||||
@@ -35,6 +38,7 @@ from rest_framework.pagination import PageNumberPagination
|
|||||||
from rest_framework.permissions import IsAuthenticated
|
from rest_framework.permissions import IsAuthenticated
|
||||||
from rest_framework.response import Response
|
from rest_framework.response import Response
|
||||||
from rest_framework.throttling import ScopedRateThrottle
|
from rest_framework.throttling import ScopedRateThrottle
|
||||||
|
from rest_framework.views import APIView
|
||||||
from rest_framework.viewsets import ModelViewSet
|
from rest_framework.viewsets import ModelViewSet
|
||||||
|
|
||||||
from documents.models import PaperlessTask
|
from documents.models import PaperlessTask
|
||||||
@@ -49,6 +53,7 @@ from paperless.serialisers import ApplicationConfigurationSerializer
|
|||||||
from paperless.serialisers import GroupSerializer
|
from paperless.serialisers import GroupSerializer
|
||||||
from paperless.serialisers import PaperlessAuthTokenSerializer
|
from paperless.serialisers import PaperlessAuthTokenSerializer
|
||||||
from paperless.serialisers import ProfileSerializer
|
from paperless.serialisers import ProfileSerializer
|
||||||
|
from paperless.serialisers import TOTPActivationSerializer
|
||||||
from paperless.serialisers import UserSerializer
|
from paperless.serialisers import UserSerializer
|
||||||
|
|
||||||
|
|
||||||
@@ -274,8 +279,16 @@ class ProfileView(GenericAPIView[Any]):
|
|||||||
|
|
||||||
@extend_schema_view(
|
@extend_schema_view(
|
||||||
get=extend_schema(
|
get=extend_schema(
|
||||||
|
description="Generate a new TOTP secret, its otpauth URL and a QR code",
|
||||||
responses={
|
responses={
|
||||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
(200, "application/json"): inline_serializer(
|
||||||
|
name="TotpSetup",
|
||||||
|
fields={
|
||||||
|
"url": serializers.CharField(),
|
||||||
|
"qr_svg": serializers.CharField(help_text="QR code as an SVG"),
|
||||||
|
"secret": serializers.CharField(),
|
||||||
|
},
|
||||||
|
),
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
post=extend_schema(
|
post=extend_schema(
|
||||||
@@ -290,7 +303,17 @@ class ProfileView(GenericAPIView[Any]):
|
|||||||
},
|
},
|
||||||
},
|
},
|
||||||
responses={
|
responses={
|
||||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
(200, "application/json"): inline_serializer(
|
||||||
|
name="TotpActivation",
|
||||||
|
fields={
|
||||||
|
"success": serializers.BooleanField(),
|
||||||
|
"recovery_codes": serializers.ListField(
|
||||||
|
child=serializers.CharField(),
|
||||||
|
allow_null=True,
|
||||||
|
help_text="Only returned when the code was valid",
|
||||||
|
),
|
||||||
|
},
|
||||||
|
),
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
delete=extend_schema(
|
delete=extend_schema(
|
||||||
@@ -306,6 +329,7 @@ class TOTPView(GenericAPIView[Any]):
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
permission_classes = [IsAuthenticated]
|
permission_classes = [IsAuthenticated]
|
||||||
|
serializer_class = TOTPActivationSerializer
|
||||||
|
|
||||||
def get(self, request, *args, **kwargs):
|
def get(self, request, *args, **kwargs):
|
||||||
"""
|
"""
|
||||||
@@ -328,15 +352,18 @@ class TOTPView(GenericAPIView[Any]):
|
|||||||
"""
|
"""
|
||||||
Validates a TOTP code and activates the TOTP authenticator
|
Validates a TOTP code and activates the TOTP authenticator
|
||||||
"""
|
"""
|
||||||
|
serializer = self.get_serializer(data=request.data)
|
||||||
|
serializer.is_valid(raise_exception=True)
|
||||||
|
secret = serializer.validated_data["secret"]
|
||||||
valid = totp_auth.validate_totp_code(
|
valid = totp_auth.validate_totp_code(
|
||||||
request.data["secret"],
|
secret,
|
||||||
request.data["code"],
|
serializer.validated_data["code"],
|
||||||
)
|
)
|
||||||
recovery_codes = None
|
recovery_codes = None
|
||||||
if valid:
|
if valid:
|
||||||
auth = totp_auth.TOTP.activate(
|
auth = totp_auth.TOTP.activate(
|
||||||
request.user,
|
request.user,
|
||||||
request.data["secret"],
|
secret,
|
||||||
).instance
|
).instance
|
||||||
signals.authenticator_added.send(
|
signals.authenticator_added.send(
|
||||||
sender=Authenticator,
|
sender=Authenticator,
|
||||||
@@ -523,7 +550,14 @@ class DisconnectSocialAccountView(GenericAPIView[Any]):
|
|||||||
@extend_schema_view(
|
@extend_schema_view(
|
||||||
get=extend_schema(
|
get=extend_schema(
|
||||||
responses={
|
responses={
|
||||||
(200, "application/json"): OpenApiTypes.OBJECT,
|
(200, "application/json"): inline_serializer(
|
||||||
|
name="SocialAccountProvider",
|
||||||
|
fields={
|
||||||
|
"name": serializers.CharField(),
|
||||||
|
"login_url": serializers.CharField(),
|
||||||
|
},
|
||||||
|
many=True,
|
||||||
|
),
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -557,3 +591,18 @@ class SocialAccountProvidersView(GenericAPIView[Any]):
|
|||||||
]
|
]
|
||||||
|
|
||||||
return Response(sorted(resp, key=lambda p: p["name"]))
|
return Response(sorted(resp, key=lambda p: p["name"]))
|
||||||
|
|
||||||
|
|
||||||
|
@extend_schema(exclude=True)
|
||||||
|
class ApiNotFoundView(APIView):
|
||||||
|
"""
|
||||||
|
A JSON 404 for any /api/ URL that no other route matches. Without this, those
|
||||||
|
URLs fall through to the frontend catch-all, which answers a redirect to the
|
||||||
|
login page or the single page app, never an error an API client can read.
|
||||||
|
"""
|
||||||
|
|
||||||
|
authentication_classes = ()
|
||||||
|
permission_classes = ()
|
||||||
|
|
||||||
|
def initial(self, request, *args, **kwargs):
|
||||||
|
raise NotFound
|
||||||
+32
-40
@@ -2,6 +2,7 @@ import datetime
|
|||||||
import imaplib
|
import imaplib
|
||||||
import itertools
|
import itertools
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
import socket
|
import socket
|
||||||
import ssl
|
import ssl
|
||||||
import tempfile
|
import tempfile
|
||||||
@@ -893,8 +894,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 +901,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 +912,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(
|
||||||
|
self._build_eml_task(
|
||||||
message,
|
message,
|
||||||
rule,
|
rule,
|
||||||
tag_ids,
|
tag_ids,
|
||||||
doc_type,
|
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(
|
||||||
|
self._build_attachment_tasks(
|
||||||
message,
|
message,
|
||||||
rule,
|
rule,
|
||||||
tag_ids,
|
tag_ids,
|
||||||
doc_type,
|
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 +1011,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 +1119,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,33 +1127,22 @@ 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(
|
fd, temp_filename = tempfile.mkstemp(
|
||||||
prefix="paperless-mail-",
|
prefix="paperless-mail-",
|
||||||
dir=settings.SCRATCH_DIR,
|
dir=settings.SCRATCH_DIR,
|
||||||
suffix=".eml",
|
suffix=".eml",
|
||||||
)
|
)
|
||||||
with Path(temp_filename).open("wb") as f:
|
with os.fdopen(fd, "wb") as f:
|
||||||
# Move "From"-header to beginning of file
|
# Move "From"-header to beginning of file
|
||||||
# TODO: This ugly workaround is needed because the parser is
|
# TODO: This ugly workaround is needed because the parser is
|
||||||
# chosen only by the mime_type detected via magic
|
# chosen only by the mime_type detected via magic
|
||||||
@@ -1191,17 +1193,7 @@ class MailAccountHandler(LoggingMixin):
|
|||||||
owner_id=rule.owner.id if rule.owner else None,
|
owner_id=rule.owner.id if rule.owner else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
consume_task = consume_file.s(
|
return consume_file.s(
|
||||||
input_doc=input_doc,
|
input_doc=input_doc,
|
||||||
overrides=doc_overrides,
|
overrides=doc_overrides,
|
||||||
).set(headers={"trigger_source": PaperlessTask.TriggerSource.EMAIL_CONSUME})
|
).set(headers={"trigger_source": PaperlessTask.TriggerSource.EMAIL_CONSUME})
|
||||||
|
|
||||||
queue_consumption_tasks(
|
|
||||||
consume_tasks=[consume_task],
|
|
||||||
rule=rule,
|
|
||||||
message=message,
|
|
||||||
uid_validity=self._current_uid_validity,
|
|
||||||
)
|
|
||||||
|
|
||||||
processed_elements = 1
|
|
||||||
return processed_elements
|
|
||||||
@@ -416,6 +416,44 @@ class TestMail(
|
|||||||
1,
|
1,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_handle_message_everything_scope_single_row(self) -> None:
|
||||||
|
"""
|
||||||
|
GIVEN:
|
||||||
|
- A rule consuming the eml and attachments, and a mail with or
|
||||||
|
without attachments
|
||||||
|
WHEN:
|
||||||
|
- The mail is handled and its queued mail action is applied
|
||||||
|
THEN:
|
||||||
|
- The eml and attachments are queued together in one call
|
||||||
|
- Exactly one ProcessedMail row exists and it is not
|
||||||
|
PROCESSED_WO_CONSUMPTION
|
||||||
|
"""
|
||||||
|
rule = MailRule.objects.create(
|
||||||
|
account=MailAccount.objects.create(
|
||||||
|
name="test",
|
||||||
|
imap_server="",
|
||||||
|
username="admin",
|
||||||
|
password="secret",
|
||||||
|
),
|
||||||
|
consumption_scope=MailRule.ConsumptionScope.EVERYTHING,
|
||||||
|
)
|
||||||
|
|
||||||
|
for attachments in (0, 2):
|
||||||
|
with self.subTest(attachments=attachments):
|
||||||
|
self.mailMocker._queue_consumption_tasks_mock.reset_mock()
|
||||||
|
message = self.mailMocker.messageBuilder.create_message(
|
||||||
|
subject=f"{attachments} attachments",
|
||||||
|
attachments=attachments,
|
||||||
|
)
|
||||||
|
|
||||||
|
result = self.mail_account_handler._handle_message(message, rule)
|
||||||
|
self.mailMocker.apply_mail_actions()
|
||||||
|
|
||||||
|
self.assertEqual(result, 1 + attachments)
|
||||||
|
self.mailMocker._queue_consumption_tasks_mock.assert_called_once()
|
||||||
|
processed = ProcessedMail.objects.get(rule=rule, uid=message.uid)
|
||||||
|
self.assertEqual(processed.status, "SUCCESS")
|
||||||
|
|
||||||
def test_handle_empty_message_long_subject(self) -> None:
|
def test_handle_empty_message_long_subject(self) -> None:
|
||||||
"""
|
"""
|
||||||
GIVEN:
|
GIVEN:
|
||||||
|
|||||||
@@ -272,8 +272,6 @@ class TestMailMessageGpgDecryptor(TestMail):
|
|||||||
"override_title": message.subject,
|
"override_title": message.subject,
|
||||||
"override_filename": f"{message.subject}.eml",
|
"override_filename": f"{message.subject}.eml",
|
||||||
},
|
},
|
||||||
],
|
|
||||||
[
|
|
||||||
{"override_title": "file_0", "override_filename": "file_0.pdf"},
|
{"override_title": "file_0", "override_filename": "file_0.pdf"},
|
||||||
{"override_title": "file_1", "override_filename": "file_1.pdf"},
|
{"override_title": "file_1", "override_filename": "file_1.pdf"},
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ from django.http import HttpResponseRedirect
|
|||||||
from django.utils import timezone
|
from django.utils import timezone
|
||||||
from django_filters.rest_framework import DjangoFilterBackend
|
from django_filters.rest_framework import DjangoFilterBackend
|
||||||
from drf_spectacular.types import OpenApiTypes
|
from drf_spectacular.types import OpenApiTypes
|
||||||
|
from drf_spectacular.utils import OpenApiParameter
|
||||||
from drf_spectacular.utils import extend_schema
|
from drf_spectacular.utils import extend_schema
|
||||||
from drf_spectacular.utils import extend_schema_view
|
from drf_spectacular.utils import extend_schema_view
|
||||||
from drf_spectacular.utils import inline_serializer
|
from drf_spectacular.utils import inline_serializer
|
||||||
@@ -254,8 +255,39 @@ class MailRuleViewSet(PassUserMixin, ModelViewSet[MailRule]):
|
|||||||
|
|
||||||
@extend_schema_view(
|
@extend_schema_view(
|
||||||
get=extend_schema(
|
get=extend_schema(
|
||||||
description="Callback view for OAuth2 authentication",
|
description=(
|
||||||
responses={200: None},
|
"Callback view for OAuth2 authentication. Redirects back to the "
|
||||||
|
"frontend, with the outcome in the query string"
|
||||||
|
),
|
||||||
|
parameters=[
|
||||||
|
OpenApiParameter(
|
||||||
|
name="code",
|
||||||
|
# An empty value is rejected
|
||||||
|
type={"type": "string", "minLength": 1},
|
||||||
|
location=OpenApiParameter.QUERY,
|
||||||
|
required=True,
|
||||||
|
description="Authorization code returned by the OAuth provider",
|
||||||
|
),
|
||||||
|
OpenApiParameter(
|
||||||
|
name="state",
|
||||||
|
# An empty value is rejected
|
||||||
|
type={"type": "string", "minLength": 1},
|
||||||
|
location=OpenApiParameter.QUERY,
|
||||||
|
required=True,
|
||||||
|
description="State value, must match the one stored in the session",
|
||||||
|
),
|
||||||
|
OpenApiParameter(
|
||||||
|
name="scope",
|
||||||
|
type=OpenApiTypes.STR,
|
||||||
|
location=OpenApiParameter.QUERY,
|
||||||
|
required=False,
|
||||||
|
description="Granted scopes, sent by Gmail but not by Outlook",
|
||||||
|
),
|
||||||
|
],
|
||||||
|
responses={
|
||||||
|
302: None,
|
||||||
|
(400, "text/html"): OpenApiTypes.STR,
|
||||||
|
},
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
class OauthCallbackView(GenericAPIView[Any]):
|
class OauthCallbackView(GenericAPIView[Any]):
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ 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
|
||||||
@@ -81,6 +82,14 @@ 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
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
"""Record first acquisitions of the global media lock during a test."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
from unittest import mock
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from collections.abc import Iterator
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True, slots=True)
|
||||||
|
class MediaLockAcquisition:
|
||||||
|
"""One first (non-reentrant) acquisition of settings.MEDIA_LOCK."""
|
||||||
|
|
||||||
|
in_user_transaction: bool
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def record_media_lock_acquisitions() -> Iterator[list[MediaLockAcquisition]]:
|
||||||
|
"""
|
||||||
|
Record every first acquisition of settings.MEDIA_LOCK made in the block.
|
||||||
|
|
||||||
|
Reentrant acquisitions by a thread that already holds the lock never wait,
|
||||||
|
so they are not recorded. Each record notes whether a real (non test case)
|
||||||
|
transaction was open at that moment, which is the lock ordering hazard.
|
||||||
|
"""
|
||||||
|
from django.conf import settings
|
||||||
|
from filelock import BaseFileLock
|
||||||
|
|
||||||
|
from documents.file_moves import in_user_transaction
|
||||||
|
|
||||||
|
records: list[MediaLockAcquisition] = []
|
||||||
|
original_acquire = BaseFileLock.acquire
|
||||||
|
|
||||||
|
def recording_acquire(self: BaseFileLock, *args: object, **kwargs: object):
|
||||||
|
if Path(self.lock_file) == Path(settings.MEDIA_LOCK) and not self.is_locked:
|
||||||
|
records.append(
|
||||||
|
MediaLockAcquisition(in_user_transaction=in_user_transaction()),
|
||||||
|
)
|
||||||
|
return original_acquire(self, *args, **kwargs)
|
||||||
|
|
||||||
|
with mock.patch.object(BaseFileLock, "acquire", recording_acquire):
|
||||||
|
yield records
|
||||||
Reference in new issue
Block a user