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
|
@@ -15,7 +15,6 @@ from ..entitlements import UserMarkedNoEntitlement
|
|
|
15
15
|
from ..browser import challenge_interaction, challenges, watchdog
|
|
16
16
|
from .batch_common import (AWAY_WAIT_SEC, DownloadResult, _IP_BLOCK_STATUS_CODES, _observe_preview)
|
|
17
17
|
|
|
18
|
-
|
|
19
18
|
class UserWaitMixin:
|
|
20
19
|
"""Waiting on the user: human verification, the PDF step's checks, the per-article wait budget."""
|
|
21
20
|
|
|
@@ -114,6 +113,7 @@ class UserWaitMixin:
|
|
|
114
113
|
def _wait_out_suspect_block(self, page: Any, result: DownloadResult, captured: dict[str, Any], suspect: str,
|
|
115
114
|
suspect_host: str, started: float) -> bool:
|
|
116
115
|
deadline = started + self.page_wait_sec
|
|
116
|
+
activity, activity_owned = self._observe_page_activity(page, result)
|
|
117
117
|
automatic: dict[str, Any] = {}
|
|
118
118
|
interaction = ExitStack()
|
|
119
119
|
manual = False
|
|
@@ -125,9 +125,6 @@ class UserWaitMixin:
|
|
|
125
125
|
except Exception:
|
|
126
126
|
reporter = None
|
|
127
127
|
shown = "" # "verification" | "login" | "unknown"
|
|
128
|
-
messages = {"verification": ("请在浏览器窗口完成人机验证", "waiting_verification", "人工验证"),
|
|
129
|
-
"login": ("请在浏览器窗口完成机构登录", "waiting_login", "机构登录"),
|
|
130
|
-
"unknown": ("请查看浏览器窗口:PDF 请求被拒绝,正在等待页面变化", "waiting_verification", "人工处理")}
|
|
131
128
|
try:
|
|
132
129
|
while time.time() < deadline:
|
|
133
130
|
self._check_user_decision(result, page)
|
|
@@ -188,11 +185,15 @@ class UserWaitMixin:
|
|
|
188
185
|
return False
|
|
189
186
|
if state == "verification":
|
|
190
187
|
self._raise_on_publisher_access_blocked(tab)
|
|
188
|
+
result._attention_page = tab
|
|
189
|
+
activity.observe(tab)
|
|
190
|
+
activity.check()
|
|
191
191
|
if not automatic:
|
|
192
192
|
deadline = min(deadline, self._wait_deadline(result))
|
|
193
|
-
if self._automatic_challenge_step(tab, result, automatic, deadline):
|
|
193
|
+
if not manual and self._automatic_challenge_step(tab, result, automatic, deadline):
|
|
194
194
|
page.wait_for_timeout(min(1000, max(0, (deadline - time.time()) * 1000)))
|
|
195
195
|
continue
|
|
196
|
+
result._attention_page = tab
|
|
196
197
|
if state != shown:
|
|
197
198
|
if state in ("verification", "login"):
|
|
198
199
|
deadline = min(deadline, self._wait_deadline(result))
|
|
@@ -201,15 +202,18 @@ class UserWaitMixin:
|
|
|
201
202
|
# The capsule requests attention; leave desktop focus with
|
|
202
203
|
# the user until they choose to open the browser themselves.
|
|
203
204
|
if reporter is not None:
|
|
204
|
-
text, stage, phase = messages[state]
|
|
205
205
|
try:
|
|
206
206
|
if shown:
|
|
207
207
|
reporter.clear_attention(attention_key)
|
|
208
|
-
|
|
209
|
-
|
|
208
|
+
if state == "login":
|
|
209
|
+
reporter.set_attention(attention_key, "请在浏览器窗口完成机构登录",
|
|
210
|
+
current=result.doi, phase="机构登录", deadline=deadline)
|
|
211
|
+
reporter.report_stage("waiting_login", current=result.doi)
|
|
210
212
|
except Exception:
|
|
211
213
|
pass
|
|
212
214
|
shown = state
|
|
215
|
+
activity.observe(tab)
|
|
216
|
+
activity.check()
|
|
213
217
|
if not manual:
|
|
214
218
|
interaction.enter_context(watchdog.pause_operation())
|
|
215
219
|
manual = True
|
|
@@ -232,6 +236,9 @@ class UserWaitMixin:
|
|
|
232
236
|
self._event(result, "ip_blocked_response", f"{suspect} | no PDF after waiting ({shown or 'nothing shown'})")
|
|
233
237
|
return False
|
|
234
238
|
finally:
|
|
239
|
+
result._attention_page = None
|
|
240
|
+
if activity_owned:
|
|
241
|
+
activity.close()
|
|
235
242
|
interaction.close()
|
|
236
243
|
if shown and reporter is not None:
|
|
237
244
|
try:
|
|
@@ -243,6 +250,10 @@ class UserWaitMixin:
|
|
|
243
250
|
"""Apply a button the user pressed in the progress window for this paper."""
|
|
244
251
|
if result is None:
|
|
245
252
|
return
|
|
253
|
+
activity = getattr(result, "_page_activity", None)
|
|
254
|
+
if activity is not None and not activity.closed:
|
|
255
|
+
if page is not None:
|
|
256
|
+
activity.observe(page)
|
|
246
257
|
self._capture_reported_issues(page, result)
|
|
247
258
|
try:
|
|
248
259
|
from .. import entitlements
|
|
@@ -256,6 +267,9 @@ class UserWaitMixin:
|
|
|
256
267
|
self._event(result, "user_entitlement_decision", str(decision))
|
|
257
268
|
raise
|
|
258
269
|
if action:
|
|
270
|
+
if action == entitlements.SHOW_BROWSER:
|
|
271
|
+
self._show_download_browser(page, result)
|
|
272
|
+
return
|
|
259
273
|
self._event(result, "user_entitlement_decision", action)
|
|
260
274
|
|
|
261
275
|
@staticmethod
|
|
@@ -323,6 +337,9 @@ class UserWaitMixin:
|
|
|
323
337
|
def _user_wait_deadline(self, result: DownloadResult) -> float:
|
|
324
338
|
"""One deadline for all waits on the user in this article (verification,
|
|
325
339
|
school login, the PDF step): ``login_timeout_sec`` from the first of them."""
|
|
340
|
+
wait = getattr(result, "_login_wait", None)
|
|
341
|
+
if wait is not None and wait.attribute == "_user_wait_deadline":
|
|
342
|
+
return wait.deadline
|
|
326
343
|
deadline = getattr(result, "_user_wait_deadline", None)
|
|
327
344
|
if deadline is None:
|
|
328
345
|
deadline = result._user_wait_deadline = time.time() + self.login_timeout_sec
|
|
@@ -371,6 +388,11 @@ class UserWaitMixin:
|
|
|
371
388
|
automatic_end = min(deadline - manual_reserve, attempt["automatic_end"])
|
|
372
389
|
if now >= automatic_end or (attempt["attempts"] >= 3 and now >= attempt["retry_at"]):
|
|
373
390
|
return False
|
|
391
|
+
if challenge_interaction.needs_manual_verification(page):
|
|
392
|
+
# We never operate this control. Waiting for it must not consume
|
|
393
|
+
# the enclosing automation budget, even if the site clears itself.
|
|
394
|
+
# The independent idle timer still decides when to remind the user.
|
|
395
|
+
return False
|
|
374
396
|
if now >= attempt["retry_at"] and attempt["attempts"] < 3:
|
|
375
397
|
# Camoufox's native humanized move can take 1.5 s before mouse-down.
|
|
376
398
|
# Leave time for that action, still inside the original wait budget.
|
|
@@ -388,17 +410,13 @@ class UserWaitMixin:
|
|
|
388
410
|
def _wait_for_challenge(self, page: Any, result: DownloadResult, *, deadline: float | None = None) -> bool:
|
|
389
411
|
"""Wait while a verification page is up, until ``_wait_deadline``."""
|
|
390
412
|
interaction = ExitStack()
|
|
413
|
+
activity, activity_owned = self._observe_page_activity(page, result)
|
|
391
414
|
automatic: dict[str, Any] = {}
|
|
392
415
|
manual = False
|
|
393
416
|
wait_interval_sec = 1 # a cleared verification goes on within a second
|
|
394
|
-
reporter = None
|
|
395
|
-
attention_key = f"publisher-challenge:{id(self)}:{result.doi}"
|
|
396
|
-
attention_open = False
|
|
397
|
-
try:
|
|
398
|
-
from .. import progress_reporter as reporter
|
|
399
|
-
except Exception:
|
|
400
|
-
reporter = None
|
|
401
417
|
started, phase_before = time.time(), ""
|
|
418
|
+
verification_wait = None
|
|
419
|
+
verification_deadline = None
|
|
402
420
|
try:
|
|
403
421
|
waited = False
|
|
404
422
|
state_before = result.state
|
|
@@ -409,30 +427,32 @@ class UserWaitMixin:
|
|
|
409
427
|
shell = self._challenge_shell(page)
|
|
410
428
|
if not shell:
|
|
411
429
|
self._raise_on_publisher_access_blocked(page)
|
|
412
|
-
if shell or self._is_challenge_page(page)
|
|
430
|
+
if (shell or self._is_challenge_page(page)
|
|
431
|
+
or (waited and challenges.continues_manual_challenge(self._title(page)))):
|
|
413
432
|
if not waited:
|
|
414
433
|
deadline = self._wait_deadline(result, deadline)
|
|
415
434
|
started, phase_before = time.time(), self._phase(result, "verification")
|
|
416
435
|
waited = True
|
|
417
436
|
result.state = "challenge_or_viewer_timeout"
|
|
437
|
+
if verification_wait is not None:
|
|
438
|
+
verification_wait.observe(page, True)
|
|
439
|
+
deadline = verification_wait.deadline
|
|
418
440
|
if time.time() >= deadline:
|
|
419
441
|
break
|
|
420
|
-
|
|
442
|
+
result._attention_page = page
|
|
443
|
+
activity.check()
|
|
444
|
+
auto_pending = not manual and self._automatic_challenge_step(page, result, automatic, deadline)
|
|
421
445
|
if not auto_pending and not manual:
|
|
446
|
+
result._attention_page = page
|
|
422
447
|
interaction.enter_context(watchdog.pause_operation())
|
|
423
448
|
manual = True
|
|
449
|
+
from .login_wait import LoginWait
|
|
450
|
+
verification_deadline = deadline
|
|
451
|
+
verification_wait = result._verification_wait = LoginWait(deadline, time.time)
|
|
452
|
+
verification_wait.observe(page, True)
|
|
424
453
|
self._event(result, "challenge_manual_wait", "complete verification in visible browser")
|
|
425
454
|
if not any(s["why"] == "waiting for the user: verification" for s in result.snapshots):
|
|
426
455
|
self._snapshot(page, result, "waiting for the user: verification")
|
|
427
|
-
if reporter is not None:
|
|
428
|
-
reporter.set_attention(
|
|
429
|
-
attention_key,
|
|
430
|
-
"请在浏览器窗口完成安全验证",
|
|
431
|
-
current=result.doi,
|
|
432
|
-
phase="人工验证",
|
|
433
|
-
deadline=deadline,
|
|
434
|
-
)
|
|
435
|
-
attention_open = True
|
|
436
456
|
checks += 1
|
|
437
457
|
self._event(result, "challenge_wait", f"{'manual' if manual else 'automatic'} {checks}")
|
|
438
458
|
# Pump browser events while the user completes verification.
|
|
@@ -450,20 +470,32 @@ class UserWaitMixin:
|
|
|
450
470
|
self._event(result, "challenge_resolved", getattr(page, "url", ""))
|
|
451
471
|
return True
|
|
452
472
|
self._raise_on_publisher_access_blocked(page)
|
|
453
|
-
passed = not self._is_challenge_page(page)
|
|
473
|
+
passed = not (self._is_challenge_page(page)
|
|
474
|
+
or (waited and challenges.continues_manual_challenge(self._title(page))))
|
|
454
475
|
if passed:
|
|
455
476
|
result.state = state_before
|
|
456
477
|
else:
|
|
457
478
|
self._wait_ran_out(result)
|
|
458
479
|
return passed
|
|
459
480
|
finally:
|
|
481
|
+
if verification_wait is not None:
|
|
482
|
+
excluded = max(0, verification_wait.close() - verification_deadline)
|
|
483
|
+
outer_wait = getattr(result, "_login_wait", None)
|
|
484
|
+
if outer_wait is not None:
|
|
485
|
+
if not outer_wait.paused:
|
|
486
|
+
outer_wait.exclude_elapsed(excluded)
|
|
487
|
+
elif isinstance(getattr(result, "_user_wait_deadline", None), (float, int)):
|
|
488
|
+
result._user_wait_deadline += excluded
|
|
489
|
+
result._verification_wait = None
|
|
460
490
|
interaction.close()
|
|
461
491
|
if waited:
|
|
462
492
|
self._phase(result, phase_before or "open")
|
|
463
493
|
self._note_wait(result, "verification", started, "passed" if result.state != "challenge_or_viewer_timeout"
|
|
464
494
|
else "not completed")
|
|
465
|
-
if
|
|
466
|
-
|
|
495
|
+
if activity_owned:
|
|
496
|
+
activity.close()
|
|
497
|
+
if getattr(result, "_attention_page", None) is page:
|
|
498
|
+
result._attention_page = None
|
|
467
499
|
|
|
468
500
|
def _challenge_shell(self, page: Any) -> bool:
|
|
469
501
|
"""Read only URL/title while a verification interstitial is active."""
|
|
@@ -485,4 +517,7 @@ class UserWaitMixin:
|
|
|
485
517
|
return False
|
|
486
518
|
if challenges.is_challenge_path(str(getattr(page, "url", "") or "")):
|
|
487
519
|
return True
|
|
488
|
-
|
|
520
|
+
title = self._title(page)
|
|
521
|
+
return (challenges.has_challenge_text(title, self._body_text(page, 1_200))
|
|
522
|
+
or (challenges.continues_manual_challenge(title)
|
|
523
|
+
and challenge_interaction.is_image_verification(page)))
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""A login deadline that stops while the user owns the authentication step.
|
|
2
|
+
|
|
3
|
+
Only events inside the dedicated login document are counted. No field values,
|
|
4
|
+
key contents, system input hooks or foreground-window observations are used.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from typing import Any, Callable
|
|
9
|
+
from uuid import uuid4
|
|
10
|
+
|
|
11
|
+
from ..browser import watchdog
|
|
12
|
+
from .batch_common import _is_browser_error
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
_READ_ACTIVITY = """token => {
|
|
16
|
+
const key = Symbol.for('paper-search:login-activity');
|
|
17
|
+
let state = window[key];
|
|
18
|
+
if (!state || state.token !== token) {
|
|
19
|
+
if (state) state.dispose();
|
|
20
|
+
state = {token, count: 0};
|
|
21
|
+
// Camoufox also marks script events trusted. Require native input
|
|
22
|
+
// metadata as well; submit/change alone cannot establish takeover.
|
|
23
|
+
const events = ['input', 'keydown', 'pointerdown'];
|
|
24
|
+
const record = event => {
|
|
25
|
+
if (!event.isTrusted || !(event.target instanceof Element)) return;
|
|
26
|
+
if (!event.composed) return;
|
|
27
|
+
const input = event.type === 'input' && event instanceof InputEvent && !!event.inputType;
|
|
28
|
+
const keyboard = event.type === 'keydown' && event instanceof KeyboardEvent
|
|
29
|
+
&& !!event.code && event.keyCode > 0;
|
|
30
|
+
const pointer = event.type === 'pointerdown' && event instanceof PointerEvent
|
|
31
|
+
&& ['mouse', 'touch', 'pen'].includes(event.pointerType);
|
|
32
|
+
if (!input && !keyboard && !pointer) return;
|
|
33
|
+
const control = event.target.closest(
|
|
34
|
+
'input:not([type=hidden]),textarea,select,button,label,a[href],[role=button],[contenteditable=true],form');
|
|
35
|
+
if (control) state.count++;
|
|
36
|
+
};
|
|
37
|
+
state.dispose = () => {
|
|
38
|
+
events.forEach(name => document.removeEventListener(name, record, true));
|
|
39
|
+
delete window[key];
|
|
40
|
+
};
|
|
41
|
+
events.forEach(name => document.addEventListener(name, record, true));
|
|
42
|
+
window[key] = state;
|
|
43
|
+
}
|
|
44
|
+
return state.count;
|
|
45
|
+
}"""
|
|
46
|
+
_REMOVE_ACTIVITY = """token => {
|
|
47
|
+
const state = window[Symbol.for('paper-search:login-activity')];
|
|
48
|
+
if (state && state.token === token) state.dispose();
|
|
49
|
+
}"""
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class LoginWait:
|
|
53
|
+
def __init__(self, deadline: float, clock: Callable[[], float], *, attribute: str = ""):
|
|
54
|
+
self._deadline = deadline
|
|
55
|
+
self._clock = clock
|
|
56
|
+
self._paused_at: float | None = None
|
|
57
|
+
self._token = uuid4().hex
|
|
58
|
+
self._frames: dict[Any, int] = {}
|
|
59
|
+
self.user_step = False
|
|
60
|
+
self.attribute = attribute
|
|
61
|
+
|
|
62
|
+
def _account(self) -> None:
|
|
63
|
+
if self._paused_at is not None:
|
|
64
|
+
now = self._clock()
|
|
65
|
+
self._deadline += max(0, now - self._paused_at)
|
|
66
|
+
self._paused_at = now
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def deadline(self) -> float:
|
|
70
|
+
self._account()
|
|
71
|
+
return self._deadline
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def paused(self) -> bool:
|
|
75
|
+
return self._paused_at is not None
|
|
76
|
+
|
|
77
|
+
def take_over(self) -> None:
|
|
78
|
+
"""An explicit capsule request counts only during a human login step."""
|
|
79
|
+
if self.user_step and not self.paused:
|
|
80
|
+
self._paused_at = self._clock()
|
|
81
|
+
|
|
82
|
+
def exclude_elapsed(self, seconds: float) -> None:
|
|
83
|
+
"""A nested manual verification already accounted for this time."""
|
|
84
|
+
self._deadline += max(0, seconds)
|
|
85
|
+
|
|
86
|
+
def observe(self, page: Any, user_step: bool) -> None:
|
|
87
|
+
self._account()
|
|
88
|
+
self.user_step = user_step
|
|
89
|
+
if not user_step:
|
|
90
|
+
self._paused_at = None
|
|
91
|
+
self._remove_listeners()
|
|
92
|
+
return
|
|
93
|
+
for frame in page.frames:
|
|
94
|
+
try:
|
|
95
|
+
count = frame.evaluate(_READ_ACTIVITY, self._token)
|
|
96
|
+
except Exception as exc:
|
|
97
|
+
if not _is_browser_error(exc):
|
|
98
|
+
raise
|
|
99
|
+
continue # navigation replaced this document; retry on the next pass
|
|
100
|
+
if type(count) is not int:
|
|
101
|
+
continue
|
|
102
|
+
previous = self._frames.get(frame, 0)
|
|
103
|
+
self._frames[frame] = count
|
|
104
|
+
if count > 0 and count != previous:
|
|
105
|
+
self.take_over()
|
|
106
|
+
|
|
107
|
+
def _remove_listeners(self) -> None:
|
|
108
|
+
frames, self._frames = self._frames, {}
|
|
109
|
+
# An interrupted browser cannot accept further calls. The document's
|
|
110
|
+
# small counter dies on navigation, or is replaced by the next token.
|
|
111
|
+
if watchdog.fired is not None or watchdog.interrupted is not None:
|
|
112
|
+
return
|
|
113
|
+
for frame in frames:
|
|
114
|
+
try:
|
|
115
|
+
frame.evaluate(_REMOVE_ACTIVITY, self._token)
|
|
116
|
+
except Exception as exc:
|
|
117
|
+
if not _is_browser_error(exc):
|
|
118
|
+
raise
|
|
119
|
+
|
|
120
|
+
def close(self) -> float:
|
|
121
|
+
self._account()
|
|
122
|
+
self._paused_at = None
|
|
123
|
+
self.user_step = False
|
|
124
|
+
self._remove_listeners()
|
|
125
|
+
return self._deadline
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
"""Remind the user after an owned page makes no progress, without driving it.
|
|
2
|
+
|
|
3
|
+
Main-document requests, navigation, a loaded document, a workflow step or
|
|
4
|
+
received file bytes refresh the timer. An in-flight navigation gets only the
|
|
5
|
+
existing page wait budget; polling and unrelated background traffic do not.
|
|
6
|
+
The request watcher can check the timer without making a browser RPC.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
from contextlib import contextmanager
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from .. import progress_reporter
|
|
16
|
+
from ..config import DEFAULT_CONFIG
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class PageActivity:
|
|
20
|
+
def __init__(self, doi: str, config: dict, *, clock=None):
|
|
21
|
+
self.after = int(config.get("browser_stall_notify_after",
|
|
22
|
+
DEFAULT_CONFIG["browser_stall_notify_after"]))
|
|
23
|
+
self._navigation_timeout = max(10.0, float(config.get("browser_page_wait_timeout")
|
|
24
|
+
or DEFAULT_CONFIG["browser_page_wait_timeout"]))
|
|
25
|
+
self._clock = clock or time.monotonic
|
|
26
|
+
self._last_progress = self._clock()
|
|
27
|
+
self._lock = threading.RLock()
|
|
28
|
+
self._key = f"page-stalled:{id(self)}:{doi}"
|
|
29
|
+
self._doi = doi
|
|
30
|
+
self._shown = False
|
|
31
|
+
self._transfers = 0
|
|
32
|
+
self.closed = False
|
|
33
|
+
self.page = None
|
|
34
|
+
self._pages: dict[int, tuple[Any, dict]] = {}
|
|
35
|
+
self._navigations: dict[int, tuple[Any, float]] = {}
|
|
36
|
+
|
|
37
|
+
def progress(self, page=None) -> None:
|
|
38
|
+
with self._lock:
|
|
39
|
+
if self.closed:
|
|
40
|
+
return
|
|
41
|
+
self._last_progress = self._clock()
|
|
42
|
+
if page is not None:
|
|
43
|
+
self.page = page
|
|
44
|
+
self._clear()
|
|
45
|
+
|
|
46
|
+
def _clear(self) -> None:
|
|
47
|
+
if self._shown:
|
|
48
|
+
progress_reporter.clear_attention(self._key)
|
|
49
|
+
self._shown = False
|
|
50
|
+
|
|
51
|
+
def check(self) -> None:
|
|
52
|
+
"""Thread safe; never inspect a page or interrupt an in-flight operation."""
|
|
53
|
+
with self._lock:
|
|
54
|
+
if self.closed:
|
|
55
|
+
return
|
|
56
|
+
if progress_reporter.has_attention(current=self._doi, excluding=self._key):
|
|
57
|
+
# School login and other explicit requests have priority. Start
|
|
58
|
+
# a fresh quiet interval when they finish rather than duplicating them.
|
|
59
|
+
self._last_progress = self._clock()
|
|
60
|
+
self._clear()
|
|
61
|
+
elif (not self._shown and not self._transfers
|
|
62
|
+
and not self._navigation_loading()
|
|
63
|
+
and self._clock() - self._last_progress >= self.after):
|
|
64
|
+
progress_reporter.set_attention(
|
|
65
|
+
self._key, "页面持续没有进展,请查看浏览器,可能需要手动操作",
|
|
66
|
+
current=self._doi, phase="需要人工处理")
|
|
67
|
+
self._shown = True
|
|
68
|
+
|
|
69
|
+
def _navigation_loading(self) -> bool:
|
|
70
|
+
pending = self._navigations.get(id(self.page))
|
|
71
|
+
return pending is not None and self._clock() < pending[1]
|
|
72
|
+
|
|
73
|
+
def observe(self, page) -> None:
|
|
74
|
+
"""Attach only on the browser thread, including this page's owned popups."""
|
|
75
|
+
if self.closed or id(page) in self._pages:
|
|
76
|
+
return
|
|
77
|
+
|
|
78
|
+
def navigated(frame):
|
|
79
|
+
if frame == page.main_frame:
|
|
80
|
+
self.progress(page)
|
|
81
|
+
|
|
82
|
+
def loaded():
|
|
83
|
+
with self._lock:
|
|
84
|
+
self._navigations.pop(id(page), None)
|
|
85
|
+
self.progress(page)
|
|
86
|
+
|
|
87
|
+
def requested(request):
|
|
88
|
+
# These are cached Playwright properties, not browser RPCs. Ads,
|
|
89
|
+
# analytics, XHR polling and subframes cannot silence a stuck page.
|
|
90
|
+
if not request.is_navigation_request() or request.frame != page.main_frame:
|
|
91
|
+
return
|
|
92
|
+
with self._lock:
|
|
93
|
+
previous = self._navigations.get(id(page))
|
|
94
|
+
deadline = (previous[1] if previous and request.redirected_from is previous[0]
|
|
95
|
+
else self._clock() + self._navigation_timeout)
|
|
96
|
+
self._navigations[id(page)] = (request, deadline)
|
|
97
|
+
self.progress(page)
|
|
98
|
+
|
|
99
|
+
def responded(response):
|
|
100
|
+
with self._lock:
|
|
101
|
+
pending = self._navigations.get(id(page))
|
|
102
|
+
if pending is not None and response.request is pending[0]:
|
|
103
|
+
self.progress(page)
|
|
104
|
+
|
|
105
|
+
def failed(request):
|
|
106
|
+
with self._lock:
|
|
107
|
+
pending = self._navigations.get(id(page))
|
|
108
|
+
if pending is not None and request is pending[0]:
|
|
109
|
+
self._navigations.pop(id(page), None)
|
|
110
|
+
self.progress(page)
|
|
111
|
+
|
|
112
|
+
def closed():
|
|
113
|
+
with self._lock:
|
|
114
|
+
self._pages.pop(id(page), None)
|
|
115
|
+
self._navigations.pop(id(page), None)
|
|
116
|
+
if self.page is page:
|
|
117
|
+
self.page = next((p for p, _ in reversed(list(self._pages.values()))), None)
|
|
118
|
+
self.progress()
|
|
119
|
+
for event, handler in handlers.items():
|
|
120
|
+
page.remove_listener(event, handler)
|
|
121
|
+
|
|
122
|
+
handlers = {"framenavigated": navigated, "domcontentloaded": loaded,
|
|
123
|
+
"request": requested, "response": responded, "requestfailed": failed,
|
|
124
|
+
"popup": self.observe, "close": closed}
|
|
125
|
+
self._pages[id(page)] = (page, handlers)
|
|
126
|
+
for event, handler in handlers.items():
|
|
127
|
+
page.on(event, handler)
|
|
128
|
+
self.progress(page)
|
|
129
|
+
|
|
130
|
+
@contextmanager
|
|
131
|
+
def transfer(self):
|
|
132
|
+
"""A browser body/save RPC exposes no byte events. Its existing network
|
|
133
|
+
and watchdog limits still apply; do not call it a page needing a click."""
|
|
134
|
+
with self._lock:
|
|
135
|
+
self._transfers += 1
|
|
136
|
+
self.progress()
|
|
137
|
+
try:
|
|
138
|
+
yield
|
|
139
|
+
finally:
|
|
140
|
+
with self._lock:
|
|
141
|
+
self._transfers -= 1
|
|
142
|
+
self.progress()
|
|
143
|
+
|
|
144
|
+
def close(self) -> None:
|
|
145
|
+
"""Detach on the browser thread and clear any reminder before the next item."""
|
|
146
|
+
with self._lock:
|
|
147
|
+
self.closed = True
|
|
148
|
+
self._navigations.clear()
|
|
149
|
+
self._clear()
|
|
150
|
+
for page, handlers in list(self._pages.values()):
|
|
151
|
+
for event, handler in handlers.items():
|
|
152
|
+
page.remove_listener(event, handler)
|
|
153
|
+
self._pages.clear()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@contextmanager
|
|
157
|
+
def transfer(result):
|
|
158
|
+
activity = getattr(result, "_page_activity", None)
|
|
159
|
+
if activity is None:
|
|
160
|
+
yield
|
|
161
|
+
else:
|
|
162
|
+
with activity.transfer():
|
|
163
|
+
yield
|
|
@@ -37,6 +37,12 @@ REQUEST_TIMEOUT_MS = 60_000
|
|
|
37
37
|
_DROPPED_CONNECTION = ("socket disconnected", "socket hang up", "ECONNRESET", "EPIPE")
|
|
38
38
|
|
|
39
39
|
|
|
40
|
+
class SupplementTooLarge(ValueError):
|
|
41
|
+
def __init__(self, size: int):
|
|
42
|
+
self.size = size
|
|
43
|
+
super().__init__("attachment exceeds file size limit")
|
|
44
|
+
|
|
45
|
+
|
|
40
46
|
def supplements_dir(output_dir: Path, doi: str) -> Path:
|
|
41
47
|
return Path(output_dir) / (re.sub(r"[^A-Za-z0-9._-]+", "_", doi) + "_supplements")
|
|
42
48
|
|
|
@@ -116,7 +122,8 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
|
|
|
116
122
|
manifest_dir: Path | None = None,
|
|
117
123
|
target_dir: Path | None = None,
|
|
118
124
|
download: Callable[[str], tuple[bytes | Path, str]] | None = None,
|
|
119
|
-
progress: Callable[[int], None] | None = None
|
|
125
|
+
progress: Callable[[int], None] | None = None,
|
|
126
|
+
activity: Callable[[], None] | None = None) -> list[dict[str, Any]]:
|
|
120
127
|
"""Fetch ``links`` with ``request`` (a Playwright APIRequestContext). A file
|
|
121
128
|
refused with 403 is taken through ``download`` when given: the browser
|
|
122
129
|
opens it and downloads it itself (Taylor & Francis behind Cloudflare
|
|
@@ -188,6 +195,8 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
|
|
|
188
195
|
break
|
|
189
196
|
fh.write(chunk)
|
|
190
197
|
last_progress = now
|
|
198
|
+
if activity is not None:
|
|
199
|
+
activity()
|
|
191
200
|
_check_interrupted()
|
|
192
201
|
if size > MAX_FILE_BYTES:
|
|
193
202
|
entry.update(status="skipped", reason="too_large", size=size)
|
|
@@ -200,6 +209,8 @@ def collect(request: Any, links: Iterable[SupplementLink], output_dir: Path, doi
|
|
|
200
209
|
finally:
|
|
201
210
|
if temporary is not None:
|
|
202
211
|
temporary.unlink(missing_ok=True)
|
|
212
|
+
except SupplementTooLarge as exc:
|
|
213
|
+
entry.update(status="skipped", reason="too_large", size=exc.size)
|
|
203
214
|
except (BrowserUnresponsive, UserMarkedNoEntitlement) as exc:
|
|
204
215
|
stopped_reason = ("batch_stopped" if isinstance(exc, UserStoppedBatch) else
|
|
205
216
|
"user_skipped" if isinstance(exc, UserSkippedArticle) else
|
|
@@ -40,6 +40,7 @@ class UserStoppedBatch(UserMarkedNoEntitlement):
|
|
|
40
40
|
|
|
41
41
|
# Not an entitlement decision: nothing is recorded, the batch ends.
|
|
42
42
|
STOP_BATCH = "stop_batch"
|
|
43
|
+
SHOW_BROWSER = "show_browser"
|
|
43
44
|
|
|
44
45
|
|
|
45
46
|
SKIP = "skip"
|
|
@@ -191,13 +192,30 @@ def clear(key: str) -> bool:
|
|
|
191
192
|
|
|
192
193
|
def request_action(current: str, action: str, run_id: str = "") -> None:
|
|
193
194
|
"""Written by the progress window when the user presses a button."""
|
|
194
|
-
if action not in _ACTIONS and action
|
|
195
|
+
if action not in _ACTIONS and action not in (STOP_BATCH, SHOW_BROWSER):
|
|
195
196
|
raise ValueError("unknown action")
|
|
196
|
-
|
|
197
|
+
data = {"current": current, "action": action, "run_id": run_id, "at": time.time()}
|
|
198
|
+
if action == STOP_BATCH and run_id:
|
|
199
|
+
# A batch stop survives both item handoff and later focus requests.
|
|
200
|
+
# A new run has a new identity, so an old stop cannot cancel it.
|
|
201
|
+
_write_json(control_path().with_name("stop.json"), data)
|
|
202
|
+
else:
|
|
203
|
+
_write_json(control_path(), data)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def batch_stop_requested() -> bool:
|
|
207
|
+
"""A durable stop for the current run, including the gap between papers."""
|
|
208
|
+
stop = _read_json(control_path().with_name("stop.json"))
|
|
209
|
+
if stop.get("action") != STOP_BATCH or not stop.get("run_id"):
|
|
210
|
+
return False
|
|
211
|
+
state = _read_json(control_path().with_name("current.json"))
|
|
212
|
+
return state.get("status") == "running" and stop["run_id"] == state.get("run_id")
|
|
197
213
|
|
|
198
214
|
|
|
199
215
|
def take_action(doi: str, since: float) -> str | None:
|
|
200
216
|
"""The user's pending action for this paper (requested after ``since``), consumed once."""
|
|
217
|
+
if batch_stop_requested():
|
|
218
|
+
return STOP_BATCH
|
|
201
219
|
path = control_path()
|
|
202
220
|
data = _read_json(path)
|
|
203
221
|
if not data or str(data.get("current", "")).lower() != (doi or "").lower():
|
|
@@ -212,7 +230,7 @@ def take_action(doi: str, since: float) -> str | None:
|
|
|
212
230
|
except OSError:
|
|
213
231
|
pass
|
|
214
232
|
action = data.get("action")
|
|
215
|
-
return action if action in _ACTIONS or action
|
|
233
|
+
return action if action in _ACTIONS or action in (STOP_BATCH, SHOW_BROWSER) else None
|
|
216
234
|
|
|
217
235
|
|
|
218
236
|
def apply_user_decision(doi: str, publisher: str, since: float) -> str | None:
|
|
@@ -220,6 +238,8 @@ def apply_user_decision(doi: str, publisher: str, since: float) -> str | None:
|
|
|
220
238
|
action = take_action(doi, since)
|
|
221
239
|
if not action:
|
|
222
240
|
return None
|
|
241
|
+
if action == SHOW_BROWSER:
|
|
242
|
+
return action # an explicit focus request, never an entitlement decision
|
|
223
243
|
if action == STOP_BATCH:
|
|
224
244
|
raise UserStoppedBatch(action)
|
|
225
245
|
if action == "skip_item":
|