reportflow-mcp bot commited on
Commit
ea1fa95
·
1 Parent(s): eb69a42

Sync Space from reportflow-mcp@ced064a

Browse files
Files changed (4) hide show
  1. README.md +4 -0
  2. app.py +174 -5
  3. oauth.py +232 -0
  4. workspace.py +170 -0
README.md CHANGED
@@ -77,6 +77,10 @@ Tools exposed here are **read-only public gallery** only:
77
  They do not copy a template into a workspace and they do not render a
78
  document. UI preview (PNG) is not an MCP tool.
79
 
 
 
 
 
80
  ## The shortest path to a PDF
81
 
82
  Use the **product** MCP, not this Space:
 
77
  They do not copy a template into a workspace and they do not render a
78
  document. UI preview (PNG) is not an MCP tool.
79
 
80
+ The App accordion **Sign in to your workspace** is a separate, browser-only
81
+ Authorization Code + PKCE flow. Hub MCP tools never start that flow. Tokens
82
+ are not written into tool results or Space Secrets.
83
+
84
  ## The shortest path to a PDF
85
 
86
  Use the **product** MCP, not this Space:
app.py CHANGED
@@ -23,6 +23,16 @@ from gallery import (
23
  mcp_template,
24
  search_templates,
25
  )
 
 
 
 
 
 
 
 
 
 
26
 
27
 
28
  def _format_results(payload: dict) -> str:
@@ -183,6 +193,115 @@ def get_register_url() -> str:
183
  return json.dumps(mcp_register(), ensure_ascii=False)
184
 
185
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
  def _category_choices() -> list[str]:
187
  try:
188
  categories = list_categories()
@@ -197,9 +316,8 @@ with gr.Blocks(title="Re:port Flow") as demo:
197
  """
198
  # Re:port Flow — public templates
199
 
200
- Browse invoice, quotation, and other document templates. **No login.**
201
- PDF generation is not available here; use a free account and the MCP server
202
- after you pick a template.
203
  """
204
  )
205
  with gr.Row():
@@ -243,9 +361,60 @@ after you pick a template.
243
  gr.api(get_gallery_template, api_name="get_gallery_template")
244
  gr.api(get_register_url, api_name="get_register_url")
245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
246
  gr.Markdown(
247
- f"[Create a free account to generate PDFs]({REGISTER_URL}) · "
248
- f"MCP: `{MCP_URL}`"
249
  )
250
 
251
 
 
23
  mcp_template,
24
  search_templates,
25
  )
26
+ from oauth import (
27
+ OAuthError,
28
+ access_token_for,
29
+ finish_authorization,
30
+ session_status,
31
+ sign_out,
32
+ start_authorization,
33
+ workspace_id_for,
34
+ )
35
+ from workspace import copy_public_template, design_parameters, list_designs, render_document
36
 
37
 
38
  def _format_results(payload: dict) -> str:
 
193
  return json.dumps(mcp_register(), ensure_ascii=False)
194
 
195
 
196
+ def _session_id(request: gr.Request) -> str:
197
+ sid = getattr(request, "session_hash", None)
198
+ if not isinstance(sid, str) or not sid:
199
+ raise OAuthError("No browser session. Reload the App tab and try again.")
200
+ return sid
201
+
202
+
203
+ def consume_oauth_redirect(request: gr.Request) -> str:
204
+ """Complete PKCE if the App was opened with ?code=&state=."""
205
+ params = getattr(request, "query_params", None) or {}
206
+ code = params.get("code") if hasattr(params, "get") else None
207
+ state = params.get("state") if hasattr(params, "get") else None
208
+ if not code or not state:
209
+ try:
210
+ return _status_markdown(_session_id(request))
211
+ except OAuthError:
212
+ return "Not signed in. Public gallery above does not need an account."
213
+ try:
214
+ finish_authorization(_session_id(request), str(code), str(state))
215
+ except OAuthError as err:
216
+ return str(err)
217
+ return _status_markdown(_session_id(request))
218
+
219
+
220
+ def _status_markdown(session_id: str) -> str:
221
+ status = session_status(session_id)
222
+ if not status.get("signedIn"):
223
+ return "Not signed in."
224
+ ws = status.get("workspaceId") or "(workspace chosen on the consent screen)"
225
+ return (
226
+ f"Signed in. Workspace is fixed server-side: `{ws}`.\n\n"
227
+ "Tokens stay on the server for this browser session. "
228
+ "They are not Hub MCP tools."
229
+ )
230
+
231
+
232
+ def start_sign_in() -> str:
233
+ """Open Re:port Flow login + workspace consent (Authorization Code + PKCE)."""
234
+ try:
235
+ url = start_authorization()
236
+ except OAuthError as err:
237
+ return str(err)
238
+ return (
239
+ f"Open this link, sign in, pick **your** workspace, then you return here:\n\n"
240
+ f"{url}"
241
+ )
242
+
243
+
244
+ def do_sign_out(request: gr.Request) -> str:
245
+ try:
246
+ sign_out(_session_id(request))
247
+ except OAuthError:
248
+ pass
249
+ return "Signed out."
250
+
251
+
252
+ def list_my_designs(request: gr.Request) -> str:
253
+ try:
254
+ payload = list_designs(access_token_for(_session_id(request)))
255
+ except OAuthError as err:
256
+ return str(err)
257
+ return json.dumps(payload, ensure_ascii=False, indent=2)
258
+
259
+
260
+ def load_param_schema(design_id: str, version: str, request: gr.Request) -> str:
261
+ try:
262
+ ver = int(version) if str(version).strip() else None
263
+ payload = design_parameters(
264
+ access_token_for(_session_id(request)), design_id, ver
265
+ )
266
+ except (OAuthError, ValueError) as err:
267
+ return str(err)
268
+ return json.dumps(payload, ensure_ascii=False, indent=2)
269
+
270
+
271
+ def copy_slug_into_workspace(slug: str, request: gr.Request) -> str:
272
+ try:
273
+ sid = _session_id(request)
274
+ payload = copy_public_template(
275
+ access_token_for(sid), workspace_id_for(sid), slug
276
+ )
277
+ except OAuthError as err:
278
+ return str(err)
279
+ return json.dumps(payload, ensure_ascii=False, indent=2)
280
+
281
+
282
+ def render_my_document(
283
+ design_id: str,
284
+ version: str,
285
+ params_json: str,
286
+ file_name: str,
287
+ request: gr.Request,
288
+ ) -> str:
289
+ try:
290
+ params = json.loads(params_json or "{}")
291
+ if not isinstance(params, dict):
292
+ raise OAuthError("params must be a JSON object of values you supplied.")
293
+ result = render_document(
294
+ access_token_for(_session_id(request)),
295
+ design_id,
296
+ int(version),
297
+ params,
298
+ file_name or "document.pdf",
299
+ )
300
+ except (OAuthError, ValueError, json.JSONDecodeError) as err:
301
+ return str(err)
302
+ return json.dumps(result, ensure_ascii=False, indent=2)
303
+
304
+
305
  def _category_choices() -> list[str]:
306
  try:
307
  categories = list_categories()
 
316
  """
317
  # Re:port Flow — public templates
318
 
319
+ Browse public templates with **no login**. To fill a document from **your**
320
+ workspace, sign in below. The Hub MCP tools on this Space stay read-only.
 
321
  """
322
  )
323
  with gr.Row():
 
361
  gr.api(get_gallery_template, api_name="get_gallery_template")
362
  gr.api(get_register_url, api_name="get_register_url")
363
 
364
+ with gr.Accordion("Sign in to your workspace", open=False):
365
+ auth_status = gr.Markdown()
366
+ sign_in_md = gr.Markdown()
367
+ with gr.Row():
368
+ sign_in_btn = gr.Button("Sign in with Re:port Flow")
369
+ sign_out_btn = gr.Button("Sign out")
370
+ demo.load(
371
+ fn=consume_oauth_redirect,
372
+ inputs=None,
373
+ outputs=[auth_status],
374
+ show_api=False,
375
+ )
376
+ sign_in_btn.click(fn=start_sign_in, outputs=[sign_in_md], show_api=False)
377
+ sign_out_btn.click(fn=do_sign_out, outputs=[auth_status], show_api=False)
378
+ ws_designs = gr.Textbox(label="Workspace designs (JSON)", lines=8)
379
+ list_btn = gr.Button("List my designs")
380
+ list_btn.click(fn=list_my_designs, outputs=[ws_designs], show_api=False)
381
+ copy_slug = gr.Textbox(label="Public slug to copy once into this workspace")
382
+ copy_btn = gr.Button("Copy slug into my workspace")
383
+ copy_out = gr.Textbox(label="Copy result")
384
+ copy_btn.click(
385
+ fn=copy_slug_into_workspace,
386
+ inputs=[copy_slug],
387
+ outputs=[copy_out],
388
+ show_api=False,
389
+ )
390
+ design_id = gr.Textbox(label="designId")
391
+ design_ver = gr.Textbox(label="version", value="1")
392
+ schema_btn = gr.Button("Load parameter schema")
393
+ schema_out = gr.Textbox(label="Parameter schema", lines=8)
394
+ schema_btn.click(
395
+ fn=load_param_schema,
396
+ inputs=[design_id, design_ver],
397
+ outputs=[schema_out],
398
+ show_api=False,
399
+ )
400
+ params_box = gr.Textbox(
401
+ label="params JSON (your values only — do not invent amounts or names)",
402
+ lines=8,
403
+ value="{}",
404
+ )
405
+ file_name = gr.Textbox(label="file name", value="document.pdf")
406
+ render_btn = gr.Button("Render from this workspace")
407
+ render_out = gr.Textbox(label="Render result")
408
+ render_btn.click(
409
+ fn=render_my_document,
410
+ inputs=[design_id, design_ver, params_box, file_name],
411
+ outputs=[render_out],
412
+ show_api=False,
413
+ )
414
+
415
  gr.Markdown(
416
+ f"[Create a free account]({REGISTER_URL}) · "
417
+ f"product MCP: `{MCP_URL}`"
418
  )
419
 
420
 
oauth.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Per-visitor OAuth for the Space UI (HF/5).
2
+
3
+ PKCE lives here, not on Hub MCP tools. Tokens stay in process memory keyed by
4
+ the Gradio session. They are never written to MCP responses or Space Secrets.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ import hashlib
11
+ import json
12
+ import os
13
+ import secrets
14
+ import time
15
+ from dataclasses import dataclass
16
+ from typing import Any
17
+ from urllib.parse import urlencode
18
+
19
+ import httpx
20
+
21
+ OAUTH_ISSUER = "https://re-port-flow.com/api/v1"
22
+ # Same AS the product MCP uses. Tokens issued here are what content-service
23
+ # already accepts from reportflow-mcp.
24
+ MCP_AS = "https://mcp.re-port-flow.com"
25
+ MCP_RESOURCE = "https://mcp.re-port-flow.com"
26
+ API_BASE = "https://api.re-port-flow.com"
27
+ SCOPE = (
28
+ "openid profile designs:read designs:write "
29
+ "templates:read templates:write pdf:generate"
30
+ )
31
+ CLIENT_NAME = "reportflow-readme-space"
32
+ APP_KEY = "reportflow-mcp"
33
+
34
+
35
+ class OAuthError(Exception):
36
+ """User-visible OAuth failure. Must not include token material."""
37
+
38
+
39
+ @dataclass
40
+ class TokenSet:
41
+ access_token: str
42
+ refresh_token: str | None
43
+ expires_at: float
44
+ workspace_id: str | None
45
+
46
+
47
+ @dataclass
48
+ class PendingAuth:
49
+ verifier: str
50
+ created_at: float
51
+
52
+
53
+ _pending: dict[str, PendingAuth] = {}
54
+ _sessions: dict[str, TokenSet] = {}
55
+ _client_id: str | None = None
56
+
57
+
58
+ def _b64url(data: bytes) -> str:
59
+ return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=")
60
+
61
+
62
+ def pkce_pair() -> tuple[str, str]:
63
+ verifier = secrets.token_urlsafe(64)[:64]
64
+ challenge = _b64url(hashlib.sha256(verifier.encode("ascii")).digest())
65
+ return verifier, challenge
66
+
67
+
68
+ def decode_workspace_id(access_token: str) -> str | None:
69
+ parts = access_token.split(".")
70
+ if len(parts) < 2:
71
+ return None
72
+ pad = "=" * (-len(parts[1]) % 4)
73
+ try:
74
+ payload = json.loads(base64.urlsafe_b64decode(parts[1] + pad))
75
+ except (ValueError, json.JSONDecodeError):
76
+ return None
77
+ ws = payload.get("workspace_id")
78
+ return ws if isinstance(ws, str) and ws else None
79
+
80
+
81
+ def redirect_uri() -> str:
82
+ host = (os.environ.get("SPACE_HOST") or "").strip()
83
+ if host:
84
+ return f"https://{host}/"
85
+ return "http://127.0.0.1:7860/"
86
+
87
+
88
+ def register_public_client(client: httpx.Client | None = None) -> str:
89
+ """DCR public client. Scope is explicit (omit → openid profile only)."""
90
+ global _client_id
91
+ if _client_id:
92
+ return _client_id
93
+ own = client is None
94
+ http = client or httpx.Client(timeout=15.0)
95
+ body = {
96
+ "client_name": CLIENT_NAME,
97
+ "redirect_uris": [redirect_uri()],
98
+ "grant_types": ["authorization_code", "refresh_token"],
99
+ "token_endpoint_auth_method": "none",
100
+ "scope": SCOPE,
101
+ }
102
+ try:
103
+ response = http.post(
104
+ f"{MCP_AS}/register",
105
+ json=body,
106
+ headers={"Accept": "application/json"},
107
+ )
108
+ response.raise_for_status()
109
+ payload = response.json()
110
+ except httpx.HTTPError as err:
111
+ raise OAuthError("Could not register the Space as an OAuth client.") from err
112
+ finally:
113
+ if own:
114
+ http.close()
115
+ client_id = payload.get("client_id")
116
+ if not isinstance(client_id, str) or not client_id:
117
+ raise OAuthError("OAuth client registration returned no client_id.")
118
+ _client_id = client_id
119
+ return client_id
120
+
121
+
122
+ def start_authorization() -> str:
123
+ verifier, challenge = pkce_pair()
124
+ state = secrets.token_urlsafe(24)
125
+ _pending[state] = PendingAuth(verifier=verifier, created_at=time.time())
126
+ client_id = register_public_client()
127
+ query = urlencode(
128
+ {
129
+ "response_type": "code",
130
+ "client_id": client_id,
131
+ "redirect_uri": redirect_uri(),
132
+ "scope": SCOPE,
133
+ "state": state,
134
+ "code_challenge": challenge,
135
+ "code_challenge_method": "S256",
136
+ "resource": MCP_RESOURCE,
137
+ }
138
+ )
139
+ return f"{MCP_AS}/authorize?{query}"
140
+
141
+
142
+ def _store_tokens(session_id: str, payload: dict[str, Any]) -> TokenSet:
143
+ access = payload.get("access_token")
144
+ if not isinstance(access, str) or not access:
145
+ raise OAuthError("Token response had no access_token.")
146
+ refresh = payload.get("refresh_token")
147
+ expires_in = payload.get("expires_in")
148
+ ttl = float(expires_in) if isinstance(expires_in, (int, float)) else 3600.0
149
+ stored = TokenSet(
150
+ access_token=access,
151
+ refresh_token=refresh if isinstance(refresh, str) else None,
152
+ expires_at=time.time() + ttl - 60.0,
153
+ workspace_id=decode_workspace_id(access),
154
+ )
155
+ _sessions[session_id] = stored
156
+ return stored
157
+
158
+
159
+ def finish_authorization(
160
+ session_id: str,
161
+ code: str,
162
+ state: str,
163
+ client: httpx.Client | None = None,
164
+ ) -> TokenSet:
165
+ if not session_id:
166
+ raise OAuthError("No Gradio session — cannot attach tokens to a visitor.")
167
+ pending = _pending.pop(state, None)
168
+ if pending is None or time.time() - pending.created_at > 600:
169
+ raise OAuthError("Sign-in expired or state did not match. Start again.")
170
+ own = client is None
171
+ http = client or httpx.Client(timeout=15.0)
172
+ try:
173
+ response = http.post(
174
+ f"{MCP_AS}/token",
175
+ data={
176
+ "grant_type": "authorization_code",
177
+ "code": code,
178
+ "redirect_uri": redirect_uri(),
179
+ "client_id": register_public_client(http),
180
+ "code_verifier": pending.verifier,
181
+ "resource": MCP_RESOURCE,
182
+ },
183
+ headers={"Accept": "application/json"},
184
+ )
185
+ response.raise_for_status()
186
+ payload = response.json()
187
+ except httpx.HTTPError as err:
188
+ raise OAuthError("Could not exchange the authorization code.") from err
189
+ finally:
190
+ if own:
191
+ http.close()
192
+ if not isinstance(payload, dict):
193
+ raise OAuthError("Token response was not JSON.")
194
+ return _store_tokens(session_id, payload)
195
+
196
+
197
+ def session_status(session_id: str) -> dict[str, Any]:
198
+ token = _sessions.get(session_id)
199
+ if token is None:
200
+ return {"signedIn": False}
201
+ return {
202
+ "signedIn": True,
203
+ "workspaceId": token.workspace_id,
204
+ "expiresSoon": time.time() >= token.expires_at,
205
+ }
206
+
207
+
208
+ def access_token_for(session_id: str) -> str:
209
+ token = _sessions.get(session_id)
210
+ if token is None:
211
+ raise OAuthError("Sign in with Re:port Flow first.")
212
+ if time.time() >= token.expires_at:
213
+ raise OAuthError("Session expired. Sign in again.")
214
+ return token.access_token
215
+
216
+
217
+ def workspace_id_for(session_id: str) -> str:
218
+ token = _sessions.get(session_id)
219
+ if token is None or not token.workspace_id:
220
+ raise OAuthError("Sign in and pick a workspace on the consent screen.")
221
+ return token.workspace_id
222
+
223
+
224
+ def sign_out(session_id: str) -> None:
225
+ _sessions.pop(session_id, None)
226
+
227
+
228
+ def reset_client_cache() -> None:
229
+ global _client_id
230
+ _client_id = None
231
+ _pending.clear()
232
+ _sessions.clear()
workspace.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Authenticated workspace calls for the Space UI only.
2
+
3
+ Not registered as Hub MCP tools. Tokens are passed in by the caller and never
4
+ returned in these payloads.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from typing import Any
11
+ from urllib.parse import unquote
12
+
13
+ import httpx
14
+
15
+ from oauth import API_BASE, APP_KEY, OAuthError
16
+
17
+ TIMEOUT_S = 60.0
18
+
19
+
20
+ def _headers(access_token: str) -> dict[str, str]:
21
+ return {
22
+ "Authorization": f"Bearer {access_token}",
23
+ "Accept": "application/json",
24
+ "app-key": APP_KEY,
25
+ }
26
+
27
+
28
+ def list_designs(access_token: str, client: httpx.Client | None = None) -> dict[str, Any]:
29
+ own = client is None
30
+ http = client or httpx.Client(timeout=TIMEOUT_S)
31
+ try:
32
+ response = http.get(f"{API_BASE}/v1/file/designs", headers=_headers(access_token))
33
+ response.raise_for_status()
34
+ payload = response.json()
35
+ except httpx.HTTPStatusError as err:
36
+ if err.response.status_code in (401, 403):
37
+ raise OAuthError("This workspace rejected the request. Sign in again.") from err
38
+ raise OAuthError(f"Workspace list returned HTTP {err.response.status_code}.") from err
39
+ except httpx.HTTPError as err:
40
+ raise OAuthError("Could not list workspace designs.") from err
41
+ finally:
42
+ if own:
43
+ http.close()
44
+ if not isinstance(payload, dict):
45
+ raise OAuthError("Workspace list was not JSON.")
46
+ return payload
47
+
48
+
49
+ def design_parameters(
50
+ access_token: str,
51
+ design_id: str,
52
+ version: int | None = None,
53
+ client: httpx.Client | None = None,
54
+ ) -> dict[str, Any]:
55
+ cleaned = design_id.strip()
56
+ if not cleaned or "/" in cleaned or ".." in cleaned:
57
+ raise OAuthError("That design id is not valid.")
58
+ own = client is None
59
+ http = client or httpx.Client(timeout=TIMEOUT_S)
60
+ params = {"version": version} if version is not None else None
61
+ try:
62
+ response = http.get(
63
+ f"{API_BASE}/v1/file/design/parameter/{cleaned}",
64
+ headers=_headers(access_token),
65
+ params=params,
66
+ )
67
+ response.raise_for_status()
68
+ payload = response.json()
69
+ except httpx.HTTPStatusError as err:
70
+ if err.response.status_code in (401, 403):
71
+ raise OAuthError("This workspace rejected the request. Sign in again.") from err
72
+ raise OAuthError(f"Parameter schema returned HTTP {err.response.status_code}.") from err
73
+ except httpx.HTTPError as err:
74
+ raise OAuthError("Could not load the parameter schema.") from err
75
+ finally:
76
+ if own:
77
+ http.close()
78
+ if not isinstance(payload, dict):
79
+ raise OAuthError("Parameter schema was not JSON.")
80
+ return payload
81
+
82
+
83
+ def copy_public_template(
84
+ access_token: str,
85
+ workspace_id: str,
86
+ slug: str,
87
+ client: httpx.Client | None = None,
88
+ ) -> dict[str, Any]:
89
+ if "/" in slug or ".." in slug or not slug.strip():
90
+ raise OAuthError("That slug is not valid.")
91
+ if "/" in workspace_id or ".." in workspace_id or not workspace_id:
92
+ raise OAuthError("Workspace id is not valid.")
93
+ own = client is None
94
+ http = client or httpx.Client(timeout=120.0)
95
+ url = (
96
+ f"https://re-port-flow.com/api/v1/{workspace_id}/my/templates/"
97
+ f"{slug.strip()}/duplicate"
98
+ )
99
+ try:
100
+ response = http.post(
101
+ url,
102
+ headers={**_headers(access_token), "Content-Type": "application/json"},
103
+ json={"workspaceId": workspace_id},
104
+ )
105
+ response.raise_for_status()
106
+ payload = response.json()
107
+ except httpx.HTTPStatusError as err:
108
+ if err.response.status_code in (401, 403):
109
+ raise OAuthError("Copy was denied for this workspace.") from err
110
+ raise OAuthError(f"Copy returned HTTP {err.response.status_code}.") from err
111
+ except httpx.HTTPError as err:
112
+ raise OAuthError("Could not copy the public template.") from err
113
+ finally:
114
+ if own:
115
+ http.close()
116
+ if not isinstance(payload, dict):
117
+ raise OAuthError("Copy response was not JSON.")
118
+ return {
119
+ "designId": payload.get("duplicatedFileId"),
120
+ "workspaceId": payload.get("workspaceId"),
121
+ "slug": payload.get("templateSlug"),
122
+ }
123
+
124
+
125
+ def render_document(
126
+ access_token: str,
127
+ design_id: str,
128
+ version: int,
129
+ params: dict[str, Any],
130
+ file_name: str = "document.pdf",
131
+ client: httpx.Client | None = None,
132
+ ) -> dict[str, Any]:
133
+ if "/" in design_id or ".." in design_id or not design_id.strip():
134
+ raise OAuthError("That design id is not valid.")
135
+ own = client is None
136
+ http = client or httpx.Client(timeout=120.0)
137
+ try:
138
+ response = http.post(
139
+ f"{API_BASE}/v1/file/sync/single",
140
+ headers={**_headers(access_token), "Content-Type": "application/json"},
141
+ json={
142
+ "designId": design_id.strip(),
143
+ "version": version,
144
+ "content": {"fileName": file_name, "params": params},
145
+ },
146
+ )
147
+ response.raise_for_status()
148
+ except httpx.HTTPStatusError as err:
149
+ if err.response.status_code in (401, 403):
150
+ raise OAuthError("Render was denied for this workspace.") from err
151
+ raise OAuthError(f"Render returned HTTP {err.response.status_code}.") from err
152
+ except httpx.HTTPError as err:
153
+ raise OAuthError("Could not render the document.") from err
154
+ finally:
155
+ if own:
156
+ http.close()
157
+ file_url = response.headers.get("File-URL") or response.headers.get("file-url")
158
+ request_id = response.headers.get("Request-Id") or response.headers.get("request-id")
159
+ mapping_raw = response.headers.get("X-File-Mapping") or response.headers.get(
160
+ "x-file-mapping"
161
+ )
162
+ file_id = None
163
+ if mapping_raw:
164
+ try:
165
+ mapping = json.loads(unquote(mapping_raw))
166
+ if isinstance(mapping, list) and mapping and isinstance(mapping[0], dict):
167
+ file_id = mapping[0].get("fileId")
168
+ except json.JSONDecodeError:
169
+ file_id = None
170
+ return {"fileUrl": file_url, "requestId": request_id, "fileId": file_id}