Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 49 minutes ago History
render_pdf.py · 9.4 KB · 232 lines
1"""action_render_pdf -- a CAPABILITY, absent by default. POST {token} or
2{source, kind}.
3
4**Browser print-to-PDF already produces a good PDF and costs nothing.** That is
5the default answer, it is said out loud on every document page rendered by this
6layer, and it is the reason this object is allowed to be absent: nobody is
7blocked by it.
8
9Server-side PDF is a real dependency decision and does not belong in the core:
10
11 WeasyPrint pango/cairo system libs -- heavy on a 1GB box
12 Chrome heavier still: a whole browser to render a page we already
13 rendered
14 wkhtmltopdf an unmaintained binary
15 ReportLab pure Python, but you rebuild the layout by hand, which is two
16 renderers again -- the exact failure this layer exists to end
17
18So this follows the pattern already used for OCR engines
19(docs/capability-objects.md) and carrier labels (app-shipping's action_buy_label
20and connectors/manual.py): the capability is named in a SETTING,
21`documents.pdf_engine`, defaulting to `none`, and an unconfigured server gets a
22409 that NAMES WHAT TO INSTALL rather than a traceback, a silent nothing, or a
23stub PDF with a watermark on it.
24
25**No surface offers a PDF button when it would 409.** object_documents.
26pdf_engine_status is the single pure answer to "is there an engine?", every
27document page consults it before drawing the button, and render_page(pdf=...)
28is the only way a button gets drawn at all. A button that 409s tells the person
29pressing it that something is broken on YOUR end -- the same reason
30site_invoice_portal only draws "Pay by card" when Stripe is actually
31configured.
32
33**There is deliberately no WeasyPrint or Chrome adapter in this file.** Nothing
34in this repo can test one; an untested integration against a heavyweight
35dependency is the worst kind of confident wrong answer; and the honest boundary
36is more useful than a guess at the far side of it. What an engine must provide
37when one is installed is exactly this: take `html` -- the SAME HTML the print
38view renders, from object_documents.render_page, never a second template -- and
39return PDF bytes. That is the whole contract, and it is why this object still
40builds the HTML and returns it in the refusal: the boundary is demonstrably the
41same document, not a promise that it would be.
42"""
43
44import hmac
45import os
46
47import object_access
48import object_documents
49import object_money
50import object_records
51
52ACTOR = "action_render_pdf"
53COLLECTION = "sent_documents"
54
55
56def _base_dir():
57 return os.environ.get("DBBASIC_DATA_DIR", "data")
58
59
60def _text(value):
61 return str(value if value is not None else "").strip()
62
63
64def _settings(base):
65 values = {}
66 try:
67 # access: box configuration
68 for row in object_records.read_collection_records("app_settings",
69 base_dir=base):
70 key, value = _text(row.get("key")), _text(row.get("value"))
71 if key and value:
72 values[key] = value
73 except Exception:
74 pass
75 return values
76
77
78def _document_by_token(base, token):
79 token = _text(token)
80 if not token:
81 return None
82 try:
83 # access: capability link: the sent document is found by its secret token
84 rows = object_records.read_collection_records(COLLECTION, base_dir=base)
85 except Exception:
86 return None
87 for row in rows:
88 candidate = _text(row.get("token"))
89 if candidate and hmac.compare_digest(candidate, token):
90 return row
91 return None
92
93
94def _model_from_source(base, kind, source, settings, access):
95 """Render a document straight from its source record -- the operator path,
96 for a document that has not been sent to anybody yet.
97
98 Only a record this subject may READ through the API, and only the lines
99 it may read. Until 2026-11-28 this read the raw row, so any signed-in
100 user could name another user's invoice and get its whole rendered page
101 back in the 409 (customer, lines, amounts). Refused and missing are one
102 404, so the action is no existence oracle for record ids."""
103 try:
104 spec = object_documents.source_spec(kind)
105 except object_documents.UnknownKindError as exc:
106 return None, {"status": 400, "error": str(exc)}
107 if spec is None:
108 return None, {"status": 409,
109 "error": f"'{kind}' documents have no source mapping yet."}
110 if source.count("/") != 1:
111 return None, {"status": 400,
112 "error": "source must look like 'collection/{id}'"}
113 collection, _, record_id = source.partition("/")
114 collection, record_id = _text(collection), _text(record_id)
115 if collection != spec["collection"]:
116 return None, {"status": 400,
117 "error": (f"a '{kind}' is rendered from "
118 f"{spec['collection']}, not {collection}")}
119 try:
120 record = access.get(collection, record_id)
121 except Exception:
122 record = None
123 if not record:
124 return None, {"status": 404, "error": f"No such record: {source}"}
125
126 lines = []
127 if spec.get("lines_collection"):
128 try:
129 rows = object_records.read_collection_records(
130 spec["lines_collection"], base_dir=base)
131 lines = access.visible(
132 spec["lines_collection"],
133 [row for row in rows
134 if _text(row.get(spec["lines_fk"])) == record_id])
135 lines.sort(key=lambda row: _text(row.get("description")))
136 except Exception:
137 lines = []
138
139 currency = _text(record.get("currency")) or "USD"
140
141 def money(cents):
142 try:
143 return object_money.format_amount(cents or 0, currency, base_dir=base)
144 except Exception:
145 return f"{cents or 0} (minor units)"
146
147 facts = object_documents.facts_from_records(kind, record, lines, money=money)
148 try:
149 model = object_documents.build_model(kind, facts, settings,
150 require_business=False)
151 except object_documents.DocumentError as exc:
152 return None, {"status": 400, "error": str(exc)}
153 return model, None
154
155
156def POST(request):
157 identity = request.get("_identity") or {}
158 if not _text(identity.get("user_id")):
159 return {"status": 403, "error": "Sign in to render a PDF."}
160
161 base = _base_dir()
162 settings = _settings(base)
163 engine = object_documents.pdf_engine_status(
164 settings.get(object_documents.PDF_ENGINE_SETTING))
165
166 token = _text(request.get("token"))
167 source = _text(request.get("source"))
168 kind = _text(request.get("kind"))
169 if not token and not source:
170 return {"status": 400,
171 "error": "pass either {token} for a sent document, or "
172 "{kind, source} for one that has not been sent"}
173
174 if token:
175 row = _document_by_token(base, token)
176 if row is None:
177 return {"status": 404, "error": "No such document."}
178 try:
179 model = object_documents.model_from_snapshot(row.get("snapshot"))
180 except object_documents.DocumentError as exc:
181 return {"status": 409, "error": str(exc)}
182 # A sent document's PDF is a PDF of what was SENT -- the snapshot, the
183 # same thing the link shows. A PDF built from the live record would be
184 # a second version of a document somebody already has.
185 else:
186 model, refusal = _model_from_source(
187 base, kind, source, settings,
188 object_access.Access(identity, base_dir=base))
189 if refusal is not None:
190 return refusal
191
192 page = object_documents.render_page(
193 model, chrome=False,
194 size=settings.get(object_documents.PAGE_SIZE_SETTING))
195 html_body = page["body"]
196
197 if not engine["available"]:
198 # The honest absent state. It names the setting, it names what to
199 # install and what each option costs, and it names the thing that
200 # already works -- so an operator gets a decision rather than an error.
201 return {
202 "status": 409,
203 "error": engine["reason"],
204 "setting": object_documents.PDF_ENGINE_SETTING,
205 "engine": engine["engine"],
206 "install": engine["install"],
207 "alternative": ("Print this document and choose Save as PDF. It "
208 "needs no dependency and produces the same page."),
209 # The boundary, demonstrated rather than described: this is the
210 # exact HTML an engine would be handed, byte for byte the page the
211 # print view serves.
212 "html": html_body,
213 }
214
215 # Unreachable today: pdf_engine_status never returns available=True,
216 # because no engine module ships with this server. The line is here so the
217 # contract is unambiguous for whoever installs one -- take `html_body`,
218 # return bytes, and never render a second template.
219 return {"status": 501,
220 "error": (f"'{engine['engine']}' reports as available but no "
221 "adapter is wired up in this build."),
222 "html": html_body}
223
224
225def GET(request):
226 """The capability, asked about rather than invoked -- so a surface can
227 check before it draws a button, without side effects."""
228 settings = _settings(_base_dir())
229 status = object_documents.pdf_engine_status(
230 settings.get(object_documents.PDF_ENGINE_SETTING))
231 return {"status": "ok", "pdf": status,
232 "alternative": "Print -> Save as PDF works today and costs nothing."}