papersearch 0.4.8 → 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 -62
- package/README.md +50 -62
- 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 +199 -24
- package/carsi/paper_search_carsi/browser/backend.py +270 -227
- package/carsi/paper_search_carsi/browser/batch_session.py +42 -0
- package/carsi/paper_search_carsi/browser/challenge_interaction.py +79 -43
- 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/capsule_placement.py +266 -0
- 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_access.py +2 -4
- 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_diagnostics.py +4 -2
- package/carsi/paper_search_carsi/engine/batch_institution.py +146 -17
- package/carsi/paper_search_carsi/engine/batch_login.py +79 -26
- package/carsi/paper_search_carsi/engine/batch_user.py +1 -1
- package/carsi/paper_search_carsi/engine/batch_waits.py +92 -37
- 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/engine/page_activity.py +15 -15
- 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_capsule.py +233 -93
- 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/paper_search_carsi/user_settings.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
|
@@ -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
|
|
@@ -261,11 +261,9 @@ class AccessMixin:
|
|
|
261
261
|
return not getattr(getattr(self, "_item_result", None), "_pdf_retry_login", False)
|
|
262
262
|
|
|
263
263
|
def _school_login_done(self) -> bool:
|
|
264
|
-
"""This item
|
|
265
|
-
back to the publisher from a login or chooser page, already."""
|
|
264
|
+
"""This item reached its IdP; selecting a school is only an attempt."""
|
|
266
265
|
result = getattr(self, "_item_result", None)
|
|
267
|
-
return result is not None and (getattr(result, "_visited_idp", False) or getattr(result, "_login_round_trip", False)
|
|
268
|
-
or any(e.get("state") in self._SCHOOL_CHOSEN for e in result.events))
|
|
266
|
+
return result is not None and (getattr(result, "_visited_idp", False) or getattr(result, "_login_round_trip", False))
|
|
269
267
|
|
|
270
268
|
def _institution_pdf_entitlement_missing(self, page: Any, snapshot: SimpleNamespace | None = None) -> bool:
|
|
271
269
|
"""The article page denies access (access_rules.denial_evidence) to a
|
|
@@ -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/")
|
|
@@ -16,6 +16,7 @@ from urllib.parse import urlencode
|
|
|
16
16
|
import requests
|
|
17
17
|
|
|
18
18
|
from ..browser import watchdog
|
|
19
|
+
from ..browser.driver import is_driver_error
|
|
19
20
|
from ..browser.challenges import looks_like_challenge
|
|
20
21
|
|
|
21
22
|
|
|
@@ -129,9 +130,8 @@ def _observe_preview(page: Any) -> None:
|
|
|
129
130
|
|
|
130
131
|
|
|
131
132
|
def _is_browser_error(exc: BaseException, name: str = "") -> bool:
|
|
132
|
-
"""A
|
|
133
|
-
return (
|
|
134
|
-
and (not name or type(exc).__name__ == name))
|
|
133
|
+
"""A driver error (optionally of class ``name``), not a program bug."""
|
|
134
|
+
return is_driver_error(exc, name)
|
|
135
135
|
|
|
136
136
|
|
|
137
137
|
def page_title(page: Any) -> str:
|
|
@@ -158,11 +158,10 @@ def _is_navigation_cut(exc: BaseException) -> bool:
|
|
|
158
158
|
return _is_browser_error(exc) and any(marker in str(exc) for marker in _NAVIGATION_CUT)
|
|
159
159
|
|
|
160
160
|
|
|
161
|
-
# The publisher's site did not answer:
|
|
162
|
-
#
|
|
163
|
-
#
|
|
164
|
-
_NETWORK_FAILURE = ("
|
|
165
|
-
"NS_ERROR_PROXY_", "net::ERR_")
|
|
161
|
+
# The publisher's site did not answer: Chromium's network errors, and a page
|
|
162
|
+
# load that ran out of time. Not a program error (thieme-connect.de's empty
|
|
163
|
+
# response and pubs.acs.org's 60 s loads, 2026-11-01).
|
|
164
|
+
_NETWORK_FAILURE = ("net::ERR_",)
|
|
166
165
|
|
|
167
166
|
|
|
168
167
|
def _is_network_failure(exc: BaseException) -> bool:
|
|
@@ -218,12 +217,54 @@ _DOCUMENT_STATE_JS = """() => [document.readyState,
|
|
|
218
217
|
document.readyState === 'loading' && document.body ? document.body.textContent.length : 0]"""
|
|
219
218
|
|
|
220
219
|
|
|
220
|
+
# A connection the network dropped before the site answered: Chromium's codes for a
|
|
221
|
+
# closed, reset or timed-out connection, a failed proxy tunnel or name lookup, a
|
|
222
|
+
# broken protocol stream. A system proxy in front of doi.org dropped 1 of 6
|
|
223
|
+
# connections and 3 articles failed on it, each fine on the next try (Windows,
|
|
224
|
+
# 2026-11-07); such a navigation is tried again after these pauses.
|
|
225
|
+
_DROPPED_CONNECTION = (
|
|
226
|
+
"net::ERR_CONNECTION_CLOSED", "net::ERR_CONNECTION_RESET", "net::ERR_CONNECTION_TIMED_OUT",
|
|
227
|
+
"net::ERR_TIMED_OUT", "net::ERR_EMPTY_RESPONSE", "net::ERR_NETWORK_CHANGED",
|
|
228
|
+
"net::ERR_PROXY_CONNECTION_FAILED", "net::ERR_TUNNEL_CONNECTION_FAILED", "net::ERR_NAME_NOT_RESOLVED",
|
|
229
|
+
"net::ERR_SSL_PROTOCOL_ERROR", "net::ERR_HTTP2_PROTOCOL_ERROR", "net::ERR_QUIC_PROTOCOL_ERROR",
|
|
230
|
+
)
|
|
231
|
+
DROPPED_CONNECTION_RETRY_MS = (2_000, 5_000)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def goto_retrying(page: Any, url: str, *, timeout_ms: int, wait_until: str = "commit",
|
|
235
|
+
started: float | None = None, **kwargs: Any) -> Any:
|
|
236
|
+
"""``page.goto``, again after a dropped connection while ``timeout_ms`` (counted
|
|
237
|
+
from ``started``, default now) allows. Every navigation of the download goes
|
|
238
|
+
through here: the article (``open_page``), its PDF, supplement tabs."""
|
|
239
|
+
started = time.monotonic() if started is None else started
|
|
240
|
+
dropped: BaseException | None = None
|
|
241
|
+
for attempt, pause_ms in enumerate((*DROPPED_CONNECTION_RETRY_MS, None)):
|
|
242
|
+
spent_ms = int((time.monotonic() - started) * 1000) if attempt else 0 # the first try: the whole budget
|
|
243
|
+
try:
|
|
244
|
+
return page.goto(url, wait_until=wait_until, timeout=max(1_000, timeout_ms - spent_ms), **kwargs)
|
|
245
|
+
except Exception as exc:
|
|
246
|
+
message = str(exc) if _is_browser_error(exc) else ""
|
|
247
|
+
if any(code in message for code in _DROPPED_CONNECTION):
|
|
248
|
+
dropped = exc
|
|
249
|
+
elif not (dropped and "net::ERR_ABORTED" in message):
|
|
250
|
+
raise
|
|
251
|
+
# After a dropped connection Chromium's error page reloads by itself and
|
|
252
|
+
# can cut the next try short (net::ERR_ABORTED): still the dropped
|
|
253
|
+
# connection, and reported as such (T&F through doi.org, Windows 2026-11-07).
|
|
254
|
+
spent_ms = int((time.monotonic() - started) * 1000)
|
|
255
|
+
if pause_ms is None or spent_ms + pause_ms >= timeout_ms:
|
|
256
|
+
raise dropped from (exc if exc is not dropped else None)
|
|
257
|
+
logger.info(" [Navigation] %s; trying again in %d s", message.splitlines()[0][:200], pause_ms // 1000)
|
|
258
|
+
page.wait_for_timeout(pause_ms)
|
|
259
|
+
raise AssertionError("unreachable")
|
|
260
|
+
|
|
261
|
+
|
|
221
262
|
def open_page(page: Any, url: str, *, timeout_ms: int = 60_000, ready_ms: int = 15_000, **kwargs: Any) -> Any:
|
|
222
263
|
"""Go to ``url`` and on as soon as its document can be read: the navigation
|
|
223
|
-
commits within ``timeout_ms
|
|
224
|
-
parsed or its text stops growing; a
|
|
225
|
-
once. The caller checks the page state
|
|
226
|
-
the verification wait). Returns the response."""
|
|
264
|
+
commits within ``timeout_ms`` (a dropped connection is tried again), then at
|
|
265
|
+
most ``ready_ms`` until the document is parsed or its text stops growing; a
|
|
266
|
+
verification page is left untouched at once. The caller checks the page state
|
|
267
|
+
it needs (``settle``, the access rule, the verification wait). Returns the response."""
|
|
227
268
|
committed = False
|
|
228
269
|
|
|
229
270
|
def navigated(frame: Any) -> None:
|
|
@@ -235,13 +276,12 @@ def open_page(page: Any, url: str, *, timeout_ms: int = 60_000, ready_ms: int =
|
|
|
235
276
|
page.on("framenavigated", navigated)
|
|
236
277
|
try:
|
|
237
278
|
try:
|
|
238
|
-
response = page
|
|
279
|
+
response = goto_retrying(page, url, timeout_ms=timeout_ms, started=started, **kwargs)
|
|
239
280
|
except Exception as exc:
|
|
240
281
|
# A script redirect can replace the requested navigation before goto
|
|
241
|
-
# returns (
|
|
282
|
+
# returns (net::ERR_ABORTED). Continue only after an observed
|
|
242
283
|
# top-level document commit; the caller still checks identity/access.
|
|
243
|
-
if not _is_browser_error(exc) or not
|
|
244
|
-
marker in str(exc) for marker in ("NS_ERROR_ABORT", "net::ERR_ABORTED")):
|
|
284
|
+
if not _is_browser_error(exc) or "net::ERR_ABORTED" not in str(exc):
|
|
245
285
|
raise
|
|
246
286
|
left = max(0, min(ready_ms, timeout_ms - int((time.monotonic() - started) * 1000)))
|
|
247
287
|
if not committed and not pump_until(page, lambda: committed, left):
|
|
@@ -117,8 +117,10 @@ class DiagnosticsMixin:
|
|
|
117
117
|
}.get(state)
|
|
118
118
|
if state == "login_state" and getattr(result, "_login_attention", ""):
|
|
119
119
|
report = ("等待在浏览器完成机构登录", "waiting_login")
|
|
120
|
-
if state == "challenge_wait" and detail.startswith("manual "):
|
|
121
|
-
report = ("等待人工安全验证", "waiting_verification")
|
|
120
|
+
if state == "challenge_manual_wait" or state == "challenge_wait" and detail.startswith("manual "):
|
|
121
|
+
report = (("等待人工安全验证", "waiting_verification")
|
|
122
|
+
if getattr(result, "_verification_attention", False)
|
|
123
|
+
else ("正在检查安全验证", "checking_access"))
|
|
122
124
|
if state == "login_attempt_started" and detail in {"1/3", "2/3", "3/3"}:
|
|
123
125
|
report = (f"机构登录:第 {detail[0]} 次尝试,共 3 次", "checking_access")
|
|
124
126
|
if state == "login_observed":
|