papersearch 0.4.6 → 0.4.8
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.
- package/.env.example +3 -0
- package/README.en.md +36 -12
- package/README.md +36 -12
- package/assets/logo.svg +15 -0
- package/assets/overview.en.png +0 -0
- package/assets/overview.png +0 -0
- package/assets/progress-capsule.en.png +0 -0
- package/assets/progress-capsule.png +0 -0
- package/carsi/paper_search_carsi/assets/capsule.html +23 -6
- package/carsi/paper_search_carsi/assets/icon-32.png +0 -0
- package/carsi/paper_search_carsi/assets/icon-512.png +0 -0
- package/carsi/paper_search_carsi/assets/icon-64.png +0 -0
- package/carsi/paper_search_carsi/assets/icon.svg +13 -16
- package/carsi/paper_search_carsi/assets/quiet-browser/api.js +24 -1
- package/carsi/paper_search_carsi/cli.py +27 -0
- package/carsi/paper_search_carsi/engine/batch.py +5 -1
- package/carsi/paper_search_carsi/engine/batch_diagnostics.py +50 -35
- package/carsi/paper_search_carsi/engine/batch_login.py +10 -6
- package/carsi/paper_search_carsi/engine/batch_waits.py +13 -2
- package/carsi/paper_search_carsi/engine/bridge.py +5 -0
- package/carsi/paper_search_carsi/engine/page_activity.py +14 -0
- package/carsi/paper_search_carsi/failure_export.py +239 -0
- package/carsi/paper_search_carsi/issues.py +8 -6
- package/carsi/paper_search_carsi/page_snapshot.py +64 -0
- package/carsi/paper_search_carsi/progress_view.py +7 -6
- package/carsi/paper_search_carsi/report_sanitizer.py +248 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
- package/dist/cli.js +56 -5
- package/dist/cli.js.map +1 -1
- package/dist/config/ConfigService.d.ts +1 -1
- package/dist/config/ConfigService.d.ts.map +1 -1
- package/dist/config/ConfigService.js +1 -0
- package/dist/config/ConfigService.js.map +1 -1
- package/dist/management/failures/exportReport.d.ts +20 -0
- package/dist/management/failures/exportReport.d.ts.map +1 -0
- package/dist/management/failures/exportReport.js +73 -0
- package/dist/management/failures/exportReport.js.map +1 -0
- package/dist/management/failures/index.d.ts +20 -0
- package/dist/management/failures/index.d.ts.map +1 -1
- package/dist/management/failures/index.js +69 -43
- package/dist/management/failures/index.js.map +1 -1
- package/dist/management/updates/index.d.ts +37 -0
- package/dist/management/updates/index.d.ts.map +1 -0
- package/dist/management/updates/index.js +185 -0
- package/dist/management/updates/index.js.map +1 -0
- package/package.json +2 -1
- package/skills/paper-search/SKILL.md +3 -1
- package/skills/paper-search/references/browser-download.md +17 -4
- package/skills/paper-search/references/carsi-setup.md +1 -1
- package/skills/paper-search/references/cli-contract.md +2 -1
- package/skills/paper-search/references/management-layer.md +8 -0
|
@@ -80,20 +80,29 @@ class DiagnosticsMixin:
|
|
|
80
80
|
"article_open", "institution_federation_selected", "article_access_ready",
|
|
81
81
|
"pdf_capture_started", "browser_pdf_response_captured", "pdf_saved",
|
|
82
82
|
"supplements_found", "supplements_saved", "challenge_resolved",
|
|
83
|
+
# The login steps the program takes itself: while it is still
|
|
84
|
+
# choosing the school the page is not waiting for the user (JBJS on
|
|
85
|
+
# OpenAthens, 2026-11-06: five remembered-school clicks in 25 s, no
|
|
86
|
+
# main-frame navigation, and a "no progress" reminder in between).
|
|
87
|
+
"sso_entry_clicked", "openathens_entry", "seamlessaccess_chooser_opened",
|
|
88
|
+
"auto_remembered_entry", "institution_selected", "auto_institution_search",
|
|
89
|
+
"institution_search_submitted", "institution_search_retyped",
|
|
90
|
+
"institution_list_submitted", "institution_continue",
|
|
91
|
+
"login_round_trip_returned", "redirect_page_passed",
|
|
83
92
|
}:
|
|
84
93
|
activity.progress()
|
|
85
94
|
# Only publish fixed phase text; event details can contain signed URLs.
|
|
86
95
|
report = {
|
|
87
96
|
"article_open": ("打开论文页面", "opening_article"),
|
|
88
|
-
"sso_start": ("
|
|
89
|
-
"institution_federation_selected": ("已进入所选机构认证联盟", "
|
|
90
|
-
"institution_selection_required": ("
|
|
91
|
-
"institution_entry_unresolved": ("官方机构入口尚未确认 CARSI", "
|
|
92
|
-
"login_state": ("
|
|
97
|
+
"sso_start": ("正在查找机构登录入口", "checking_access"),
|
|
98
|
+
"institution_federation_selected": ("已进入所选机构认证联盟", "checking_access"),
|
|
99
|
+
"institution_selection_required": ("检查学校选择入口", "checking_access"),
|
|
100
|
+
"institution_entry_unresolved": ("官方机构入口尚未确认 CARSI", "checking_access"),
|
|
101
|
+
"login_state": ("检查机构登录页面", "checking_access"),
|
|
93
102
|
"idp_confirmation_required": ("请在浏览器里确认学校认证页的提示(信息发送同意、使用条款或二次验证)", "waiting_login"),
|
|
94
|
-
"login_attempt_started": ("正在尝试机构登录", "
|
|
95
|
-
"login_retry_wait": ("机构登录暂未完成,准备重试", "
|
|
96
|
-
"login_navigation_interrupted": ("登录跳转中断,检查是否可重试", "
|
|
103
|
+
"login_attempt_started": ("正在尝试机构登录", "checking_access"),
|
|
104
|
+
"login_retry_wait": ("机构登录暂未完成,准备重试", "checking_access"),
|
|
105
|
+
"login_navigation_interrupted": ("登录跳转中断,检查是否可重试", "checking_access"),
|
|
97
106
|
"login_stopped": ("机构登录未完成", "route_failed"),
|
|
98
107
|
"challenge_manual_wait": ("等待人工安全验证", "waiting_verification"),
|
|
99
108
|
"challenge_wait": ("正在检查安全验证", "checking_access"),
|
|
@@ -106,17 +115,19 @@ class DiagnosticsMixin:
|
|
|
106
115
|
"browser_pdf_response_captured": ("PDF 已捕获,正在保存", "pdf_captured"),
|
|
107
116
|
"pdf_saved": ("PDF 已保存,待内容核验", "saved_pending_verification"),
|
|
108
117
|
}.get(state)
|
|
118
|
+
if state == "login_state" and getattr(result, "_login_attention", ""):
|
|
119
|
+
report = ("等待在浏览器完成机构登录", "waiting_login")
|
|
109
120
|
if state == "challenge_wait" and detail.startswith("manual "):
|
|
110
121
|
report = ("等待人工安全验证", "waiting_verification")
|
|
111
122
|
if state == "login_attempt_started" and detail in {"1/3", "2/3", "3/3"}:
|
|
112
|
-
report = (f"机构登录:第 {detail[0]} 次尝试,共 3 次", "
|
|
123
|
+
report = (f"机构登录:第 {detail[0]} 次尝试,共 3 次", "checking_access")
|
|
113
124
|
if state == "login_observed":
|
|
114
125
|
if detail == "verification":
|
|
115
126
|
report = ("正在检查安全验证", "checking_access")
|
|
116
127
|
elif detail == "human_login":
|
|
117
128
|
report = ("等待在浏览器完成机构登录", "waiting_login")
|
|
118
129
|
else:
|
|
119
|
-
report = ("检查机构登录页面", "
|
|
130
|
+
report = ("检查机构登录页面", "checking_access")
|
|
120
131
|
# A click can finish after a synchronous PDF response was captured;
|
|
121
132
|
# capture_started supplies its stage without moving it backwards.
|
|
122
133
|
if report:
|
|
@@ -153,7 +164,12 @@ class DiagnosticsMixin:
|
|
|
153
164
|
def _snapshot(self, page: Any, result: DownloadResult | None, why: str) -> None:
|
|
154
165
|
"""The page's URL and title, and a small picture of the window with every
|
|
155
166
|
form field masked (never their values), in the article's diagnostics folder."""
|
|
156
|
-
|
|
167
|
+
from ..browser import watchdog
|
|
168
|
+
if watchdog.fired:
|
|
169
|
+
return
|
|
170
|
+
if (result is None or len(result.snapshots) >= self.MAX_SNAPSHOTS
|
|
171
|
+
or (self.config.get("supplements") == "with" and len(result.snapshots) >= self.MAX_SNAPSHOTS - 1
|
|
172
|
+
and not why.startswith("supplements"))):
|
|
157
173
|
return
|
|
158
174
|
url = str(getattr(page, "url", "") or "")
|
|
159
175
|
entry = {"at": datetime.now().strftime("%H:%M:%S"), "why": why, "url": url[:500],
|
|
@@ -162,13 +178,9 @@ class DiagnosticsMixin:
|
|
|
162
178
|
if run_dir is not None:
|
|
163
179
|
folder = Path(run_dir) / "diagnostics" / safe_name(result.doi)
|
|
164
180
|
path = folder / f"snapshot-{len(result.snapshots) + 1}-{re.sub(r'[^a-z0-9]+', '-', why.lower())[:40]}.jpg"
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
mask=[page.locator("input, textarea, select")])
|
|
169
|
-
entry["screenshot"] = str(path)
|
|
170
|
-
except Exception:
|
|
171
|
-
pass # the URL and title are kept
|
|
181
|
+
from ..page_snapshot import capture_structure, masked_screenshot
|
|
182
|
+
entry.update(capture_structure(page, path.with_suffix(".html"), self.config))
|
|
183
|
+
entry.update(masked_screenshot(page, path))
|
|
172
184
|
result.snapshots.append(entry)
|
|
173
185
|
self._event(result, "snapshot", f"{why} | {url[:160]} | {entry['title'][:80]}")
|
|
174
186
|
|
|
@@ -176,9 +188,10 @@ class DiagnosticsMixin:
|
|
|
176
188
|
"""A successful article keeps its snapshots' URLs and titles, not their
|
|
177
189
|
pictures (the live preview's frames go the same way)."""
|
|
178
190
|
for entry in result.snapshots:
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
191
|
+
for key in ("screenshot", "html"):
|
|
192
|
+
artifact = entry.pop(key, None)
|
|
193
|
+
if artifact:
|
|
194
|
+
Path(artifact).unlink(missing_ok=True)
|
|
182
195
|
|
|
183
196
|
def _note_wait(self, result: DownloadResult | None, what: str, started: float, why: str) -> None:
|
|
184
197
|
"""A wait of more than ``LONG_WAIT_SEC``: what it waited for and why it ended."""
|
|
@@ -197,6 +210,8 @@ class DiagnosticsMixin:
|
|
|
197
210
|
# Persist fixed classifications, without changing the live workflow state.
|
|
198
211
|
packet = serialize_download_result({**asdict(result),
|
|
199
212
|
"final_url": getattr(page, "url", result.final_url)}, diagnostic=True)
|
|
213
|
+
import platform
|
|
214
|
+
packet["capture_system"] = platform.system()
|
|
200
215
|
packet["adapter"] = type(self.adapter).__name__
|
|
201
216
|
packet["browser"] = getattr(self, "browser", {})
|
|
202
217
|
from ..browser import watchdog
|
|
@@ -210,22 +225,22 @@ class DiagnosticsMixin:
|
|
|
210
225
|
except Exception as exc:
|
|
211
226
|
packet["access_state"], packet["access_evidence"] = "unknown", [f"probe failed: {type(exc).__name__}"]
|
|
212
227
|
packet_path = diag_dir / "diagnostic.json"
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
page.screenshot(path=str(diag_dir / "screenshot.png"), full_page=True)
|
|
217
|
-
except Exception:
|
|
218
|
-
pass
|
|
219
|
-
# Other tabs (a PDF or verification tab) are where the problem usually is.
|
|
228
|
+
if not stopped and result.reason != "publisher_access_blocked":
|
|
229
|
+
from ..page_snapshot import capture_structure, masked_screenshot
|
|
230
|
+
pages = []
|
|
220
231
|
try:
|
|
221
|
-
|
|
232
|
+
pages = [p for p in list(page.context.pages) if p is not page and not p.is_closed()][:2]
|
|
222
233
|
except Exception:
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
234
|
+
pass # The working page is still captured; no other tab is known.
|
|
235
|
+
packet["pages"] = []
|
|
236
|
+
for index, tab in enumerate([page] + pages):
|
|
237
|
+
stem = "screenshot" if index == 0 else f"screenshot-tab{index}"
|
|
238
|
+
row = {"url": str(getattr(tab, "url", "") or ""), "title": self._title(tab)[:200], "why": "download failed"}
|
|
239
|
+
row.update(capture_structure(tab, diag_dir / f"{stem}.html", self.config))
|
|
240
|
+
if self.adapter.diagnostic_screenshots:
|
|
241
|
+
row.update(masked_screenshot(tab, diag_dir / f"{stem}.png"))
|
|
242
|
+
packet["pages"].append(row)
|
|
243
|
+
packet_path.write_text(json.dumps(packet, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
229
244
|
result.diagnostic_path = str(packet_path)
|
|
230
245
|
|
|
231
246
|
def _denial_line(self, page: Any) -> str:
|
|
@@ -1281,12 +1281,16 @@ class LoginMixin:
|
|
|
1281
1281
|
and not self._personal_login_box(page, url))
|
|
1282
1282
|
|
|
1283
1283
|
def _personal_login_box(self, page: Any, url: str) -> bool:
|
|
1284
|
-
"""
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
return
|
|
1289
|
-
|
|
1284
|
+
"""A publisher account form can be on an article, login page or SSO host.
|
|
1285
|
+
|
|
1286
|
+
An untouched form next to a separate institutional entry is not the
|
|
1287
|
+
school's credentials step. Preserve a known IdP and any form the user
|
|
1288
|
+
is already filling; return only field presence/activity, never values.
|
|
1289
|
+
"""
|
|
1290
|
+
if self._is_idp_host(urlparse(url).netloc) or self._has_visible_editable_input(page):
|
|
1291
|
+
return False
|
|
1292
|
+
return ((self._on_publisher_host(url) and self._is_success_article_url(url) and not self._is_auth_page(url))
|
|
1293
|
+
or isinstance(page.evaluate(self._INSTITUTION_ENTRY_JS), dict))
|
|
1290
1294
|
|
|
1291
1295
|
def _follow_federated_login_option(self, page: Any, result: DownloadResult) -> bool:
|
|
1292
1296
|
"""The publisher's login page offers an institutional option next to the
|
|
@@ -187,12 +187,12 @@ class UserWaitMixin:
|
|
|
187
187
|
self._raise_on_publisher_access_blocked(tab)
|
|
188
188
|
result._attention_page = tab
|
|
189
189
|
activity.observe(tab)
|
|
190
|
-
activity.check()
|
|
191
190
|
if not automatic:
|
|
192
191
|
deadline = min(deadline, self._wait_deadline(result))
|
|
193
192
|
if not manual and self._automatic_challenge_step(tab, result, automatic, deadline):
|
|
194
193
|
page.wait_for_timeout(min(1000, max(0, (deadline - time.time()) * 1000)))
|
|
195
194
|
continue
|
|
195
|
+
activity.automatic_for(0)
|
|
196
196
|
result._attention_page = tab
|
|
197
197
|
if state != shown:
|
|
198
198
|
if state in ("verification", "login"):
|
|
@@ -236,6 +236,7 @@ class UserWaitMixin:
|
|
|
236
236
|
self._event(result, "ip_blocked_response", f"{suspect} | no PDF after waiting ({shown or 'nothing shown'})")
|
|
237
237
|
return False
|
|
238
238
|
finally:
|
|
239
|
+
activity.automatic_for(0)
|
|
239
240
|
result._attention_page = None
|
|
240
241
|
if activity_owned:
|
|
241
242
|
activity.close()
|
|
@@ -386,6 +387,11 @@ class UserWaitMixin:
|
|
|
386
387
|
bound = min(deadline, now + remaining) if remaining is not None else deadline
|
|
387
388
|
attempt["automatic_end"] = bound - manual_reserve
|
|
388
389
|
automatic_end = min(deadline - manual_reserve, attempt["automatic_end"])
|
|
390
|
+
activity = getattr(result, "_page_activity", None)
|
|
391
|
+
if activity is not None:
|
|
392
|
+
# The separate request watcher also checks idle time during these
|
|
393
|
+
# RPCs. Use the frozen automatic bound; never renew the wait budget.
|
|
394
|
+
activity.automatic_for(automatic_end - now)
|
|
389
395
|
if now >= automatic_end or (attempt["attempts"] >= 3 and now >= attempt["retry_at"]):
|
|
390
396
|
return False
|
|
391
397
|
if challenge_interaction.needs_manual_verification(page):
|
|
@@ -403,6 +409,8 @@ class UserWaitMixin:
|
|
|
403
409
|
if outcome != "absent":
|
|
404
410
|
attempt["attempts"] += 1
|
|
405
411
|
attempt["retry_at"] = time.time() + 3
|
|
412
|
+
if outcome == "clicked" and activity is not None:
|
|
413
|
+
activity.progress(page)
|
|
406
414
|
self._event(result, "challenge_interaction",
|
|
407
415
|
f"checkbox {outcome}; attempt {attempt['attempts']}/3; awaiting verification")
|
|
408
416
|
return time.time() < automatic_end
|
|
@@ -440,8 +448,10 @@ class UserWaitMixin:
|
|
|
440
448
|
if time.time() >= deadline:
|
|
441
449
|
break
|
|
442
450
|
result._attention_page = page
|
|
443
|
-
activity.check()
|
|
444
451
|
auto_pending = not manual and self._automatic_challenge_step(page, result, automatic, deadline)
|
|
452
|
+
if not auto_pending:
|
|
453
|
+
activity.automatic_for(0)
|
|
454
|
+
activity.check()
|
|
445
455
|
if not auto_pending and not manual:
|
|
446
456
|
result._attention_page = page
|
|
447
457
|
interaction.enter_context(watchdog.pause_operation())
|
|
@@ -478,6 +488,7 @@ class UserWaitMixin:
|
|
|
478
488
|
self._wait_ran_out(result)
|
|
479
489
|
return passed
|
|
480
490
|
finally:
|
|
491
|
+
activity.automatic_for(0)
|
|
481
492
|
if verification_wait is not None:
|
|
482
493
|
excluded = max(0, verification_wait.close() - verification_deadline)
|
|
483
494
|
outer_wait = getattr(result, "_login_wait", None)
|
|
@@ -565,6 +565,10 @@ def _try_browser_batch_download(
|
|
|
565
565
|
manifest.write_text(json.dumps({"doi": doi, "files": result.supplements},
|
|
566
566
|
ensure_ascii=False, indent=2), encoding="utf-8")
|
|
567
567
|
result.record_path = str(manifest)
|
|
568
|
+
if ((result.ok and result.verified_match) or supplements_mode == "only") and all(
|
|
569
|
+
f.get("status") == "saved" for f in result.supplements
|
|
570
|
+
):
|
|
571
|
+
downloader._drop_snapshot_pictures(result)
|
|
568
572
|
_note_supplements(result, written)
|
|
569
573
|
finally:
|
|
570
574
|
try:
|
|
@@ -639,6 +643,7 @@ def _note_supplements(result: Any, written: int) -> None:
|
|
|
639
643
|
data = json.loads(path.read_text(encoding="utf-8"))
|
|
640
644
|
data["events"] = list(data.get("events") or []) + list(getattr(result, "events", [])[written:])
|
|
641
645
|
data["supplements"] = getattr(result, "supplements", [])
|
|
646
|
+
data["snapshots"] = getattr(result, "snapshots", [])
|
|
642
647
|
data["pdf_path"] = str(getattr(result, "pdf_path", "") or "")
|
|
643
648
|
if getattr(result, "phases", None):
|
|
644
649
|
data["phases"] = {k: round(float(v), 1) for k, v in result.phases.items()}
|
|
@@ -29,6 +29,7 @@ class PageActivity:
|
|
|
29
29
|
self._doi = doi
|
|
30
30
|
self._shown = False
|
|
31
31
|
self._transfers = 0
|
|
32
|
+
self._automatic_until = 0.0
|
|
32
33
|
self.closed = False
|
|
33
34
|
self.page = None
|
|
34
35
|
self._pages: dict[int, tuple[Any, dict]] = {}
|
|
@@ -48,6 +49,18 @@ class PageActivity:
|
|
|
48
49
|
progress_reporter.clear_attention(self._key)
|
|
49
50
|
self._shown = False
|
|
50
51
|
|
|
52
|
+
def automatic_for(self, seconds: float) -> None:
|
|
53
|
+
"""Defer idle reminders until the caller's existing automatic deadline.
|
|
54
|
+
|
|
55
|
+
This is a finite lease, not progress: polling must pass only the time
|
|
56
|
+
remaining on the original bound. Zero releases it at manual handoff.
|
|
57
|
+
The watcher can still remind if the browser call never returns.
|
|
58
|
+
"""
|
|
59
|
+
with self._lock:
|
|
60
|
+
self._automatic_until = self._clock() + max(0.0, seconds)
|
|
61
|
+
if seconds > 0:
|
|
62
|
+
self._clear()
|
|
63
|
+
|
|
51
64
|
def check(self) -> None:
|
|
52
65
|
"""Thread safe; never inspect a page or interrupt an in-flight operation."""
|
|
53
66
|
with self._lock:
|
|
@@ -59,6 +72,7 @@ class PageActivity:
|
|
|
59
72
|
self._last_progress = self._clock()
|
|
60
73
|
self._clear()
|
|
61
74
|
elif (not self._shown and not self._transfers
|
|
75
|
+
and self._clock() >= self._automatic_until
|
|
62
76
|
and not self._navigation_loading()
|
|
63
77
|
and self._clock() - self._last_progress >= self.after):
|
|
64
78
|
progress_reporter.set_attention(
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
"""Offline failure packet export. Never opens a browser or modifies evidence."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import platform
|
|
8
|
+
import re
|
|
9
|
+
import tempfile
|
|
10
|
+
import zipfile
|
|
11
|
+
from datetime import datetime, timezone
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from .report_sanitizer import MAX_HTML_BYTES, Redactor, sanitize_html
|
|
15
|
+
|
|
16
|
+
MAX_REQUEST_BYTES = 8 * 1024 * 1024
|
|
17
|
+
MAX_JSON_BYTES = 4 * 1024 * 1024
|
|
18
|
+
MAX_IMAGE_BYTES = 2 * 1024 * 1024
|
|
19
|
+
MAX_PACKAGE_BYTES = 64 * 1024 * 1024
|
|
20
|
+
MAX_PAPERS = 100
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ExportError(ValueError):
|
|
24
|
+
"""Stable public error code; never includes original contents/paths."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _read(path: Path, limit: int) -> bytes:
|
|
28
|
+
if path.is_symlink() or not path.is_file():
|
|
29
|
+
raise ExportError('missing_or_unsafe_file')
|
|
30
|
+
with path.open('rb') as handle:
|
|
31
|
+
data = handle.read(limit + 1)
|
|
32
|
+
if len(data) > limit:
|
|
33
|
+
raise ExportError('file_size_limit')
|
|
34
|
+
return data
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _artifact(root: Path, raw: str, limit: int) -> bytes:
|
|
38
|
+
path = Path(raw)
|
|
39
|
+
if not path.is_absolute():
|
|
40
|
+
path = root / path
|
|
41
|
+
# No symlinks or traversal out of the diagnostic directory. We never glob
|
|
42
|
+
# a download directory (which can contain PDFs, cookies and profiles).
|
|
43
|
+
try:
|
|
44
|
+
relative = path.absolute().relative_to(root.absolute())
|
|
45
|
+
if '..' in relative.parts:
|
|
46
|
+
raise ValueError()
|
|
47
|
+
current = root
|
|
48
|
+
for part in relative.parts:
|
|
49
|
+
current = current / part
|
|
50
|
+
if current.is_symlink():
|
|
51
|
+
raise ValueError()
|
|
52
|
+
path.resolve().relative_to(root.resolve())
|
|
53
|
+
except ValueError:
|
|
54
|
+
raise ExportError('unsafe_artifact_path') from None
|
|
55
|
+
return _read(path, limit)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _load_record(row: dict) -> tuple[dict, Path | None, str | None]:
|
|
59
|
+
source = row.get('diagnostic') or row.get('record')
|
|
60
|
+
if not isinstance(source, str) or not source:
|
|
61
|
+
return row.get('detail') or {}, None, 'diagnostic_missing; ledger_only'
|
|
62
|
+
path = Path(source)
|
|
63
|
+
try:
|
|
64
|
+
data = json.loads(_read(path, MAX_JSON_BYTES))
|
|
65
|
+
if not isinstance(data, dict) or str(data.get('doi') or data.get('raw_doi') or '').lower() != row['doi'].lower():
|
|
66
|
+
raise ExportError('diagnostic_identity_mismatch')
|
|
67
|
+
if any(key in data and not isinstance(data[key], list) for key in ('events', 'snapshots', 'pages')):
|
|
68
|
+
raise ExportError('invalid_diagnostic_shape')
|
|
69
|
+
return data, path.parent, None
|
|
70
|
+
except (OSError, ValueError) as exc:
|
|
71
|
+
reason = str(exc) if isinstance(exc, ExportError) else 'diagnostic_unreadable'
|
|
72
|
+
return row.get('detail') or {}, None, reason + '; ledger_only'
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def export_report(request: dict, output: Path, config: dict | None = None) -> dict:
|
|
76
|
+
if request.get('schemaVersion') != 1 or not isinstance(request.get('papers'), list):
|
|
77
|
+
raise ExportError('invalid_export_request')
|
|
78
|
+
rows = request['papers']
|
|
79
|
+
if not rows:
|
|
80
|
+
raise ExportError('no_matching_failures')
|
|
81
|
+
if len(rows) > MAX_PAPERS:
|
|
82
|
+
raise ExportError('too_many_failures; select_a_run_or_doi; limit=100')
|
|
83
|
+
if any(not isinstance(row, dict) or not isinstance(row.get('doi'), str)
|
|
84
|
+
or ('detail' in row and not isinstance(row['detail'], dict)) for row in rows):
|
|
85
|
+
raise ExportError('invalid_export_request')
|
|
86
|
+
if output.suffix.lower() != '.zip':
|
|
87
|
+
raise ExportError('export_path_must_end_in_zip')
|
|
88
|
+
if output.exists() or output.is_symlink():
|
|
89
|
+
raise ExportError('export_target_exists')
|
|
90
|
+
redactor = Redactor(config)
|
|
91
|
+
loaded = []
|
|
92
|
+
total_input = 0
|
|
93
|
+
for row in rows:
|
|
94
|
+
data, root, problem = _load_record(row)
|
|
95
|
+
total_input += len(json.dumps(data, ensure_ascii=False).encode('utf-8'))
|
|
96
|
+
if total_input > MAX_PACKAGE_BYTES:
|
|
97
|
+
raise ExportError('source_size_limit; select_a_run_or_doi')
|
|
98
|
+
loaded.append((row, data, root, problem))
|
|
99
|
+
redactor.observe(row)
|
|
100
|
+
redactor.observe(data)
|
|
101
|
+
manifest = {
|
|
102
|
+
'schemaVersion': 1, 'createdAt': datetime.now(timezone.utc).isoformat(),
|
|
103
|
+
'version': redactor.text(str(request.get('version') or 'unknown')),
|
|
104
|
+
'exportSystem': platform.system(),
|
|
105
|
+
'reviewRequired': True, 'papers': [], 'files': [],
|
|
106
|
+
'limits': {'papers': MAX_PAPERS, 'htmlBytes': MAX_HTML_BYTES,
|
|
107
|
+
'imageBytes': MAX_IMAGE_BYTES, 'packageBytes': MAX_PACKAGE_BYTES},
|
|
108
|
+
}
|
|
109
|
+
output = output.expanduser().absolute()
|
|
110
|
+
output.parent.mkdir(parents=True, exist_ok=True)
|
|
111
|
+
fd, temp = tempfile.mkstemp(prefix='.papersearch-report-', suffix='.zip', dir=output.parent)
|
|
112
|
+
os.close(fd)
|
|
113
|
+
total = 0
|
|
114
|
+
try:
|
|
115
|
+
with zipfile.ZipFile(temp, 'w', compression=zipfile.ZIP_DEFLATED) as archive:
|
|
116
|
+
def add(name: str, content: bytes) -> None:
|
|
117
|
+
nonlocal total
|
|
118
|
+
total += len(content)
|
|
119
|
+
if total > MAX_PACKAGE_BYTES:
|
|
120
|
+
raise ExportError('package_size_limit; select_a_run_or_doi')
|
|
121
|
+
archive.writestr(name, content)
|
|
122
|
+
manifest['files'].append({'path': name, 'bytes': len(content),
|
|
123
|
+
'sha256': hashlib.sha256(content).hexdigest()})
|
|
124
|
+
|
|
125
|
+
for i, (row, data, root, problem) in enumerate(loaded, 1):
|
|
126
|
+
folder = f'papers/{i:03d}' # no DOI/path/user content in archive paths
|
|
127
|
+
paper = redactor.clean({k: row.get(k) for k in
|
|
128
|
+
('doi', 'runId', 'publisher', 'failureClass', 'code', 'part', 'stoppedAt', 'evidence')})
|
|
129
|
+
paper.update(folder=folder, materials=[], omitted=[])
|
|
130
|
+
if not paper.get('stoppedAt'):
|
|
131
|
+
steps = [e for e in data.get('events', []) if isinstance(e, dict) and e.get('state')
|
|
132
|
+
and e['state'] not in {'snapshot', 'wait', 'publisher_session_saved'}]
|
|
133
|
+
paper['stoppedAt'] = redactor.text(str(steps[-1]['state'] if steps else data.get('state') or row.get('code') or 'unknown'))
|
|
134
|
+
paper['finalUrl'] = redactor.text(str(data.get('final_url') or data.get('article_url') or 'unknown'))
|
|
135
|
+
paper['captureSystem'] = redactor.clean(data.get('capture_system') or 'unknown (legacy record)')
|
|
136
|
+
paper['captureVersion'] = redactor.clean(data.get('capture_version') or 'unknown (legacy record)')
|
|
137
|
+
if problem:
|
|
138
|
+
paper['omitted'].append(problem)
|
|
139
|
+
clean = redactor.clean(data)
|
|
140
|
+
add(folder + '/diagnostic.json', _json(clean))
|
|
141
|
+
# Ledger provides the caller's attachment outcome even when the
|
|
142
|
+
# backend's original record pre-dates the supplementary step.
|
|
143
|
+
add(folder + '/outcome.json', _json(redactor.clean(row.get('outcome') or {})))
|
|
144
|
+
pages = [p for key in ('snapshots', 'pages') for p in (data.get(key) or []) if isinstance(p, dict)]
|
|
145
|
+
if len(pages) > 8:
|
|
146
|
+
paper['omitted'].append('page_count_limit')
|
|
147
|
+
for number, page in enumerate(pages[:8], 1):
|
|
148
|
+
for kind, limit, suffix in (('html', MAX_HTML_BYTES, '.html'), ('screenshot', MAX_IMAGE_BYTES, '.png')):
|
|
149
|
+
source = page.get(kind)
|
|
150
|
+
if not source or root is None:
|
|
151
|
+
if page.get(kind + '_omitted'):
|
|
152
|
+
paper['omitted'].append(f'page{number}/{kind}: capture_unavailable')
|
|
153
|
+
continue
|
|
154
|
+
if kind == 'screenshot':
|
|
155
|
+
if (page.get('screenshot_masked') is not True or page.get('screenshot_private') is True
|
|
156
|
+
or page.get('html_omitted') or redactor.private_page(
|
|
157
|
+
str(page.get('url') or ''), str(page.get('title') or ''), str(page.get('why') or '')
|
|
158
|
+
)):
|
|
159
|
+
paper['omitted'].append(f'page{number}/screenshot: login_school_or_unverified_origin')
|
|
160
|
+
continue
|
|
161
|
+
try:
|
|
162
|
+
content = _artifact(root, str(source), limit)
|
|
163
|
+
if kind == 'html':
|
|
164
|
+
content, truncated = sanitize_html(content.decode('utf-8'), redactor)
|
|
165
|
+
content = content.encode('utf-8')
|
|
166
|
+
if truncated or page.get('html_truncated'):
|
|
167
|
+
paper['omitted'].append(f'page{number}/html: truncated')
|
|
168
|
+
else:
|
|
169
|
+
if content.startswith(b'\x89PNG\r\n\x1a\n'):
|
|
170
|
+
suffix = '.png'
|
|
171
|
+
elif content.startswith(b'\xff\xd8\xff'):
|
|
172
|
+
suffix = '.jpg'
|
|
173
|
+
else:
|
|
174
|
+
raise ExportError('invalid_image')
|
|
175
|
+
name = f'{folder}/pages/{number:02d}{suffix}'
|
|
176
|
+
add(name, content)
|
|
177
|
+
paper['materials'].append({'path': name, 'kind': kind,
|
|
178
|
+
'url': redactor.text(str(page.get('url') or '')),
|
|
179
|
+
'why': redactor.text(str(page.get('why') or ''))})
|
|
180
|
+
except (OSError, ValueError, UnicodeError) as exc:
|
|
181
|
+
if isinstance(exc, ExportError) and str(exc).startswith('package_size_limit'):
|
|
182
|
+
raise
|
|
183
|
+
code = str(exc) if isinstance(exc, ExportError) else 'artifact_unreadable'
|
|
184
|
+
paper['omitted'].append(f'page{number}/{kind}: {code}')
|
|
185
|
+
if not any(p['kind'] == 'html' for p in paper['materials']):
|
|
186
|
+
paper['omitted'].append('html_unavailable; original_page_cannot_be_reconstructed')
|
|
187
|
+
if not any(p['kind'] == 'screenshot' for p in paper['materials']):
|
|
188
|
+
paper['omitted'].append('screenshots_unavailable_or_excluded')
|
|
189
|
+
manifest['papers'].append(paper)
|
|
190
|
+
add('summary.md', _summary(manifest).encode('utf-8'))
|
|
191
|
+
manifest_bytes = _json(manifest)
|
|
192
|
+
if total + len(manifest_bytes) > MAX_PACKAGE_BYTES:
|
|
193
|
+
raise ExportError('package_size_limit; select_a_run_or_doi')
|
|
194
|
+
archive.writestr('manifest.json', manifest_bytes)
|
|
195
|
+
# Exclusive final publication: a racing export cannot overwrite another
|
|
196
|
+
# report. Temporary file is on the same filesystem on Windows and Unix.
|
|
197
|
+
os.link(temp, output)
|
|
198
|
+
finally:
|
|
199
|
+
Path(temp).unlink(missing_ok=True)
|
|
200
|
+
return {'ok': True, 'schemaVersion': 1, 'path': str(output), 'papers': len(rows),
|
|
201
|
+
'files': len(manifest['files']) + 1, 'bytes': output.stat().st_size,
|
|
202
|
+
'reviewRequired': True,
|
|
203
|
+
'incompletePapers': sum(bool(p['omitted']) for p in manifest['papers'])}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _json(data) -> bytes:
|
|
207
|
+
return json.dumps(data, ensure_ascii=False, indent=2).encode('utf-8')
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def _summary(manifest: dict) -> str:
|
|
211
|
+
# Keep site text from becoming active Markdown/HTML or injected issue UI.
|
|
212
|
+
def plain(value) -> str:
|
|
213
|
+
text = str(value or 'unknown').replace('\n', ' ').replace('\r', ' ').replace('<', '<').replace('>', '>').replace('`', "'")
|
|
214
|
+
return re.sub(r'([\\*_{}\[\]()#+!|])', r'\\\1', text)
|
|
215
|
+
|
|
216
|
+
lines = ['# PaperSearch 下载失败记录', '',
|
|
217
|
+
f"导出版本:{plain(manifest['version'])};导出系统:{plain(manifest['exportSystem'])}", '',
|
|
218
|
+
'## 公开前请核对', '',
|
|
219
|
+
'- [ ] 检查所有 HTML、诊断文本和截图中的姓名、邮箱、学号、学校标识及其他个人信息。',
|
|
220
|
+
'- [ ] 检查图片;字符串脱敏不能保证移除图片像素中的个人信息。',
|
|
221
|
+
'- [ ] 确认只分享这个导出包,不附原始 diagnostics、浏览器 profile、Cookie 或下载正文。',
|
|
222
|
+
'', 'HTML 为不可执行结构快照,href/action 记录为 data-href/data-action;只保留有限文本片段。',
|
|
223
|
+
'旧记录缺失的材料不会补造;导出不会重跑下载。', '']
|
|
224
|
+
for p in manifest['papers']:
|
|
225
|
+
lines.extend([f"## {plain(p['doi'])}", '',
|
|
226
|
+
f"- 出版社:{plain(p['publisher'])}",
|
|
227
|
+
f"- 失败部分:{plain(p.get('part') or 'main')};分类:{plain(p['failureClass'])};原因:{plain(p['code'])}",
|
|
228
|
+
f"- 停止步骤:{plain(p['stoppedAt'])}",
|
|
229
|
+
f"- 最后网址:`{plain(p['finalUrl'])}`",
|
|
230
|
+
f"- 采集版本 / 系统:{plain(p['captureVersion'])} / {plain(p['captureSystem'])}",
|
|
231
|
+
f"- 材料目录:{p['folder']}"])
|
|
232
|
+
if p.get('evidence'):
|
|
233
|
+
lines.append(f"- 依据:{plain(p['evidence'])}")
|
|
234
|
+
for material in p['materials']:
|
|
235
|
+
lines.append(f"- 检查文件:{material['path']}")
|
|
236
|
+
for omission in p['omitted']:
|
|
237
|
+
lines.append(f"- 材料缺项或限制:{plain(omission)}")
|
|
238
|
+
lines.append('')
|
|
239
|
+
return '\n'.join(lines)
|
|
@@ -150,6 +150,9 @@ def attach_page(folder: Path, page: Any, events: list[dict[str, Any]] | None = N
|
|
|
150
150
|
tabs = [p for p in list(page.context.pages) if not p.is_closed()]
|
|
151
151
|
except Exception:
|
|
152
152
|
tabs = [page]
|
|
153
|
+
from .page_snapshot import capture_structure, masked_screenshot
|
|
154
|
+
from .config import load_config
|
|
155
|
+
config = load_config()
|
|
153
156
|
for index, tab in enumerate(tabs[:6], 1):
|
|
154
157
|
row: dict[str, Any] = {"index": index, "working_tab": tab is page}
|
|
155
158
|
for key, getter in (("url", lambda t: t.url), ("title", lambda t: t.title())):
|
|
@@ -161,12 +164,11 @@ def attach_page(folder: Path, page: Any, events: list[dict[str, Any]] | None = N
|
|
|
161
164
|
row["text_excerpt"] = tab.evaluate("() => (document.body ? document.body.innerText : '').slice(0, 3000)")
|
|
162
165
|
except Exception:
|
|
163
166
|
row["text_excerpt"] = ""
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
pass
|
|
167
|
+
row.update(capture_structure(tab, folder / f"tab{index}.html", config))
|
|
168
|
+
row.update(masked_screenshot(tab, folder / f"tab{index}.png"))
|
|
169
|
+
for key in ("html", "screenshot"):
|
|
170
|
+
if key in row:
|
|
171
|
+
row[key] = Path(row[key]).name
|
|
170
172
|
info["tabs"].append(row)
|
|
171
173
|
if events is not None:
|
|
172
174
|
info["recent_events"] = events[-40:]
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Bounded, inert page specimens shared by download diagnostics and issues."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from .report_sanitizer import MAX_HTML_BYTES, Redactor, sanitize_html
|
|
8
|
+
|
|
9
|
+
# Walk live DOM without copying a script, a form value or an entire article.
|
|
10
|
+
# The RPC is bounded in time, number of nodes, depth, text and returned size.
|
|
11
|
+
_STRUCTURE = r"""(root, limit) => {
|
|
12
|
+
let size = 0, nodes = 0, textLeft = 6000, truncated = false;
|
|
13
|
+
const out = [], drop = new Set(['SCRIPT','STYLE','NOSCRIPT','IFRAME','OBJECT','EMBED','SVG','MATH','TEMPLATE','CANVAS']);
|
|
14
|
+
const attrs = new Set(['id','class','role','name','type','title','alt','aria-label','aria-labelledby','aria-describedby','aria-expanded','aria-controls','data-testid','data-test','href','action','disabled']);
|
|
15
|
+
const esc = s => s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
|
|
16
|
+
const push = s => { if (size + s.length <= limit) { out.push(s); size += s.length; } else truncated = true; };
|
|
17
|
+
const walk = (node, depth) => {
|
|
18
|
+
if (++nodes > 6000 || depth > 60 || size >= limit - 1024) { truncated = true; return; }
|
|
19
|
+
if (node.nodeType === 3) {
|
|
20
|
+
const s = node.textContent.trim().slice(0, Math.min(160, textLeft));
|
|
21
|
+
textLeft -= s.length; if (s) push(esc(s)); return;
|
|
22
|
+
}
|
|
23
|
+
if (node.nodeType !== 1 || drop.has(node.tagName) || (node.tagName === 'INPUT' && node.type === 'hidden')) return;
|
|
24
|
+
const tag = node.tagName.toLowerCase();
|
|
25
|
+
push('<' + tag + Array.from(node.attributes).filter(a => attrs.has(a.name)).map(a => ' ' + a.name + '="' + esc(a.value.slice(0,500)) + '"').join('') + '>');
|
|
26
|
+
if (['textarea','select'].includes(tag)) { push('</' + tag + '>'); return; }
|
|
27
|
+
for (const child of node.childNodes) { if (nodes >= 6000 || size >= limit - 1024) { truncated = true; break; } walk(child, depth + 1); }
|
|
28
|
+
if (!['input','img','br','hr','meta','link'].includes(tag)) push('</' + tag + '>');
|
|
29
|
+
};
|
|
30
|
+
walk(root, 0); return {html: out.join(''), truncated: truncated || textLeft <= 0,
|
|
31
|
+
private: !!root.querySelector('input[type=password],input[autocomplete=username],input[autocomplete=current-password]')};
|
|
32
|
+
}"""
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def capture_structure(page: Any, path: Path, config: dict | None = None) -> dict:
|
|
36
|
+
"""Optional evidence failure is recorded, never changes the download result."""
|
|
37
|
+
try:
|
|
38
|
+
from .browser import watchdog
|
|
39
|
+
if watchdog.fired:
|
|
40
|
+
return {'html_omitted': 'browser_stopped'}
|
|
41
|
+
raw = page.locator('html').evaluate(_STRUCTURE, MAX_HTML_BYTES // 2, timeout=3000)
|
|
42
|
+
if not isinstance(raw, dict) or not isinstance(raw.get('html'), str):
|
|
43
|
+
return {'html_omitted': 'capture_unavailable'}
|
|
44
|
+
content, truncated = sanitize_html(raw['html'], Redactor(config))
|
|
45
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
46
|
+
path.write_text(content, encoding='utf-8')
|
|
47
|
+
return {'html': str(path), 'html_truncated': bool(truncated or raw.get('truncated')),
|
|
48
|
+
'screenshot_private': bool(raw.get('private'))}
|
|
49
|
+
except Exception as exc:
|
|
50
|
+
return {'html_omitted': type(exc).__name__}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def masked_screenshot(page: Any, path: Path) -> dict:
|
|
54
|
+
try:
|
|
55
|
+
from .browser import watchdog
|
|
56
|
+
if watchdog.fired:
|
|
57
|
+
return {'screenshot_omitted': 'browser_stopped'}
|
|
58
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
59
|
+
encoding = {"type": "jpeg", "quality": 50} if path.suffix.lower() in {".jpg", ".jpeg"} else {"type": "png"}
|
|
60
|
+
page.screenshot(path=str(path), **encoding, full_page=False, timeout=3000,
|
|
61
|
+
mask=[page.locator('input, textarea, select, [contenteditable]')])
|
|
62
|
+
return {'screenshot': str(path), 'screenshot_masked': True}
|
|
63
|
+
except Exception as exc:
|
|
64
|
+
return {'screenshot_omitted': type(exc).__name__}
|