papersearch 0.4.4 → 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 +112 -32
- 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 +73 -21
- 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/supplement_transfer.py +55 -0
- package/carsi/paper_search_carsi/engine/supplements.py +96 -24
- package/carsi/paper_search_carsi/entitlements.py +23 -3
- package/carsi/paper_search_carsi/progress_capsule.py +246 -30
- 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
|
@@ -11,6 +11,7 @@ Part of ``PublisherBatchDownloader`` (batch.py), which combines the mixins."""
|
|
|
11
11
|
|
|
12
12
|
from __future__ import annotations
|
|
13
13
|
|
|
14
|
+
import sys
|
|
14
15
|
import threading
|
|
15
16
|
import time
|
|
16
17
|
from pathlib import Path
|
|
@@ -20,6 +21,17 @@ from urllib.parse import urlparse
|
|
|
20
21
|
from .. import progress_reporter
|
|
21
22
|
from ..entitlements import UserMarkedNoEntitlement
|
|
22
23
|
from .batch_common import DownloadResult, open_page
|
|
24
|
+
from .page_activity import PageActivity
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class _UserWatch(threading.Event):
|
|
28
|
+
def __init__(self, activity: PageActivity):
|
|
29
|
+
super().__init__()
|
|
30
|
+
self.activity = activity
|
|
31
|
+
|
|
32
|
+
def set(self) -> None:
|
|
33
|
+
super().set()
|
|
34
|
+
self.activity.close()
|
|
23
35
|
|
|
24
36
|
|
|
25
37
|
class UserProvidedPdf(Exception):
|
|
@@ -51,15 +63,28 @@ class UserRequestsMixin:
|
|
|
51
63
|
from .. import entitlements, issues
|
|
52
64
|
from ..browser import watchdog
|
|
53
65
|
|
|
54
|
-
|
|
66
|
+
activity, _ = self._observe_page_activity(page, result)
|
|
67
|
+
stop = _UserWatch(activity)
|
|
55
68
|
publisher = str(getattr(getattr(self, "profile", None), "name", "") or "")
|
|
56
69
|
since = getattr(self, "_item_started", 0.0)
|
|
57
70
|
scheduled: set[str] = set()
|
|
71
|
+
if sys.platform == "darwin":
|
|
72
|
+
from ..browser.foreground import mac_browser_pid
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
pid = mac_browser_pid(page, self.config)
|
|
76
|
+
except Exception as exc:
|
|
77
|
+
self._event(result, "browser_focus_unavailable", type(exc).__name__)
|
|
78
|
+
pid = 0
|
|
79
|
+
progress_reporter.update(browser_pid=pid)
|
|
58
80
|
|
|
59
81
|
def watch() -> None:
|
|
60
82
|
while not stop.wait(1.0):
|
|
83
|
+
activity.check()
|
|
61
84
|
try:
|
|
62
|
-
entitlements.apply_user_decision(result.doi, publisher, since)
|
|
85
|
+
action = entitlements.apply_user_decision(result.doi, publisher, since)
|
|
86
|
+
if action == entitlements.SHOW_BROWSER:
|
|
87
|
+
watchdog.run_soon(lambda: self._show_download_browser(page, result))
|
|
63
88
|
except UserMarkedNoEntitlement as decision:
|
|
64
89
|
self._event(result, "user_entitlement_decision", str(decision))
|
|
65
90
|
watchdog.interrupt(decision)
|
|
@@ -77,6 +102,46 @@ class UserRequestsMixin:
|
|
|
77
102
|
threading.Thread(target=watch, name="user-requests", daemon=True).start()
|
|
78
103
|
return stop
|
|
79
104
|
|
|
105
|
+
def _observe_page_activity(self, page: Any, result: DownloadResult) -> tuple[PageActivity, bool]:
|
|
106
|
+
activity = getattr(result, "_page_activity", None)
|
|
107
|
+
owned = activity is None or activity.closed
|
|
108
|
+
if owned:
|
|
109
|
+
result._page_activity = activity = PageActivity(result.doi, self.config)
|
|
110
|
+
if page is not None:
|
|
111
|
+
activity.observe(page)
|
|
112
|
+
return activity, owned
|
|
113
|
+
|
|
114
|
+
def _show_download_browser(self, page: Any, result: DownloadResult) -> None:
|
|
115
|
+
"""Focus the existing task page only after the user requests it."""
|
|
116
|
+
from ..browser import watchdog
|
|
117
|
+
|
|
118
|
+
try:
|
|
119
|
+
page = getattr(result, "_attention_page", None) or page
|
|
120
|
+
activity = getattr(result, "_page_activity", None)
|
|
121
|
+
if not getattr(result, "_attention_page", None) and activity is not None and not activity.closed:
|
|
122
|
+
page = activity.page or page
|
|
123
|
+
if page is None or page.is_closed():
|
|
124
|
+
self._tell_user("下载浏览器已关闭", result)
|
|
125
|
+
return
|
|
126
|
+
from ..browser.foreground import show
|
|
127
|
+
|
|
128
|
+
wait = getattr(result, "_login_wait", None)
|
|
129
|
+
if wait is not None and getattr(result, "_login_attention", ""):
|
|
130
|
+
wait.take_over()
|
|
131
|
+
self._set_login_attention(result, result._login_attention, page=page)
|
|
132
|
+
verification_wait = getattr(result, "_verification_wait", None)
|
|
133
|
+
if verification_wait is not None:
|
|
134
|
+
verification_wait.take_over()
|
|
135
|
+
show(page, self.config)
|
|
136
|
+
except (watchdog.BrowserUnresponsive, UserMarkedNoEntitlement):
|
|
137
|
+
raise
|
|
138
|
+
except Exception as exc:
|
|
139
|
+
self._event(result, "browser_focus_failed", type(exc).__name__)
|
|
140
|
+
self._tell_user("未能切到下载浏览器,请从程序坞或任务栏打开", result)
|
|
141
|
+
return
|
|
142
|
+
self._event(result, "browser_shown", "requested from progress capsule")
|
|
143
|
+
self._tell_user("已切到下载浏览器", result)
|
|
144
|
+
|
|
80
145
|
def _handle_report(self, folder: Path, page: Any, result: DownloadResult, *, act: bool = True) -> None:
|
|
81
146
|
"""Capture the live page for a report and, while the article runs (``act``),
|
|
82
147
|
do what it asks. Raises only to end the article (an open PDF that is this
|
|
@@ -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
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Stream attachments with the active browser session, outside the RPC body channel."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from contextlib import contextmanager
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import requests
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class Response:
|
|
11
|
+
def __init__(self, response: requests.Response):
|
|
12
|
+
self._response = response
|
|
13
|
+
self.status = response.status_code
|
|
14
|
+
self.ok = response.ok
|
|
15
|
+
self.headers = response.headers
|
|
16
|
+
|
|
17
|
+
def chunks(self):
|
|
18
|
+
# read1 returns available data instead of waiting to fill a whole chunk;
|
|
19
|
+
# the collector can enforce its deadline even on a trickling server.
|
|
20
|
+
while chunk := self._response.raw.read1(64 * 1024, decode_content=True):
|
|
21
|
+
yield chunk
|
|
22
|
+
|
|
23
|
+
def dispose(self):
|
|
24
|
+
self._response.close()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Request:
|
|
28
|
+
def __init__(self, session: requests.Session):
|
|
29
|
+
self._session = session
|
|
30
|
+
|
|
31
|
+
def get(self, url: str, *, timeout: int):
|
|
32
|
+
# Only connection/header acquisition happens here. Subsequent reads have
|
|
33
|
+
# an idle timeout; a progressing large file is not a frozen browser RPC.
|
|
34
|
+
return Response(self._session.get(url, stream=True, timeout=(10, timeout / 1000)))
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@contextmanager
|
|
38
|
+
def browser_request(page: Any, config: dict, *, proxy: str | None = None):
|
|
39
|
+
"""Keep cookie domain/path/secure scope and the browser's configured egress.
|
|
40
|
+
|
|
41
|
+
Cookies remain in memory. Requests' redirect handling reapplies cookie scope
|
|
42
|
+
on each host; no manually copied Cookie header follows cross-site redirects.
|
|
43
|
+
"""
|
|
44
|
+
with requests.Session() as session:
|
|
45
|
+
session.trust_env = False
|
|
46
|
+
proxy = str(proxy or config.get("browser_static_proxy") or config.get("network_proxy") or "").strip()
|
|
47
|
+
if proxy:
|
|
48
|
+
session.proxies.update(http=proxy, https=proxy)
|
|
49
|
+
session.headers.update({"User-Agent": page.evaluate("navigator.userAgent"),
|
|
50
|
+
"Referer": str(page.url)})
|
|
51
|
+
for cookie in page.context.cookies():
|
|
52
|
+
session.cookies.set(cookie["name"], cookie["value"], domain=cookie["domain"],
|
|
53
|
+
path=cookie.get("path", "/"), secure=bool(cookie.get("secure")),
|
|
54
|
+
expires=int(cookie["expires"]) if cookie.get("expires", -1) > 0 else None)
|
|
55
|
+
yield Request(session)
|