somestuff-paperlessstuff 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- somestuff/paperlessstuff/__init__.py +127 -0
- somestuff/paperlessstuff/__main__.py +5 -0
- somestuff/paperlessstuff/api.py +466 -0
- somestuff/paperlessstuff/config.py +512 -0
- somestuff/paperlessstuff/filetypes.py +58 -0
- somestuff/paperlessstuff/folder/__init__.py +11 -0
- somestuff/paperlessstuff/folder/intake.py +161 -0
- somestuff/paperlessstuff/folder/scan.py +154 -0
- somestuff/paperlessstuff/hook.py +968 -0
- somestuff/paperlessstuff/hook_api.py +439 -0
- somestuff/paperlessstuff/jira2paperless/__init__.py +12 -0
- somestuff/paperlessstuff/jira2paperless/__main__.py +5 -0
- somestuff/paperlessstuff/jira2paperless/cli.py +103 -0
- somestuff/paperlessstuff/jira2paperless/clients.py +461 -0
- somestuff/paperlessstuff/jira2paperless/company_review.py +221 -0
- somestuff/paperlessstuff/jira2paperless/config.py +339 -0
- somestuff/paperlessstuff/jira2paperless/importer.py +148 -0
- somestuff/paperlessstuff/jira2paperless/jira2paperless.example.toml +73 -0
- somestuff/paperlessstuff/jira2paperless/models.py +221 -0
- somestuff/paperlessstuff/jira2paperless/reconcile.py +104 -0
- somestuff/paperlessstuff/jira2paperless/rules.py +293 -0
- somestuff/paperlessstuff/mail/__init__.py +12 -0
- somestuff/paperlessstuff/mail/intake.py +349 -0
- somestuff/paperlessstuff/mail/parse.py +335 -0
- somestuff/paperlessstuff/plugins.py +206 -0
- somestuff/paperlessstuff/py.typed +0 -0
- somestuff/paperlessstuff/rules.toml +131 -0
- somestuff/paperlessstuff/upload.py +161 -0
- somestuff_paperlessstuff-0.1.0.dist-info/METADATA +302 -0
- somestuff_paperlessstuff-0.1.0.dist-info/RECORD +33 -0
- somestuff_paperlessstuff-0.1.0.dist-info/WHEEL +4 -0
- somestuff_paperlessstuff-0.1.0.dist-info/entry_points.txt +3 -0
- somestuff_paperlessstuff-0.1.0.dist-info/licenses/LICENSE.md +163 -0
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""paperlessstuff — Paperless-ngx helpers.
|
|
2
|
+
|
|
3
|
+
* :mod:`somestuff.paperlessstuff.hook` — company field -> company tags and view groups, origin rules, sweep
|
|
4
|
+
* :mod:`somestuff.paperlessstuff.hook_api` — FastAPI webhook service + CLI ``paperless-hook`` (extra ``api``)
|
|
5
|
+
* :mod:`somestuff.paperlessstuff.api` — typed Paperless REST client
|
|
6
|
+
* :mod:`somestuff.paperlessstuff.config` — pydantic models of ``rules.toml`` / ``companies.toml``
|
|
7
|
+
* :mod:`somestuff.paperlessstuff.mail` — IMAP mail intake (IDLE), attachment selection like Paperless
|
|
8
|
+
* :mod:`somestuff.paperlessstuff.folder` — polled folder intake (NFS)
|
|
9
|
+
* :mod:`somestuff.paperlessstuff.upload` — shared upload path of both intakes
|
|
10
|
+
* :mod:`somestuff.paperlessstuff.plugins` — plugin directory (``on_added`` / ``on_updated``)
|
|
11
|
+
|
|
12
|
+
Central logging setup lives here (loguru), mirroring broadlinkstuff's setup. The
|
|
13
|
+
modules log via the stdlib ``logging`` module, so :func:`configure_logging`
|
|
14
|
+
installs an intercept handler that funnels those records into loguru.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
import inspect
|
|
18
|
+
import logging
|
|
19
|
+
import os
|
|
20
|
+
import sys
|
|
21
|
+
from collections.abc import Callable
|
|
22
|
+
from types import FrameType
|
|
23
|
+
from typing import TYPE_CHECKING
|
|
24
|
+
|
|
25
|
+
from loguru import logger as glogger
|
|
26
|
+
from tabulate import tabulate
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from loguru import Record
|
|
30
|
+
|
|
31
|
+
__version__ = "0.1.0"
|
|
32
|
+
|
|
33
|
+
__all__ = ["__version__", "configure_logging", "print_banner"]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _loguru_skiplog_filter(record: "Record") -> bool:
|
|
37
|
+
"""Decide whether a loguru record should be emitted.
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
record: The loguru record about to be handled by a sink.
|
|
41
|
+
|
|
42
|
+
Returns:
|
|
43
|
+
``False`` for records whose ``extra['skiplog']`` flag is truthy (they are
|
|
44
|
+
hidden), ``True`` otherwise.
|
|
45
|
+
"""
|
|
46
|
+
return not record.get("extra", {}).get("skiplog", False)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _InterceptHandler(logging.Handler):
|
|
50
|
+
"""Route stdlib ``logging`` records into loguru with correct call-site info.
|
|
51
|
+
|
|
52
|
+
The modules in this package use ``logging.getLogger(...)``; installing this
|
|
53
|
+
on the root logger lets :func:`configure_logging` govern all of them (format,
|
|
54
|
+
level, colour) without touching the individual call sites.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
def emit(self, record: logging.LogRecord) -> None:
|
|
58
|
+
"""Forward a single stdlib record to loguru.
|
|
59
|
+
|
|
60
|
+
Args:
|
|
61
|
+
record: The stdlib log record to re-emit through loguru, preserving
|
|
62
|
+
its level, message, exception info and originating call site.
|
|
63
|
+
"""
|
|
64
|
+
# Map the stdlib level name to a loguru level, falling back to the number.
|
|
65
|
+
level: str | int
|
|
66
|
+
try:
|
|
67
|
+
level = glogger.level(record.levelname).name
|
|
68
|
+
except ValueError:
|
|
69
|
+
level = record.levelno
|
|
70
|
+
# Walk out of the logging module so {module}/{function}/{line} point at the
|
|
71
|
+
# real caller rather than at this handler (canonical loguru intercept recipe).
|
|
72
|
+
frame: FrameType | None = inspect.currentframe()
|
|
73
|
+
depth = 0
|
|
74
|
+
while frame and (depth == 0 or frame.f_code.co_filename == logging.__file__):
|
|
75
|
+
frame = frame.f_back
|
|
76
|
+
depth += 1
|
|
77
|
+
glogger.bind(classname=record.name).opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def configure_logging(
|
|
81
|
+
verbose: bool = False, loguru_filter: Callable[["Record"], bool] = _loguru_skiplog_filter
|
|
82
|
+
) -> None:
|
|
83
|
+
"""Configure a default ``loguru`` sink and funnel stdlib logging into it.
|
|
84
|
+
|
|
85
|
+
The sink is stderr, deliberately: ``--sweep-once`` prints its statistics to
|
|
86
|
+
stdout, so they survive a pipe without log lines mixed in.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
verbose: ``True`` logs at DEBUG, otherwise honours ``LOGURU_LEVEL`` (INFO
|
|
90
|
+
by default).
|
|
91
|
+
loguru_filter: Predicate deciding, per loguru record, whether it is emitted
|
|
92
|
+
by the sink. Defaults to :func:`_loguru_skiplog_filter`.
|
|
93
|
+
"""
|
|
94
|
+
level_name: str = "DEBUG" if verbose else os.getenv("LOGURU_LEVEL", "INFO")
|
|
95
|
+
os.environ["LOGURU_LEVEL"] = level_name
|
|
96
|
+
glogger.remove()
|
|
97
|
+
logger_fmt: str = (
|
|
98
|
+
"<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green> | <level>{level: <8}</level> | <cyan>{module}</cyan>::<cyan>{extra[classname]}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - <level>{message}</level>"
|
|
99
|
+
)
|
|
100
|
+
glogger.add(sys.stderr, level=level_name, format=logger_fmt, filter=loguru_filter) # type: ignore[arg-type]
|
|
101
|
+
glogger.configure(extra={"classname": "None", "skiplog": False})
|
|
102
|
+
# Replace any stdlib handlers with the intercept so all ``logging`` output
|
|
103
|
+
# (this package's and third-party libraries') flows through loguru.
|
|
104
|
+
logging.basicConfig(handlers=[_InterceptHandler()], level=logging.getLevelNamesMapping()[level_name], force=True)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def print_banner(title: str) -> None:
|
|
108
|
+
"""Log the startup banner with version, build time and project links.
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
title: Tool-specific banner title, e.g. ``"paperless-hook"``.
|
|
112
|
+
"""
|
|
113
|
+
startup_rows = [
|
|
114
|
+
["version", __version__],
|
|
115
|
+
["buildtime", os.getenv("BUILDTIME", "unknown")],
|
|
116
|
+
["github", "https://github.com/vroomfondel/somestuff/tree/main/somestuff/paperlessstuff"],
|
|
117
|
+
["Docker Hub", "https://hub.docker.com/r/xomoxcc/somestuff"],
|
|
118
|
+
]
|
|
119
|
+
table_str = tabulate(startup_rows, tablefmt="mixed_grid")
|
|
120
|
+
lines = table_str.split("\n")
|
|
121
|
+
table_width = len(lines[0])
|
|
122
|
+
banner_title = f"{title} starting up"
|
|
123
|
+
title_border = "┍" + "━" * (table_width - 2) + "┑"
|
|
124
|
+
title_row = "│ " + banner_title.center(table_width - 4) + " │"
|
|
125
|
+
separator = lines[0].replace("┍", "┝").replace("┑", "┥").replace("┯", "┿")
|
|
126
|
+
|
|
127
|
+
glogger.opt(raw=True).info(f"\n{title_border}\n{title_row}\n{separator}\n{'\n'.join(lines[1:])}\n")
|
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
"""Typed Paperless-ngx REST client (stdlib ``urllib``, API version 9).
|
|
2
|
+
|
|
3
|
+
Responses are validated into pydantic models that keep only the fields paperless-hook reads,
|
|
4
|
+
request bodies are pydantic models as well. Custom fields are never written via PATCH
|
|
5
|
+
``custom_fields`` (that replaces the whole list), only via ``bulk_edit`` ``modify_custom_fields``
|
|
6
|
+
or as ``custom_fields`` of ``post_document``.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import http.client
|
|
10
|
+
import json
|
|
11
|
+
import time
|
|
12
|
+
import urllib.error
|
|
13
|
+
import urllib.parse
|
|
14
|
+
import urllib.request
|
|
15
|
+
import uuid
|
|
16
|
+
from collections.abc import Iterator, Mapping
|
|
17
|
+
from datetime import datetime
|
|
18
|
+
from typing import Literal
|
|
19
|
+
|
|
20
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
21
|
+
|
|
22
|
+
type JSON = dict[str, JSON] | list[JSON] | str | int | float | bool | None
|
|
23
|
+
type Params = Mapping[str, str | int]
|
|
24
|
+
type CustomFieldValue = str | int | float | bool | list[int] | None
|
|
25
|
+
|
|
26
|
+
API_VERSION = 9
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class PaperlessError(Exception):
|
|
30
|
+
"""A Paperless request failed or answered something unexpected."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class _Response(BaseModel):
|
|
34
|
+
"""Base model of API responses; unknown fields are ignored."""
|
|
35
|
+
|
|
36
|
+
model_config = ConfigDict(extra="ignore")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class NamedObject(_Response):
|
|
40
|
+
"""Tag, group or correspondent.
|
|
41
|
+
|
|
42
|
+
Attributes:
|
|
43
|
+
id: Object id.
|
|
44
|
+
name: Object name.
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
id: int
|
|
48
|
+
name: str
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class UserObject(_Response):
|
|
52
|
+
"""Paperless user.
|
|
53
|
+
|
|
54
|
+
Attributes:
|
|
55
|
+
id: User id.
|
|
56
|
+
username: Login name.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
id: int
|
|
60
|
+
username: str
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class SelectOption(_Response):
|
|
64
|
+
"""Option of a select custom field.
|
|
65
|
+
|
|
66
|
+
Attributes:
|
|
67
|
+
id: Option id (string since API version 7).
|
|
68
|
+
label: Visible label.
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
id: str
|
|
72
|
+
label: str
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class CustomFieldExtra(_Response):
|
|
76
|
+
"""``extra_data`` of a custom field.
|
|
77
|
+
|
|
78
|
+
Attributes:
|
|
79
|
+
select_options: Options of a select field.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
select_options: list[SelectOption] | None = None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class CustomFieldObject(_Response):
|
|
86
|
+
"""Custom field definition.
|
|
87
|
+
|
|
88
|
+
Attributes:
|
|
89
|
+
id: Field id.
|
|
90
|
+
name: Field name.
|
|
91
|
+
data_type: Paperless data type (``string``, ``select``, ...).
|
|
92
|
+
extra_data: Type specific data.
|
|
93
|
+
"""
|
|
94
|
+
|
|
95
|
+
id: int
|
|
96
|
+
name: str
|
|
97
|
+
data_type: str = ""
|
|
98
|
+
extra_data: CustomFieldExtra | None = None
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class CustomFieldInstance(_Response):
|
|
102
|
+
"""Value of one custom field on a document.
|
|
103
|
+
|
|
104
|
+
Attributes:
|
|
105
|
+
field: Field id.
|
|
106
|
+
value: Field value; select fields carry the option id.
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
field: int
|
|
110
|
+
value: CustomFieldValue = None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class PermissionSet(BaseModel):
|
|
114
|
+
"""Users and groups of one permission.
|
|
115
|
+
|
|
116
|
+
Attributes:
|
|
117
|
+
users: User ids.
|
|
118
|
+
groups: Group ids.
|
|
119
|
+
"""
|
|
120
|
+
|
|
121
|
+
users: list[int] = Field(default_factory=list)
|
|
122
|
+
groups: list[int] = Field(default_factory=list)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
class Permissions(BaseModel):
|
|
126
|
+
"""``view`` and ``change`` permissions of a document.
|
|
127
|
+
|
|
128
|
+
Attributes:
|
|
129
|
+
view: View permission.
|
|
130
|
+
change: Change permission.
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
view: PermissionSet = Field(default_factory=PermissionSet)
|
|
134
|
+
change: PermissionSet = Field(default_factory=PermissionSet)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class DocumentObject(_Response):
|
|
138
|
+
"""Document as requested with ``full_perms`` and the field list of the hook.
|
|
139
|
+
|
|
140
|
+
Attributes:
|
|
141
|
+
id: Document id.
|
|
142
|
+
title: Title.
|
|
143
|
+
tags: Tag ids.
|
|
144
|
+
owner: Owner user id.
|
|
145
|
+
custom_fields: Custom field values.
|
|
146
|
+
permissions: Permissions (only with ``full_perms``).
|
|
147
|
+
added: Time the document was added.
|
|
148
|
+
modified: Last modification.
|
|
149
|
+
original_file_name: Original file name.
|
|
150
|
+
correspondent: Correspondent id.
|
|
151
|
+
"""
|
|
152
|
+
|
|
153
|
+
id: int
|
|
154
|
+
title: str | None = None
|
|
155
|
+
tags: list[int] = Field(default_factory=list)
|
|
156
|
+
owner: int | None = None
|
|
157
|
+
custom_fields: list[CustomFieldInstance] = Field(default_factory=list)
|
|
158
|
+
permissions: Permissions | None = None
|
|
159
|
+
added: datetime | None = None
|
|
160
|
+
modified: datetime | None = None
|
|
161
|
+
original_file_name: str | None = None
|
|
162
|
+
correspondent: int | None = None
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
class DocumentId(_Response):
|
|
166
|
+
"""Document reduced to its id.
|
|
167
|
+
|
|
168
|
+
Attributes:
|
|
169
|
+
id: Document id.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
id: int
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class DuplicateRef(_Response):
|
|
176
|
+
"""Duplicate reported by a consume task.
|
|
177
|
+
|
|
178
|
+
Attributes:
|
|
179
|
+
id: Id of the existing document.
|
|
180
|
+
title: Its title.
|
|
181
|
+
"""
|
|
182
|
+
|
|
183
|
+
id: int
|
|
184
|
+
title: str | None = None
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
class TaskObject(_Response):
|
|
188
|
+
"""Consume task in API version 9.
|
|
189
|
+
|
|
190
|
+
Attributes:
|
|
191
|
+
task_id: Celery task id.
|
|
192
|
+
status: ``PENDING``, ``STARTED``, ``SUCCESS``, ``FAILURE`` or ``REVOKED``.
|
|
193
|
+
result: Human readable result.
|
|
194
|
+
related_document: New document id, or the duplicate's id.
|
|
195
|
+
duplicate_documents: Existing documents with the same content.
|
|
196
|
+
"""
|
|
197
|
+
|
|
198
|
+
task_id: str
|
|
199
|
+
status: str
|
|
200
|
+
result: str | None = None
|
|
201
|
+
related_document: int | None = None
|
|
202
|
+
duplicate_documents: list[DuplicateRef] = Field(default_factory=list)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class BulkEditResult(_Response):
|
|
206
|
+
"""Answer of ``bulk_edit``.
|
|
207
|
+
|
|
208
|
+
Attributes:
|
|
209
|
+
result: ``OK`` on success.
|
|
210
|
+
"""
|
|
211
|
+
|
|
212
|
+
result: str | None = None
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
class ModifyCustomFields(BaseModel):
|
|
216
|
+
"""Parameters of ``modify_custom_fields``.
|
|
217
|
+
|
|
218
|
+
Attributes:
|
|
219
|
+
add_custom_fields: Field id (as string) -> value.
|
|
220
|
+
remove_custom_fields: Field ids to remove.
|
|
221
|
+
"""
|
|
222
|
+
|
|
223
|
+
add_custom_fields: dict[str, str]
|
|
224
|
+
remove_custom_fields: list[int] = Field(default_factory=list)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
class ModifyTags(BaseModel):
|
|
228
|
+
"""Parameters of ``modify_tags``.
|
|
229
|
+
|
|
230
|
+
Attributes:
|
|
231
|
+
add_tags: Tag ids to add.
|
|
232
|
+
remove_tags: Tag ids to remove.
|
|
233
|
+
"""
|
|
234
|
+
|
|
235
|
+
add_tags: list[int]
|
|
236
|
+
remove_tags: list[int]
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
class BulkEdit(BaseModel):
|
|
240
|
+
"""Body of ``documents/bulk_edit/``.
|
|
241
|
+
|
|
242
|
+
Attributes:
|
|
243
|
+
documents: Document ids.
|
|
244
|
+
method: Bulk edit method.
|
|
245
|
+
parameters: Method parameters.
|
|
246
|
+
"""
|
|
247
|
+
|
|
248
|
+
documents: list[int]
|
|
249
|
+
method: Literal["modify_custom_fields", "modify_tags"]
|
|
250
|
+
parameters: ModifyCustomFields | ModifyTags
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
class DocumentPatch(BaseModel):
|
|
254
|
+
"""Body of ``PATCH documents/<id>/``; unset fields are not sent.
|
|
255
|
+
|
|
256
|
+
Attributes:
|
|
257
|
+
owner: New owner id.
|
|
258
|
+
set_permissions: Complete permissions.
|
|
259
|
+
"""
|
|
260
|
+
|
|
261
|
+
owner: int | None = None
|
|
262
|
+
set_permissions: Permissions | None = None
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _decode(content: bytes) -> JSON:
|
|
266
|
+
"""Decode a JSON answer.
|
|
267
|
+
|
|
268
|
+
Args:
|
|
269
|
+
content: Response body.
|
|
270
|
+
|
|
271
|
+
Returns:
|
|
272
|
+
The decoded value.
|
|
273
|
+
"""
|
|
274
|
+
value: JSON = json.loads(content)
|
|
275
|
+
return value
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _page(raw: JSON, path: str) -> tuple[list[JSON], str | None]:
|
|
279
|
+
"""Split one page of a paginated list.
|
|
280
|
+
|
|
281
|
+
Args:
|
|
282
|
+
raw: Decoded answer.
|
|
283
|
+
path: Requested path, for the error message.
|
|
284
|
+
|
|
285
|
+
Returns:
|
|
286
|
+
The raw entries and the URL of the next page.
|
|
287
|
+
|
|
288
|
+
Raises:
|
|
289
|
+
PaperlessError: The answer is not a page.
|
|
290
|
+
"""
|
|
291
|
+
if not isinstance(raw, dict) or not isinstance(raw.get("results"), list):
|
|
292
|
+
raise PaperlessError(f"GET {path}: no paginated answer")
|
|
293
|
+
results = raw["results"]
|
|
294
|
+
nxt = raw.get("next")
|
|
295
|
+
return (results if isinstance(results, list) else []), (nxt if isinstance(nxt, str) else None)
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
class Api:
|
|
299
|
+
"""Minimal Paperless REST client.
|
|
300
|
+
|
|
301
|
+
Args:
|
|
302
|
+
base: Base URL without ``/api``.
|
|
303
|
+
token: API token.
|
|
304
|
+
version: API version sent in the ``Accept`` header.
|
|
305
|
+
timeout: Socket timeout per request in seconds.
|
|
306
|
+
"""
|
|
307
|
+
|
|
308
|
+
def __init__(self, base: str, token: str, version: int = API_VERSION, timeout: int = 60) -> None:
|
|
309
|
+
self.base = base.rstrip("/")
|
|
310
|
+
self.token = token
|
|
311
|
+
self.version = version
|
|
312
|
+
self.timeout = timeout
|
|
313
|
+
|
|
314
|
+
def req(
|
|
315
|
+
self,
|
|
316
|
+
method: str,
|
|
317
|
+
path: str,
|
|
318
|
+
params: Params | None = None,
|
|
319
|
+
body: BaseModel | None = None,
|
|
320
|
+
*,
|
|
321
|
+
raw: bytes | None = None,
|
|
322
|
+
content_type: str | None = None,
|
|
323
|
+
) -> JSON:
|
|
324
|
+
"""Send one request; GET is retried up to three times on network errors and 5xx.
|
|
325
|
+
|
|
326
|
+
Args:
|
|
327
|
+
method: HTTP method.
|
|
328
|
+
path: Path below ``/api/``.
|
|
329
|
+
params: Query parameters.
|
|
330
|
+
body: JSON body; ``None`` fields are left out.
|
|
331
|
+
raw: Raw body, used when ``body`` is ``None``.
|
|
332
|
+
content_type: Content type of ``raw``.
|
|
333
|
+
|
|
334
|
+
Returns:
|
|
335
|
+
The decoded JSON answer, ``None`` for an empty answer.
|
|
336
|
+
|
|
337
|
+
Raises:
|
|
338
|
+
PaperlessError: HTTP error or network failure.
|
|
339
|
+
"""
|
|
340
|
+
url = f"{self.base}/api/{path.lstrip('/')}"
|
|
341
|
+
if params:
|
|
342
|
+
url += "?" + urllib.parse.urlencode(params, doseq=True)
|
|
343
|
+
data = body.model_dump_json(exclude_none=True).encode() if body is not None else raw
|
|
344
|
+
headers = {"Authorization": f"Token {self.token}", "Accept": f"application/json; version={self.version}"}
|
|
345
|
+
if data is not None:
|
|
346
|
+
headers["Content-Type"] = content_type or "application/json"
|
|
347
|
+
last: PaperlessError | None = None
|
|
348
|
+
for attempt in range(3 if method == "GET" else 1):
|
|
349
|
+
try:
|
|
350
|
+
r = urllib.request.Request(url, data=data, method=method, headers=headers)
|
|
351
|
+
resp: http.client.HTTPResponse
|
|
352
|
+
with urllib.request.urlopen(r, timeout=self.timeout) as resp:
|
|
353
|
+
content = resp.read()
|
|
354
|
+
return _decode(content) if content else None
|
|
355
|
+
except urllib.error.HTTPError as e:
|
|
356
|
+
msg = e.read()[:300].decode("utf-8", "replace")
|
|
357
|
+
last = PaperlessError(f"{method} {path}: HTTP {e.code} {msg}")
|
|
358
|
+
if e.code < 500:
|
|
359
|
+
break
|
|
360
|
+
except (urllib.error.URLError, TimeoutError, OSError) as e:
|
|
361
|
+
last = PaperlessError(f"{method} {path}: {e}")
|
|
362
|
+
time.sleep(1 + attempt)
|
|
363
|
+
if last is None:
|
|
364
|
+
raise PaperlessError(f"{method} {path}: no attempt made")
|
|
365
|
+
raise last
|
|
366
|
+
|
|
367
|
+
def get[M: BaseModel](self, path: str, model: type[M], params: Params | None = None) -> M:
|
|
368
|
+
"""GET one object.
|
|
369
|
+
|
|
370
|
+
Args:
|
|
371
|
+
path: Path below ``/api/``.
|
|
372
|
+
model: Response model.
|
|
373
|
+
params: Query parameters.
|
|
374
|
+
|
|
375
|
+
Returns:
|
|
376
|
+
The validated object.
|
|
377
|
+
"""
|
|
378
|
+
return model.model_validate(self.req("GET", path, params))
|
|
379
|
+
|
|
380
|
+
def get_all[M: BaseModel](self, path: str, model: type[M], params: Params | None = None) -> Iterator[M]:
|
|
381
|
+
"""Iterate over all pages of a list endpoint.
|
|
382
|
+
|
|
383
|
+
Args:
|
|
384
|
+
path: Path below ``/api/``.
|
|
385
|
+
model: Model of one entry.
|
|
386
|
+
params: Query parameters, ``page``/``page_size`` are added.
|
|
387
|
+
|
|
388
|
+
Yields:
|
|
389
|
+
Validated entries.
|
|
390
|
+
"""
|
|
391
|
+
page = 1
|
|
392
|
+
while True:
|
|
393
|
+
raw = self.req("GET", path, {"page_size": 100, "page": page, **(params or {})})
|
|
394
|
+
results, nxt = _page(raw, path)
|
|
395
|
+
yield from (model.model_validate(r) for r in results)
|
|
396
|
+
if not nxt:
|
|
397
|
+
return
|
|
398
|
+
page += 1
|
|
399
|
+
|
|
400
|
+
def get_list[M: BaseModel](self, path: str, model: type[M], params: Params | None = None) -> list[M]:
|
|
401
|
+
"""GET an endpoint that answers either a plain list or one page.
|
|
402
|
+
|
|
403
|
+
Args:
|
|
404
|
+
path: Path below ``/api/``.
|
|
405
|
+
model: Model of one entry.
|
|
406
|
+
params: Query parameters.
|
|
407
|
+
|
|
408
|
+
Returns:
|
|
409
|
+
Validated entries of the first page.
|
|
410
|
+
"""
|
|
411
|
+
raw = self.req("GET", path, params)
|
|
412
|
+
results = raw if isinstance(raw, list) else _page(raw, path)[0]
|
|
413
|
+
return [model.model_validate(r) for r in results]
|
|
414
|
+
|
|
415
|
+
def bulk_edit(self, body: BulkEdit) -> BulkEditResult:
|
|
416
|
+
"""Run one ``bulk_edit`` operation.
|
|
417
|
+
|
|
418
|
+
Args:
|
|
419
|
+
body: Operation.
|
|
420
|
+
|
|
421
|
+
Returns:
|
|
422
|
+
The answer, ``result == "OK"`` on success.
|
|
423
|
+
|
|
424
|
+
Raises:
|
|
425
|
+
PaperlessError: Request failed or the answer is not ``OK``.
|
|
426
|
+
"""
|
|
427
|
+
answer = self.req("POST", "documents/bulk_edit/", body=body)
|
|
428
|
+
r = BulkEditResult.model_validate(answer) if isinstance(answer, dict) else BulkEditResult()
|
|
429
|
+
if r.result not in ("OK", None):
|
|
430
|
+
raise PaperlessError(f"bulk_edit {body.method} {body.documents}: {r.result}")
|
|
431
|
+
return r
|
|
432
|
+
|
|
433
|
+
def post_document(self, filename: str, payload: bytes, form: list[tuple[str, str]]) -> str:
|
|
434
|
+
"""Upload a file via ``documents/post_document/``.
|
|
435
|
+
|
|
436
|
+
Args:
|
|
437
|
+
filename: File name sent in the multipart part.
|
|
438
|
+
payload: File content.
|
|
439
|
+
form: Additional form fields, e.g. ``("tags", "3")`` or ``("custom_fields", "{...}")``.
|
|
440
|
+
|
|
441
|
+
Returns:
|
|
442
|
+
The id of the consume task.
|
|
443
|
+
|
|
444
|
+
Raises:
|
|
445
|
+
PaperlessError: Upload failed or no task id returned.
|
|
446
|
+
"""
|
|
447
|
+
boundary = f"----paperless-hook-{uuid.uuid4().hex}"
|
|
448
|
+
quoted = filename.replace("\\", "_").replace('"', "_").replace("\r", "").replace("\n", "")
|
|
449
|
+
parts: list[bytes] = [
|
|
450
|
+
f'--{boundary}\r\nContent-Disposition: form-data; name="{name}"\r\n\r\n{value}\r\n'.encode()
|
|
451
|
+
for name, value in form
|
|
452
|
+
]
|
|
453
|
+
parts.append(
|
|
454
|
+
f'--{boundary}\r\nContent-Disposition: form-data; name="document"; filename="{quoted}"\r\n'
|
|
455
|
+
"Content-Type: application/octet-stream\r\n\r\n".encode() + payload + b"\r\n"
|
|
456
|
+
)
|
|
457
|
+
parts.append(f"--{boundary}--\r\n".encode())
|
|
458
|
+
r = self.req(
|
|
459
|
+
"POST",
|
|
460
|
+
"documents/post_document/",
|
|
461
|
+
raw=b"".join(parts),
|
|
462
|
+
content_type=f"multipart/form-data; boundary={boundary}",
|
|
463
|
+
)
|
|
464
|
+
if not isinstance(r, str) or not r:
|
|
465
|
+
raise PaperlessError(f"post_document: unexpected answer {r!r}")
|
|
466
|
+
return r
|