modora 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.
- modora/__init__.py +12 -0
- modora/addons/__init__.py +11 -0
- modora/addons/base/__init__.py +6 -0
- modora/addons/base/__manifest__.py +22 -0
- modora/addons/base/controllers/__init__.py +7 -0
- modora/addons/base/controllers/content.py +58 -0
- modora/addons/base/controllers/export.py +51 -0
- modora/addons/base/controllers/main.py +23 -0
- modora/addons/base/controllers/report.py +36 -0
- modora/addons/base/controllers/rest.py +41 -0
- modora/addons/base/controllers/rpc.py +18 -0
- modora/addons/base/controllers/session.py +93 -0
- modora/addons/base/data/base_records.py +44 -0
- modora/addons/base/data/crons.py +22 -0
- modora/addons/base/data/menus.py +44 -0
- modora/addons/base/data/sys.lang.csv +52 -0
- modora/addons/base/data/sys_config.py +19 -0
- modora/addons/base/demo/users.py +18 -0
- modora/addons/base/models/__init__.py +75 -0
- modora/addons/base/models/auth.py +317 -0
- modora/addons/base/models/org_company.py +71 -0
- modora/addons/base/models/sys_access.py +251 -0
- modora/addons/base/models/sys_attachment.py +124 -0
- modora/addons/base/models/sys_bus.py +132 -0
- modora/addons/base/models/sys_config.py +58 -0
- modora/addons/base/models/sys_cron.py +177 -0
- modora/addons/base/models/sys_external_id.py +24 -0
- modora/addons/base/models/sys_import.py +107 -0
- modora/addons/base/models/sys_job.py +250 -0
- modora/addons/base/models/sys_lang.py +75 -0
- modora/addons/base/models/sys_model.py +72 -0
- modora/addons/base/models/sys_module.py +101 -0
- modora/addons/base/models/sys_sequence.py +158 -0
- modora/addons/base/models/sys_session.py +172 -0
- modora/addons/base/models/sys_ui.py +198 -0
- modora/addons/base/models/sys_view.py +138 -0
- modora/addons/base/security/groups.py +29 -0
- modora/addons/base/security/sys.access.csv +38 -0
- modora/addons/base/static/icons/settings.svg +7 -0
- modora/addons/contact/__init__.py +6 -0
- modora/addons/contact/__manifest__.py +17 -0
- modora/addons/contact/data/menus.py +16 -0
- modora/addons/contact/demo/contacts.py +32 -0
- modora/addons/contact/models/__init__.py +4 -0
- modora/addons/contact/models/contact.py +207 -0
- modora/addons/contact/security/sys.access.csv +4 -0
- modora/addons/contact/static/icons/app.svg +7 -0
- modora/addons/locale/__init__.py +23 -0
- modora/addons/locale/__manifest__.py +19 -0
- modora/addons/locale/data/countries.py +47 -0
- modora/addons/locale/data/currencies.py +26 -0
- modora/addons/locale/data/defaults.py +11 -0
- modora/addons/locale/data/menus.py +15 -0
- modora/addons/locale/models/__init__.py +6 -0
- modora/addons/locale/models/country.py +72 -0
- modora/addons/locale/models/currency.py +209 -0
- modora/addons/locale/models/org_company.py +29 -0
- modora/addons/locale/security/sys.access.csv +9 -0
- modora/addons/mail/__init__.py +7 -0
- modora/addons/mail/__manifest__.py +13 -0
- modora/addons/mail/data/menus.py +16 -0
- modora/addons/mail/models/__init__.py +18 -0
- modora/addons/mail/models/activity.py +101 -0
- modora/addons/mail/models/bus.py +36 -0
- modora/addons/mail/models/follower.py +21 -0
- modora/addons/mail/models/message.py +201 -0
- modora/addons/mail/models/template.py +230 -0
- modora/addons/mail/models/thread.py +283 -0
- modora/addons/mail/security/sys.access.csv +8 -0
- modora/addons/mail/transport.py +77 -0
- modora/addons/web/__init__.py +6 -0
- modora/addons/web/__manifest__.py +12 -0
- modora/addons/web/controllers/__init__.py +4 -0
- modora/addons/web/controllers/main.py +157 -0
- modora/addons/web/static/dist/THIRD-PARTY-LICENSES.txt +1356 -0
- modora/addons/web/static/dist/assets/index-0i4GsfAI.css +1 -0
- modora/addons/web/static/dist/assets/index-0i4GsfAI.css.br +0 -0
- modora/addons/web/static/dist/assets/index-0i4GsfAI.css.gz +0 -0
- modora/addons/web/static/dist/assets/index-Bk_B461G.js +1 -0
- modora/addons/web/static/dist/assets/index-CdE-3s5j.js +53 -0
- modora/addons/web/static/dist/assets/index-CdE-3s5j.js.br +0 -0
- modora/addons/web/static/dist/assets/index-CdE-3s5j.js.gz +0 -0
- modora/addons/web/static/dist/assets/index-D0nCnqYz.js +1 -0
- modora/addons/web/static/dist/assets/index-D0nCnqYz.js.br +0 -0
- modora/addons/web/static/dist/assets/index-D0nCnqYz.js.gz +0 -0
- modora/addons/web/static/dist/assets/index-cgBTXj4B.js +1 -0
- modora/addons/web/static/dist/assets/index-cgBTXj4B.js.br +0 -0
- modora/addons/web/static/dist/assets/index-cgBTXj4B.js.gz +0 -0
- modora/addons/web/static/dist/assets/jsx-runtime-u17CrQMm.js +1 -0
- modora/addons/web/static/dist/assets/sdk-DCh0ASeY.js +1 -0
- modora/addons/web/static/dist/assets/sdk-DCh0ASeY.js.br +0 -0
- modora/addons/web/static/dist/assets/sdk-DCh0ASeY.js.gz +0 -0
- modora/addons/web/static/dist/index.html +30 -0
- modora/addons/web/static/dist/modora-web.js +1 -0
- modora/addons/web/static/dist/react-dom.js +1 -0
- modora/addons/web/static/dist/react-jsx-runtime.js +1 -0
- modora/addons/web/static/dist/react.js +1 -0
- modora/addons/web/static/dist/react.js.br +0 -0
- modora/addons/web/static/dist/react.js.gz +0 -0
- modora/bus.py +195 -0
- modora/cli/__init__.py +6 -0
- modora/cli/main.py +809 -0
- modora/cli/shell.py +65 -0
- modora/cli/webclient.py +208 -0
- modora/config.py +206 -0
- modora/data.py +152 -0
- modora/db/__init__.py +7 -0
- modora/db/cursor.py +338 -0
- modora/db/errors.py +149 -0
- modora/db/functions.py +233 -0
- modora/db/listen.py +120 -0
- modora/db/manage.py +221 -0
- modora/exceptions.py +30 -0
- modora/http/__init__.py +43 -0
- modora/http/content.py +220 -0
- modora/http/errors.py +132 -0
- modora/http/request.py +256 -0
- modora/http/responses.py +57 -0
- modora/http/rest.py +377 -0
- modora/http/routing.py +310 -0
- modora/http/rpc.py +106 -0
- modora/http/serve.py +55 -0
- modora/http/server.py +601 -0
- modora/http/websocket.py +169 -0
- modora/jobs.py +400 -0
- modora/modules/__init__.py +45 -0
- modora/modules/archive.py +218 -0
- modora/modules/data_loader.py +384 -0
- modora/modules/discovery.py +277 -0
- modora/modules/loader.py +593 -0
- modora/modules/manifest.py +200 -0
- modora/modules/migrations.py +69 -0
- modora/modules/registries.py +98 -0
- modora/orm/__init__.py +9 -0
- modora/orm/api.py +95 -0
- modora/orm/client.py +391 -0
- modora/orm/commands.py +87 -0
- modora/orm/data_exchange.py +400 -0
- modora/orm/domains.py +617 -0
- modora/orm/environment.py +285 -0
- modora/orm/fields.py +1122 -0
- modora/orm/json_read.py +234 -0
- modora/orm/models.py +1861 -0
- modora/orm/registry.py +555 -0
- modora/orm/schema.py +482 -0
- modora/py.typed +0 -0
- modora/report.py +792 -0
- modora/tests/__init__.py +102 -0
- modora/tests/case.py +137 -0
- modora/tests/fixtures.py +323 -0
- modora/tests/runner.py +135 -0
- modora/tests/smtp.py +139 -0
- modora/tools/__init__.py +6 -0
- modora/tools/_py_speedups.py +48 -0
- modora/tools/expr.py +66 -0
- modora/tools/filestore.py +135 -0
- modora/tools/formatting.py +141 -0
- modora/tools/html.py +131 -0
- modora/tools/i18n.py +373 -0
- modora/tools/json.py +119 -0
- modora/tools/passwords.py +49 -0
- modora/tools/speedups.py +47 -0
- modora/tools/sql.py +32 -0
- modora/tools/tabular.py +140 -0
- modora/ui.py +329 -0
- modora/views/__init__.py +18 -0
- modora/views/definitions.py +234 -0
- modora/views/expressions.py +344 -0
- modora/views/inheritance.py +242 -0
- modora/views/validation.py +274 -0
- modora-0.1.0.dist-info/METADATA +152 -0
- modora-0.1.0.dist-info/RECORD +176 -0
- modora-0.1.0.dist-info/WHEEL +4 -0
- modora-0.1.0.dist-info/entry_points.txt +9 -0
- modora-0.1.0.dist-info/licenses/LICENSE +201 -0
- modora-0.1.0.dist-info/licenses/NOTICE +16 -0
modora/tests/smtp.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""A minimal SMTP server that keeps what it receives, for tests of outgoing email::
|
|
3
|
+
|
|
4
|
+
with SmtpSink() as sink:
|
|
5
|
+
env["sys.config"].set_param("mail.smtp_host", sink.host)
|
|
6
|
+
env["sys.config"].set_param("mail.smtp_port", str(sink.port))
|
|
7
|
+
...send...
|
|
8
|
+
assert sink.messages[0]["Subject"] == "Order SO00001"
|
|
9
|
+
|
|
10
|
+
It speaks enough SMTP for :mod:`smtplib` (``EHLO``/``HELO``, ``MAIL``, ``RCPT``, ``DATA``,
|
|
11
|
+
``RSET``, ``NOOP``, ``QUIT``), without authentication or TLS.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import email
|
|
17
|
+
import email.policy
|
|
18
|
+
import socketserver
|
|
19
|
+
import threading
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from email.message import EmailMessage
|
|
22
|
+
from typing import Any, Self
|
|
23
|
+
|
|
24
|
+
__all__ = ["Received", "SmtpSink"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class Received:
|
|
29
|
+
"""One email: the envelope and the parsed message."""
|
|
30
|
+
|
|
31
|
+
sender: str
|
|
32
|
+
recipients: list[str]
|
|
33
|
+
message: EmailMessage
|
|
34
|
+
raw: bytes = field(repr=False, default=b"")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _Handler(socketserver.StreamRequestHandler):
|
|
38
|
+
server: _Server
|
|
39
|
+
|
|
40
|
+
def reply(self, line: str) -> None:
|
|
41
|
+
self.wfile.write(line.encode() + b"\r\n")
|
|
42
|
+
|
|
43
|
+
def handle(self) -> None:
|
|
44
|
+
self.reply("220 modora-test-smtp ready")
|
|
45
|
+
sender, recipients = "", []
|
|
46
|
+
while True:
|
|
47
|
+
raw = self.rfile.readline()
|
|
48
|
+
if not raw:
|
|
49
|
+
return
|
|
50
|
+
line = raw.decode("utf-8", "replace").rstrip("\r\n")
|
|
51
|
+
verb = line[:4].upper()
|
|
52
|
+
if verb in ("EHLO", "HELO"):
|
|
53
|
+
self.reply("250-modora-test-smtp" if verb == "EHLO" else "250 ok")
|
|
54
|
+
if verb == "EHLO":
|
|
55
|
+
self.reply("250-8BITMIME")
|
|
56
|
+
self.reply("250 SMTPUTF8")
|
|
57
|
+
elif verb == "MAIL":
|
|
58
|
+
sender, recipients = line.split(":", 1)[1].split()[0].strip("<>"), []
|
|
59
|
+
self.reply("250 ok")
|
|
60
|
+
elif verb == "RCPT":
|
|
61
|
+
recipients.append(line.split(":", 1)[1].split()[0].strip("<>"))
|
|
62
|
+
self.reply("250 ok")
|
|
63
|
+
elif verb == "DATA":
|
|
64
|
+
self.reply("354 end with <CRLF>.<CRLF>")
|
|
65
|
+
lines = []
|
|
66
|
+
while True:
|
|
67
|
+
chunk = self.rfile.readline()
|
|
68
|
+
if chunk in (b".\r\n", b".\n", b""):
|
|
69
|
+
break
|
|
70
|
+
lines.append(chunk[1:] if chunk.startswith(b"..") else chunk)
|
|
71
|
+
data = b"".join(lines)
|
|
72
|
+
parsed = email.message_from_bytes(data, policy=email.policy.default)
|
|
73
|
+
self.server.sink._add(Received(sender, recipients, parsed, data)) # type: ignore[arg-type]
|
|
74
|
+
self.reply("250 queued")
|
|
75
|
+
elif verb == "RSET":
|
|
76
|
+
sender, recipients = "", []
|
|
77
|
+
self.reply("250 ok")
|
|
78
|
+
elif verb == "NOOP":
|
|
79
|
+
self.reply("250 ok")
|
|
80
|
+
elif verb == "QUIT":
|
|
81
|
+
self.reply("221 bye")
|
|
82
|
+
return
|
|
83
|
+
else:
|
|
84
|
+
self.reply("502 not implemented")
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class _Server(socketserver.ThreadingTCPServer):
|
|
88
|
+
daemon_threads = True
|
|
89
|
+
allow_reuse_address = True
|
|
90
|
+
sink: SmtpSink
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class SmtpSink:
|
|
94
|
+
"""An SMTP server on ``127.0.0.1`` (a free port) collecting emails in :attr:`received`."""
|
|
95
|
+
|
|
96
|
+
def __init__(self) -> None:
|
|
97
|
+
self._server = _Server(("127.0.0.1", 0), _Handler)
|
|
98
|
+
self._server.sink = self
|
|
99
|
+
self.host, self.port = self._server.server_address[:2]
|
|
100
|
+
self.received: list[Received] = []
|
|
101
|
+
self._lock = threading.Lock()
|
|
102
|
+
self._arrived = threading.Condition(self._lock)
|
|
103
|
+
self._thread = threading.Thread(target=self._server.serve_forever, daemon=True)
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def messages(self) -> list[EmailMessage]:
|
|
107
|
+
with self._lock:
|
|
108
|
+
return [item.message for item in self.received]
|
|
109
|
+
|
|
110
|
+
def _add(self, item: Received) -> None:
|
|
111
|
+
with self._arrived:
|
|
112
|
+
self.received.append(item)
|
|
113
|
+
self._arrived.notify_all()
|
|
114
|
+
|
|
115
|
+
def wait(self, count: int = 1, timeout: float = 10) -> bool:
|
|
116
|
+
"""Wait until ``count`` emails arrived."""
|
|
117
|
+
with self._arrived:
|
|
118
|
+
return self._arrived.wait_for(lambda: len(self.received) >= count, timeout)
|
|
119
|
+
|
|
120
|
+
def configure(self, env: Any) -> None:
|
|
121
|
+
"""Point the ``mail`` transport of ``env``'s database at this server."""
|
|
122
|
+
config = env["sys.config"].sudo()
|
|
123
|
+
config.set_param("mail.transport", "smtp")
|
|
124
|
+
config.set_param("mail.smtp_host", str(self.host))
|
|
125
|
+
config.set_param("mail.smtp_port", str(self.port))
|
|
126
|
+
|
|
127
|
+
def start(self) -> Self:
|
|
128
|
+
self._thread.start()
|
|
129
|
+
return self
|
|
130
|
+
|
|
131
|
+
def stop(self) -> None:
|
|
132
|
+
self._server.shutdown()
|
|
133
|
+
self._server.server_close()
|
|
134
|
+
|
|
135
|
+
def __enter__(self) -> Self:
|
|
136
|
+
return self.start()
|
|
137
|
+
|
|
138
|
+
def __exit__(self, *_: object) -> None:
|
|
139
|
+
self.stop()
|
modora/tools/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Pure-Python implementations of the native speedups (``modora-speedups``).
|
|
3
|
+
|
|
4
|
+
Each function here has a Rust twin in ``packages/modora-speedups``; both pass the same tests
|
|
5
|
+
(``tests/tools/test_speedups.py``). Use them through :mod:`modora.tools.speedups`.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import math
|
|
12
|
+
from collections.abc import Iterable, Sequence
|
|
13
|
+
from datetime import date
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from modora.tools import json as fast_json
|
|
17
|
+
|
|
18
|
+
__all__ = ["encode_rows"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def encode_rows(columns: Sequence[str], rows: Iterable[Sequence[Any]]) -> bytes:
|
|
22
|
+
"""Rows (values in ``columns`` order) as a JSON array of objects."""
|
|
23
|
+
names = list(columns)
|
|
24
|
+
objects = []
|
|
25
|
+
for index, row in enumerate(rows):
|
|
26
|
+
if len(row) != len(names):
|
|
27
|
+
raise ValueError(f"row {index} has {len(row)} values for {len(names)} columns")
|
|
28
|
+
objects.append(dict(zip(names, row, strict=True)))
|
|
29
|
+
try:
|
|
30
|
+
return fast_json.dumps(objects)
|
|
31
|
+
except TypeError as exc:
|
|
32
|
+
if "64-bit" not in str(exc): # orjson stops at 64-bit integers; json does not
|
|
33
|
+
raise
|
|
34
|
+
return json.dumps(_plain(objects), ensure_ascii=False, separators=(",", ":")).encode()
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _plain(value: Any) -> Any:
|
|
38
|
+
if isinstance(value, float):
|
|
39
|
+
return value if math.isfinite(value) else None
|
|
40
|
+
if isinstance(value, date):
|
|
41
|
+
return value.isoformat()
|
|
42
|
+
if isinstance(value, dict):
|
|
43
|
+
return {key: _plain(item) for key, item in value.items()}
|
|
44
|
+
if isinstance(value, list | tuple):
|
|
45
|
+
return [_plain(item) for item in value]
|
|
46
|
+
if value is None or isinstance(value, str | int):
|
|
47
|
+
return value
|
|
48
|
+
raise TypeError(f"cannot encode {type(value).__name__} as JSON")
|
modora/tools/expr.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Safe evaluation of literal expressions stored as text (record-rule domains).
|
|
3
|
+
|
|
4
|
+
Only literals (numbers, strings, booleans, ``None``), lists, tuples, dicts, unary minus and
|
|
5
|
+
``not``, names from an explicit mapping, and attribute access on those names (never names
|
|
6
|
+
starting with ``_``) are allowed. The expression is parsed with :mod:`ast` and interpreted
|
|
7
|
+
node by node; nothing is ever passed to ``eval``.
|
|
8
|
+
|
|
9
|
+
>>> safe_eval("[('create_uid', '=', user.id)]", {"user": user})
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import ast
|
|
15
|
+
from collections.abc import Mapping
|
|
16
|
+
from functools import lru_cache
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
__all__ = ["ExpressionError", "safe_eval"]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ExpressionError(ValueError):
|
|
23
|
+
"""The expression uses something that is not allowed."""
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@lru_cache(maxsize=512)
|
|
27
|
+
def _parse(source: str) -> ast.expr:
|
|
28
|
+
try:
|
|
29
|
+
return ast.parse(source.strip(), mode="eval").body
|
|
30
|
+
except SyntaxError as exc:
|
|
31
|
+
raise ExpressionError(f"invalid expression {source!r}: {exc.msg}") from None
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def safe_eval(source: str, names: Mapping[str, Any] | None = None) -> Any:
|
|
35
|
+
"""Evaluate ``source`` with ``names`` available as variables."""
|
|
36
|
+
return _eval(_parse(source), names or {})
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _eval(node: ast.expr, names: Mapping[str, Any]) -> Any:
|
|
40
|
+
match node:
|
|
41
|
+
case ast.Constant(value=value):
|
|
42
|
+
return value
|
|
43
|
+
case ast.List(elts=items):
|
|
44
|
+
return [_eval(item, names) for item in items]
|
|
45
|
+
case ast.Tuple(elts=items):
|
|
46
|
+
return tuple(_eval(item, names) for item in items)
|
|
47
|
+
case ast.Dict(keys=keys, values=values):
|
|
48
|
+
if any(key is None for key in keys):
|
|
49
|
+
raise ExpressionError("dict unpacking is not allowed")
|
|
50
|
+
return {_eval(k, names): _eval(v, names) for k, v in zip(keys, values, strict=True)} # type: ignore[arg-type]
|
|
51
|
+
case ast.UnaryOp(op=ast.USub(), operand=operand):
|
|
52
|
+
return -_eval(operand, names)
|
|
53
|
+
case ast.UnaryOp(op=ast.Not(), operand=operand):
|
|
54
|
+
return not _eval(operand, names)
|
|
55
|
+
case ast.Name(id=name):
|
|
56
|
+
if name in ("True", "False", "None"):
|
|
57
|
+
return {"True": True, "False": False, "None": None}[name]
|
|
58
|
+
if name not in names:
|
|
59
|
+
raise ExpressionError(f"unknown name {name!r}")
|
|
60
|
+
return names[name]
|
|
61
|
+
case ast.Attribute(value=value, attr=attr):
|
|
62
|
+
if attr.startswith("_"):
|
|
63
|
+
raise ExpressionError(f"private attribute {attr!r} is not allowed")
|
|
64
|
+
return getattr(_eval(value, names), attr)
|
|
65
|
+
case _:
|
|
66
|
+
raise ExpressionError(f"{type(node).__name__} is not allowed in expressions")
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""A content-addressed file store for attachments.
|
|
3
|
+
|
|
4
|
+
Files are named after the SHA-256 of their content, ``<root>/<ab>/<abcdef…>``, so identical
|
|
5
|
+
contents are stored once and writing is idempotent. Files are never deleted when an attachment
|
|
6
|
+
goes away (the transaction might roll back, or another attachment might share the content);
|
|
7
|
+
:meth:`FileStore.collect_garbage` removes the files no attachment refers to, once they are
|
|
8
|
+
older than a grace period that covers transactions still in progress.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import hashlib
|
|
14
|
+
import os
|
|
15
|
+
import re
|
|
16
|
+
import tempfile
|
|
17
|
+
import time
|
|
18
|
+
from collections.abc import Iterable
|
|
19
|
+
from pathlib import Path
|
|
20
|
+
from typing import Any, BinaryIO
|
|
21
|
+
|
|
22
|
+
__all__ = ["FileStore", "checksum", "store_dir"]
|
|
23
|
+
|
|
24
|
+
_RELATIVE = re.compile(r"^[0-9a-f]{2}/[0-9a-f]{64}$")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def store_dir(data_dir: str | os.PathLike[str], database: Any) -> Path:
|
|
28
|
+
"""The file store folder of ``database`` (a :class:`~modora.db.Database`) under
|
|
29
|
+
``data_dir``: ``<data_dir>/filestore/<name>`` (``<name>.<schema>`` for a PostgreSQL schema)."""
|
|
30
|
+
name = database.name if not database.schema else f"{database.name}.{database.schema}"
|
|
31
|
+
return Path(data_dir) / "filestore" / name
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def checksum(content: bytes) -> str:
|
|
35
|
+
"""Hex SHA-256 of ``content``."""
|
|
36
|
+
return hashlib.sha256(content).hexdigest()
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class FileStore:
|
|
40
|
+
"""Files of one database under ``root``."""
|
|
41
|
+
|
|
42
|
+
def __init__(self, root: str | os.PathLike[str]) -> None:
|
|
43
|
+
self.root = Path(root)
|
|
44
|
+
|
|
45
|
+
def __repr__(self) -> str:
|
|
46
|
+
return f"FileStore({str(self.root)!r})"
|
|
47
|
+
|
|
48
|
+
def path(self, relative: str) -> Path:
|
|
49
|
+
"""Absolute path of a stored file (``relative`` as returned by :meth:`write`)."""
|
|
50
|
+
if not _RELATIVE.match(relative):
|
|
51
|
+
raise ValueError(f"invalid file store path: {relative!r}")
|
|
52
|
+
return self.root / relative
|
|
53
|
+
|
|
54
|
+
def write(self, content: bytes) -> str:
|
|
55
|
+
"""Store ``content``; returns its path relative to the root (``ab/abcdef…``)."""
|
|
56
|
+
digest = checksum(content)
|
|
57
|
+
relative = f"{digest[:2]}/{digest}"
|
|
58
|
+
target = self.root / relative
|
|
59
|
+
if target.exists():
|
|
60
|
+
os.utime(target) # restart the garbage-collection grace period
|
|
61
|
+
return relative
|
|
62
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
63
|
+
fd, tmp = tempfile.mkstemp(dir=target.parent, prefix=".tmp-")
|
|
64
|
+
try:
|
|
65
|
+
with os.fdopen(fd, "wb") as handle:
|
|
66
|
+
handle.write(content)
|
|
67
|
+
os.replace(tmp, target)
|
|
68
|
+
except BaseException:
|
|
69
|
+
Path(tmp).unlink(missing_ok=True)
|
|
70
|
+
raise
|
|
71
|
+
return relative
|
|
72
|
+
|
|
73
|
+
def write_stream(self, stream: BinaryIO, chunk_size: int = 1 << 20) -> tuple[str, int, str]:
|
|
74
|
+
"""Store the content of a binary file object without loading it in memory; returns
|
|
75
|
+
``(relative path, size, checksum)``."""
|
|
76
|
+
self.root.mkdir(parents=True, exist_ok=True)
|
|
77
|
+
digest = hashlib.sha256()
|
|
78
|
+
size = 0
|
|
79
|
+
fd, tmp = tempfile.mkstemp(dir=self.root, prefix=".tmp-")
|
|
80
|
+
try:
|
|
81
|
+
with os.fdopen(fd, "wb") as handle:
|
|
82
|
+
while chunk := stream.read(chunk_size):
|
|
83
|
+
digest.update(chunk)
|
|
84
|
+
size += len(chunk)
|
|
85
|
+
handle.write(chunk)
|
|
86
|
+
hexdigest = digest.hexdigest()
|
|
87
|
+
relative = f"{hexdigest[:2]}/{hexdigest}"
|
|
88
|
+
target = self.root / relative
|
|
89
|
+
if target.exists():
|
|
90
|
+
os.utime(target)
|
|
91
|
+
Path(tmp).unlink()
|
|
92
|
+
else:
|
|
93
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
94
|
+
os.replace(tmp, target)
|
|
95
|
+
except BaseException:
|
|
96
|
+
Path(tmp).unlink(missing_ok=True)
|
|
97
|
+
raise
|
|
98
|
+
return relative, size, hexdigest
|
|
99
|
+
|
|
100
|
+
def read(self, relative: str) -> bytes | None:
|
|
101
|
+
"""The content of a stored file, or ``None`` when it is missing."""
|
|
102
|
+
try:
|
|
103
|
+
return self.path(relative).read_bytes()
|
|
104
|
+
except FileNotFoundError:
|
|
105
|
+
return None
|
|
106
|
+
|
|
107
|
+
def files(self) -> Iterable[str]:
|
|
108
|
+
"""Relative paths of every stored file."""
|
|
109
|
+
if not self.root.is_dir():
|
|
110
|
+
return
|
|
111
|
+
for folder in sorted(self.root.iterdir()):
|
|
112
|
+
if not folder.is_dir() or len(folder.name) != 2:
|
|
113
|
+
continue
|
|
114
|
+
for file in sorted(folder.iterdir()):
|
|
115
|
+
relative = f"{folder.name}/{file.name}"
|
|
116
|
+
if _RELATIVE.match(relative):
|
|
117
|
+
yield relative
|
|
118
|
+
|
|
119
|
+
def collect_garbage(self, referenced: Iterable[str], grace_seconds: float = 3600) -> list[str]:
|
|
120
|
+
"""Delete the files not in ``referenced`` and older than ``grace_seconds``; returns
|
|
121
|
+
their relative paths."""
|
|
122
|
+
keep = set(referenced)
|
|
123
|
+
limit = time.time() - grace_seconds
|
|
124
|
+
removed = []
|
|
125
|
+
for relative in list(self.files()):
|
|
126
|
+
if relative in keep:
|
|
127
|
+
continue
|
|
128
|
+
path = self.root / relative
|
|
129
|
+
try:
|
|
130
|
+
if path.stat().st_mtime < limit:
|
|
131
|
+
path.unlink()
|
|
132
|
+
removed.append(relative)
|
|
133
|
+
except FileNotFoundError:
|
|
134
|
+
continue
|
|
135
|
+
return removed
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""Formatting values for people: numbers, amounts, dates and field values, per language.
|
|
3
|
+
|
|
4
|
+
Used by reports (:mod:`modora.report`) and mail templates. Languages are ``sys.lang`` codes
|
|
5
|
+
(``en_US``, ``fr_FR``); formats come from Unicode CLDR through Babel.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from datetime import date, datetime
|
|
11
|
+
from functools import lru_cache
|
|
12
|
+
from typing import TYPE_CHECKING, Any
|
|
13
|
+
from zoneinfo import ZoneInfo
|
|
14
|
+
|
|
15
|
+
from babel import Locale, UnknownLocaleError
|
|
16
|
+
from babel import dates as babel_dates
|
|
17
|
+
from babel import numbers as babel_numbers
|
|
18
|
+
|
|
19
|
+
if TYPE_CHECKING:
|
|
20
|
+
from modora.orm.models import BaseModel
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"format_amount",
|
|
24
|
+
"format_date",
|
|
25
|
+
"format_datetime",
|
|
26
|
+
"format_field",
|
|
27
|
+
"format_number",
|
|
28
|
+
"locale_of",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@lru_cache(maxsize=64)
|
|
33
|
+
def locale_of(lang: str | None) -> Locale:
|
|
34
|
+
"""The Babel locale of a language code (``en_US`` when unknown)."""
|
|
35
|
+
try:
|
|
36
|
+
return Locale.parse(lang or "en_US")
|
|
37
|
+
except (UnknownLocaleError, ValueError):
|
|
38
|
+
return Locale.parse("en_US")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def format_number(
|
|
42
|
+
value: float | int | None, digits: int | None = None, lang: str | None = None
|
|
43
|
+
) -> str:
|
|
44
|
+
"""``1234.5`` → ``1,234.50`` (with ``digits=2``), grouped as the language does."""
|
|
45
|
+
if value is None or value is False:
|
|
46
|
+
return ""
|
|
47
|
+
if digits is None:
|
|
48
|
+
if isinstance(value, int):
|
|
49
|
+
return babel_numbers.format_decimal(value, locale=locale_of(lang))
|
|
50
|
+
return babel_numbers.format_decimal(value, format="#,##0.###", locale=locale_of(lang))
|
|
51
|
+
pattern = "#,##0" + ("." + "0" * digits if digits > 0 else "")
|
|
52
|
+
return babel_numbers.format_decimal(value, format=pattern, locale=locale_of(lang))
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def format_amount(value: float | int | None, currency: Any = None, lang: str | None = None) -> str:
|
|
56
|
+
"""An amount with its currency: ``format_amount(7.5, usd)`` → ``$7.50``.
|
|
57
|
+
|
|
58
|
+
``currency`` is a ``locale.currency`` record, an ISO code or ``None`` (a plain number with
|
|
59
|
+
two decimals).
|
|
60
|
+
"""
|
|
61
|
+
if value is None or value is False:
|
|
62
|
+
return ""
|
|
63
|
+
code = getattr(currency, "name", currency) if currency else None
|
|
64
|
+
digits = getattr(currency, "decimal_places", None) if currency is not None else None
|
|
65
|
+
if not code or not isinstance(code, str):
|
|
66
|
+
return format_number(value, 2 if digits is None else int(digits), lang)
|
|
67
|
+
kwargs: dict[str, Any] = {"locale": locale_of(lang)}
|
|
68
|
+
if isinstance(digits, int):
|
|
69
|
+
kwargs["currency_digits"] = False
|
|
70
|
+
kwargs["format"] = "¤#,##0" + ("." + "0" * digits if digits > 0 else "")
|
|
71
|
+
return babel_numbers.format_currency(value, code, **kwargs)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def format_date(value: date | str | None, lang: str | None = None, format: str = "medium") -> str:
|
|
75
|
+
"""``date(2026, 3, 1)`` → ``Mar 1, 2026`` (``format``: short, medium, long, or a pattern)."""
|
|
76
|
+
if not value:
|
|
77
|
+
return ""
|
|
78
|
+
if isinstance(value, str):
|
|
79
|
+
value = date.fromisoformat(value[:10])
|
|
80
|
+
if isinstance(value, datetime):
|
|
81
|
+
value = value.date()
|
|
82
|
+
return babel_dates.format_date(value, format=format, locale=locale_of(lang))
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def format_datetime(
|
|
86
|
+
value: datetime | str | None,
|
|
87
|
+
lang: str | None = None,
|
|
88
|
+
tz: str | None = None,
|
|
89
|
+
format: str = "medium",
|
|
90
|
+
) -> str:
|
|
91
|
+
"""A naive UTC datetime shown in time zone ``tz`` (default UTC)."""
|
|
92
|
+
if not value:
|
|
93
|
+
return ""
|
|
94
|
+
if isinstance(value, str):
|
|
95
|
+
value = datetime.fromisoformat(value)
|
|
96
|
+
try:
|
|
97
|
+
zone = ZoneInfo(tz or "UTC")
|
|
98
|
+
except (KeyError, ValueError):
|
|
99
|
+
zone = ZoneInfo("UTC")
|
|
100
|
+
if value.tzinfo is None:
|
|
101
|
+
value = value.replace(tzinfo=ZoneInfo("UTC"))
|
|
102
|
+
return babel_dates.format_datetime(
|
|
103
|
+
value.astimezone(zone), format=format, locale=locale_of(lang)
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def format_field(record: BaseModel, name: str) -> str:
|
|
108
|
+
"""The value of field ``name`` of one record, as text for people (``""`` when empty)."""
|
|
109
|
+
record.ensure_one()
|
|
110
|
+
field: Any = record._fields[name]
|
|
111
|
+
value: Any = record[name]
|
|
112
|
+
lang = record.env.lang
|
|
113
|
+
kind = field.type
|
|
114
|
+
if kind == "boolean":
|
|
115
|
+
return "Yes" if value else "No"
|
|
116
|
+
if _is_empty(value):
|
|
117
|
+
return ""
|
|
118
|
+
if kind in ("many2one", "one2many", "many2many"):
|
|
119
|
+
return ", ".join(value.mapped("display_name"))
|
|
120
|
+
if kind == "selection":
|
|
121
|
+
return str(dict(field.get_values(record)).get(value, value))
|
|
122
|
+
if kind == "monetary":
|
|
123
|
+
currency_field = getattr(field, "currency_field", None) or "currency_id"
|
|
124
|
+
currency = record[currency_field] if currency_field in record._fields else None
|
|
125
|
+
return format_amount(value, currency or None, lang)
|
|
126
|
+
if kind == "float":
|
|
127
|
+
digits = getattr(field, "digits", None)
|
|
128
|
+
return format_number(value, digits[1] if digits else None, lang)
|
|
129
|
+
if kind == "integer":
|
|
130
|
+
return format_number(int(value), None, lang)
|
|
131
|
+
if kind == "date":
|
|
132
|
+
return format_date(value, lang)
|
|
133
|
+
if kind == "datetime":
|
|
134
|
+
return format_datetime(value, lang, record.env.context.get("tz"))
|
|
135
|
+
if kind in ("binary", "json"):
|
|
136
|
+
return ""
|
|
137
|
+
return str(value)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _is_empty(value: Any) -> bool:
|
|
141
|
+
return value is None or value is False
|
modora/tools/html.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
2
|
+
"""HTML helpers: an allow-list sanitizer and plain text ⇄ HTML conversions.
|
|
3
|
+
|
|
4
|
+
:func:`sanitize_html` keeps formatting tags and drops everything that can run code or load
|
|
5
|
+
content from elsewhere: ``<script>``/``<style>``/``<iframe>`` (with their content), event
|
|
6
|
+
handler and ``style`` attributes, and links whose scheme is not ``http``, ``https`` or
|
|
7
|
+
``mailto`` (images: ``https`` and inline ``data:image/…``, except SVG). Message bodies are
|
|
8
|
+
sanitized when stored, so clients may show them as HTML.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import html
|
|
14
|
+
import re
|
|
15
|
+
from html.parser import HTMLParser
|
|
16
|
+
|
|
17
|
+
__all__ = ["html_to_text", "sanitize_html", "text_to_html"]
|
|
18
|
+
|
|
19
|
+
_ALLOWED: dict[str, set[str]] = {
|
|
20
|
+
"a": {"href", "title", "target", "rel"},
|
|
21
|
+
"abbr": {"title"},
|
|
22
|
+
"b": set(), "blockquote": set(), "br": set(), "code": set(), "div": set(), "em": set(),
|
|
23
|
+
"h1": set(), "h2": set(), "h3": set(), "h4": set(), "h5": set(), "h6": set(), "hr": set(),
|
|
24
|
+
"i": set(), "li": set(), "ol": set(), "p": set(), "pre": set(), "s": set(), "small": set(),
|
|
25
|
+
"span": set(), "strong": set(), "sub": set(), "sup": set(), "u": set(), "ul": set(),
|
|
26
|
+
"table": set(), "thead": set(), "tbody": set(), "tfoot": set(), "tr": set(),
|
|
27
|
+
"th": {"colspan", "rowspan"}, "td": {"colspan", "rowspan"},
|
|
28
|
+
"img": {"src", "alt", "width", "height", "title"},
|
|
29
|
+
} # fmt: skip
|
|
30
|
+
_VOID = {"br", "hr", "img"}
|
|
31
|
+
_DROP_CONTENT = {"script", "style", "iframe", "object", "embed", "template", "noscript", "title"}
|
|
32
|
+
_LINK_SCHEMES = ("http:", "https:", "mailto:")
|
|
33
|
+
_IMAGE_DATA = re.compile(r"^data:image/(png|jpe?g|gif|webp);base64,[a-z0-9+/=\s]*$", re.I)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _safe_url(value: str, *, image: bool) -> bool:
|
|
37
|
+
url = re.sub(r"[\x00-\x20]+", "", value).lower()
|
|
38
|
+
if image:
|
|
39
|
+
return url.startswith("https:") or bool(_IMAGE_DATA.match(value.strip()))
|
|
40
|
+
if url.startswith(("/", "#", "?")) and not url.startswith("//"):
|
|
41
|
+
return True # relative to the server
|
|
42
|
+
return url.startswith(_LINK_SCHEMES)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class _Sanitizer(HTMLParser):
|
|
46
|
+
def __init__(self) -> None:
|
|
47
|
+
super().__init__(convert_charrefs=True)
|
|
48
|
+
self.out: list[str] = []
|
|
49
|
+
self.open: list[str] = []
|
|
50
|
+
self.dropping = 0
|
|
51
|
+
|
|
52
|
+
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
53
|
+
if tag in _DROP_CONTENT:
|
|
54
|
+
self.dropping += 1
|
|
55
|
+
return
|
|
56
|
+
if self.dropping or tag not in _ALLOWED:
|
|
57
|
+
return
|
|
58
|
+
kept = []
|
|
59
|
+
for name, value in attrs:
|
|
60
|
+
if name not in _ALLOWED[tag] or value is None:
|
|
61
|
+
continue
|
|
62
|
+
if name in ("href", "src") and not _safe_url(value, image=tag == "img"):
|
|
63
|
+
continue
|
|
64
|
+
kept.append(f' {name}="{html.escape(value, quote=True)}"')
|
|
65
|
+
if tag == "img" and not any(a.startswith(" src=") for a in kept):
|
|
66
|
+
return
|
|
67
|
+
if tag == "a":
|
|
68
|
+
kept = [a for a in kept if not a.startswith((" rel=", " target="))]
|
|
69
|
+
kept.append(' rel="noopener noreferrer" target="_blank"')
|
|
70
|
+
self.out.append(f"<{tag}{''.join(kept)}>")
|
|
71
|
+
if tag not in _VOID:
|
|
72
|
+
self.open.append(tag)
|
|
73
|
+
|
|
74
|
+
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
75
|
+
self.handle_starttag(tag, attrs)
|
|
76
|
+
if tag in self.open and tag not in _VOID and self.open[-1] == tag:
|
|
77
|
+
self.handle_endtag(tag)
|
|
78
|
+
|
|
79
|
+
def handle_endtag(self, tag: str) -> None:
|
|
80
|
+
if tag in _DROP_CONTENT:
|
|
81
|
+
self.dropping = max(0, self.dropping - 1)
|
|
82
|
+
return
|
|
83
|
+
if self.dropping or tag not in self.open:
|
|
84
|
+
return
|
|
85
|
+
while self.open:
|
|
86
|
+
last = self.open.pop()
|
|
87
|
+
self.out.append(f"</{last}>")
|
|
88
|
+
if last == tag:
|
|
89
|
+
break
|
|
90
|
+
|
|
91
|
+
def handle_data(self, data: str) -> None:
|
|
92
|
+
if not self.dropping:
|
|
93
|
+
self.out.append(html.escape(data, quote=False))
|
|
94
|
+
|
|
95
|
+
def result(self) -> str:
|
|
96
|
+
self.close()
|
|
97
|
+
while self.open:
|
|
98
|
+
self.out.append(f"</{self.open.pop()}>")
|
|
99
|
+
return "".join(self.out)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def sanitize_html(value: str | None) -> str:
|
|
103
|
+
"""``value`` with only allowed tags, attributes and URLs (see the module docstring)."""
|
|
104
|
+
if not value:
|
|
105
|
+
return ""
|
|
106
|
+
parser = _Sanitizer()
|
|
107
|
+
parser.feed(value)
|
|
108
|
+
return parser.result()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def text_to_html(text: str | None) -> str:
|
|
112
|
+
"""Plain text as HTML paragraphs (blank lines) and line breaks, escaped."""
|
|
113
|
+
if not text:
|
|
114
|
+
return ""
|
|
115
|
+
paragraphs = re.split(r"\n\s*\n", text.strip())
|
|
116
|
+
return "".join(
|
|
117
|
+
"<p>" + "<br>".join(html.escape(line) for line in part.splitlines()) + "</p>"
|
|
118
|
+
for part in paragraphs
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def html_to_text(value: str | None) -> str:
|
|
123
|
+
"""The text of an HTML fragment (for plain-text email parts), blocks on their own lines."""
|
|
124
|
+
if not value:
|
|
125
|
+
return ""
|
|
126
|
+
value = re.sub(r"(?i)<br\s*/?>", "\n", value)
|
|
127
|
+
value = re.sub(r"(?i)</(p|div|h[1-6]|li|tr|table|blockquote)>", "\n", value)
|
|
128
|
+
value = re.sub(r"(?is)<(script|style)[^>]*>.*?</\1>", "", value)
|
|
129
|
+
value = re.sub(r"<[^>]+>", "", value)
|
|
130
|
+
lines = [line.strip() for line in html.unescape(value).splitlines()]
|
|
131
|
+
return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip()
|