papersearch 0.4.5 → 0.4.7

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.
Files changed (71) hide show
  1. package/README.en.md +7 -4
  2. package/README.md +7 -4
  3. package/carsi/paper_search_carsi/adapters/ams/__init__.py +34 -1
  4. package/carsi/paper_search_carsi/adapters/annual_reviews/__init__.py +26 -1
  5. package/carsi/paper_search_carsi/adapters/aps/__init__.py +25 -2
  6. package/carsi/paper_search_carsi/adapters/copernicus/__init__.py +27 -1
  7. package/carsi/paper_search_carsi/adapters/elsevier/__init__.py +19 -1
  8. package/carsi/paper_search_carsi/adapters/ieee/__init__.py +102 -2
  9. package/carsi/paper_search_carsi/adapters/iop/__init__.py +41 -2
  10. package/carsi/paper_search_carsi/adapters/lww/ovid.py +4 -2
  11. package/carsi/paper_search_carsi/adapters/optica/__init__.py +14 -1
  12. package/carsi/paper_search_carsi/adapters/oup/__init__.py +105 -94
  13. package/carsi/paper_search_carsi/adapters/platforms/atypon/__init__.py +26 -12
  14. package/carsi/paper_search_carsi/adapters/platforms/figshare/__init__.py +20 -11
  15. package/carsi/paper_search_carsi/adapters/platforms/silverchair/__init__.py +1 -1
  16. package/carsi/paper_search_carsi/adapters/plos/__init__.py +31 -1
  17. package/carsi/paper_search_carsi/adapters/thieme/__init__.py +25 -2
  18. package/carsi/paper_search_carsi/assets/capsule.html +64 -21
  19. package/carsi/paper_search_carsi/assets/papersearch-notifier +0 -0
  20. package/carsi/paper_search_carsi/assets/quiet-browser/api.js +142 -0
  21. package/carsi/paper_search_carsi/assets/quiet-browser/manifest.json +24 -0
  22. package/carsi/paper_search_carsi/assets/quiet-browser/schema.json +1 -0
  23. package/carsi/paper_search_carsi/browser/backend.py +36 -0
  24. package/carsi/paper_search_carsi/browser/background.py +68 -0
  25. package/carsi/paper_search_carsi/browser/challenge_interaction.py +35 -0
  26. package/carsi/paper_search_carsi/browser/challenges.py +10 -0
  27. package/carsi/paper_search_carsi/browser/foreground.py +201 -0
  28. package/carsi/paper_search_carsi/browser/login.py +3 -1
  29. package/carsi/paper_search_carsi/browser/preview.py +3 -1
  30. package/carsi/paper_search_carsi/config.py +4 -1
  31. package/carsi/paper_search_carsi/engine/batch.py +62 -20
  32. package/carsi/paper_search_carsi/engine/batch_capture.py +54 -19
  33. package/carsi/paper_search_carsi/engine/batch_common.py +29 -2
  34. package/carsi/paper_search_carsi/engine/batch_diagnostics.py +31 -10
  35. package/carsi/paper_search_carsi/engine/batch_institution.py +56 -14
  36. package/carsi/paper_search_carsi/engine/batch_login.py +264 -204
  37. package/carsi/paper_search_carsi/engine/batch_user.py +67 -2
  38. package/carsi/paper_search_carsi/engine/batch_waits.py +76 -30
  39. package/carsi/paper_search_carsi/engine/login_wait.py +125 -0
  40. package/carsi/paper_search_carsi/engine/page_activity.py +177 -0
  41. package/carsi/paper_search_carsi/engine/supplements.py +12 -1
  42. package/carsi/paper_search_carsi/entitlements.py +23 -3
  43. package/carsi/paper_search_carsi/progress_capsule.py +130 -18
  44. package/carsi/paper_search_carsi/progress_macos.py +166 -0
  45. package/carsi/paper_search_carsi/progress_reporter.py +22 -1
  46. package/carsi/paper_search_carsi/progress_view.py +8 -6
  47. package/carsi/paper_search_carsi/publishers/profiles.py +5 -3
  48. package/carsi/paper_search_carsi/server.py +17 -1
  49. package/carsi/paper_search_carsi/user_settings.py +4 -4
  50. package/carsi/pyproject.toml +1 -1
  51. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js +2 -2
  52. package/dist/capabilities/pdf-discovery/OpenAccessFallbackService.js.map +1 -1
  53. package/dist/capabilities/pdf-discovery/batch.d.ts.map +1 -1
  54. package/dist/capabilities/pdf-discovery/batch.js +28 -4
  55. package/dist/capabilities/pdf-discovery/batch.js.map +1 -1
  56. package/dist/capabilities/pdf-discovery/carsi/CarsiMcpClient.js +1 -1
  57. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts +2 -6
  58. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.d.ts.map +1 -1
  59. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js +1 -0
  60. package/dist/capabilities/pdf-discovery/tiers/entitledAccess.js.map +1 -1
  61. package/dist/infrastructure/runlog/failureClass.d.ts.map +1 -1
  62. package/dist/infrastructure/runlog/failureClass.js +3 -2
  63. package/dist/infrastructure/runlog/failureClass.js.map +1 -1
  64. package/dist/management/carsi/installer.d.ts +2 -1
  65. package/dist/management/carsi/installer.d.ts.map +1 -1
  66. package/dist/management/carsi/installer.js +24 -1
  67. package/dist/management/carsi/installer.js.map +1 -1
  68. package/package.json +1 -1
  69. package/skills/paper-search/references/browser-download.md +11 -7
  70. package/skills/paper-search/references/carsi-setup.md +1 -0
  71. 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)
191
190
  if not automatic:
192
191
  deadline = min(deadline, self._wait_deadline(result))
193
- if self._automatic_challenge_step(tab, result, automatic, deadline):
192
+ if not manual and self._automatic_challenge_step(tab, result, automatic, deadline):
194
193
  page.wait_for_timeout(min(1000, max(0, (deadline - time.time()) * 1000)))
195
194
  continue
195
+ activity.automatic_for(0)
196
+ 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
- reporter.set_attention(attention_key, text, current=result.doi, phase=phase, deadline=deadline)
209
- reporter.report_stage(stage, current=result.doi)
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,10 @@ 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
+ activity.automatic_for(0)
240
+ result._attention_page = None
241
+ if activity_owned:
242
+ activity.close()
235
243
  interaction.close()
236
244
  if shown and reporter is not None:
237
245
  try:
@@ -243,6 +251,10 @@ class UserWaitMixin:
243
251
  """Apply a button the user pressed in the progress window for this paper."""
244
252
  if result is None:
245
253
  return
254
+ activity = getattr(result, "_page_activity", None)
255
+ if activity is not None and not activity.closed:
256
+ if page is not None:
257
+ activity.observe(page)
246
258
  self._capture_reported_issues(page, result)
247
259
  try:
248
260
  from .. import entitlements
@@ -256,6 +268,9 @@ class UserWaitMixin:
256
268
  self._event(result, "user_entitlement_decision", str(decision))
257
269
  raise
258
270
  if action:
271
+ if action == entitlements.SHOW_BROWSER:
272
+ self._show_download_browser(page, result)
273
+ return
259
274
  self._event(result, "user_entitlement_decision", action)
260
275
 
261
276
  @staticmethod
@@ -323,6 +338,9 @@ class UserWaitMixin:
323
338
  def _user_wait_deadline(self, result: DownloadResult) -> float:
324
339
  """One deadline for all waits on the user in this article (verification,
325
340
  school login, the PDF step): ``login_timeout_sec`` from the first of them."""
341
+ wait = getattr(result, "_login_wait", None)
342
+ if wait is not None and wait.attribute == "_user_wait_deadline":
343
+ return wait.deadline
326
344
  deadline = getattr(result, "_user_wait_deadline", None)
327
345
  if deadline is None:
328
346
  deadline = result._user_wait_deadline = time.time() + self.login_timeout_sec
@@ -369,8 +387,18 @@ class UserWaitMixin:
369
387
  bound = min(deadline, now + remaining) if remaining is not None else deadline
370
388
  attempt["automatic_end"] = bound - manual_reserve
371
389
  automatic_end = min(deadline - manual_reserve, attempt["automatic_end"])
390
+ activity = getattr(result, "_page_activity", None)
391
+ if activity is not None:
392
+ # The separate request watcher also checks idle time during these
393
+ # RPCs. Use the frozen automatic bound; never renew the wait budget.
394
+ activity.automatic_for(automatic_end - now)
372
395
  if now >= automatic_end or (attempt["attempts"] >= 3 and now >= attempt["retry_at"]):
373
396
  return False
397
+ if challenge_interaction.needs_manual_verification(page):
398
+ # We never operate this control. Waiting for it must not consume
399
+ # the enclosing automation budget, even if the site clears itself.
400
+ # The independent idle timer still decides when to remind the user.
401
+ return False
374
402
  if now >= attempt["retry_at"] and attempt["attempts"] < 3:
375
403
  # Camoufox's native humanized move can take 1.5 s before mouse-down.
376
404
  # Leave time for that action, still inside the original wait budget.
@@ -381,6 +409,8 @@ class UserWaitMixin:
381
409
  if outcome != "absent":
382
410
  attempt["attempts"] += 1
383
411
  attempt["retry_at"] = time.time() + 3
412
+ if outcome == "clicked" and activity is not None:
413
+ activity.progress(page)
384
414
  self._event(result, "challenge_interaction",
385
415
  f"checkbox {outcome}; attempt {attempt['attempts']}/3; awaiting verification")
386
416
  return time.time() < automatic_end
@@ -388,17 +418,13 @@ class UserWaitMixin:
388
418
  def _wait_for_challenge(self, page: Any, result: DownloadResult, *, deadline: float | None = None) -> bool:
389
419
  """Wait while a verification page is up, until ``_wait_deadline``."""
390
420
  interaction = ExitStack()
421
+ activity, activity_owned = self._observe_page_activity(page, result)
391
422
  automatic: dict[str, Any] = {}
392
423
  manual = False
393
424
  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
425
  started, phase_before = time.time(), ""
426
+ verification_wait = None
427
+ verification_deadline = None
402
428
  try:
403
429
  waited = False
404
430
  state_before = result.state
@@ -409,30 +435,34 @@ class UserWaitMixin:
409
435
  shell = self._challenge_shell(page)
410
436
  if not shell:
411
437
  self._raise_on_publisher_access_blocked(page)
412
- if shell or self._is_challenge_page(page):
438
+ if (shell or self._is_challenge_page(page)
439
+ or (waited and challenges.continues_manual_challenge(self._title(page)))):
413
440
  if not waited:
414
441
  deadline = self._wait_deadline(result, deadline)
415
442
  started, phase_before = time.time(), self._phase(result, "verification")
416
443
  waited = True
417
444
  result.state = "challenge_or_viewer_timeout"
445
+ if verification_wait is not None:
446
+ verification_wait.observe(page, True)
447
+ deadline = verification_wait.deadline
418
448
  if time.time() >= deadline:
419
449
  break
420
- auto_pending = self._automatic_challenge_step(page, result, automatic, deadline)
450
+ result._attention_page = page
451
+ auto_pending = not manual and self._automatic_challenge_step(page, result, automatic, deadline)
452
+ if not auto_pending:
453
+ activity.automatic_for(0)
454
+ activity.check()
421
455
  if not auto_pending and not manual:
456
+ result._attention_page = page
422
457
  interaction.enter_context(watchdog.pause_operation())
423
458
  manual = True
459
+ from .login_wait import LoginWait
460
+ verification_deadline = deadline
461
+ verification_wait = result._verification_wait = LoginWait(deadline, time.time)
462
+ verification_wait.observe(page, True)
424
463
  self._event(result, "challenge_manual_wait", "complete verification in visible browser")
425
464
  if not any(s["why"] == "waiting for the user: verification" for s in result.snapshots):
426
465
  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
466
  checks += 1
437
467
  self._event(result, "challenge_wait", f"{'manual' if manual else 'automatic'} {checks}")
438
468
  # Pump browser events while the user completes verification.
@@ -450,20 +480,33 @@ class UserWaitMixin:
450
480
  self._event(result, "challenge_resolved", getattr(page, "url", ""))
451
481
  return True
452
482
  self._raise_on_publisher_access_blocked(page)
453
- passed = not self._is_challenge_page(page)
483
+ passed = not (self._is_challenge_page(page)
484
+ or (waited and challenges.continues_manual_challenge(self._title(page))))
454
485
  if passed:
455
486
  result.state = state_before
456
487
  else:
457
488
  self._wait_ran_out(result)
458
489
  return passed
459
490
  finally:
491
+ activity.automatic_for(0)
492
+ if verification_wait is not None:
493
+ excluded = max(0, verification_wait.close() - verification_deadline)
494
+ outer_wait = getattr(result, "_login_wait", None)
495
+ if outer_wait is not None:
496
+ if not outer_wait.paused:
497
+ outer_wait.exclude_elapsed(excluded)
498
+ elif isinstance(getattr(result, "_user_wait_deadline", None), (float, int)):
499
+ result._user_wait_deadline += excluded
500
+ result._verification_wait = None
460
501
  interaction.close()
461
502
  if waited:
462
503
  self._phase(result, phase_before or "open")
463
504
  self._note_wait(result, "verification", started, "passed" if result.state != "challenge_or_viewer_timeout"
464
505
  else "not completed")
465
- if attention_open and reporter is not None:
466
- reporter.clear_attention(attention_key)
506
+ if activity_owned:
507
+ activity.close()
508
+ if getattr(result, "_attention_page", None) is page:
509
+ result._attention_page = None
467
510
 
468
511
  def _challenge_shell(self, page: Any) -> bool:
469
512
  """Read only URL/title while a verification interstitial is active."""
@@ -485,4 +528,7 @@ class UserWaitMixin:
485
528
  return False
486
529
  if challenges.is_challenge_path(str(getattr(page, "url", "") or "")):
487
530
  return True
488
- return challenges.has_challenge_text(self._title(page), self._body_text(page, 1_200))
531
+ title = self._title(page)
532
+ return (challenges.has_challenge_text(title, self._body_text(page, 1_200))
533
+ or (challenges.continues_manual_challenge(title)
534
+ 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,177 @@
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._automatic_until = 0.0
33
+ self.closed = False
34
+ self.page = None
35
+ self._pages: dict[int, tuple[Any, dict]] = {}
36
+ self._navigations: dict[int, tuple[Any, float]] = {}
37
+
38
+ def progress(self, page=None) -> None:
39
+ with self._lock:
40
+ if self.closed:
41
+ return
42
+ self._last_progress = self._clock()
43
+ if page is not None:
44
+ self.page = page
45
+ self._clear()
46
+
47
+ def _clear(self) -> None:
48
+ if self._shown:
49
+ progress_reporter.clear_attention(self._key)
50
+ self._shown = False
51
+
52
+ def automatic_for(self, seconds: float) -> None:
53
+ """Defer idle reminders until the caller's existing automatic deadline.
54
+
55
+ This is a finite lease, not progress: polling must pass only the time
56
+ remaining on the original bound. Zero releases it at manual handoff.
57
+ The watcher can still remind if the browser call never returns.
58
+ """
59
+ with self._lock:
60
+ self._automatic_until = self._clock() + max(0.0, seconds)
61
+ if seconds > 0:
62
+ self._clear()
63
+
64
+ def check(self) -> None:
65
+ """Thread safe; never inspect a page or interrupt an in-flight operation."""
66
+ with self._lock:
67
+ if self.closed:
68
+ return
69
+ if progress_reporter.has_attention(current=self._doi, excluding=self._key):
70
+ # School login and other explicit requests have priority. Start
71
+ # a fresh quiet interval when they finish rather than duplicating them.
72
+ self._last_progress = self._clock()
73
+ self._clear()
74
+ elif (not self._shown and not self._transfers
75
+ and self._clock() >= self._automatic_until
76
+ and not self._navigation_loading()
77
+ and self._clock() - self._last_progress >= self.after):
78
+ progress_reporter.set_attention(
79
+ self._key, "页面持续没有进展,请查看浏览器,可能需要手动操作",
80
+ current=self._doi, phase="需要人工处理")
81
+ self._shown = True
82
+
83
+ def _navigation_loading(self) -> bool:
84
+ pending = self._navigations.get(id(self.page))
85
+ return pending is not None and self._clock() < pending[1]
86
+
87
+ def observe(self, page) -> None:
88
+ """Attach only on the browser thread, including this page's owned popups."""
89
+ if self.closed or id(page) in self._pages:
90
+ return
91
+
92
+ def navigated(frame):
93
+ if frame == page.main_frame:
94
+ self.progress(page)
95
+
96
+ def loaded():
97
+ with self._lock:
98
+ self._navigations.pop(id(page), None)
99
+ self.progress(page)
100
+
101
+ def requested(request):
102
+ # These are cached Playwright properties, not browser RPCs. Ads,
103
+ # analytics, XHR polling and subframes cannot silence a stuck page.
104
+ if not request.is_navigation_request() or request.frame != page.main_frame:
105
+ return
106
+ with self._lock:
107
+ previous = self._navigations.get(id(page))
108
+ deadline = (previous[1] if previous and request.redirected_from is previous[0]
109
+ else self._clock() + self._navigation_timeout)
110
+ self._navigations[id(page)] = (request, deadline)
111
+ self.progress(page)
112
+
113
+ def responded(response):
114
+ with self._lock:
115
+ pending = self._navigations.get(id(page))
116
+ if pending is not None and response.request is pending[0]:
117
+ self.progress(page)
118
+
119
+ def failed(request):
120
+ with self._lock:
121
+ pending = self._navigations.get(id(page))
122
+ if pending is not None and request is pending[0]:
123
+ self._navigations.pop(id(page), None)
124
+ self.progress(page)
125
+
126
+ def closed():
127
+ with self._lock:
128
+ self._pages.pop(id(page), None)
129
+ self._navigations.pop(id(page), None)
130
+ if self.page is page:
131
+ self.page = next((p for p, _ in reversed(list(self._pages.values()))), None)
132
+ self.progress()
133
+ for event, handler in handlers.items():
134
+ page.remove_listener(event, handler)
135
+
136
+ handlers = {"framenavigated": navigated, "domcontentloaded": loaded,
137
+ "request": requested, "response": responded, "requestfailed": failed,
138
+ "popup": self.observe, "close": closed}
139
+ self._pages[id(page)] = (page, handlers)
140
+ for event, handler in handlers.items():
141
+ page.on(event, handler)
142
+ self.progress(page)
143
+
144
+ @contextmanager
145
+ def transfer(self):
146
+ """A browser body/save RPC exposes no byte events. Its existing network
147
+ and watchdog limits still apply; do not call it a page needing a click."""
148
+ with self._lock:
149
+ self._transfers += 1
150
+ self.progress()
151
+ try:
152
+ yield
153
+ finally:
154
+ with self._lock:
155
+ self._transfers -= 1
156
+ self.progress()
157
+
158
+ def close(self) -> None:
159
+ """Detach on the browser thread and clear any reminder before the next item."""
160
+ with self._lock:
161
+ self.closed = True
162
+ self._navigations.clear()
163
+ self._clear()
164
+ for page, handlers in list(self._pages.values()):
165
+ for event, handler in handlers.items():
166
+ page.remove_listener(event, handler)
167
+ self._pages.clear()
168
+
169
+
170
+ @contextmanager
171
+ def transfer(result):
172
+ activity = getattr(result, "_page_activity", None)
173
+ if activity is None:
174
+ yield
175
+ else:
176
+ with activity.transfer():
177
+ 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) -> list[dict[str, Any]]:
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 != STOP_BATCH:
195
+ if action not in _ACTIONS and action not in (STOP_BATCH, SHOW_BROWSER):
195
196
  raise ValueError("unknown action")
196
- _write_json(control_path(), {"current": current, "action": action, "run_id": run_id, "at": time.time()})
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 == STOP_BATCH else None
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":