papersearch 0.4.9 → 0.4.10
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/README.en.md +50 -63
- package/README.md +50 -63
- 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/README.md +5 -6
- package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +1 -1
- package/carsi/paper_search_carsi/adapters/ieee/__init__.py +1 -1
- package/carsi/paper_search_carsi/adapters/jama/__init__.py +3 -1
- package/carsi/paper_search_carsi/adapters/karger/__init__.py +2 -1
- package/carsi/paper_search_carsi/adapters/lww/ovid.py +2 -2
- package/carsi/paper_search_carsi/adapters/oup/__init__.py +3 -4
- package/carsi/paper_search_carsi/adapters/world_scientific/__init__.py +5 -4
- package/carsi/paper_search_carsi/assets/capsule.html +114 -15
- package/carsi/paper_search_carsi/browser/backend.py +269 -233
- package/carsi/paper_search_carsi/browser/batch_session.py +42 -0
- package/carsi/paper_search_carsi/browser/challenge_interaction.py +28 -9
- package/carsi/paper_search_carsi/browser/cookies.py +8 -8
- package/carsi/paper_search_carsi/browser/driver.py +29 -0
- package/carsi/paper_search_carsi/browser/engine.py +17 -23
- package/carsi/paper_search_carsi/browser/foreground.py +21 -15
- package/carsi/paper_search_carsi/browser/login.py +12 -18
- package/carsi/paper_search_carsi/browser/preview.py +31 -12
- package/carsi/paper_search_carsi/browser/profiles.py +16 -23
- package/carsi/paper_search_carsi/browser/watchdog.py +61 -55
- package/carsi/paper_search_carsi/cli.py +22 -7
- package/carsi/paper_search_carsi/cold_start.py +65 -51
- package/carsi/paper_search_carsi/config.py +6 -4
- package/carsi/paper_search_carsi/engine/batch.py +9 -5
- package/carsi/paper_search_carsi/engine/batch_capture.py +56 -20
- package/carsi/paper_search_carsi/engine/batch_common.py +56 -16
- package/carsi/paper_search_carsi/engine/batch_institution.py +122 -13
- package/carsi/paper_search_carsi/engine/batch_login.py +30 -2
- package/carsi/paper_search_carsi/engine/batch_user.py +1 -1
- package/carsi/paper_search_carsi/engine/batch_waits.py +21 -7
- package/carsi/paper_search_carsi/engine/bridge.py +23 -13
- package/carsi/paper_search_carsi/engine/login_wait.py +1 -1
- package/carsi/paper_search_carsi/mcp_progress.py +13 -5
- package/carsi/paper_search_carsi/network.py +1 -1
- package/carsi/paper_search_carsi/progress_reporter.py +88 -7
- package/carsi/paper_search_carsi/progress_view.py +61 -0
- package/carsi/paper_search_carsi/server.py +47 -10
- package/carsi/paper_search_carsi/session_broker.py +1 -1
- package/carsi/pyproject.toml +7 -7
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +6 -0
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
- package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/batch.js +15 -5
- package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
- package/dist/capabilities/pdf-discovery/batchSummary.d.ts +22 -0
- package/dist/capabilities/pdf-discovery/batchSummary.d.ts.map +1 -0
- package/dist/capabilities/pdf-discovery/batchSummary.js +131 -0
- package/dist/capabilities/pdf-discovery/batchSummary.js.map +1 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts +1 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js +52 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiAttempt.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts +8 -4
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +89 -30
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts +4 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js +10 -0
- package/dist/capabilities/pdf-discovery/carsi/CarsiReadiness.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.d.ts +2 -2
- package/dist/capabilities/pdf-discovery/carsi/index.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.js +1 -1
- package/dist/capabilities/pdf-discovery/carsi/index.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/types.d.ts +36 -0
- package/dist/capabilities/pdf-discovery/carsi/types.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/handler.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/handler.js +11 -6
- package/dist/capabilities/pdf-discovery/handler.js.map +1 -1
- package/dist/capabilities/pdf-discovery/types.d.ts +3 -0
- package/dist/capabilities/pdf-discovery/types.d.ts.map +1 -1
- package/dist/cli.js +13 -9
- package/dist/cli.js.map +1 -1
- package/dist/management/carsi/installer.d.ts +26 -14
- package/dist/management/carsi/installer.d.ts.map +1 -1
- package/dist/management/carsi/installer.js +113 -69
- package/dist/management/carsi/installer.js.map +1 -1
- package/dist/management/carsi/runtime.d.ts +12 -1
- package/dist/management/carsi/runtime.d.ts.map +1 -1
- package/dist/management/carsi/runtime.js +30 -1
- package/dist/management/carsi/runtime.js.map +1 -1
- package/package.json +1 -1
- package/skills/paper-search/SKILL.md +4 -4
- package/skills/paper-search/references/browser-download.md +3 -3
- package/skills/paper-search/references/carsi-setup.md +7 -6
- package/skills/paper-search/references/cli-contract.md +4 -4
- package/skills/paper-search/references/management-layer.md +2 -2
- package/carsi/paper_search_carsi/assets/quiet-browser/api.js +0 -142
- package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +0 -24
- package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +0 -1
- package/carsi/paper_search_carsi/browser/background.py +0 -68
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"""End an item whose browser call never returns.
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
after a Cloudflare check had passed): the backend sits at CPU 0 and the batch
|
|
3
|
+
A driver call can wait forever for an answer (2026-10-31, on the earlier
|
|
4
|
+
Firefox-based browser, after a Cloudflare check had passed): the backend sits at CPU 0 and the batch
|
|
5
5
|
waits for its 20-minute item timeout. Every sync Playwright call is timed
|
|
6
6
|
here; one still running after ``LIMIT_SEC`` is logged with its caller and
|
|
7
7
|
cancelled, and it and every later browser call of this process raise
|
|
@@ -66,6 +66,10 @@ class BrowserOperationTimeout(BrowserUnresponsive):
|
|
|
66
66
|
"""The whole page operation exhausted its budget across browser calls."""
|
|
67
67
|
|
|
68
68
|
|
|
69
|
+
class BrowserBudgetExhausted(BrowserOperationTimeout):
|
|
70
|
+
"""No time remained to send another call; the driver did not stall."""
|
|
71
|
+
|
|
72
|
+
|
|
69
73
|
@contextmanager
|
|
70
74
|
def operation(seconds: float, label: str):
|
|
71
75
|
"""One monotonic deadline shared by all calls and retries in this scope."""
|
|
@@ -111,65 +115,67 @@ def _timeout_error() -> BrowserUnresponsive:
|
|
|
111
115
|
|
|
112
116
|
|
|
113
117
|
def install(limit_sec: float = LIMIT_SEC) -> None:
|
|
114
|
-
"""Time every sync
|
|
118
|
+
"""Time every sync driver call of this process (once)."""
|
|
115
119
|
global _installed
|
|
116
120
|
if _installed:
|
|
117
121
|
return
|
|
118
|
-
from
|
|
119
|
-
|
|
120
|
-
original
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
if fired is not None:
|
|
125
|
-
coro.close()
|
|
126
|
-
raise _timeout_error()
|
|
127
|
-
if interrupted is not None:
|
|
128
|
-
coro.close()
|
|
129
|
-
raise interrupted
|
|
130
|
-
if _soon and not _running_soon:
|
|
131
|
-
try:
|
|
132
|
-
_run_soon_calls()
|
|
133
|
-
except BaseException:
|
|
134
|
-
coro.close()
|
|
135
|
-
raise
|
|
136
|
-
key = id(coro)
|
|
137
|
-
started = time.monotonic()
|
|
138
|
-
_inflight[key] = (started, name, traceback.format_stack(limit=8)[:-1],
|
|
139
|
-
getattr(self, "_loop", None), coro)
|
|
140
|
-
budgets = getattr(_local, "budgets", [])
|
|
141
|
-
if budgets:
|
|
142
|
-
_call_deadlines[key] = tuple(min(budgets, key=lambda budget: budget[0]))
|
|
143
|
-
ended = "returned"
|
|
144
|
-
try:
|
|
145
|
-
# Refuse to start another candidate after the shared budget expired.
|
|
146
|
-
if key in _call_deadlines and started >= _call_deadlines[key][0]:
|
|
147
|
-
check(limit_sec)
|
|
122
|
+
from .driver import sync_bases
|
|
123
|
+
|
|
124
|
+
def timing(original: Any) -> Any:
|
|
125
|
+
def timed_sync(self: Any, coro: Any) -> Any:
|
|
126
|
+
name = getattr(coro, "__qualname__", "") or type(coro).__name__
|
|
127
|
+
if fired is not None:
|
|
148
128
|
coro.close()
|
|
149
129
|
raise _timeout_error()
|
|
150
|
-
return original(self, coro)
|
|
151
|
-
except asyncio.CancelledError:
|
|
152
|
-
ended = "cancelled"
|
|
153
|
-
if fired is not None:
|
|
154
|
-
raise _timeout_error() from None
|
|
155
130
|
if interrupted is not None:
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
if
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
131
|
+
coro.close()
|
|
132
|
+
raise interrupted
|
|
133
|
+
if _soon and not _running_soon:
|
|
134
|
+
try:
|
|
135
|
+
_run_soon_calls()
|
|
136
|
+
except BaseException:
|
|
137
|
+
coro.close()
|
|
138
|
+
raise
|
|
139
|
+
key = id(coro)
|
|
140
|
+
started = time.monotonic()
|
|
141
|
+
budgets = getattr(_local, "budgets", [])
|
|
142
|
+
if budgets:
|
|
143
|
+
deadline, label = min(budgets, key=lambda budget: budget[0])
|
|
144
|
+
# An unsent call cannot indicate a stalled driver. Keep the browser
|
|
145
|
+
# usable outside this operation, including cleanup and the next item.
|
|
146
|
+
if started >= deadline:
|
|
147
|
+
coro.close()
|
|
148
|
+
raise BrowserBudgetExhausted(f"{label} exhausted its page budget before {name}")
|
|
149
|
+
_call_deadlines[key] = (deadline, label)
|
|
150
|
+
_inflight[key] = (started, name, traceback.format_stack(limit=8)[:-1],
|
|
151
|
+
getattr(self, "_loop", None), coro)
|
|
152
|
+
ended = "returned"
|
|
153
|
+
try:
|
|
154
|
+
return original(self, coro)
|
|
155
|
+
except asyncio.CancelledError:
|
|
156
|
+
ended = "cancelled"
|
|
157
|
+
if fired is not None:
|
|
158
|
+
raise _timeout_error() from None
|
|
159
|
+
if interrupted is not None:
|
|
160
|
+
raise interrupted from None
|
|
161
|
+
raise
|
|
162
|
+
except BaseException as exc:
|
|
163
|
+
ended = type(exc).__name__
|
|
164
|
+
raise
|
|
165
|
+
finally:
|
|
166
|
+
_inflight.pop(key, None)
|
|
167
|
+
_call_deadlines.pop(key, None)
|
|
168
|
+
elapsed = time.monotonic() - started
|
|
169
|
+
_period["calls"] += 1
|
|
170
|
+
_period["seconds"] += elapsed
|
|
171
|
+
if elapsed > _period["slowest_sec"]:
|
|
172
|
+
_period["slowest"], _period["slowest_sec"] = name, elapsed
|
|
173
|
+
if elapsed > SLOW_CALL_SEC and on_slow_call is not None:
|
|
174
|
+
_report_slow(name, elapsed, ended)
|
|
175
|
+
return timed_sync
|
|
176
|
+
|
|
177
|
+
for base in sync_bases():
|
|
178
|
+
base._sync = timing(base._sync)
|
|
173
179
|
_installed = True
|
|
174
180
|
threading.Thread(target=_watch, args=(limit_sec,), name="browser-watchdog", daemon=True).start()
|
|
175
181
|
|
|
@@ -53,8 +53,11 @@ def _institutional_summary(cfg: dict[str, Any]) -> dict[str, Any]:
|
|
|
53
53
|
}
|
|
54
54
|
|
|
55
55
|
|
|
56
|
-
def _environment_check(cfg: dict[str, Any]) -> tuple[bool, list[dict[str, str]]]:
|
|
56
|
+
def _environment_check(cfg: dict[str, Any]) -> tuple[bool, list[dict[str, str]], dict[str, Any]]:
|
|
57
|
+
"""(ready, checks, browser): ``browser`` is the chrome backend's browser
|
|
58
|
+
(backend.browser_check) when that backend is configured, else {}."""
|
|
57
59
|
checks: list[dict[str, str]] = []
|
|
60
|
+
browser: dict[str, Any] = {}
|
|
58
61
|
|
|
59
62
|
def add(item: str, ok: bool, detail: str) -> None:
|
|
60
63
|
checks.append({"item": item, "status": "ok" if ok else "missing", "detail": detail})
|
|
@@ -64,10 +67,16 @@ def _environment_check(cfg: dict[str, Any]) -> tuple[bool, list[dict[str, str]]]
|
|
|
64
67
|
add("config_file", (data_dir / "config.json").exists(), str(data_dir / "config.json"))
|
|
65
68
|
|
|
66
69
|
try:
|
|
67
|
-
from .browser.backend import is_available, resolve_backend
|
|
70
|
+
from .browser.backend import BACKEND_CHROME, CHROME_MISSING, browser_check, is_available, resolve_backend
|
|
68
71
|
|
|
69
72
|
backend = resolve_backend(cfg)
|
|
70
|
-
|
|
73
|
+
if backend == BACKEND_CHROME:
|
|
74
|
+
browser = browser_check(cfg)
|
|
75
|
+
found = f"{browser['browser']} {browser['version']} ({browser['path']}), {browser['driver']}"
|
|
76
|
+
add("browser_backend", bool(is_available(backend, cfg)),
|
|
77
|
+
f"chrome: {found}" if browser["browser"] else f"chrome: {CHROME_MISSING}")
|
|
78
|
+
else:
|
|
79
|
+
add("browser_backend", bool(is_available(backend, cfg)), backend)
|
|
71
80
|
except Exception as exc: # pragma: no cover - import problems are themselves a finding
|
|
72
81
|
add("browser_backend", False, f"{type(exc).__name__}")
|
|
73
82
|
|
|
@@ -82,7 +91,7 @@ def _environment_check(cfg: dict[str, Any]) -> tuple[bool, list[dict[str, str]]]
|
|
|
82
91
|
for item in ("output_dir", "cache_dir"):
|
|
83
92
|
value = cfg.get(item) or ""
|
|
84
93
|
add(item, bool(value), value)
|
|
85
|
-
return all(c["status"] == "ok" for c in checks), checks
|
|
94
|
+
return all(c["status"] == "ok" for c in checks), checks, browser
|
|
86
95
|
|
|
87
96
|
|
|
88
97
|
def _carsi_school_list(cfg: dict[str, Any]) -> tuple[list[Any], dict[str, Any] | None]:
|
|
@@ -168,8 +177,14 @@ def _cmd_setup(args: argparse.Namespace) -> int:
|
|
|
168
177
|
save_config(cfg)
|
|
169
178
|
|
|
170
179
|
if args.check:
|
|
171
|
-
ready, checks = _environment_check(cfg)
|
|
172
|
-
|
|
180
|
+
ready, checks, browser = _environment_check(cfg)
|
|
181
|
+
report: dict[str, Any] = {"ready": ready, "checks": checks, "settings": _institutional_summary(cfg)}
|
|
182
|
+
if browser:
|
|
183
|
+
report["browser"] = browser
|
|
184
|
+
if browser.get("outdated"):
|
|
185
|
+
report["warnings"] = [f"Google Chrome {browser['version']} 低于测试过的 {browser['tested']}:"
|
|
186
|
+
"请先更新 Chrome(菜单 → 帮助 → 关于 Google Chrome)"]
|
|
187
|
+
print(json.dumps(report, ensure_ascii=False, indent=2))
|
|
173
188
|
return 0 if ready else 2
|
|
174
189
|
|
|
175
190
|
print(json.dumps({"updated": changed, "settings": _institutional_summary(cfg)}, ensure_ascii=False, indent=2))
|
|
@@ -478,7 +493,7 @@ def main(argv: list[str] | None = None) -> int:
|
|
|
478
493
|
|
|
479
494
|
cs = sub.add_parser("cold-start", help="forget school sessions in the download browser (lists first)")
|
|
480
495
|
cs.add_argument("--yes", action="store_true", help="delete without asking")
|
|
481
|
-
cs.add_argument("--profile", help="another
|
|
496
|
+
cs.add_argument("--profile", help="another Chrome profile directory (default: the download profile)")
|
|
482
497
|
cs.add_argument("--cache-dir", help="the cache whose saved cookie files to filter "
|
|
483
498
|
"(default: the configured one; none with --profile)")
|
|
484
499
|
cs.set_defaults(func=_cmd_cold_start)
|
|
@@ -7,16 +7,18 @@ start forgets:
|
|
|
7
7
|
federation services that remember a school (CARSI, OpenAthens,
|
|
8
8
|
SeamlessAccess, SAMS Sigma, Atypon's SSO hub);
|
|
9
9
|
- the publishers' sessions and remembered schools;
|
|
10
|
-
- every other site's cookies and site data: the
|
|
10
|
+
- every other site's cookies and site data: the Chrome profile belongs to
|
|
11
11
|
the download engine alone, so the rest are journal sites (cell.com,
|
|
12
12
|
thelancet.com, ...) and their trackers.
|
|
13
13
|
|
|
14
14
|
It keeps bot-verification records (Cloudflare), personal publisher accounts
|
|
15
15
|
and cookie-consent choices. Besides the profile's own cookie store it filters
|
|
16
16
|
the files that put cookies back: the session cookies saved for the next
|
|
17
|
-
launch and the saved publisher cookies.
|
|
18
|
-
|
|
19
|
-
|
|
17
|
+
launch and the saved publisher cookies. IndexedDB goes per site. Chrome keeps
|
|
18
|
+
every site's local storage in one database, which goes whole when it holds a
|
|
19
|
+
site to forget (the kept categories live in cookies). Chrome's session-restore
|
|
20
|
+
files and session storage are removed whole. The plan lists hosts and cookie
|
|
21
|
+
names only, never values; nothing is changed until it is confirmed.
|
|
20
22
|
"""
|
|
21
23
|
from __future__ import annotations
|
|
22
24
|
|
|
@@ -27,7 +29,7 @@ import sqlite3
|
|
|
27
29
|
from pathlib import Path
|
|
28
30
|
from typing import Any, Iterable
|
|
29
31
|
|
|
30
|
-
from .browser.backend import SESSION_COOKIES_FILE,
|
|
32
|
+
from .browser.backend import SESSION_COOKIES_FILE, chrome_profile_dir, profile_holder
|
|
31
33
|
from .browser.cookies import _CLOUDFLARE_COOKIE_NAMES, PUBLISHER_DOMAINS
|
|
32
34
|
from .engine.batch_institution import InstitutionMixin, _school_auth_patterns
|
|
33
35
|
|
|
@@ -82,17 +84,15 @@ class Classifier:
|
|
|
82
84
|
return "other_site"
|
|
83
85
|
|
|
84
86
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
if not origin.startswith(("https+++", "http+++")):
|
|
89
|
-
return ""
|
|
90
|
-
return origin.split("+++", 1)[1].split("+", 1)[0]
|
|
87
|
+
_INDEXEDDB_DIR = re.compile(r"^https?_(.+)_\d+\.indexeddb\.(?:leveldb|blob)$")
|
|
88
|
+
# A site's entry in Chrome's local storage database: "META:<origin>".
|
|
89
|
+
_LOCAL_STORAGE_ORIGIN = re.compile(rb"META:https?://([a-z0-9.-]+)")
|
|
91
90
|
|
|
92
91
|
|
|
93
|
-
def
|
|
94
|
-
"""``
|
|
95
|
-
|
|
92
|
+
def _storage_host(dirname: str) -> str:
|
|
93
|
+
"""``https_www.sciencedirect.com_0.indexeddb.leveldb`` -> host; '' for anything else."""
|
|
94
|
+
found = _INDEXEDDB_DIR.match(dirname)
|
|
95
|
+
return found.group(1) if found else ""
|
|
96
96
|
|
|
97
97
|
|
|
98
98
|
def _netscape_rows(path: Path) -> list[list[str]]:
|
|
@@ -107,19 +107,33 @@ class ColdStart:
|
|
|
107
107
|
|
|
108
108
|
# -- reading ------------------------------------------------------------
|
|
109
109
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
110
|
+
@property
|
|
111
|
+
def _default(self) -> Path:
|
|
112
|
+
return self.profile / "Default"
|
|
113
|
+
|
|
114
|
+
def _cookies_db(self) -> Path:
|
|
115
|
+
"""Chrome's cookie store: ``Default/Network/Cookies`` (Windows), else ``Default/Cookies``."""
|
|
116
|
+
network = self._default / "Network" / "Cookies"
|
|
117
|
+
return network if network.exists() else self._default / "Cookies"
|
|
116
118
|
|
|
117
|
-
def
|
|
118
|
-
path = self.
|
|
119
|
+
def _cookie_rows(self) -> list[tuple[int, str, str]]:
|
|
120
|
+
path = self._cookies_db()
|
|
119
121
|
if not path.exists():
|
|
120
122
|
return []
|
|
121
123
|
with sqlite3.connect(f"file:{path}?mode=ro", uri=True) as db:
|
|
122
|
-
return
|
|
124
|
+
return list(db.execute("SELECT rowid, host_key, name FROM cookies"))
|
|
125
|
+
|
|
126
|
+
def _local_storage_hosts(self) -> list[str]:
|
|
127
|
+
"""The sites with an entry in Chrome's local storage database."""
|
|
128
|
+
hosts: set[str] = set()
|
|
129
|
+
store = self._default / "Local Storage" / "leveldb"
|
|
130
|
+
for path in sorted(store.iterdir()) if store.is_dir() else []:
|
|
131
|
+
if path.suffix in (".log", ".ldb"):
|
|
132
|
+
try:
|
|
133
|
+
hosts.update(h.decode() for h in _LOCAL_STORAGE_ORIGIN.findall(path.read_bytes()))
|
|
134
|
+
except OSError:
|
|
135
|
+
continue
|
|
136
|
+
return sorted(hosts)
|
|
123
137
|
|
|
124
138
|
def _cookie_files(self) -> list[Path]:
|
|
125
139
|
files = [self.profile / SESSION_COOKIES_FILE]
|
|
@@ -135,25 +149,25 @@ class ColdStart:
|
|
|
135
149
|
return data, [c for c in cookies if isinstance(c, dict)]
|
|
136
150
|
|
|
137
151
|
def _session_files(self) -> list[Path]:
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
152
|
+
"""Chrome's session restore (tabs, and their session cookies) and session storage."""
|
|
153
|
+
sessions = self._default / "Sessions"
|
|
154
|
+
files = sorted(p for p in sessions.iterdir() if p.is_file()) if sessions.is_dir() else []
|
|
155
|
+
storage = self._default / "Session Storage"
|
|
156
|
+
return files + ([storage] if storage.is_dir() else [])
|
|
141
157
|
|
|
142
158
|
# -- the plan -----------------------------------------------------------
|
|
143
159
|
|
|
144
160
|
def plan(self) -> dict[str, Any]:
|
|
145
|
-
owner = _profile_owner_pid(str(self.profile))
|
|
146
161
|
cookies: dict[str, dict[str, set[str]]] = {c: {} for c in DELETE + KEEP}
|
|
147
162
|
for _id, host, name in self._cookie_rows():
|
|
148
163
|
cookies[self.classify(host, name)].setdefault(host.lstrip("."), set()).add(name)
|
|
149
164
|
site_data: dict[str, list[str]] = {"delete": [], "keep": []}
|
|
150
|
-
storage = self.
|
|
165
|
+
storage = self._default / "IndexedDB"
|
|
151
166
|
for entry in sorted(storage.iterdir()) if storage.is_dir() else []:
|
|
152
167
|
host = _storage_host(entry.name)
|
|
153
168
|
if host:
|
|
154
169
|
site_data["delete" if self.classify(host) in DELETE else "keep"].append(entry.name)
|
|
155
|
-
local =
|
|
156
|
-
if self.classify(_webappsstore_host(k)) in DELETE})
|
|
170
|
+
local = [h for h in self._local_storage_hosts() if self.classify(h) in DELETE]
|
|
157
171
|
files = []
|
|
158
172
|
for path in self._cookie_files():
|
|
159
173
|
try:
|
|
@@ -168,11 +182,14 @@ class ColdStart:
|
|
|
168
182
|
lines = [r for r in _netscape_rows(twin) if len(r) >= 7 and not r[0].startswith("#")]
|
|
169
183
|
gone = sum(self.classify(r[0], r[5]) in DELETE for r in lines)
|
|
170
184
|
files.append({"path": str(twin), "action": "filter", "remove": gone, "keep": len(lines) - gone})
|
|
171
|
-
|
|
185
|
+
if local:
|
|
186
|
+
files.append({"path": str(self._default / "Local Storage"), "action": "delete",
|
|
187
|
+
"why": "Chrome local storage, one database for all sites"})
|
|
188
|
+
files += [{"path": str(p), "action": "delete", "why": "Chrome session restore and session storage"}
|
|
172
189
|
for p in self._session_files()]
|
|
173
190
|
return {
|
|
174
191
|
"profile": str(self.profile),
|
|
175
|
-
"browser_running": bool(
|
|
192
|
+
"browser_running": bool(profile_holder(str(self.profile))),
|
|
176
193
|
"delete": {c: {"hosts": len(cookies[c]), "cookies": sum(len(v) for v in cookies[c].values()),
|
|
177
194
|
"items": [{"host": h, "names": sorted(n)} for h, n in sorted(cookies[c].items())]}
|
|
178
195
|
for c in DELETE},
|
|
@@ -184,32 +201,26 @@ class ColdStart:
|
|
|
184
201
|
# -- applying -----------------------------------------------------------
|
|
185
202
|
|
|
186
203
|
def apply(self) -> dict[str, Any]:
|
|
187
|
-
|
|
188
|
-
if
|
|
189
|
-
raise RuntimeError(f"the download browser (
|
|
204
|
+
holder = profile_holder(str(self.profile))
|
|
205
|
+
if holder:
|
|
206
|
+
raise RuntimeError(f"the download browser ({holder}) is using this profile; close it first")
|
|
190
207
|
done: dict[str, Any] = {"cookies": 0, "site_data": 0, "local_storage": 0, "files": []}
|
|
191
|
-
path = self.
|
|
208
|
+
path = self._cookies_db()
|
|
192
209
|
if path.exists():
|
|
193
210
|
gone = [i for i, host, name in self._cookie_rows() if self.classify(host, name) in DELETE]
|
|
194
211
|
with sqlite3.connect(path) as db:
|
|
195
|
-
db.executemany("DELETE FROM
|
|
196
|
-
with sqlite3.connect(path) as db:
|
|
197
|
-
db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
|
212
|
+
db.executemany("DELETE FROM cookies WHERE rowid = ?", [(i,) for i in gone])
|
|
198
213
|
done["cookies"] = len(gone)
|
|
199
|
-
storage = self.
|
|
214
|
+
storage = self._default / "IndexedDB"
|
|
200
215
|
for entry in sorted(storage.iterdir()) if storage.is_dir() else []:
|
|
201
216
|
host = _storage_host(entry.name)
|
|
202
217
|
if host and self.classify(host) in DELETE:
|
|
203
218
|
shutil.rmtree(entry)
|
|
204
219
|
done["site_data"] += 1
|
|
205
|
-
local = self.
|
|
206
|
-
if local
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
db.executemany("DELETE FROM webappsstore2 WHERE originKey = ?", [(k,) for k in keys])
|
|
210
|
-
with sqlite3.connect(local) as db:
|
|
211
|
-
db.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
|
212
|
-
done["local_storage"] = len(keys)
|
|
220
|
+
local = [h for h in self._local_storage_hosts() if self.classify(h) in DELETE]
|
|
221
|
+
if local:
|
|
222
|
+
shutil.rmtree(self._default / "Local Storage")
|
|
223
|
+
done["local_storage"] = len(local)
|
|
213
224
|
for file in self._cookie_files():
|
|
214
225
|
try:
|
|
215
226
|
data, rows = self._file_cookies(file)
|
|
@@ -226,7 +237,10 @@ class ColdStart:
|
|
|
226
237
|
twin.write_text("".join("\t".join(r) + "\n" for r in keep_txt), encoding="utf-8")
|
|
227
238
|
done["files"].append({"path": str(twin), "removed": len(rows_txt) - len(keep_txt)})
|
|
228
239
|
for file in self._session_files():
|
|
229
|
-
file.
|
|
240
|
+
if file.is_dir():
|
|
241
|
+
shutil.rmtree(file)
|
|
242
|
+
else:
|
|
243
|
+
file.unlink()
|
|
230
244
|
done["files"].append({"path": str(file), "removed": "file"})
|
|
231
245
|
return done
|
|
232
246
|
|
|
@@ -239,7 +253,7 @@ def _write_json(path: Path, data: Any) -> None:
|
|
|
239
253
|
|
|
240
254
|
|
|
241
255
|
def for_config(config: dict[str, Any], profile: str | None = None, cache_dir: str | None = None) -> ColdStart:
|
|
242
|
-
"""The cold start for the configured download profile (
|
|
256
|
+
"""The cold start for the configured download profile (Chrome's own directory)
|
|
243
257
|
and the configured cache. Another profile comes with only the cache named for
|
|
244
258
|
it: the configured cache belongs to the configured profile."""
|
|
245
259
|
from .config import DATA_DIR
|
|
@@ -248,4 +262,4 @@ def for_config(config: dict[str, Any], profile: str | None = None, cache_dir: st
|
|
|
248
262
|
if profile:
|
|
249
263
|
return ColdStart(Path(profile), Path(cache_dir) if cache_dir else None, config)
|
|
250
264
|
cache = cache_dir or config.get("cache_dir", str(DATA_DIR / "cache"))
|
|
251
|
-
return ColdStart(
|
|
265
|
+
return ColdStart(chrome_profile_dir(_resolve_profile_dir(config)), Path(cache), config)
|
|
@@ -23,7 +23,7 @@ DEFAULT_SCIHUB_DOMAINS = [
|
|
|
23
23
|
# ALTCHA-protected (stable; used as manual-download hint)
|
|
24
24
|
"https://sci-hub.ru",
|
|
25
25
|
"https://sci-hub.ee",
|
|
26
|
-
# Cloudflare-protected (requires
|
|
26
|
+
# Cloudflare-protected (requires a browser to pass the JS challenge)
|
|
27
27
|
"https://sci-hub.st",
|
|
28
28
|
# Reported intermittent (2026-06); kept but deprioritized
|
|
29
29
|
"https://sci-hub.mksa.top",
|
|
@@ -87,9 +87,11 @@ DEFAULT_CONFIG: dict[str, Any] = {
|
|
|
87
87
|
"min_pdf_size_bytes": 10000,
|
|
88
88
|
"browser_headless": False,
|
|
89
89
|
"browser_humanize": True,
|
|
90
|
-
# 浏览器后端,二选一:
|
|
91
|
-
# 或 ego
|
|
92
|
-
"browser_backend": "
|
|
90
|
+
# 浏览器后端,二选一:chrome(默认,本机安装的 Google Chrome,经 Patchright 驱动)
|
|
91
|
+
# 或 ego(正在运行的 ego-lite 浏览器,经远程调试连接)。旧值 camoufox/patchright/cloakbrowser 自动按 chrome 处理。
|
|
92
|
+
"browser_backend": "chrome",
|
|
93
|
+
# 装在别处的 Google Chrome 的程序路径;留空时在默认安装位置找。
|
|
94
|
+
"chrome_executable": "",
|
|
93
95
|
# 批量下载时每 N 篇回收一次浏览器上下文(cookie 内存交接,登录态不丢)。
|
|
94
96
|
# 0 = 关闭。长批次(上千篇)建议 100-200,避免 Chrome 长会话内存漂移。
|
|
95
97
|
"browser_restart_every": 0,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Profile-driven
|
|
1
|
+
"""Profile-driven browser batch downloader with retryable machine states.
|
|
2
2
|
|
|
3
3
|
``PublisherBatchDownloader`` keeps the article flow (``fetch_one``) here and combines
|
|
4
4
|
one mixin per responsibility from the ``batch_*.py`` modules: login, institution
|
|
@@ -48,6 +48,7 @@ from ..adapters import PublisherAdapter, adapter_class # noqa: E402
|
|
|
48
48
|
from .batch_common import (
|
|
49
49
|
page_operation, # re-exported: other modules import these from batch
|
|
50
50
|
open_page,
|
|
51
|
+
goto_retrying,
|
|
51
52
|
settle,
|
|
52
53
|
_is_network_failure,
|
|
53
54
|
DownloadResult,
|
|
@@ -146,8 +147,8 @@ class PublisherBatchDownloader(
|
|
|
146
147
|
deadline = time.monotonic() + 60
|
|
147
148
|
try:
|
|
148
149
|
referer = str(page.url)
|
|
149
|
-
tab
|
|
150
|
-
|
|
150
|
+
goto_retrying(tab, url, timeout_ms=60_000, wait_until="load",
|
|
151
|
+
**({"referer": referer} if referer.startswith(("http://", "https://")) else {}))
|
|
151
152
|
except Exception as exc:
|
|
152
153
|
if not _is_browser_error(exc):
|
|
153
154
|
raise
|
|
@@ -623,8 +624,11 @@ class PublisherBatchDownloader(
|
|
|
623
624
|
self._write_diagnostic(page, result, run_dir)
|
|
624
625
|
return result
|
|
625
626
|
except watchdog.BrowserUnresponsive as exc:
|
|
626
|
-
|
|
627
|
-
|
|
627
|
+
if isinstance(exc, watchdog.BrowserBudgetExhausted) and result.state == "challenge_or_viewer_timeout":
|
|
628
|
+
result.reason = result.state
|
|
629
|
+
else:
|
|
630
|
+
result.reason = result.state = ("browser_operation_timeout" if isinstance(exc, watchdog.BrowserOperationTimeout)
|
|
631
|
+
else "browser_unresponsive")
|
|
628
632
|
self._event(result, result.state, str(exc))
|
|
629
633
|
self._write_diagnostic(page, result, run_dir)
|
|
630
634
|
return result
|
|
@@ -32,6 +32,7 @@ from .batch_common import (
|
|
|
32
32
|
_REFERENCE_AREA,
|
|
33
33
|
_IP_BLOCK_STATUS_CODES,
|
|
34
34
|
_is_browser_error,
|
|
35
|
+
goto_retrying,
|
|
35
36
|
)
|
|
36
37
|
|
|
37
38
|
|
|
@@ -215,6 +216,9 @@ class CaptureMixin:
|
|
|
215
216
|
|
|
216
217
|
with pause_preview(getattr(page, "context", None)):
|
|
217
218
|
body, url, block = self._capture_pdf_channels(page, doi, result)
|
|
219
|
+
if (body is None and not block and len(result.pdf_attempts) == tried_before
|
|
220
|
+
and not result.reason and self._wait_for_pdf_candidates(page, doi, result)):
|
|
221
|
+
body, url, block = self._capture_pdf_channels(page, doi, result)
|
|
218
222
|
if body is None and not block and self._fallback_pdf is not None:
|
|
219
223
|
body, url = self._fallback_pdf
|
|
220
224
|
self._event(result, "pdf_saved_unconfirmed", f"{url} | no DOI or title on the first pages")
|
|
@@ -226,6 +230,38 @@ class CaptureMixin:
|
|
|
226
230
|
finally:
|
|
227
231
|
self._fallback_pdf = None
|
|
228
232
|
|
|
233
|
+
@staticmethod
|
|
234
|
+
def _chromium_pdf_patterns(native: tuple[str, ...]) -> list[dict[str, str]]:
|
|
235
|
+
"""Responses Chrome pauses during the PDF step: the adapter's PDF addresses,
|
|
236
|
+
and every document the tab opens wherever it is served. A PDF address can
|
|
237
|
+
redirect to a delivery host no adapter lists (JAMA's articlepdf to
|
|
238
|
+
Silverchair's watermark host, 2026-11-07); the checks on each paused
|
|
239
|
+
response decide, and other documents go on at once."""
|
|
240
|
+
return [*({"urlPattern": pattern, "requestStage": "Response"} for pattern in native),
|
|
241
|
+
{"urlPattern": "*", "resourceType": "Document", "requestStage": "Response"}]
|
|
242
|
+
|
|
243
|
+
PDF_CANDIDATE_WAIT_MS = 8_000
|
|
244
|
+
|
|
245
|
+
def _wait_for_pdf_candidates(self, page: Any, doi: str, result: DownloadResult) -> bool:
|
|
246
|
+
"""A page that offered no PDF address may still be loading or about to move
|
|
247
|
+
on: Thieme right after the school login, on its token address before the
|
|
248
|
+
article (2026-11-02 on Firefox, 2026-11-07 on Chrome). Look again for a
|
|
249
|
+
while; True once it offers one."""
|
|
250
|
+
def offered() -> bool:
|
|
251
|
+
try:
|
|
252
|
+
return bool(self._pdf_candidates(page, doi))
|
|
253
|
+
except Exception as exc:
|
|
254
|
+
if not _is_browser_error(exc):
|
|
255
|
+
raise
|
|
256
|
+
return False # the page is moving on: look at it again
|
|
257
|
+
|
|
258
|
+
started = time.time()
|
|
259
|
+
if not pump_until(page, offered, self.PDF_CANDIDATE_WAIT_MS, step_ms=500):
|
|
260
|
+
return False
|
|
261
|
+
self._event(result, "pdf_candidates_appeared",
|
|
262
|
+
f"after {time.time() - started:.1f} s at {str(getattr(page, 'url', ''))[:160]}")
|
|
263
|
+
return True
|
|
264
|
+
|
|
229
265
|
def _nothing_tried_evidence(self, page: Any, doi: str) -> str:
|
|
230
266
|
"""The page and its access verdict, and the PDF addresses it offered."""
|
|
231
267
|
try:
|
|
@@ -407,7 +443,11 @@ class CaptureMixin:
|
|
|
407
443
|
status=event.get("responseStatusCode", 0), history=history,
|
|
408
444
|
)
|
|
409
445
|
final_pdf = (self._article_pdf_url_matches(url, doi, **article_options)
|
|
410
|
-
or self.adapter.is_pdf_cdn_url(url, doi)
|
|
446
|
+
or self.adapter.is_pdf_cdn_url(url, doi)
|
|
447
|
+
# The bound PDF's own file on the host its address redirects
|
|
448
|
+
# to, as _response_matches_article accepts it (JAMA's
|
|
449
|
+
# articlepdf -> Silverchair's watermarked copy, 2026-11-07).
|
|
450
|
+
or self._bound_pdf_copy(url, response, doi, article_options))
|
|
411
451
|
if (len(history) > 20 or not final_pdf
|
|
412
452
|
or not self._response_matches_article(response, doi, **article_options)):
|
|
413
453
|
rejected_pdf_urls.update(self._response_urls(response))
|
|
@@ -557,8 +597,8 @@ class CaptureMixin:
|
|
|
557
597
|
def on_request_failed(request: Any) -> None:
|
|
558
598
|
# A request for a PDF address that ended without an answer: what the
|
|
559
599
|
# browser said and after how long, for the record (Karger's PDF
|
|
560
|
-
# navigation ended
|
|
561
|
-
#
|
|
600
|
+
# navigation ended aborted after 46 s, and whether the click's own
|
|
601
|
+
# request had failed was not known, 2026-11-02).
|
|
562
602
|
try:
|
|
563
603
|
url = str(request.url)
|
|
564
604
|
if not self._is_pdf_candidate_url(url) or self._is_supplementary_url(url):
|
|
@@ -591,18 +631,14 @@ class CaptureMixin:
|
|
|
591
631
|
try:
|
|
592
632
|
native_pdf_patterns = ((self.adapter.metadata_pdf_patterns if metadata_pdf_urls else ())
|
|
593
633
|
or self.adapter.native_pdf_patterns)
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
cdp_session.send("Fetch.enable", {"patterns": [
|
|
603
|
-
{"urlPattern": pattern, "requestStage": "Response"}
|
|
604
|
-
for pattern in native_pdf_patterns
|
|
605
|
-
]})
|
|
634
|
+
browser = getattr(page.context, "browser", None)
|
|
635
|
+
if browser is not None and browser.browser_type.name == "chromium":
|
|
636
|
+
cdp_session = page.context.new_cdp_session(page)
|
|
637
|
+
if self._uses_article_pdf_validation():
|
|
638
|
+
cdp_session.on("Network.requestWillBeSent", on_native_request)
|
|
639
|
+
cdp_session.send("Network.enable")
|
|
640
|
+
cdp_session.on("Fetch.requestPaused", on_paused_response)
|
|
641
|
+
cdp_session.send("Fetch.enable", {"patterns": self._chromium_pdf_patterns(native_pdf_patterns)})
|
|
606
642
|
self._return_to_record_article_if_needed(page, result, doi)
|
|
607
643
|
# A login can return directly to a PDF before these listeners were
|
|
608
644
|
# installed. PDF.js has no article button or metadata to discover.
|
|
@@ -697,8 +733,8 @@ class CaptureMixin:
|
|
|
697
733
|
return None, final_url, captured["block_reason"]
|
|
698
734
|
continue
|
|
699
735
|
try:
|
|
700
|
-
response = page
|
|
701
|
-
|
|
736
|
+
response = goto_retrying(page, pdf_url, timeout_ms=self.pdf_timeout_ms,
|
|
737
|
+
**({"referer": article_page} if article_page.startswith("https://") else {}))
|
|
702
738
|
if not self._resolve_suspect_block(page, result, captured):
|
|
703
739
|
return None, "", captured["block_reason"]
|
|
704
740
|
if captured["block_reason"]:
|
|
@@ -1142,7 +1178,7 @@ class CaptureMixin:
|
|
|
1142
1178
|
try:
|
|
1143
1179
|
with expect_download(timeout=self.pdf_timeout_ms) as download_info:
|
|
1144
1180
|
try:
|
|
1145
|
-
page
|
|
1181
|
+
goto_retrying(page, pdf_url, timeout_ms=self.pdf_timeout_ms)
|
|
1146
1182
|
except Exception as exc:
|
|
1147
1183
|
if not self._is_download_navigation_abort(exc):
|
|
1148
1184
|
raise
|
|
@@ -1343,7 +1379,7 @@ class CaptureMixin:
|
|
|
1343
1379
|
deadline = time.time() + timeout_sec
|
|
1344
1380
|
attempted.clear()
|
|
1345
1381
|
continue
|
|
1346
|
-
# Firefox
|
|
1382
|
+
# Firefox can leave the native PDF.js shell visible while
|
|
1347
1383
|
# the document is already available (or while its loading task is
|
|
1348
1384
|
# idle). Read that document in the viewer's own realm before
|
|
1349
1385
|
# falling back to a second HTTP request, which may lose the
|
|
@@ -1384,7 +1420,7 @@ class CaptureMixin:
|
|
|
1384
1420
|
const documentUri = String(nativeDocument?.documentURI || "");
|
|
1385
1421
|
const app = nativeWindow.PDFViewerApplication;
|
|
1386
1422
|
// Older builds expose the resource:// viewer shell; Firefox 156
|
|
1387
|
-
//
|
|
1423
|
+
// keeps the https PDF URL on a document whose
|
|
1388
1424
|
// contentType is application/pdf.
|
|
1389
1425
|
const isNativePdfViewer = nativeLocation.startsWith("resource://pdf.js/")
|
|
1390
1426
|
|| documentUri.startsWith("resource://pdf.js/")
|