papersearch 0.4.5 → 0.4.6
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 +7 -4
- package/README.md +7 -4
- package/carsi/paper_search_carsi/adapters/ams/__init__.py +34 -1
- package/carsi/paper_search_carsi/adapters/annual_reviews/__init__.py +26 -1
- package/carsi/paper_search_carsi/adapters/aps/__init__.py +25 -2
- package/carsi/paper_search_carsi/adapters/copernicus/__init__.py +27 -1
- package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +19 -1
- package/carsi/paper_search_carsi/adapters/ieee/__init__.py +102 -2
- package/carsi/paper_search_carsi/adapters/iop/__init__.py +41 -2
- package/carsi/paper_search_carsi/adapters/lww/ovid.py +4 -2
- package/carsi/paper_search_carsi/adapters/optica/__init__.py +14 -1
- package/carsi/paper_search_carsi/adapters/oup/__init__.py +105 -94
- package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +26 -12
- package/carsi/paper_search_carsi/adapters/platforms/figshare/__init__.py +20 -11
- package/carsi/paper_search_carsi/adapters/platforms/silverchair/__init__.py +1 -1
- package/carsi/paper_search_carsi/adapters/plos/__init__.py +31 -1
- package/carsi/paper_search_carsi/adapters/thieme/__init__.py +25 -2
- package/carsi/paper_search_carsi/assets/capsule.html +45 -19
- package/carsi/paper_search_carsi/assets/papersearch-notifier +0 -0
- package/carsi/paper_search_carsi/assets/quiet-browser/api.js +119 -0
- package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +24 -0
- package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +1 -0
- package/carsi/paper_search_carsi/browser/backend.py +36 -0
- package/carsi/paper_search_carsi/browser/background.py +68 -0
- package/carsi/paper_search_carsi/browser/challenge_interaction.py +35 -0
- package/carsi/paper_search_carsi/browser/challenges.py +10 -0
- package/carsi/paper_search_carsi/browser/foreground.py +201 -0
- package/carsi/paper_search_carsi/browser/login.py +3 -1
- package/carsi/paper_search_carsi/browser/preview.py +3 -1
- package/carsi/paper_search_carsi/config.py +4 -1
- package/carsi/paper_search_carsi/engine/batch.py +62 -20
- package/carsi/paper_search_carsi/engine/batch_capture.py +54 -19
- package/carsi/paper_search_carsi/engine/batch_common.py +29 -2
- package/carsi/paper_search_carsi/engine/batch_diagnostics.py +10 -0
- package/carsi/paper_search_carsi/engine/batch_institution.py +56 -14
- package/carsi/paper_search_carsi/engine/batch_login.py +254 -198
- package/carsi/paper_search_carsi/engine/batch_user.py +67 -2
- package/carsi/paper_search_carsi/engine/batch_waits.py +65 -30
- package/carsi/paper_search_carsi/engine/login_wait.py +125 -0
- package/carsi/paper_search_carsi/engine/page_activity.py +163 -0
- package/carsi/paper_search_carsi/engine/supplements.py +12 -1
- package/carsi/paper_search_carsi/entitlements.py +23 -3
- package/carsi/paper_search_carsi/progress_capsule.py +130 -18
- package/carsi/paper_search_carsi/progress_macos.py +166 -0
- package/carsi/paper_search_carsi/progress_reporter.py +22 -1
- package/carsi/paper_search_carsi/progress_view.py +1 -0
- package/carsi/paper_search_carsi/publishers/profiles.py +5 -3
- package/carsi/paper_search_carsi/server.py +17 -1
- package/carsi/paper_search_carsi/user_settings.py +4 -4
- package/carsi/pyproject.toml +1 -1
- package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +2 -2
- 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 +28 -4
- package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
- package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts +2 -6
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts.map +1 -1
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js +1 -0
- package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js.map +1 -1
- package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
- package/dist/infrastructure/runlog/failureClass.js +3 -2
- package/dist/infrastructure/runlog/failureClass.js.map +1 -1
- package/dist/management/carsi/installer.d.ts +2 -1
- package/dist/management/carsi/installer.d.ts.map +1 -1
- package/dist/management/carsi/installer.js +24 -1
- package/dist/management/carsi/installer.js.map +1 -1
- package/package.json +1 -1
- package/skills/paper-search/references/browser-download.md +11 -7
- package/skills/paper-search/references/carsi-setup.md +1 -0
- package/skills/paper-search/references/publisher-support.md +42 -41
|
@@ -126,32 +126,58 @@ class PublisherBatchDownloader(
|
|
|
126
126
|
self._adapter = cls(self)
|
|
127
127
|
return self._adapter
|
|
128
128
|
|
|
129
|
-
def _download_in_new_tab(self, page: Any, url: str) -> tuple[Path, str]:
|
|
129
|
+
def _download_in_new_tab(self, page: Any, url: str, *, result: DownloadResult | None = None) -> tuple[Path, str]:
|
|
130
130
|
"""Open the file in a new tab, as typed in the address bar, and take what
|
|
131
131
|
the browser downloads. Clicks on the page were flaky after the first
|
|
132
132
|
file (a later file's download never started); new tabs took 8 of 8
|
|
133
133
|
(Taylor & Francis with ego, 2026-11-01)."""
|
|
134
|
+
from .page_activity import transfer
|
|
135
|
+
from .supplements import MAX_FILE_BYTES
|
|
136
|
+
|
|
134
137
|
tab = page.context.new_page()
|
|
138
|
+
path = None
|
|
139
|
+
completed = False
|
|
135
140
|
try:
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
141
|
+
activity = getattr(result, "_page_activity", None)
|
|
142
|
+
if activity is not None:
|
|
143
|
+
activity.observe(tab)
|
|
144
|
+
downloads = []
|
|
145
|
+
tab.on("download", lambda item: downloads.append(item))
|
|
146
|
+
deadline = time.monotonic() + 60
|
|
147
|
+
try:
|
|
148
|
+
referer = str(page.url)
|
|
149
|
+
tab.goto(url, timeout=60_000,
|
|
150
|
+
**({"referer": referer} if referer.startswith(("http://", "https://")) else {}))
|
|
151
|
+
except Exception as exc:
|
|
152
|
+
if not _is_browser_error(exc):
|
|
153
|
+
raise
|
|
143
154
|
with tempfile.NamedTemporaryFile(prefix="papersearch-supplement-", suffix=".part", delete=False) as fh:
|
|
144
155
|
path = Path(fh.name)
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
156
|
+
while time.monotonic() < deadline:
|
|
157
|
+
if result is not None:
|
|
158
|
+
self._check_user_decision(result, tab)
|
|
159
|
+
if downloads:
|
|
160
|
+
download = downloads[0]
|
|
161
|
+
with transfer(result):
|
|
162
|
+
download.save_as(str(path))
|
|
163
|
+
name = download.suggested_filename
|
|
164
|
+
download.delete()
|
|
165
|
+
completed = True
|
|
166
|
+
return path, name
|
|
167
|
+
if self._pdf_viewer_present(tab):
|
|
168
|
+
# Inline attachments produce no download event. Reuse the
|
|
169
|
+
# native reader, copying at most 1 MiB across each bridge
|
|
170
|
+
# call directly to disk, under the attachment size limit.
|
|
171
|
+
with transfer(result):
|
|
172
|
+
saved = self._capture_loaded_pdf_viewer(tab, url, output=path, max_bytes=MAX_FILE_BYTES)
|
|
173
|
+
if saved == path:
|
|
174
|
+
completed = True
|
|
175
|
+
return path, Path(unquote(urlparse(url).path)).name or "supplement.pdf"
|
|
176
|
+
tab.wait_for_timeout(min(250, max(1, int((deadline - time.monotonic()) * 1000))))
|
|
177
|
+
raise TimeoutError("attachment download or native PDF was not ready")
|
|
154
178
|
finally:
|
|
179
|
+
if path is not None and not completed:
|
|
180
|
+
path.unlink(missing_ok=True)
|
|
155
181
|
tab.close()
|
|
156
182
|
|
|
157
183
|
def collect_supplements(self, context: Any, doi: str, output_dir: Path,
|
|
@@ -162,6 +188,7 @@ class PublisherBatchDownloader(
|
|
|
162
188
|
from .supplement_transfer import browser_request
|
|
163
189
|
|
|
164
190
|
self._phase(result, "supplements")
|
|
191
|
+
main_state = result.state
|
|
165
192
|
progress_reporter.update(part="supplements", supplements_saved=0, supplements_total=None)
|
|
166
193
|
try:
|
|
167
194
|
page = context.new_page()
|
|
@@ -191,8 +218,20 @@ class PublisherBatchDownloader(
|
|
|
191
218
|
self._event(result, "supplements_failed", "verification not completed")
|
|
192
219
|
return [{"status": "failed", "reason": "challenge_timeout", "url": url, "label": ""}]
|
|
193
220
|
settle(page, 2_000)
|
|
194
|
-
|
|
195
|
-
|
|
221
|
+
while True:
|
|
222
|
+
# The initial check can finish on a blank redirect, and
|
|
223
|
+
# the adapter can trigger a later navigation. Neither is
|
|
224
|
+
# evidence that the article has no supplementary files.
|
|
225
|
+
self._wait_for_page_text(page, result)
|
|
226
|
+
if not self._wait_for_challenge(page, result):
|
|
227
|
+
self._event(result, "supplements_failed", "verification not completed")
|
|
228
|
+
return [{"status": "failed", "reason": "challenge_timeout", "url": url, "label": ""}]
|
|
229
|
+
self._wait_for_page_text(page, result)
|
|
230
|
+
if self._challenge_shell(page) or self._is_challenge_page(page):
|
|
231
|
+
continue
|
|
232
|
+
links = self._settled_supplement_links(page, doi)
|
|
233
|
+
if not (self._challenge_shell(page) or self._is_challenge_page(page)):
|
|
234
|
+
break
|
|
196
235
|
if links is None:
|
|
197
236
|
self._event(result, "supplements_not_supported", self.profile.name)
|
|
198
237
|
return [{"status": "skipped", "reason": "supplements_not_supported", "url": url, "label": ""}]
|
|
@@ -215,7 +254,8 @@ class PublisherBatchDownloader(
|
|
|
215
254
|
files = supplements.collect(request, links, Path(output_dir), doi,
|
|
216
255
|
manifest_dir=manifest_dir,
|
|
217
256
|
target_dir=Path(output_dir) / "supplements" if self.config.get("diagnostics_dir") else None,
|
|
218
|
-
download=lambda url: self._download_in_new_tab(page, url),
|
|
257
|
+
download=lambda url: self._download_in_new_tab(page, url, result=result),
|
|
258
|
+
activity=user_watch.activity.progress,
|
|
219
259
|
progress=lambda saved: progress_reporter.update(supplements_saved=saved))
|
|
220
260
|
saved = sum(1 for f in files if f.get("status") == "saved")
|
|
221
261
|
self._event(result, "supplements_saved", f"{saved}/{len(files)}")
|
|
@@ -250,6 +290,8 @@ class PublisherBatchDownloader(
|
|
|
250
290
|
finally:
|
|
251
291
|
user_watch.set()
|
|
252
292
|
watchdog.clear_interrupt()
|
|
293
|
+
if result.ok:
|
|
294
|
+
result.state = main_state
|
|
253
295
|
self._close_phase(result)
|
|
254
296
|
try:
|
|
255
297
|
page.close()
|
|
@@ -19,6 +19,7 @@ from urllib.parse import urljoin, urlparse
|
|
|
19
19
|
import requests
|
|
20
20
|
|
|
21
21
|
from . import access_rules
|
|
22
|
+
from .page_activity import transfer
|
|
22
23
|
from .batch_common import (
|
|
23
24
|
page_operation,
|
|
24
25
|
POLL_MS,
|
|
@@ -173,7 +174,8 @@ class CaptureMixin:
|
|
|
173
174
|
continue
|
|
174
175
|
tries[url] = tries.get(url, 0) + 1
|
|
175
176
|
try:
|
|
176
|
-
|
|
177
|
+
with transfer(result):
|
|
178
|
+
fetched = page.evaluate(self._FETCH_PDF_JS, {"url": url, "timeout": int(min(10, remaining) * 1000)})
|
|
177
179
|
except Exception as exc:
|
|
178
180
|
if not _is_browser_error(exc):
|
|
179
181
|
raise
|
|
@@ -410,7 +412,8 @@ class CaptureMixin:
|
|
|
410
412
|
or not self._response_matches_article(response, doi, **article_options)):
|
|
411
413
|
rejected_pdf_urls.update(self._response_urls(response))
|
|
412
414
|
return
|
|
413
|
-
|
|
415
|
+
with transfer(result):
|
|
416
|
+
payload = cdp_session.send("Fetch.getResponseBody", {"requestId": request_id})
|
|
414
417
|
body = (
|
|
415
418
|
base64.b64decode(payload["body"], validate=True)
|
|
416
419
|
if payload.get("base64Encoded")
|
|
@@ -534,7 +537,8 @@ class CaptureMixin:
|
|
|
534
537
|
if self._should_defer_response_body(url):
|
|
535
538
|
captured["deferred_url"] = url
|
|
536
539
|
return
|
|
537
|
-
|
|
540
|
+
with transfer(result):
|
|
541
|
+
body = response.body()
|
|
538
542
|
# Body-level block-page detection (some block pages are 200
|
|
539
543
|
# with an HTML "IP Address Blocked" body).
|
|
540
544
|
if not body[:5] == b"%PDF-" and not captured["block_reason"]:
|
|
@@ -714,7 +718,8 @@ class CaptureMixin:
|
|
|
714
718
|
if not self._refusal_answer(response):
|
|
715
719
|
rejected_pdf_urls.update(self._response_urls(response))
|
|
716
720
|
else:
|
|
717
|
-
|
|
721
|
+
with transfer(result):
|
|
722
|
+
body = response.body()
|
|
718
723
|
if self._accept_pdf_body(body, response_url):
|
|
719
724
|
captured["bytes"] = body
|
|
720
725
|
captured["url"] = response.url
|
|
@@ -1145,7 +1150,8 @@ class CaptureMixin:
|
|
|
1145
1150
|
if (self._uses_article_pdf_validation()
|
|
1146
1151
|
and self._is_supplementary_url(str(getattr(download, "suggested_filename", "") or ""))):
|
|
1147
1152
|
return None, pdf_url
|
|
1148
|
-
|
|
1153
|
+
with transfer(result):
|
|
1154
|
+
path = download.path()
|
|
1149
1155
|
body = Path(path).read_bytes()
|
|
1150
1156
|
final_url = str(getattr(download, "url", "") or pdf_url)
|
|
1151
1157
|
if self._uses_article_pdf_validation() and (
|
|
@@ -1358,7 +1364,8 @@ class CaptureMixin:
|
|
|
1358
1364
|
page.wait_for_timeout(2 * POLL_MS)
|
|
1359
1365
|
return None, ""
|
|
1360
1366
|
|
|
1361
|
-
def _capture_loaded_pdf_viewer(self, page: Any, source_url: str
|
|
1367
|
+
def _capture_loaded_pdf_viewer(self, page: Any, source_url: str, *,
|
|
1368
|
+
output: Path | None = None, max_bytes: int | None = None) -> bytes | Path | None:
|
|
1362
1369
|
"""Read a PDF already loaded by Firefox's native PDF.js viewer.
|
|
1363
1370
|
|
|
1364
1371
|
The viewer runs in a privileged native realm. Accessing its
|
|
@@ -1369,7 +1376,7 @@ class CaptureMixin:
|
|
|
1369
1376
|
repeated ``app.open`` calls while the document loads.
|
|
1370
1377
|
"""
|
|
1371
1378
|
script = r"""
|
|
1372
|
-
async (sourceUrl) => {
|
|
1379
|
+
async ({sourceUrl, maxBytes}) => {
|
|
1373
1380
|
try {
|
|
1374
1381
|
const nativeWindow = window.wrappedJSObject || window;
|
|
1375
1382
|
const nativeLocation = String(nativeWindow.location?.href || "");
|
|
@@ -1409,7 +1416,12 @@ class CaptureMixin:
|
|
|
1409
1416
|
if (!app.pdfDocument || typeof app.pdfDocument.getData !== "function") {
|
|
1410
1417
|
return null;
|
|
1411
1418
|
}
|
|
1419
|
+
if (maxBytes) {
|
|
1420
|
+
const info = await app.pdfDocument.getDownloadInfo();
|
|
1421
|
+
if (info.length > maxBytes) return {oversized: info.length};
|
|
1422
|
+
}
|
|
1412
1423
|
const data = await app.pdfDocument.getData();
|
|
1424
|
+
if (maxBytes && data.byteLength > maxBytes) return {oversized: data.byteLength};
|
|
1413
1425
|
// Crossing the Xray/automation boundary with one large Blob
|
|
1414
1426
|
// causes a large transient allocation. Keep the native bytes
|
|
1415
1427
|
// here and transfer at most 1 MiB per bridge call instead.
|
|
@@ -1439,11 +1451,14 @@ class CaptureMixin:
|
|
|
1439
1451
|
}
|
|
1440
1452
|
"""
|
|
1441
1453
|
try:
|
|
1442
|
-
encoded = page.evaluate(script, source_url)
|
|
1454
|
+
encoded = page.evaluate(script, {"sourceUrl": source_url, "maxBytes": max_bytes})
|
|
1443
1455
|
except Exception:
|
|
1444
1456
|
return None
|
|
1457
|
+
if isinstance(encoded, dict) and "oversized" in encoded:
|
|
1458
|
+
from .supplements import SupplementTooLarge
|
|
1459
|
+
raise SupplementTooLarge(encoded["oversized"])
|
|
1445
1460
|
if isinstance(encoded, dict) and isinstance(encoded.get("transfer"), str):
|
|
1446
|
-
return self._read_viewer_chunks(page, encoded["transfer"], encoded.get("size"))
|
|
1461
|
+
return self._read_viewer_chunks(page, encoded["transfer"], encoded.get("size"), output=output)
|
|
1447
1462
|
if not isinstance(encoded, str) or not encoded.startswith("data:"):
|
|
1448
1463
|
return None
|
|
1449
1464
|
try:
|
|
@@ -1452,11 +1467,14 @@ class CaptureMixin:
|
|
|
1452
1467
|
except (ValueError, TypeError):
|
|
1453
1468
|
return None
|
|
1454
1469
|
if len(body) > MIN_PDF_BYTES and body.startswith(b"%PDF-"):
|
|
1470
|
+
if output is not None:
|
|
1471
|
+
output.write_bytes(body)
|
|
1472
|
+
return output
|
|
1455
1473
|
return body
|
|
1456
1474
|
return None
|
|
1457
1475
|
|
|
1458
1476
|
@staticmethod
|
|
1459
|
-
def _read_viewer_chunks(page: Any, token: str, size: Any) -> bytes | None:
|
|
1477
|
+
def _read_viewer_chunks(page: Any, token: str, size: Any, *, output: Path | None = None) -> bytes | Path | None:
|
|
1460
1478
|
"""Bound bridge/Blob allocations while preserving exact bytes and cleanup."""
|
|
1461
1479
|
read_chunk = r"""async ({token, offset, length}) => {
|
|
1462
1480
|
try {
|
|
@@ -1476,22 +1494,38 @@ class CaptureMixin:
|
|
|
1476
1494
|
} catch (_) { return null; }
|
|
1477
1495
|
}"""
|
|
1478
1496
|
body = bytearray()
|
|
1497
|
+
sink = None
|
|
1498
|
+
complete = False
|
|
1479
1499
|
try:
|
|
1480
1500
|
if type(size) is not int or size <= MIN_PDF_BYTES:
|
|
1481
1501
|
return None
|
|
1502
|
+
if output is not None:
|
|
1503
|
+
sink = output.open("wb")
|
|
1482
1504
|
for offset in range(0, size, 1024 * 1024):
|
|
1483
1505
|
length = min(1024 * 1024, size - offset)
|
|
1484
1506
|
encoded = page.evaluate(read_chunk, {"token": token, "offset": offset, "length": length})
|
|
1485
1507
|
if not isinstance(encoded, str) or not encoded.startswith("data:"):
|
|
1486
1508
|
return None
|
|
1487
1509
|
part = base64.b64decode(encoded.split(",", 1)[1], validate=True)
|
|
1488
|
-
if len(part) != length:
|
|
1510
|
+
if len(part) != length or (offset == 0 and not part.startswith(b"%PDF-")):
|
|
1489
1511
|
return None
|
|
1490
|
-
|
|
1512
|
+
if sink is not None:
|
|
1513
|
+
sink.write(part)
|
|
1514
|
+
else:
|
|
1515
|
+
body.extend(part)
|
|
1516
|
+
complete = True
|
|
1517
|
+
if output is not None:
|
|
1518
|
+
return output
|
|
1491
1519
|
return bytes(body) if body.startswith(b"%PDF-") else None
|
|
1492
1520
|
except Exception:
|
|
1521
|
+
if output is not None:
|
|
1522
|
+
raise
|
|
1493
1523
|
return None
|
|
1494
1524
|
finally:
|
|
1525
|
+
if sink is not None:
|
|
1526
|
+
sink.close()
|
|
1527
|
+
if output is not None and not complete:
|
|
1528
|
+
output.unlink(missing_ok=True)
|
|
1495
1529
|
try:
|
|
1496
1530
|
page.evaluate("""token => { const w = window.wrappedJSObject || window;
|
|
1497
1531
|
if (w.__carsiPdfTransfer?.token === token) delete w.__carsiPdfTransfer; }""", token)
|
|
@@ -1547,13 +1581,14 @@ class CaptureMixin:
|
|
|
1547
1581
|
from ..network import proxy_dict
|
|
1548
1582
|
proxies = proxy_dict(ctx_proxy)
|
|
1549
1583
|
try:
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1584
|
+
with transfer(getattr(self, "_item_result", None)):
|
|
1585
|
+
resp = requests.get(
|
|
1586
|
+
url,
|
|
1587
|
+
headers=headers,
|
|
1588
|
+
timeout=(10, 60),
|
|
1589
|
+
allow_redirects=True,
|
|
1590
|
+
proxies=proxies,
|
|
1591
|
+
)
|
|
1557
1592
|
# This request is not the browser: a 403/429 here (bot protection,
|
|
1558
1593
|
# ScienceDirect's challenge, 2026-10-31) says nothing about the
|
|
1559
1594
|
# browser's access and must not stop the batch. Only a block page counts.
|
|
@@ -212,7 +212,10 @@ def pump_until(page: Any, done: Callable[[], bool], timeout_ms: int, step_ms: in
|
|
|
212
212
|
# after the request and held DOMContentLoaded back until 33 s on an ad script
|
|
213
213
|
# that never answered (headless probe, 2026-11-02); the login's returns to the
|
|
214
214
|
# article waited 32-40 s each for it.
|
|
215
|
-
|
|
215
|
+
# This is DOM readiness, not an access verdict. Avoid laying out the whole
|
|
216
|
+
# article, and do not read its body at all once the parser has finished.
|
|
217
|
+
_DOCUMENT_STATE_JS = """() => [document.readyState,
|
|
218
|
+
document.readyState === 'loading' && document.body ? document.body.textContent.length : 0]"""
|
|
216
219
|
|
|
217
220
|
|
|
218
221
|
def open_page(page: Any, url: str, *, timeout_ms: int = 60_000, ready_ms: int = 15_000, **kwargs: Any) -> Any:
|
|
@@ -221,7 +224,31 @@ def open_page(page: Any, url: str, *, timeout_ms: int = 60_000, ready_ms: int =
|
|
|
221
224
|
parsed or its text stops growing; a verification page is left untouched at
|
|
222
225
|
once. The caller checks the page state it needs (``settle``, the access rule,
|
|
223
226
|
the verification wait). Returns the response."""
|
|
224
|
-
|
|
227
|
+
committed = False
|
|
228
|
+
|
|
229
|
+
def navigated(frame: Any) -> None:
|
|
230
|
+
nonlocal committed
|
|
231
|
+
if frame == page.main_frame and str(frame.url).startswith(("https://", "http://")):
|
|
232
|
+
committed = True
|
|
233
|
+
|
|
234
|
+
started = time.monotonic()
|
|
235
|
+
page.on("framenavigated", navigated)
|
|
236
|
+
try:
|
|
237
|
+
try:
|
|
238
|
+
response = page.goto(url, wait_until="commit", timeout=timeout_ms, **kwargs)
|
|
239
|
+
except Exception as exc:
|
|
240
|
+
# A script redirect can replace the requested navigation before goto
|
|
241
|
+
# returns (Firefox NS_ERROR_ABORT). Continue only after an observed
|
|
242
|
+
# top-level document commit; the caller still checks identity/access.
|
|
243
|
+
if not _is_browser_error(exc) or not any(
|
|
244
|
+
marker in str(exc) for marker in ("NS_ERROR_ABORT", "net::ERR_ABORTED")):
|
|
245
|
+
raise
|
|
246
|
+
left = max(0, min(ready_ms, timeout_ms - int((time.monotonic() - started) * 1000)))
|
|
247
|
+
if not committed and not pump_until(page, lambda: committed, left):
|
|
248
|
+
raise
|
|
249
|
+
response = None
|
|
250
|
+
finally:
|
|
251
|
+
page.remove_listener("framenavigated", navigated)
|
|
225
252
|
text = {"size": -1, "since": time.time()} # the body text's length, and since when
|
|
226
253
|
|
|
227
254
|
def readable() -> bool:
|
|
@@ -75,6 +75,13 @@ class DiagnosticsMixin:
|
|
|
75
75
|
f"{spent['slowest']} {spent['slowest_sec']:.0f} s")
|
|
76
76
|
result._last_event_at = now
|
|
77
77
|
result.events.append(item)
|
|
78
|
+
activity = getattr(result, "_page_activity", None)
|
|
79
|
+
if activity is not None and state in {
|
|
80
|
+
"article_open", "institution_federation_selected", "article_access_ready",
|
|
81
|
+
"pdf_capture_started", "browser_pdf_response_captured", "pdf_saved",
|
|
82
|
+
"supplements_found", "supplements_saved", "challenge_resolved",
|
|
83
|
+
}:
|
|
84
|
+
activity.progress()
|
|
78
85
|
# Only publish fixed phase text; event details can contain signed URLs.
|
|
79
86
|
report = {
|
|
80
87
|
"article_open": ("打开论文页面", "opening_article"),
|
|
@@ -125,6 +132,9 @@ class DiagnosticsMixin:
|
|
|
125
132
|
return ""
|
|
126
133
|
now = time.monotonic()
|
|
127
134
|
current = getattr(result, "_phase_now", None)
|
|
135
|
+
activity = getattr(result, "_page_activity", None)
|
|
136
|
+
if activity is not None and name and (current is None or current[0] != name):
|
|
137
|
+
activity.progress()
|
|
128
138
|
if current:
|
|
129
139
|
result.phases[current[0]] = round(result.phases.get(current[0], 0.0) + now - current[1], 1)
|
|
130
140
|
result._phase_now = (name, now) if name else None
|
|
@@ -190,9 +190,10 @@ class InstitutionMixin:
|
|
|
190
190
|
}
|
|
191
191
|
return null;
|
|
192
192
|
}"""
|
|
193
|
-
# The chooser's own submit: the nearest
|
|
194
|
-
# the first after it
|
|
195
|
-
#
|
|
193
|
+
# The chooser's own submit: the nearest control around what was chosen,
|
|
194
|
+
# the first after it. A custom UI can hide both its school list and native
|
|
195
|
+
# submit; a unique nearby native Select/Continue still belongs to it.
|
|
196
|
+
# What was chosen is a list (its index among document.querySelectorAll('select')) or
|
|
196
197
|
# an entry (a selector), whose form's controls only, or with no form none of
|
|
197
198
|
# another form's; ``controls`` names the controls that count (null: any button
|
|
198
199
|
# or link-button). Never a control of the page outside the chooser, such as the
|
|
@@ -200,18 +201,23 @@ class InstitutionMixin:
|
|
|
200
201
|
_LIST_SUBMIT_JS = r"""([anchor, controls]) => {
|
|
201
202
|
const s = typeof anchor === 'number' ? document.querySelectorAll('select')[anchor] : document.querySelector(anchor);
|
|
202
203
|
if (!s) return null;
|
|
203
|
-
const own =
|
|
204
|
+
const own = s.form || s.closest('form');
|
|
204
205
|
const shown = el => el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden' && !el.disabled;
|
|
205
|
-
const text = el => (el.innerText || el.value || el.getAttribute('aria-label') || el.getAttribute('title') || '')
|
|
206
|
+
const text = el => (el.innerText || el.value || el.textContent || el.getAttribute('aria-label') || el.getAttribute('title') || '')
|
|
206
207
|
.replace(/\s+/g, ' ').trim();
|
|
207
208
|
const CONTROL = controls || ('button, input[type="submit"], input[type="button"], input[type="image"], '
|
|
208
209
|
+ 'a[href^="javascript" i], a[role="button"], [role="button"], a.button, a.btn');
|
|
209
|
-
const NOT = /cancel|back|reset|clear|register|personal|sign ?up|help|close|remember|forgot/i;
|
|
210
|
+
const NOT = /cancel|back|reset|clear|register|personal|sign ?up|help|close|remember|forgot|subscribe|purchase|\bbuy\b/i;
|
|
211
|
+
const NATIVE_ACTION = /^(?:select|continue|go|next|sign\s*in|log\s*in|选择|继续|登录)$|access.*institut/i;
|
|
210
212
|
for (let box = s.parentElement, n = 0; box && n < 6; box = box.parentElement, n++) {
|
|
211
|
-
const
|
|
212
|
-
&& !NOT.test(text(c)) && (
|
|
213
|
-
|
|
214
|
-
const
|
|
213
|
+
const candidates = [...box.querySelectorAll(CONTROL)].filter(c => !s.contains(c) && !c.disabled && text(c).length <= 60
|
|
214
|
+
&& !NOT.test(text(c)) && (('form' in c ? c.form : c.closest('form')) === own));
|
|
215
|
+
const found = candidates.filter(shown);
|
|
216
|
+
const native = typeof anchor === 'number' && !shown(s) && own
|
|
217
|
+
? candidates.filter(c => c.type === 'submit' && c.form === own && !shown(c) && NATIVE_ACTION.test(text(c))) : [];
|
|
218
|
+
if (!found.length && native.length !== 1) continue;
|
|
219
|
+
const pick = native.length === 1 ? native[0]
|
|
220
|
+
: (found.find(c => s.compareDocumentPosition(c) & Node.DOCUMENT_POSITION_FOLLOWING) || found[found.length - 1]);
|
|
215
221
|
document.querySelectorAll('[data-paper-search-submit]').forEach(e => e.removeAttribute('data-paper-search-submit'));
|
|
216
222
|
pick.setAttribute('data-paper-search-submit', '');
|
|
217
223
|
return text(pick).slice(0, 80) || pick.tagName;
|
|
@@ -260,9 +266,18 @@ class InstitutionMixin:
|
|
|
260
266
|
|
|
261
267
|
@staticmethod
|
|
262
268
|
def _filled_lists(lists: Any, federation: dict) -> dict:
|
|
263
|
-
"""
|
|
269
|
+
"""Filled school lists, not the header's journal/language/search lists.
|
|
270
|
+
|
|
271
|
+
Only positive institution evidence can establish that a school is
|
|
272
|
+
missing. An unrelated filled dropdown says nothing about an empty
|
|
273
|
+
institution list that is still loading.
|
|
274
|
+
"""
|
|
275
|
+
school = re.compile(r"institut|school|universit|\buniv\b|college|organi[sz]ation|\bidp\b|大学|学院|研究院", re.I)
|
|
264
276
|
return {str(s.get("name")): list(s.get("options") or ()) for s in lists or ()
|
|
265
|
-
if s.get("i") != federation.get("i") and len(s.get("options") or ()) > 1
|
|
277
|
+
if s.get("i") != federation.get("i") and len(s.get("options") or ()) > 1
|
|
278
|
+
and (school.search(str(s.get("name") or "")) or any(
|
|
279
|
+
school.search(str(o[1])) for o in s.get("options") or ()
|
|
280
|
+
if isinstance(o, (list, tuple)) and len(o) == 2))}
|
|
266
281
|
|
|
267
282
|
# The list chosen in, marked by its index among document.querySelectorAll('select'):
|
|
268
283
|
# a locator's "select" would also count lists inside shadow roots.
|
|
@@ -591,12 +606,39 @@ class InstitutionMixin:
|
|
|
591
606
|
entries = []
|
|
592
607
|
for role in ("link", "button"):
|
|
593
608
|
try:
|
|
594
|
-
for entry in page.get_by_role(role, name=re.compile(r"^\s*access through\s
|
|
609
|
+
for entry in page.get_by_role(role, name=re.compile(r"^\s*access through\s*\S", re.I)).all()[:10]:
|
|
595
610
|
if entry.is_visible() is True:
|
|
596
|
-
label = re.sub(r"^\s*access through\s
|
|
611
|
+
label = re.sub(r"^\s*access through\s*", "", entry.inner_text(timeout=1_000), flags=re.I)
|
|
597
612
|
entries.append((self._institution_match_score(label), label, entry))
|
|
598
613
|
except Exception:
|
|
599
614
|
continue
|
|
615
|
+
if not any(score >= 2 for score, _, _ in entries):
|
|
616
|
+
# A widget's accessible name can differ from its visible school
|
|
617
|
+
# text, or it can be a clickable div/span without a role. Use
|
|
618
|
+
# the visible control text, still requiring a click affordance.
|
|
619
|
+
candidates = page.evaluate("""() => {
|
|
620
|
+
document.querySelectorAll('[data-paper-search-remembered]').forEach(e =>
|
|
621
|
+
e.removeAttribute('data-paper-search-remembered'));
|
|
622
|
+
const items = [...document.querySelectorAll('a,button,[role="button"],div,span')].filter(el => {
|
|
623
|
+
const native = el.matches('a[href],button,[role="button"]');
|
|
624
|
+
if (!native && el.closest('a,button,[role="button"]')) return false;
|
|
625
|
+
const text = (el.textContent || '').trim();
|
|
626
|
+
return text.length <= 160 && /^access through\\s*\\S/i.test(text)
|
|
627
|
+
&& el.getClientRects().length > 0 && getComputedStyle(el).visibility !== 'hidden'
|
|
628
|
+
&& !el.disabled && el.getAttribute('aria-disabled') !== 'true'
|
|
629
|
+
&& (native || typeof el.onclick === 'function' || getComputedStyle(el).cursor === 'pointer');
|
|
630
|
+
});
|
|
631
|
+
return items.filter(el => !items.some(other => other !== el && el.contains(other)))
|
|
632
|
+
.slice(0,10).map((el,i) => {
|
|
633
|
+
el.setAttribute('data-paper-search-remembered', String(i));
|
|
634
|
+
return {i, text:(el.textContent || '').trim()};
|
|
635
|
+
});
|
|
636
|
+
}""")
|
|
637
|
+
if isinstance(candidates, list):
|
|
638
|
+
for candidate in candidates:
|
|
639
|
+
label = re.sub(r"^\s*access through\s*", "", candidate["text"], flags=re.I)
|
|
640
|
+
entries.append((self._institution_match_score(label), label,
|
|
641
|
+
page.locator(f'[data-paper-search-remembered="{candidate["i"]}"]')))
|
|
600
642
|
top = max((score for score, _, _ in entries), default=0)
|
|
601
643
|
best = [(label, entry) for score, label, entry in entries if score == top]
|
|
602
644
|
if top >= 2 and len(best) == 1:
|