hap-cli 0.9.0__py3-none-any.whl → 0.9.2__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.
app_live_tests/smoke.py CHANGED
@@ -226,6 +226,146 @@ def case_custom_action(app_id: str, section_id: str) -> None:
226
226
  hap(["worksheet", "delete", ws_id, "-a", app_id, "-y"], check=False)
227
227
 
228
228
 
229
+ def case_custom_action_update(app_id: str, section_id: str) -> None:
230
+ """bug #455751: --action-spec with --btn-id edits the action in place."""
231
+ print("scenario: custom-action update by id")
232
+ ws_id = _make_worksheet(app_id, section_id, "LT-action-update")
233
+ try:
234
+ ok, res = _try(["worksheet", "create-custom-action", ws_id, "-a",
235
+ app_id, "--action-spec", json.dumps(
236
+ {"name": "ORIGINAL", "type": "triggerWorkflow",
237
+ "color": "#2196F3"})])
238
+ check("update: workflow action created", ok, str(res)[:160])
239
+ btn_id = res.get("actionId") if ok else ""
240
+ proc_id = res.get("processId") if ok else ""
241
+ ok, res = _try(["worksheet", "create-custom-action", ws_id, "-a",
242
+ app_id, "--btn-id", btn_id, "--action-spec",
243
+ json.dumps({"name": "UPDATED"})])
244
+ check("update: edit succeeds", ok, str(res)[:160])
245
+ check("update: the id is unchanged",
246
+ ok and res.get("actionId") == btn_id, str(res)[:160])
247
+ check("update: the same workflow is reported",
248
+ ok and res.get("processId") == proc_id, str(res)[:160])
249
+ acts = _actions(ws_id)
250
+ check("update: still one action", len(acts) == 1,
251
+ str([(a.get("btnId"), a.get("name")) for a in acts]))
252
+ got = acts[0] if acts else {}
253
+ check("update: renamed in place",
254
+ got.get("btnId") == btn_id and got.get("name") == "UPDATED",
255
+ str((got.get("btnId"), got.get("name"))))
256
+ check("update: unnamed settings kept",
257
+ got.get("color") == "#2196F3" and got.get("clickType") == 1,
258
+ str((got.get("color"), got.get("clickType"))))
259
+ wf = [r for r in _workflow_rows(app_id)
260
+ if r.get("id") == proc_id or r.get("processId") == proc_id]
261
+ check("update: the action's workflow survives", bool(wf),
262
+ proc_id)
263
+
264
+ # A fill action edited by id stays a fill action and keeps its fields.
265
+ title = next((c["controlId"] for c in _fields(ws_id)
266
+ if c.get("attribute") == 1), "")
267
+ ok, res = _try(["worksheet", "create-custom-action", ws_id, "-a",
268
+ app_id, "--action-spec", json.dumps(
269
+ {"name": "FILL", "type": "updateCurrentRecord",
270
+ "updateFields": [title]})])
271
+ fill_id = res.get("actionId") if ok else ""
272
+ ok, res = _try(["worksheet", "create-custom-action", ws_id, "-a",
273
+ app_id, "--btn-id", fill_id, "--action-spec",
274
+ json.dumps({"name": "FILL2"})])
275
+ check("update: fill action edit succeeds", ok, str(res)[:160])
276
+ acts = _actions(ws_id)
277
+ fill = next((a for a in acts if a.get("btnId") == fill_id), {})
278
+ check("update: two actions after editing the second", len(acts) == 2,
279
+ str([(a.get("btnId"), a.get("name")) for a in acts]))
280
+ check("update: fill action keeps its kind and field",
281
+ fill.get("name") == "FILL2" and fill.get("clickType") == 3
282
+ and [w.get("controlId") for w in fill.get("writeControls")
283
+ or []] == [title],
284
+ str((fill.get("name"), fill.get("clickType"),
285
+ fill.get("writeControls"))))
286
+
287
+ ok, res = _try(["worksheet", "create-custom-action", ws_id, "-a",
288
+ app_id, "--btn-id", "000000000000000000000000",
289
+ "--action-spec", json.dumps({"name": "GHOST"})])
290
+ check("update: unknown id is refused", not ok, str(res)[:160])
291
+ check("update: nothing created for an unknown id",
292
+ len(_actions(ws_id)) == 2, str(len(_actions(ws_id))))
293
+ finally:
294
+ hap(["worksheet", "delete", ws_id, "-a", app_id, "-y"], check=False)
295
+
296
+
297
+ def case_hidden_defaults(app_id: str, section_id: str) -> None:
298
+ """bug #455757: a hidden field's default goes in with a new record.
299
+
300
+ The form submits every non-empty cell on create, hidden ones included,
301
+ so the defaults the CLI fills in must not be judged as the caller
302
+ writing a hidden field. Writing one yourself is still refused.
303
+ """
304
+ print("scenario: hidden defaults on create")
305
+ ws_id = _make_worksheet(app_id, section_id, "LT-hidden-defaults")
306
+
307
+ def static(value):
308
+ return {"defsource": json.dumps(
309
+ [{"cid": "", "rcid": "", "staticValue": value}])}
310
+ try:
311
+ ok, res = _try(["worksheet", "add-fields", ws_id, "--controls",
312
+ json.dumps([
313
+ {"type": 2, "controlName": "Stage",
314
+ "fieldPermission": "110",
315
+ "advancedSetting": static("Draft")},
316
+ {"type": 2, "controlName": "Status",
317
+ "fieldPermission": "110",
318
+ "advancedSetting": static("Open")}])])
319
+ check("hidden: fields added", ok, str(res)[:160])
320
+ ids = {c.get("controlName"): c.get("controlId")
321
+ for c in _fields(ws_id)}
322
+ name_id = next((c["controlId"] for c in _fields(ws_id)
323
+ if c.get("attribute") == 1), "")
324
+ stage, status = ids.get("Stage"), ids.get("Status")
325
+
326
+ ok, res = _try(["worksheet", "record", "create", ws_id, "-a", app_id,
327
+ "--fields-json", json.dumps(
328
+ [{"id": name_id, "value": "visible-only"}])])
329
+ check("hidden: create with only the visible field succeeds", ok,
330
+ str(res)[:200])
331
+ row_id = ((res.get("data") or {}).get("rowid")
332
+ if ok and isinstance(res, dict) else "")
333
+ got = (hap(["worksheet", "record", "get", ws_id, row_id, "-a",
334
+ app_id]) or {}) if row_id else {}
335
+ got = got.get("data", got) if isinstance(got, dict) else {}
336
+ check("hidden: the hidden defaults were stored",
337
+ got.get(stage) == "Draft" and got.get(status) == "Open",
338
+ str({k: got.get(k) for k in (name_id, stage, status)}))
339
+
340
+ ok, res = _try(["worksheet", "record", "create", ws_id, "-a", app_id,
341
+ "--fields-json", json.dumps(
342
+ [{"id": name_id, "value": "sneaky"},
343
+ {"id": stage, "value": "Won"}])])
344
+ check("hidden: writing a hidden field yourself is refused",
345
+ not ok and "Stage" in str(res) and "Status" not in str(res),
346
+ str(res)[:240])
347
+
348
+ rows = json.dumps([{name_id: "batch-1"}, {name_id: "batch-2"}])
349
+ ok, res = _try(["worksheet", "record", "batch-create", ws_id,
350
+ "-a", app_id, "--rows", rows])
351
+ check("hidden: batch create with only visible fields succeeds", ok,
352
+ str(res)[:200])
353
+ rows = json.dumps([{name_id: "batch-3"},
354
+ {name_id: "batch-4", stage: "Won"}])
355
+ ok, res = _try(["worksheet", "record", "batch-create", ws_id,
356
+ "-a", app_id, "--rows", rows])
357
+ check("hidden: batch writing a hidden field is refused on its row",
358
+ not ok and "row 2" in str(res) and "row 1" not in str(res),
359
+ str(res)[:240])
360
+ listed = (hap(["worksheet", "record", "list", ws_id, "-a", app_id])
361
+ or {}).get("rows") or []
362
+ blob = json.dumps(listed, ensure_ascii=False)
363
+ check("hidden: the refused batch wrote nothing",
364
+ "batch-3" not in blob and "batch-1" in blob, blob[:200])
365
+ finally:
366
+ hap(["worksheet", "delete", ws_id, "-a", app_id, "-y"], check=False)
367
+
368
+
229
369
  def _items(app_id: str) -> dict[str, str]:
230
370
  """All sidebar items (worksheets, pages, chatbots) name -> id."""
231
371
  detail = hap(["app", "info", "-a", app_id])
@@ -3397,6 +3537,71 @@ def case_fb_subtable_read(app_id: str, section_id: str) -> None:
3397
3537
  hap(["worksheet", "delete", parent, "--yes"], check=False)
3398
3538
 
3399
3539
 
3540
+ def case_editor_inline_subtable(app_id: str, section_id: str) -> None:
3541
+ """Bug #455768: edit-spec field ops on an inline sub-table's own sheet."""
3542
+ print("\nscenario: editor field ops on an inline sub-table (#455768)")
3543
+ import json as _json
3544
+ name = "BUG455768-sub-parent"
3545
+ parent = _make_worksheet(app_id, section_id, name)
3546
+ check("inline-subtable: a throwaway parent was created", bool(parent))
3547
+ if not parent:
3548
+ return
3549
+ try:
3550
+ hap(["worksheet", "update-fields", parent, "--title-name", "名称",
3551
+ "--no-verify", "--fields", _json.dumps([
3552
+ {"type": "TEXT", "name": "名称"},
3553
+ {"type": "SUB_LIST", "name": "内嵌明细", "child_fields": [
3554
+ {"type": "TEXT", "name": "行名称"},
3555
+ {"type": "NUMBER", "name": "行数量"}]},
3556
+ ], ensure_ascii=False)], check=False)
3557
+ child = next((c.get("dataSource") for c in _fields(parent)
3558
+ if c.get("type") == 34), "")
3559
+ check("inline-subtable: the parent names its child sheet",
3560
+ bool(child), str(child))
3561
+ if not child:
3562
+ return
3563
+
3564
+ def _child_cols() -> list[dict]:
3565
+ got = hap(["worksheet", "fields", child, "--raw",
3566
+ "--parent", parent], check=False)
3567
+ return [c for c in got if len(c.get("controlId") or "") == 24] \
3568
+ if isinstance(got, list) else []
3569
+
3570
+ rc, out, err = editor_apply({"app": app_id, "ops": [
3571
+ {"type": "field.update", "worksheet": child, "field": "行名称",
3572
+ "set": {"hint": "按id改"}}]})
3573
+ check("inline-subtable: field.update by sheet id applies", rc == 0,
3574
+ (err or out)[-300:])
3575
+ cols = {c["controlName"]: c for c in _child_cols()}
3576
+ check("inline-subtable: the hint reads back",
3577
+ (cols.get("行名称") or {}).get("hint") == "按id改",
3578
+ str(cols.get("行名称"))[:200])
3579
+
3580
+ rc, out, err = editor_apply({"app": app_id, "ops": [
3581
+ {"type": "field.update", "worksheet": f"{name}/内嵌明细",
3582
+ "field": "行数量", "rename": "数量", "set": {}},
3583
+ {"type": "field.add", "worksheet": child,
3584
+ "field": {"name": "行备注", "type": "Text"}},
3585
+ {"type": "field.reorder", "worksheet": child,
3586
+ "order": ["行备注", "数量"]},
3587
+ {"type": "field.delete", "worksheet": child, "field": "行名称",
3588
+ "confirm": True}]})
3589
+ check("inline-subtable: add / reorder / delete apply", rc == 0,
3590
+ (err or out)[-300:])
3591
+ names = [c["controlName"] for c in
3592
+ sorted(_child_cols(), key=lambda c: c.get("row", 0))]
3593
+ check("inline-subtable: columns read back renamed, added, "
3594
+ "reordered and deleted", names == ["行备注", "数量"],
3595
+ str(names))
3596
+ sub = next((c for c in _fields(parent) if c.get("type") == 34), {})
3597
+ shown = {c["controlId"]: c["controlName"] for c in _child_cols()}
3598
+ check("inline-subtable: the new column is shown in the sub-table",
3599
+ [shown.get(i) for i in sub.get("showControls") or []]
3600
+ == ["行备注", "数量"], str(sub.get("showControls")))
3601
+ finally:
3602
+ hap(["worksheet", "delete", parent, "-a", app_id, "-y"], check=False)
3603
+
3604
+
3400
3605
  def case_fb_subgroups(app_id: str, section_id: str) -> None:
3401
3606
  """WO-FB 3.1: the editor can see worksheets in second-level groups."""
3402
3607
  print("\nscenario: sub-group visibility (WO-FB 3.1)")
@@ -4546,6 +4751,8 @@ _CASES = {
4546
4751
  "view": case_view,
4547
4752
  "role": case_role,
4548
4753
  "custom-action": case_custom_action,
4754
+ "custom-action-update": case_custom_action_update,
4755
+ "hidden-defaults": case_hidden_defaults,
4549
4756
  "chatbot": case_chatbot,
4550
4757
  "custom-page": case_custom_page,
4551
4758
  "component": case_component,
@@ -4585,6 +4792,7 @@ _CASES = {
4585
4792
  "fb-layout-check": case_fb_layout_check,
4586
4793
  "fb-pair-relation": case_fb_pair_relation,
4587
4794
  "fb-subtable-read": case_fb_subtable_read,
4795
+ "editor-inline-subtable": case_editor_inline_subtable,
4588
4796
  "fb-subgroups": case_fb_subgroups,
4589
4797
  "fb-button-target": case_fb_button_target,
4590
4798
  "g6-advanced-fields": case_g6_advanced_fields,
hap_cli/README.md CHANGED
@@ -283,6 +283,7 @@ discover every subcommand.
283
283
 
284
284
  | Command | Description |
285
285
  |---|---|
286
+ | `attachment download FILE_ID --worksheet-id WS --row-id ROW --control-id FIELD [-o PATH]` | Download a worksheet-record attachment with the same record and field permission checks as the web app; existing local files are never overwritten |
286
287
  | `attachment share [ADDRESS]` | Create a link to a stored file that you can pass on (`--hours`, default 48; `--file-id` to share by attachment id, `--short` for a landing page instead of the storage address) |
287
288
 
288
289
  > ADDRESS is the file's link — one that has already stopped working is fine, paste it as-is — or just the path part of it. The file itself does not expire, only the link does, so a dead link can always be revived.
hap_cli/README_CN.md CHANGED
@@ -262,6 +262,7 @@ hap --json worksheet record list WORKSHEET_ID
262
262
 
263
263
  | 命令 | 说明 |
264
264
  |---|---|
265
+ | `attachment download FILE_ID --worksheet-id WS --row-id ROW --control-id FIELD [-o PATH]` | 按网页端相同的记录和字段权限校验下载工作表记录附件;不会覆盖已有本地文件 |
265
266
  | `attachment share [ADDRESS]` | 为已存储的文件生成一条可以转给别人的链接(`--hours`,默认 48 小时;`--file-id` 按附件 ID 分享,`--short` 返回文件介绍页而非存储地址) |
266
267
 
267
268
  > ADDRESS 传文件的链接即可——**已经失效的链接照样能传,原样粘贴**——也可以只传路径部分。文件本身不会过期,过期的只是链接,所以失效链接随时可以重新生成。
hap_cli/__init__.py CHANGED
@@ -3,7 +3,7 @@
3
3
  import sys as _sys
4
4
  import types as _types
5
5
 
6
- __version__ = "0.9.0"
6
+ __version__ = "0.9.2"
7
7
 
8
8
  # The command tree used to live in hap_cli/hap_cli.py. A module named
9
9
  # after the package it sits in shadows that package: run python with the
@@ -1,5 +1,7 @@
1
1
  """CLI commands for files stored as attachments."""
2
2
 
3
+ from pathlib import Path
4
+
3
5
  import click
4
6
 
5
7
  from hap_cli.context import pass_context
@@ -55,7 +57,43 @@ def attachment_share(ctx, address, hours, file_id, short, display_name, size):
55
57
  ctx.handle_error(e)
56
58
 
57
59
 
60
+ @attachment.command("download")
61
+ @click.argument("file_id")
62
+ @click.option("--worksheet-id", required=True, help="Worksheet containing the record.")
63
+ @click.option("--row-id", required=True, help="Record containing the attachment.")
64
+ @click.option("--control-id", required=True, help="Attachment field containing the file.")
65
+ @click.option(
66
+ "--output", "-o", "output", type=click.Path(path_type=Path, dir_okay=False),
67
+ default=None, help="Save as this path. By default, uses the attachment name.",
68
+ )
69
+ @pass_context
70
+ def attachment_download(ctx, file_id, worksheet_id, row_id, control_id, output):
71
+ """Download a file attached to a worksheet record.
72
+
73
+ FILE_ID is listed in an attachment field or a record operation log.
74
+ Existing local files are never overwritten.
75
+ """
76
+ try:
77
+ session = ctx.get_session()
78
+ data = attachment_mod.download_attachment(
79
+ session,
80
+ file_id,
81
+ worksheet_id=worksheet_id,
82
+ row_id=row_id,
83
+ control_id=control_id,
84
+ output=output,
85
+ )
86
+ ctx.output(data, _download_human)
87
+ except Exception as e:
88
+ ctx.handle_error(e)
89
+
90
+
58
91
  def _human(d):
59
92
  click.echo(d["url"])
60
93
  if d.get("expiresAt"):
61
94
  click.echo(f"Usable until {d['expiresAt']}")
95
+
96
+
97
+ def _download_human(d):
98
+ click.echo(d["path"])
99
+ click.echo(f"{d['bytes']} bytes")
@@ -246,6 +246,7 @@ def chat_messages(
246
246
  page_index=page,
247
247
  page_size=num,
248
248
  category=category,
249
+ keyword=keyword,
249
250
  )
250
251
  if mark_read and category:
251
252
  chat_mod.mark_inbox_read(session, category)
@@ -1299,7 +1299,7 @@ def worksheet_save_button(ctx, worksheet_id, btn_config, action_spec,
1299
1299
  eff_app = app_id or getattr(session, "default_app_id", "") or ""
1300
1300
  data = ws_mod.create_custom_action(
1301
1301
  session, worksheet_id, json.loads(action_spec),
1302
- app_id=eff_app,
1302
+ app_id=eff_app, btn_id=btn_id,
1303
1303
  )
1304
1304
  else:
1305
1305
  btn_data = json.loads(btn_config)
@@ -22,10 +22,16 @@ rebuilds the one prefix that works.
22
22
  from __future__ import annotations
23
23
 
24
24
  import logging
25
+ import os
26
+ from pathlib import Path
27
+ import tempfile
25
28
  from typing import Any, Optional
26
- from urllib.parse import urlparse
29
+ from urllib.parse import urlencode, urlparse, urlunparse
30
+
31
+ import requests
27
32
 
28
33
  from hap_cli.core.session import APIError, Session, SessionError
34
+ from hap_cli.utils.parameter_mapping import parameter_mapping
29
35
 
30
36
  logger = logging.getLogger("hap_cli.attachment")
31
37
 
@@ -33,6 +39,212 @@ logger = logging.getLogger("hap_cli.attachment")
33
39
  DEFAULT_SHARE_HOURS = 48
34
40
 
35
41
 
42
+ def _same_server_download_headers(session: Session, url: str) -> dict[str, str]:
43
+ """Browser-equivalent auth for HAP-hosted downloads, never for a CDN."""
44
+ def _origin(address: str) -> Optional[tuple[str, str, int]]:
45
+ parsed = urlparse(address)
46
+ scheme = parsed.scheme.casefold()
47
+ if scheme not in {"http", "https"} or not parsed.hostname:
48
+ return None
49
+ port = parsed.port or (443 if scheme == "https" else 80)
50
+ return scheme, parsed.hostname.casefold(), port
51
+
52
+ target_origin = _origin(url)
53
+ matched_address = next(
54
+ (
55
+ candidate
56
+ for candidate in (session.login_url, session.server_url)
57
+ if candidate and _origin(candidate) == target_origin
58
+ ),
59
+ None,
60
+ )
61
+ if target_origin is None or matched_address is None:
62
+ return {}
63
+ origin_parsed = urlparse(matched_address)
64
+ origin = f"{origin_parsed.scheme}://{origin_parsed.netloc}"
65
+ headers = {
66
+ "Authorization": f"md_pss_id {session.auth_token}",
67
+ "Origin": origin,
68
+ "Referer": origin + "/",
69
+ "X-Requested-With": "XMLHttpRequest",
70
+ }
71
+ if session.account_id:
72
+ headers["AccountId"] = session.account_id
73
+ return headers
74
+
75
+
76
+ def _download_name(detail: dict[str, Any], file_id: str) -> str:
77
+ """Choose a safe local filename from attachment metadata."""
78
+ def _without_controls(value: Any) -> str:
79
+ return "".join(
80
+ char for char in str(value)
81
+ if ord(char) >= 32 and not 127 <= ord(char) <= 159
82
+ )
83
+
84
+ fallback = Path(_without_controls(file_id).replace("\\", "/")).name
85
+ if fallback in {"", ".", ".."}:
86
+ fallback = "attachment"
87
+ raw_name = _without_controls(
88
+ detail.get("originalFilename")
89
+ or detail.get("originalFileName")
90
+ or detail.get("fileName")
91
+ or fallback
92
+ )
93
+ name = Path(raw_name.replace("\\", "/")).name
94
+ if name in {"", ".", ".."}:
95
+ name = fallback
96
+ raw_ext = _without_controls(detail.get("fileExt") or detail.get("ext") or "")
97
+ ext = Path(raw_ext.replace("\\", "/")).name
98
+ if ext in {"", ".", ".."}:
99
+ ext = ""
100
+ if ext and not ext.startswith("."):
101
+ ext = "." + ext
102
+ if ext and not name.lower().endswith(ext.lower()):
103
+ name += ext
104
+ safe_name = Path(name.replace("\\", "/")).name
105
+ return safe_name if safe_name not in {"", ".", ".."} else fallback
106
+
107
+
108
+ @parameter_mapping("attachment.download.record-context")
109
+ def download_attachment(
110
+ session: Session,
111
+ file_id: str,
112
+ *,
113
+ worksheet_id: str,
114
+ row_id: str,
115
+ control_id: str,
116
+ output: Optional[Path] = None,
117
+ output_dir: Optional[Path] = None,
118
+ ) -> dict[str, Any]:
119
+ """Download one worksheet-record attachment to a new local file.
120
+
121
+ The web UI first calls ``Attachment/GetAttachmentDetail`` with the full
122
+ record context, then downloads its signed ``downloadUrl`` (MDPublic
123
+ ``src/pages/worksheet/controllers/record.js``
124
+ ``downloadAttachmentById``). Keeping those identifiers in the request
125
+ preserves the same record/field permission check as the UI.
126
+ """
127
+ if not file_id:
128
+ raise ValueError("file_id is required")
129
+ if not worksheet_id or not row_id or not control_id:
130
+ raise ValueError(
131
+ "worksheet_id, row_id, and control_id are required for a record attachment"
132
+ )
133
+
134
+ # Refuse before any network request when the caller named an existing path.
135
+ target = Path(output).expanduser() if output is not None else None
136
+ if target is not None and target.exists():
137
+ raise FileExistsError(f"Refusing to overwrite existing file: {target}")
138
+
139
+ detail = session.api_call(
140
+ "Attachment",
141
+ "GetAttachmentDetail",
142
+ {
143
+ "fileId": file_id,
144
+ "worksheetId": worksheet_id,
145
+ "rowId": row_id,
146
+ "controlId": control_id,
147
+ },
148
+ )
149
+ if not isinstance(detail, dict) or not detail.get("downloadUrl"):
150
+ raise APIError(
151
+ "The attachment has no downloadable address. Check that it still "
152
+ "exists and that you can download files from this record."
153
+ )
154
+
155
+ if target is None:
156
+ directory = Path(output_dir or Path.cwd()).expanduser().resolve()
157
+ target = directory / _download_name(detail, file_id)
158
+ target = target.resolve()
159
+ if target.exists():
160
+ raise FileExistsError(f"Refusing to overwrite existing file: {target}")
161
+ if not target.parent.is_dir():
162
+ raise FileNotFoundError(f"Output directory does not exist: {target.parent}")
163
+
164
+ url = str(detail["downloadUrl"])
165
+ parsed_download = urlparse(url)
166
+ log_query = urlencode({"controlId": control_id, "rowId": row_id})
167
+ url = urlunparse(parsed_download._replace(
168
+ query="&".join(part for part in (parsed_download.query, log_query) if part)
169
+ ))
170
+ candidates = [url]
171
+ private_url = str(detail.get("privateDownloadUrl") or "")
172
+ if private_url and private_url != url:
173
+ candidates.append(private_url)
174
+
175
+ response = None
176
+ for index, candidate in enumerate(candidates):
177
+ parsed = urlparse(candidate)
178
+ safe_url = urlunparse(parsed._replace(query="", fragment=""))
179
+ logger.info("HAP GET %s stream=true", safe_url)
180
+ download_headers = (
181
+ _same_server_download_headers(session, candidate)
182
+ if index == 0 else {}
183
+ )
184
+ request_kwargs: dict[str, Any] = {"stream": True, "timeout": 60}
185
+ if download_headers:
186
+ request_kwargs["headers"] = download_headers
187
+ response = requests.get(candidate, **request_kwargs)
188
+ logger.info(
189
+ "HAP GET %s -> %s content-length=%s",
190
+ safe_url,
191
+ response.status_code,
192
+ response.headers.get("Content-Length", ""),
193
+ )
194
+ try:
195
+ response.raise_for_status()
196
+ except requests.HTTPError:
197
+ response.close()
198
+ if response.status_code == 403 and index + 1 < len(candidates):
199
+ logger.warning(
200
+ "HAP download route refused the signed redirect; "
201
+ "retrying the private attachment URL",
202
+ )
203
+ continue
204
+ raise
205
+ break
206
+
207
+ if response is None: # pragma: no cover - candidates always has url
208
+ raise APIError("The attachment has no downloadable address.")
209
+
210
+ written = 0
211
+ temp_path: Optional[Path] = None
212
+ try:
213
+ fd, temp_name = tempfile.mkstemp(
214
+ dir=target.parent,
215
+ prefix=f".{target.name}.",
216
+ suffix=".part",
217
+ )
218
+ temp_path = Path(temp_name)
219
+ with os.fdopen(fd, "wb") as handle:
220
+ for chunk in response.iter_content(chunk_size=1024 * 1024):
221
+ if chunk:
222
+ handle.write(chunk)
223
+ written += len(chunk)
224
+ handle.flush()
225
+ os.fsync(handle.fileno())
226
+
227
+ # Hard-linking within the same directory publishes the fully-written
228
+ # file atomically and fails instead of replacing a path that appeared
229
+ # during the download.
230
+ os.link(temp_path, target)
231
+ temp_path.unlink()
232
+ temp_path = None
233
+ except BaseException:
234
+ if temp_path is not None and temp_path.exists():
235
+ temp_path.unlink()
236
+ raise
237
+ finally:
238
+ response.close()
239
+
240
+ return {
241
+ "fileId": file_id,
242
+ "name": target.name,
243
+ "path": str(target),
244
+ "bytes": written,
245
+ }
246
+
247
+
36
248
  def store_key(address: str) -> str:
37
249
  """Reduce any form of a stored file's address to its store key.
38
250